1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/lib/config"
20 "git.curoverse.com/arvados.git/lib/controller/localdb"
21 "git.curoverse.com/arvados.git/lib/controller/rpc"
22 "git.curoverse.com/arvados.git/sdk/go/arvados"
23 "git.curoverse.com/arvados.git/sdk/go/auth"
24 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
28 cluster *arvados.Cluster
30 remotes map[string]backend
33 func New(cluster *arvados.Cluster) *Conn {
34 local := localdb.NewConn(cluster)
35 remotes := map[string]backend{}
36 for id, remote := range cluster.RemoteClusters {
40 remotes[id] = rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(local, id))
50 // Return a new rpc.TokenProvider that takes the client-provided
51 // tokens from an incoming request context, determines whether they
52 // should (and can) be salted for the given remoteID, and returns the
54 func saltedTokenProvider(local backend, remoteID string) rpc.TokenProvider {
55 return func(ctx context.Context) ([]string, error) {
57 incoming, ok := auth.FromContext(ctx)
59 return nil, errors.New("no token provided")
61 for _, token := range incoming.Tokens {
62 salted, err := auth.SaltToken(token, remoteID)
65 tokens = append(tokens, salted)
67 tokens = append(tokens, token)
68 case auth.ErrObsoleteToken:
69 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
70 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
71 if errStatus(err) == http.StatusUnauthorized {
72 // pass through unmodified
73 tokens = append(tokens, token)
75 } else if err != nil {
78 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
82 tokens = append(tokens, salted)
91 // Return suitable backend for a query about the given cluster ID
92 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
93 func (conn *Conn) chooseBackend(id string) backend {
96 } else if len(id) != 5 {
100 if id == conn.cluster.ClusterID {
102 } else if be, ok := conn.remotes[id]; ok {
105 // TODO: return an "always error" backend?
110 // Call fn with the local backend; then, if fn returned 404, call fn
111 // on the available remote backends (possibly concurrently) until one
114 // The second argument to fn is the cluster ID of the remote backend,
115 // or "" for the local backend.
117 // A non-nil error means all backends failed.
118 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, fn func(context.Context, string, backend) error) error {
119 if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound {
123 ctx, cancel := context.WithCancel(ctx)
125 errchan := make(chan error, len(conn.remotes))
126 for remoteID, be := range conn.remotes {
127 remoteID, be := remoteID, be
129 errchan <- fn(ctx, remoteID, be)
134 for i := 0; i < cap(errchan); i++ {
139 all404 = all404 && errStatus(err) == http.StatusNotFound
140 errs = append(errs, err)
143 return notFoundError{}
145 return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
148 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
149 return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
152 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
153 return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
156 func rewriteManifest(mt, remoteID string) string {
157 return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
158 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
162 // this could be in sdk/go/arvados
163 func portableDataHash(mt string) string {
165 blkRe := regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
167 _ = regexp.MustCompile(` ?[^ ]*`).ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
168 if m := blkRe.Find(tok); m != nil {
169 // write hash+size, ignore remaining block hints
172 n, err := h.Write(tok)
179 return fmt.Sprintf("%x+%d", h.Sum(nil), size)
182 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
184 err := config.ExportJSON(&buf, conn.cluster)
185 return json.RawMessage(buf.Bytes()), err
188 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
189 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
190 // defer entire login procedure to designated cluster
191 remote, ok := conn.remotes[id]
193 return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
195 baseURL := remote.BaseURL()
196 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
198 return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
200 target.RawQuery = url.Values{
201 "return_to": []string{options.ReturnTo},
202 "remote": []string{options.Remote},
204 return arvados.LoginResponse{
205 RedirectLocation: target.String(),
208 return conn.local.Login(ctx, options)
212 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
213 if len(options.UUID) == 27 {
214 // UUID is really a UUID
215 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
216 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
217 c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
222 first := make(chan arvados.Collection, 1)
223 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
224 c, err := be.CollectionGet(ctx, options)
228 // options.UUID is either hash+size or
229 // hash+size+hints; only hash+size need to
230 // match the computed PDH.
231 if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
232 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
233 ctxlog.FromContext(ctx).Warn(err)
237 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
243 // lost race, return value doesn't matter
248 return arvados.Collection{}, err
254 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
255 return conn.generated_CollectionList(ctx, options)
258 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
259 return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
262 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
263 return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
266 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
267 return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
270 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
271 return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
274 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
275 return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
278 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
279 return conn.generated_ContainerList(ctx, options)
282 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
283 return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
286 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
287 return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
290 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
291 return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
294 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
295 return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
298 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
299 return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
302 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
303 return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
306 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
307 return conn.generated_SpecimenList(ctx, options)
310 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
311 return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
314 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
315 return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
318 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
319 return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
322 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
323 return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
326 var userAttrsCachedFromLoginCluster = map[string]bool{
334 "modified_by_client_uuid": true,
335 "modified_by_user_uuid": true,
340 "identity_url": false,
346 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
347 logger := ctxlog.FromContext(ctx)
348 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
349 resp, err := conn.chooseBackend(id).UserList(ctx, options)
353 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
354 for _, user := range resp.Items {
355 if !strings.HasPrefix(user.UUID, id) {
358 logger.Debug("cache user info for uuid %q", user.UUID)
359 var allFields map[string]interface{}
360 buf, err := json.Marshal(user)
362 return arvados.UserList{}, fmt.Errorf("error encoding user record from remote response: %s", err)
364 err = json.Unmarshal(buf, &allFields)
366 return arvados.UserList{}, fmt.Errorf("error transcoding user record from remote response: %s", err)
369 if len(options.Select) > 0 {
370 updates = map[string]interface{}{}
371 for _, k := range options.Select {
372 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
377 for k := range updates {
378 if !userAttrsCachedFromLoginCluster[k] {
383 _, err = conn.local.UserUpdate(ctxRoot, arvados.UpdateOptions{
387 if errStatus(err) == http.StatusNotFound {
388 updates["uuid"] = user.UUID
389 _, err = conn.local.UserCreate(ctxRoot, arvados.CreateOptions{
394 logger.WithError(err).WithField("UUID", user.UUID).Error("error updating local user record")
395 return arvados.UserList{}, fmt.Errorf("error updating local user record: %s", err)
400 return conn.generated_UserList(ctx, options)
404 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
405 return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
408 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
409 return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
412 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
413 return conn.chooseBackend(options.UUID).UserUpdateUUID(ctx, options)
416 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
417 return conn.chooseBackend(options.OldUserUUID).UserMerge(ctx, options)
420 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
421 return conn.chooseBackend(options.UUID).UserActivate(ctx, options)
424 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
425 return conn.chooseBackend(options.UUID).UserSetup(ctx, options)
428 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
429 return conn.chooseBackend(options.UUID).UserUnsetup(ctx, options)
432 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
433 return conn.chooseBackend(options.UUID).UserGet(ctx, options)
436 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
437 return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
440 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
441 return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
444 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
445 return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
448 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
449 return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
452 type backend interface {
457 type notFoundError struct{}
459 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
460 func (notFoundError) Error() string { return "not found" }
462 func errStatus(err error) int {
463 if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
464 return httpErr.HTTPStatus()
466 return http.StatusInternalServerError