1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/lib/config"
21 "git.curoverse.com/arvados.git/lib/controller/localdb"
22 "git.curoverse.com/arvados.git/lib/controller/rpc"
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/auth"
25 "git.curoverse.com/arvados.git/sdk/go/ctxlog"
29 cluster *arvados.Cluster
31 remotes map[string]backend
34 func New(cluster *arvados.Cluster) *Conn {
35 local := localdb.NewConn(cluster)
36 remotes := map[string]backend{}
37 for id, remote := range cluster.RemoteClusters {
41 remotes[id] = rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(local, id))
51 // Return a new rpc.TokenProvider that takes the client-provided
52 // tokens from an incoming request context, determines whether they
53 // should (and can) be salted for the given remoteID, and returns the
55 func saltedTokenProvider(local backend, remoteID string) rpc.TokenProvider {
56 return func(ctx context.Context) ([]string, error) {
58 incoming, ok := auth.FromContext(ctx)
60 return nil, errors.New("no token provided")
62 for _, token := range incoming.Tokens {
63 salted, err := auth.SaltToken(token, remoteID)
66 tokens = append(tokens, salted)
68 tokens = append(tokens, token)
69 case auth.ErrObsoleteToken:
70 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
71 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
72 if errStatus(err) == http.StatusUnauthorized {
73 // pass through unmodified
74 tokens = append(tokens, token)
76 } else if err != nil {
79 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
83 tokens = append(tokens, salted)
92 // Return suitable backend for a query about the given cluster ID
93 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
94 func (conn *Conn) chooseBackend(id string) backend {
97 } else if len(id) != 5 {
101 if id == conn.cluster.ClusterID {
103 } else if be, ok := conn.remotes[id]; ok {
106 // TODO: return an "always error" backend?
111 // Call fn with the local backend; then, if fn returned 404, call fn
112 // on the available remote backends (possibly concurrently) until one
115 // The second argument to fn is the cluster ID of the remote backend,
116 // or "" for the local backend.
118 // A non-nil error means all backends failed.
119 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, fn func(context.Context, string, backend) error) error {
120 if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound {
124 ctx, cancel := context.WithCancel(ctx)
126 errchan := make(chan error, len(conn.remotes))
127 for remoteID, be := range conn.remotes {
128 remoteID, be := remoteID, be
130 errchan <- fn(ctx, remoteID, be)
135 for i := 0; i < cap(errchan); i++ {
140 all404 = all404 && errStatus(err) == http.StatusNotFound
141 errs = append(errs, err)
144 return notFoundError{}
146 return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
149 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
150 return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
153 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
154 return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
157 func rewriteManifest(mt, remoteID string) string {
158 return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
159 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
163 // this could be in sdk/go/arvados
164 func portableDataHash(mt string) string {
166 blkRe := regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
168 _ = regexp.MustCompile(` ?[^ ]*`).ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
169 if m := blkRe.Find(tok); m != nil {
170 // write hash+size, ignore remaining block hints
173 n, err := h.Write(tok)
180 return fmt.Sprintf("%x+%d", h.Sum(nil), size)
183 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
185 err := config.ExportJSON(&buf, conn.cluster)
186 return json.RawMessage(buf.Bytes()), err
189 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
190 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
191 // defer entire login procedure to designated cluster
192 remote, ok := conn.remotes[id]
194 return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
196 baseURL := remote.BaseURL()
197 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
199 return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
201 params := url.Values{
202 "return_to": []string{options.ReturnTo},
204 if options.Remote != "" {
205 params.Set("remote", options.Remote)
207 target.RawQuery = params.Encode()
208 return arvados.LoginResponse{
209 RedirectLocation: target.String(),
212 return conn.local.Login(ctx, options)
216 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
217 if len(options.UUID) == 27 {
218 // UUID is really a UUID
219 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
220 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
221 c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
226 first := make(chan arvados.Collection, 1)
227 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
228 c, err := be.CollectionGet(ctx, options)
232 // options.UUID is either hash+size or
233 // hash+size+hints; only hash+size need to
234 // match the computed PDH.
235 if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
236 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
237 ctxlog.FromContext(ctx).Warn(err)
241 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
247 // lost race, return value doesn't matter
252 return arvados.Collection{}, err
258 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
259 return conn.generated_CollectionList(ctx, options)
262 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
263 return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
266 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
267 return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
270 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
271 return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
274 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
275 return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
278 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
279 return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
282 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
283 return conn.generated_ContainerList(ctx, options)
286 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
287 return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
290 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
291 return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
294 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
295 return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
298 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
299 return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
302 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
303 return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
306 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
307 return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
310 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
311 return conn.generated_SpecimenList(ctx, options)
314 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
315 return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
318 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
319 return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
322 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
323 return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
326 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
327 return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
330 var userAttrsCachedFromLoginCluster = map[string]bool{
338 "modified_by_client_uuid": true,
339 "modified_by_user_uuid": true,
344 "identity_url": false,
350 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
351 logger := ctxlog.FromContext(ctx)
352 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
353 resp, err := conn.chooseBackend(id).UserList(ctx, options)
357 batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
358 for _, user := range resp.Items {
359 if !strings.HasPrefix(user.UUID, id) {
362 logger.Debugf("cache user info for uuid %q", user.UUID)
364 // If the remote cluster has null timestamps
365 // (e.g., test server with incomplete
366 // fixtures) use dummy timestamps (instead of
367 // the zero time, which causes a Rails API
368 // error "year too big to marshal: 1 UTC").
369 if user.ModifiedAt.IsZero() {
370 user.ModifiedAt = time.Now()
372 if user.CreatedAt.IsZero() {
373 user.CreatedAt = time.Now()
376 var allFields map[string]interface{}
377 buf, err := json.Marshal(user)
379 return arvados.UserList{}, fmt.Errorf("error encoding user record from remote response: %s", err)
381 err = json.Unmarshal(buf, &allFields)
383 return arvados.UserList{}, fmt.Errorf("error transcoding user record from remote response: %s", err)
386 if len(options.Select) > 0 {
387 updates = map[string]interface{}{}
388 for _, k := range options.Select {
389 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
394 for k := range updates {
395 if !userAttrsCachedFromLoginCluster[k] {
400 batchOpts.Updates[user.UUID] = updates
402 if len(batchOpts.Updates) > 0 {
403 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
404 _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
406 return arvados.UserList{}, fmt.Errorf("error updating local user records: %s", err)
411 return conn.generated_UserList(ctx, options)
415 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
416 return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
419 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
420 return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
423 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
424 return conn.chooseBackend(options.UUID).UserUpdateUUID(ctx, options)
427 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
428 return conn.chooseBackend(options.OldUserUUID).UserMerge(ctx, options)
431 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
432 return conn.chooseBackend(options.UUID).UserActivate(ctx, options)
435 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
436 return conn.chooseBackend(options.UUID).UserSetup(ctx, options)
439 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
440 return conn.chooseBackend(options.UUID).UserUnsetup(ctx, options)
443 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
444 return conn.chooseBackend(options.UUID).UserGet(ctx, options)
447 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
448 return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
451 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
452 return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
455 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
456 return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
459 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
460 return conn.local.UserBatchUpdate(ctx, options)
463 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
464 return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
467 type backend interface {
472 type notFoundError struct{}
474 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
475 func (notFoundError) Error() string { return "not found" }
477 func errStatus(err error) int {
478 if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
479 return httpErr.HTTPStatus()
481 return http.StatusInternalServerError