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/railsproxy"
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 := railsproxy.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 // FIXME: choose appropriate HTTP status
146 return fmt.Errorf("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) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
190 if len(options.UUID) == 27 {
191 // UUID is really a UUID
192 c, err := conn.chooseBackend(options.UUID).CollectionGet(ctx, options)
193 if err == nil && options.UUID[:5] != conn.cluster.ClusterID {
194 c.ManifestText = rewriteManifest(c.ManifestText, options.UUID[:5])
199 first := make(chan arvados.Collection, 1)
200 err := conn.tryLocalThenRemotes(ctx, func(ctx context.Context, remoteID string, be backend) error {
201 c, err := be.CollectionGet(ctx, options)
205 // options.UUID is either hash+size or
206 // hash+size+hints; only hash+size need to
207 // match the computed PDH.
208 if pdh := portableDataHash(c.ManifestText); pdh != options.UUID && !strings.HasPrefix(options.UUID, pdh+"+") {
209 ctxlog.FromContext(ctx).Warnf("bad portable data hash %q received from remote %q (expected %q)", pdh, remoteID, options.UUID)
210 return notFoundError{}
213 c.ManifestText = rewriteManifest(c.ManifestText, remoteID)
219 // lost race, return value doesn't matter
224 return arvados.Collection{}, err
230 func (conn *Conn) CollectionProvenance(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
231 return conn.chooseBackend(options.UUID).CollectionProvenance(ctx, options)
234 func (conn *Conn) CollectionUsedBy(ctx context.Context, options arvados.GetOptions) (map[string]interface{}, error) {
235 return conn.chooseBackend(options.UUID).CollectionUsedBy(ctx, options)
238 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
239 return conn.chooseBackend(options.UUID).CollectionDelete(ctx, options)
242 func (conn *Conn) CollectionTrash(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
243 return conn.chooseBackend(options.UUID).CollectionTrash(ctx, options)
246 func (conn *Conn) CollectionUntrash(ctx context.Context, options arvados.UntrashOptions) (arvados.Collection, error) {
247 return conn.chooseBackend(options.UUID).CollectionUntrash(ctx, options)
250 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
251 return conn.chooseBackend(options.ClusterID).ContainerCreate(ctx, options)
254 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
255 return conn.chooseBackend(options.UUID).ContainerUpdate(ctx, options)
258 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
259 return conn.chooseBackend(options.UUID).ContainerGet(ctx, options)
262 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
263 return conn.chooseBackend(options.UUID).ContainerDelete(ctx, options)
266 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
267 return conn.chooseBackend(options.UUID).ContainerLock(ctx, options)
270 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
271 return conn.chooseBackend(options.UUID).ContainerUnlock(ctx, options)
274 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
275 return conn.chooseBackend(options.ClusterID).SpecimenCreate(ctx, options)
278 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
279 return conn.chooseBackend(options.UUID).SpecimenUpdate(ctx, options)
282 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
283 return conn.chooseBackend(options.UUID).SpecimenGet(ctx, options)
286 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
287 return conn.chooseBackend(options.UUID).SpecimenDelete(ctx, options)
290 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
291 return conn.chooseBackend(options.UUID).APIClientAuthorizationCurrent(ctx, options)
294 type backend interface{ arvados.API }
296 type notFoundError struct{}
298 func (notFoundError) HTTPStatus() int { return http.StatusNotFound }
299 func (notFoundError) Error() string { return "not found" }
301 func errStatus(err error) int {
302 if httpErr, ok := err.(interface{ HTTPStatus() int }); ok {
303 return httpErr.HTTPStatus()
305 return http.StatusInternalServerError