1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/config"
21 "git.arvados.org/arvados.git/lib/controller/localdb"
22 "git.arvados.org/arvados.git/lib/controller/rpc"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/auth"
25 "git.arvados.org/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 conn := rpc.NewConn(id, &url.URL{Scheme: remote.Scheme, Host: remote.Host}, remote.Insecure, saltedTokenProvider(local, id))
42 // Older versions of controller rely on the Via header
44 conn.SendHeader = http.Header{"Via": {"HTTP/1.1 arvados-controller"}}
55 // Return a new rpc.TokenProvider that takes the client-provided
56 // tokens from an incoming request context, determines whether they
57 // should (and can) be salted for the given remoteID, and returns the
59 func saltedTokenProvider(local backend, remoteID string) rpc.TokenProvider {
60 return func(ctx context.Context) ([]string, error) {
62 incoming, ok := auth.FromContext(ctx)
64 return nil, errors.New("no token provided")
66 for _, token := range incoming.Tokens {
67 salted, err := auth.SaltToken(token, remoteID)
70 tokens = append(tokens, salted)
72 tokens = append(tokens, token)
73 case auth.ErrObsoleteToken:
74 ctx := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{token}})
75 aca, err := local.APIClientAuthorizationCurrent(ctx, arvados.GetOptions{})
76 if errStatus(err) == http.StatusUnauthorized {
77 // pass through unmodified
78 tokens = append(tokens, token)
80 } else if err != nil {
83 salted, err := auth.SaltToken(aca.TokenV2(), remoteID)
87 tokens = append(tokens, salted)
96 // Return suitable backend for a query about the given cluster ID
97 // ("aaaaa") or object UUID ("aaaaa-dz642-abcdefghijklmno").
98 func (conn *Conn) chooseBackend(id string) backend {
101 } else if len(id) != 5 {
105 if id == conn.cluster.ClusterID {
107 } else if be, ok := conn.remotes[id]; ok {
110 // TODO: return an "always error" backend?
115 // Call fn with the local backend; then, if fn returned 404, call fn
116 // on the available remote backends (possibly concurrently) until one
119 // The second argument to fn is the cluster ID of the remote backend,
120 // or "" for the local backend.
122 // A non-nil error means all backends failed.
123 func (conn *Conn) tryLocalThenRemotes(ctx context.Context, forwardedFor string, fn func(context.Context, string, backend) error) error {
124 if err := fn(ctx, "", conn.local); err == nil || errStatus(err) != http.StatusNotFound || forwardedFor != "" {
125 // Note: forwardedFor != "" means this request came
126 // from a remote cluster, so we don't take a second
127 // hop. This avoids cycles, redundant calls to a
128 // mutually reachable remote, and use of double-salted
133 ctx, cancel := context.WithCancel(ctx)
135 errchan := make(chan error, len(conn.remotes))
136 for remoteID, be := range conn.remotes {
137 remoteID, be := remoteID, be
139 errchan <- fn(ctx, remoteID, be)
144 for i := 0; i < cap(errchan); i++ {
149 all404 = all404 && errStatus(err) == http.StatusNotFound
150 errs = append(errs, err)
153 return notFoundError{}
155 return httpErrorf(http.StatusBadGateway, "errors: %v", errs)
158 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
159 return conn.chooseBackend(options.ClusterID).CollectionCreate(ctx, options)
162 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
163 return conn.chooseBackend(options.UUID).CollectionUpdate(ctx, options)
166 func rewriteManifest(mt, remoteID string) string {
167 return regexp.MustCompile(` [0-9a-f]{32}\+[^ ]*`).ReplaceAllStringFunc(mt, func(tok string) string {
168 return strings.Replace(tok, "+A", "+R"+remoteID+"-", -1)
172 // this could be in sdk/go/arvados
173 func portableDataHash(mt string) string {
175 blkRe := regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
177 _ = regexp.MustCompile(` ?[^ ]*`).ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
178 if m := blkRe.Find(tok); m != nil {
179 // write hash+size, ignore remaining block hints
182 n, err := h.Write(tok)
189 return fmt.Sprintf("%x+%d", h.Sum(nil), size)
192 func (conn *Conn) ConfigGet(ctx context.Context) (json.RawMessage, error) {
194 err := config.ExportJSON(&buf, conn.cluster)
195 return json.RawMessage(buf.Bytes()), err
198 func (conn *Conn) Login(ctx context.Context, options arvados.LoginOptions) (arvados.LoginResponse, error) {
199 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
200 // defer entire login procedure to designated cluster
201 remote, ok := conn.remotes[id]
203 return arvados.LoginResponse{}, fmt.Errorf("configuration problem: designated login cluster %q is not defined", id)
205 baseURL := remote.BaseURL()
206 target, err := baseURL.Parse(arvados.EndpointLogin.Path)
208 return arvados.LoginResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
210 params := url.Values{
211 "return_to": []string{options.ReturnTo},
213 if options.Remote != "" {
214 params.Set("remote", options.Remote)
216 target.RawQuery = params.Encode()
217 return arvados.LoginResponse{
218 RedirectLocation: target.String(),
221 return conn.local.Login(ctx, options)
225 func (conn *Conn) Logout(ctx context.Context, options arvados.LogoutOptions) (arvados.LogoutResponse, error) {
226 // If the logout request comes with an API token from a known
227 // remote cluster, redirect to that cluster's logout handler
228 // so it has an opportunity to clear sessions, expire tokens,
229 // etc. Otherwise use the local endpoint.
230 reqauth, ok := auth.FromContext(ctx)
231 if !ok || len(reqauth.Tokens) == 0 || len(reqauth.Tokens[0]) < 8 || !strings.HasPrefix(reqauth.Tokens[0], "v2/") {
232 return conn.local.Logout(ctx, options)
234 id := reqauth.Tokens[0][3:8]
235 if id == conn.cluster.ClusterID {
236 return conn.local.Logout(ctx, options)
238 remote, ok := conn.remotes[id]
240 return conn.local.Logout(ctx, options)
242 baseURL := remote.BaseURL()
243 target, err := baseURL.Parse(arvados.EndpointLogout.Path)
245 return arvados.LogoutResponse{}, fmt.Errorf("internal error getting redirect target: %s", err)
247 target.RawQuery = url.Values{"return_to": {options.ReturnTo}}.Encode()
248 return arvados.LogoutResponse{RedirectLocation: target.String()}, nil
251 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
252 if len(options.UUID) == 27 {
253 // UUID is really a UUID
254 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
255 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
256 c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
261 first := make(chan arvados.Collection, 1)
262 err := conn.tryLocalThenRemotes(ctx, options.ForwardedFor, func(ctx context.Context, remoteID string, be backend) error {
263 remoteOpts := options
264 remoteOpts.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
265 c, err := be.CollectionGet(ctx, remoteOpts)
269 // options.UUID is either hash+size or
270 // hash+size+hints; only hash+size need to
271 // match the computed PDH.
272 if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
273 err = httpErrorf(http.StatusBadGateway, "bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
274 ctxlog.FromContext(ctx).Warn(err)
278 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
284 // lost race, return value doesn't matter
289 return arvados.Collection{}, err
295 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
296 return conn.generated_CollectionList(ctx, options)
299 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
300 return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
303 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
304 return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
307 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
308 return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
311 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
312 return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
315 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
316 return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
319 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
320 return conn.generated_ContainerList(ctx, options)
323 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
324 return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
327 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
328 return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
331 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
332 return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
335 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
336 return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
339 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
340 return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
343 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
344 return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
347 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
348 return conn.generated_SpecimenList(ctx, options)
351 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
352 return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
355 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
356 return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
359 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
360 return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
363 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
364 return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
367 var userAttrsCachedFromLoginCluster = map[string]bool{
380 "identity_url": false,
382 "modified_by_client_uuid": false,
383 "modified_by_user_uuid": false,
386 "writable_by": false,
389 func (conn *Conn) UserList(ctx context.Context, options arvados.ListOptions) (arvados.UserList, error) {
390 logger := ctxlog.FromContext(ctx)
391 if id := conn.cluster.Login.LoginCluster; id != "" && id != conn.cluster.ClusterID {
392 resp, err := conn.chooseBackend(id).UserList(ctx, options)
396 batchOpts := arvados.UserBatchUpdateOptions{Updates: map[string]map[string]interface{}{}}
397 for _, user := range resp.Items {
398 if !strings.HasPrefix(user.UUID, id) {
401 logger.Debugf("cache user info for uuid %q", user.UUID)
403 // If the remote cluster has null timestamps
404 // (e.g., test server with incomplete
405 // fixtures) use dummy timestamps (instead of
406 // the zero time, which causes a Rails API
407 // error "year too big to marshal: 1 UTC").
408 if user.ModifiedAt.IsZero() {
409 user.ModifiedAt = time.Now()
411 if user.CreatedAt.IsZero() {
412 user.CreatedAt = time.Now()
415 var allFields map[string]interface{}
416 buf, err := json.Marshal(user)
418 return arvados.UserList{}, fmt.Errorf("error encoding user record from remote response: %s", err)
420 err = json.Unmarshal(buf, &allFields)
422 return arvados.UserList{}, fmt.Errorf("error transcoding user record from remote response: %s", err)
425 if len(options.Select) > 0 {
426 updates = map[string]interface{}{}
427 for _, k := range options.Select {
428 if v, ok := allFields[k]; ok && userAttrsCachedFromLoginCluster[k] {
433 for k := range updates {
434 if !userAttrsCachedFromLoginCluster[k] {
439 batchOpts.Updates[user.UUID] = updates
441 if len(batchOpts.Updates) > 0 {
442 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{conn.cluster.SystemRootToken}})
443 _, err = conn.local.UserBatchUpdate(ctxRoot, batchOpts)
445 return arvados.UserList{}, fmt.Errorf("error updating local user records: %s", err)
450 return conn.generated_UserList(ctx, options)
454 func (conn *Conn) UserCreate(ctx context.Context, options arvados.CreateOptions) (arvados.User, error) {
455 return conn.chooseBackend(options.ClusterID).UserCreate(ctx, options)
458 func (conn *Conn) UserUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.User, error) {
459 return conn.chooseBackend(options.UUID).UserUpdate(ctx, options)
462 func (conn *Conn) UserUpdateUUID(ctx context.Context, options arvados.UpdateUUIDOptions) (arvados.User, error) {
463 return conn.chooseBackend(options.UUID).UserUpdateUUID(ctx, options)
466 func (conn *Conn) UserMerge(ctx context.Context, options arvados.UserMergeOptions) (arvados.User, error) {
467 return conn.chooseBackend(options.OldUserUUID).UserMerge(ctx, options)
470 func (conn *Conn) UserActivate(ctx context.Context, options arvados.UserActivateOptions) (arvados.User, error) {
471 return conn.chooseBackend(options.UUID).UserActivate(ctx, options)
474 func (conn *Conn) UserSetup(ctx context.Context, options arvados.UserSetupOptions) (map[string]interface{}, error) {
475 return conn.chooseBackend(options.UUID).UserSetup(ctx, options)
478 func (conn *Conn) UserUnsetup(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
479 return conn.chooseBackend(options.UUID).UserUnsetup(ctx, options)
482 func (conn *Conn) UserGet(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
483 return conn.chooseBackend(options.UUID).UserGet(ctx, options)
486 func (conn *Conn) UserGetCurrent(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
487 return conn.chooseBackend(options.UUID).UserGetCurrent(ctx, options)
490 func (conn *Conn) UserGetSystem(ctx context.Context, options arvados.GetOptions) (arvados.User, error) {
491 return conn.chooseBackend(options.UUID).UserGetSystem(ctx, options)
494 func (conn *Conn) UserDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.User, error) {
495 return conn.chooseBackend(options.UUID).UserDelete(ctx, options)
498 func (conn *Conn) UserBatchUpdate(ctx context.Context, options arvados.UserBatchUpdateOptions) (arvados.UserList, error) {
499 return conn.local.UserBatchUpdate(ctx, options)
502 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
503 return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
506 type backend interface {
511 type notFoundError struct{}
513 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
514 func (notFoundError) Error() string { return "not found" }
516 func errStatus(err error) int {
517 if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
518 return httpErr.HTTPStatus()
520 return http.StatusInternalServerError