File: service.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (256 lines) | stat: -rw-r--r-- 6,922 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright (c) 2020, Control Command Inc. All rights reserved.
// Copyright (c) 2019-2023, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package endpoint

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	jsonresp "github.com/sylabs/json-resp"
	"github.com/sylabs/singularity/v4/internal/pkg/remote/credential"
	useragent "github.com/sylabs/singularity/v4/pkg/util/user-agent"
)

const defaultTimeout = 10 * time.Second

// Default Sylabs cloud service endpoints.
const (
	// SCSConfigPath is the path to the exposed configuration information of an SCS / Singularity Enterprise instance.
	SCSConfigPath = "/assets/config/config.prod.json"
	// SCSDefaultCloudURI is the primary hostname for Sylabs Singularity Container Services.
	SCSDefaultCloudURI = "cloud.sylabs.io"
	// SCSDefaultLibraryURI is the URI for the library service in SCS.
	SCSDefaultLibraryURI = "https://library.sylabs.io"
	// SCSDefaultKeyserverURI is the URI for the keyserver service in SCS.
	SCSDefaultKeyserverURI = "https://keys.sylabs.io"
	// SCSDefaultBuilderURI is the URI for the remote build service in SCS.
	SCSDefaultBuilderURI = "https://build.sylabs.io"
)

// SCS cloud services - suffixed with 'API' in config.prod.json.
const (
	Consent   = "consent"
	Token     = "token"
	Library   = "library"
	Keystore  = "keystore" // alias for keyserver
	Keyserver = "keyserver"
	Builder   = "builder"
)

// RegistryURIConfigKey is the config key for the library OCI registry URI
const RegistryURIConfigKey = "registryUri"

var errorCodeMap = map[int]string{
	404: "Invalid Credentials",
	500: "Internal Server Error",
}

// ErrStatusNotSupported represents the error returned by
// a service which doesn't support SCS status check.
var ErrStatusNotSupported = errors.New("status not supported")

// Service represents a remote service, accessible at Service.URI
type Service interface {
	// URI returns the URI used to access the remote service.
	URI() string
	// Status returns the status of the remote service, if supported.
	Status() (string, error)
	// configKey returns the value of a requested configuration key, if set.
	configVal(string) string
}

type service struct {
	// cfg holds the serializable service configuration.
	cfg *ServiceConfig
	// configMap holds additional specific service configuration key/val pairs.
	// e.g. `registryURI` most be known for the SCS/Enterprise library service to facilitate OCI-SIF push/pull/
	configMap map[string]string
}

// URI returns the service URI.
func (s *service) URI() string {
	return s.cfg.URI
}

// Status checks the service status and returns the version
// of the corresponding service. An ErrStatusNotSupported is
// returned if the service doesn't support this check.
func (s *service) Status() (version string, err error) {
	if s.cfg.External {
		return "", ErrStatusNotSupported
	}

	client := &http.Client{
		Timeout: (30 * time.Second),
	}

	req, err := http.NewRequest(http.MethodGet, s.cfg.URI+"/version", nil)
	if err != nil {
		return "", err
	}

	req.Header.Set("User-Agent", useragent.Value())

	res, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("error making request to server: %v", err)
	}
	defer res.Body.Close()

	if res.StatusCode != http.StatusOK {
		return "", fmt.Errorf("error response from server: %v", res.StatusCode)
	}

	var vRes struct {
		Version string `json:"version"`
	}

	if err := jsonresp.ReadResponse(res.Body, &vRes); err != nil {
		return "", err
	}

	return vRes.Version, nil
}

// configVal returns the value of the specified key (if present), in the
// service's additional known configuration.
func (s *service) configVal(key string) string {
	return s.configMap[key]
}

func (ep *Config) GetAllServices() (map[string][]Service, error) {
	if ep.services != nil {
		return ep.services, nil
	}

	ep.services = make(map[string][]Service)

	client := &http.Client{
		Timeout: defaultTimeout,
	}

	epURL, err := ep.GetURL()
	if err != nil {
		return nil, err
	}

	configURL := epURL + SCSConfigPath

	req, err := http.NewRequest(http.MethodGet, configURL, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("User-Agent", useragent.Value())

	cacheReader := getCachedConfig(epURL)
	reader := cacheReader

	if cacheReader == nil {
		res, err := client.Do(req) //nolint:bodyclose
		if err != nil {
			return nil, fmt.Errorf("error making request to server: %s", err)
		} else if res.StatusCode != http.StatusOK {
			return nil, fmt.Errorf("error response from server: %s", err)
		}
		reader = res.Body
	}
	defer reader.Close()

	b, err := io.ReadAll(reader)
	if err != nil {
		return nil, fmt.Errorf("while reading response body: %v", err)
	}

	var a map[string]map[string]interface{}

	if err := json.Unmarshal(b, &a); err != nil {
		return nil, fmt.Errorf("jsonresp: failed to unmarshal response: %v", err)
	}

	if reader != cacheReader {
		updateCachedConfig(epURL, b)
	}

	for k, v := range a {
		s := strings.TrimSuffix(k, "API")
		uri, ok := v["uri"].(string)
		if !ok {
			continue
		}

		sConfig := &ServiceConfig{
			URI: uri,
			credential: &credential.Config{
				URI:  uri,
				Auth: credential.TokenPrefix + ep.Token,
			},
		}
		sConfigMap := map[string]string{}

		// If the SCS/Enterprise instance reports a service called 'keystore'
		// then override this to 'keyserver', as Singularity uses 'keyserver'
		// internally.
		if s == Keystore {
			s = Keyserver
		}

		// Store the backing OCI registry URI for the library service (if any).
		if s == Library {
			registryURI, ok := v[RegistryURIConfigKey].(string)
			if ok {
				sConfigMap[RegistryURIConfigKey] = registryURI
			}
		}

		ep.services[s] = []Service{
			&service{
				cfg:       sConfig,
				configMap: sConfigMap,
			},
		}
	}

	return ep.services, nil
}

// GetServiceURI returns the URI for the service at the specified SCS endpoint
// Examples of services: consent, build, library, key, token
func (ep *Config) GetServiceURI(service string) (string, error) {
	services, err := ep.GetAllServices()
	if err != nil {
		return "", err
	}

	s, ok := services[service]
	if !ok || len(s) == 0 {
		return "", fmt.Errorf("%v is not a service at endpoint", service)
	} else if s[0].URI() == "" {
		return "", fmt.Errorf("%v service at endpoint failed to provide URI in response", service)
	}

	return s[0].URI(), nil
}

// getServiceConfigVal returns the value for the additional config key associated with service.
func (ep *Config) getServiceConfigVal(service, key string) (string, error) {
	services, err := ep.GetAllServices()
	if err != nil {
		return "", err
	}

	s, ok := services[service]
	if !ok || len(s) == 0 {
		return "", fmt.Errorf("%v is not a service at endpoint", service)
	}
	return s[0].configVal(key), nil
}