Merge branch '17587-workbench-federated-query'
[arvados.git] / lib / controller / federation / list.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package federation
6
7 import (
8         "context"
9         "fmt"
10         "net/http"
11         "sort"
12         "sync"
13         "sync/atomic"
14
15         "git.arvados.org/arvados.git/sdk/go/arvados"
16         "git.arvados.org/arvados.git/sdk/go/httpserver"
17 )
18
19 //go:generate go run generate.go
20
21 // CollectionList is used as a template to auto-generate List()
22 // methods for other types; see generate.go.
23
24 func (conn *Conn) generated_CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
25         var mtx sync.Mutex
26         var merged arvados.CollectionList
27         var needSort atomic.Value
28         needSort.Store(false)
29         err := conn.splitListRequest(ctx, options, func(ctx context.Context, _ string, backend arvados.API, options arvados.ListOptions) ([]string, error) {
30                 options.ForwardedFor = conn.cluster.ClusterID + "-" + options.ForwardedFor
31                 cl, err := backend.CollectionList(ctx, options)
32                 if err != nil {
33                         return nil, err
34                 }
35                 mtx.Lock()
36                 defer mtx.Unlock()
37                 if len(merged.Items) == 0 {
38                         merged = cl
39                 } else if len(cl.Items) > 0 {
40                         merged.Items = append(merged.Items, cl.Items...)
41                         needSort.Store(true)
42                 }
43                 uuids := make([]string, 0, len(cl.Items))
44                 for _, item := range cl.Items {
45                         uuids = append(uuids, item.UUID)
46                 }
47                 return uuids, nil
48         })
49         if needSort.Load().(bool) {
50                 // Apply the default/implied order, "modified_at desc"
51                 sort.Slice(merged.Items, func(i, j int) bool {
52                         mi, mj := merged.Items[i].ModifiedAt, merged.Items[j].ModifiedAt
53                         return mj.Before(mi)
54                 })
55         }
56         if merged.Items == nil {
57                 // Return empty results as [], not null
58                 // (https://github.com/golang/go/issues/27589 might be
59                 // a better solution in the future)
60                 merged.Items = []arvados.Collection{}
61         }
62         return merged, err
63 }
64
65 // Call fn on one or more local/remote backends if opts indicates a
66 // federation-wide list query, i.e.:
67 //
68 // * There is at least one filter of the form
69 //   ["uuid","in",[a,b,c,...]] or ["uuid","=",a]
70 //
71 // * One or more of the supplied UUIDs (a,b,c,...) has a non-local
72 //   prefix.
73 //
74 // * There are no other filters
75 //
76 // (If opts doesn't indicate a federation-wide list query, fn is just
77 // called once with the local backend.)
78 //
79 // fn is called more than once only if the query meets the following
80 // restrictions:
81 //
82 // * Count=="none"
83 //
84 // * Limit<0
85 //
86 // * len(Order)==0
87 //
88 // * Each filter is either "uuid = ..." or "uuid in [...]".
89 //
90 // * The maximum possible response size (total number of objects that
91 //   could potentially be matched by all of the specified filters)
92 //   exceeds the local cluster's response page size limit.
93 //
94 // If the query involves multiple backends but doesn't meet these
95 // restrictions, an error is returned without calling fn.
96 //
97 // Thus, the caller can assume that either:
98 //
99 // * splitListRequest() returns an error, or
100 //
101 // * fn is called exactly once, or
102 //
103 // * fn is called more than once, with options that satisfy the above
104 //   restrictions.
105 //
106 // Each call to fn indicates a single (local or remote) backend and a
107 // corresponding options argument suitable for sending to that
108 // backend.
109 func (conn *Conn) splitListRequest(ctx context.Context, opts arvados.ListOptions, fn func(context.Context, string, arvados.API, arvados.ListOptions) ([]string, error)) error {
110
111         if opts.BypassFederation || opts.ForwardedFor != "" {
112                 // Client requested no federation.  Pass through.
113                 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
114                 return err
115         }
116
117         cannotSplit := false
118         var matchAllFilters map[string]bool
119         for _, f := range opts.Filters {
120                 matchThisFilter := map[string]bool{}
121                 if f.Attr != "uuid" {
122                         cannotSplit = true
123                         continue
124                 }
125                 if f.Operator == "=" {
126                         if uuid, ok := f.Operand.(string); ok {
127                                 matchThisFilter[uuid] = true
128                         } else {
129                                 return httpErrorf(http.StatusBadRequest, "invalid operand type %T for filter %q", f.Operand, f)
130                         }
131                 } else if f.Operator == "in" {
132                         if operand, ok := f.Operand.([]interface{}); ok {
133                                 // skip any elements that aren't
134                                 // strings (thus can't match a UUID,
135                                 // thus can't affect the response).
136                                 for _, v := range operand {
137                                         if uuid, ok := v.(string); ok {
138                                                 matchThisFilter[uuid] = true
139                                         }
140                                 }
141                         } else if strings, ok := f.Operand.([]string); ok {
142                                 for _, uuid := range strings {
143                                         matchThisFilter[uuid] = true
144                                 }
145                         } else {
146                                 return httpErrorf(http.StatusBadRequest, "invalid operand type %T in filter %q", f.Operand, f)
147                         }
148                 } else {
149                         cannotSplit = true
150                         continue
151                 }
152
153                 if matchAllFilters == nil {
154                         matchAllFilters = matchThisFilter
155                 } else {
156                         // Reduce matchAllFilters to the intersection
157                         // of matchAllFilters ∩ matchThisFilter.
158                         for uuid := range matchAllFilters {
159                                 if !matchThisFilter[uuid] {
160                                         delete(matchAllFilters, uuid)
161                                 }
162                         }
163                 }
164         }
165
166         if matchAllFilters == nil {
167                 // Not filtering by UUID at all; just query the local
168                 // cluster.
169                 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
170                 return err
171         }
172
173         // Collate UUIDs in matchAllFilters by remote cluster ID --
174         // e.g., todoByRemote["aaaaa"]["aaaaa-4zz18-000000000000000"]
175         // will be true -- and count the total number of UUIDs we're
176         // filtering on, so we can compare it to our max page size
177         // limit.
178         nUUIDs := 0
179         todoByRemote := map[string]map[string]bool{}
180         for uuid := range matchAllFilters {
181                 if len(uuid) != 27 {
182                         // Cannot match anything, just drop it
183                 } else {
184                         if todoByRemote[uuid[:5]] == nil {
185                                 todoByRemote[uuid[:5]] = map[string]bool{}
186                         }
187                         todoByRemote[uuid[:5]][uuid] = true
188                         nUUIDs++
189                 }
190         }
191
192         if len(todoByRemote) == 0 {
193                 return nil
194         }
195         if len(todoByRemote) == 1 && todoByRemote[conn.cluster.ClusterID] != nil {
196                 // All UUIDs are local, so proxy a single request. The
197                 // generic case has some limitations (see below) which
198                 // we don't want to impose on local requests.
199                 _, err := fn(ctx, conn.cluster.ClusterID, conn.local, opts)
200                 return err
201         }
202         if cannotSplit {
203                 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query: each filter must be either 'uuid = ...' or 'uuid in [...]'")
204         }
205         if opts.Count != "none" {
206                 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query unless count==\"none\"")
207         }
208         if (opts.Limit >= 0 && opts.Limit < int64(nUUIDs)) || opts.Offset != 0 || len(opts.Order) > 0 {
209                 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query with limit (%d) < nUUIDs (%d), offset (%d) > 0, or order (%v) parameter", opts.Limit, nUUIDs, opts.Offset, opts.Order)
210         }
211         if max := conn.cluster.API.MaxItemsPerResponse; nUUIDs > max {
212                 return httpErrorf(http.StatusBadRequest, "cannot execute federated list query because number of UUIDs (%d) exceeds page size limit %d", nUUIDs, max)
213         }
214
215         ctx, cancel := context.WithCancel(ctx)
216         defer cancel()
217         errs := make(chan error, len(todoByRemote))
218         for clusterID, todo := range todoByRemote {
219                 go func(clusterID string, todo map[string]bool) {
220                         // This goroutine sends exactly one value to
221                         // errs.
222                         batch := make([]string, 0, len(todo))
223                         for uuid := range todo {
224                                 batch = append(batch, uuid)
225                         }
226
227                         var backend arvados.API
228                         if clusterID == conn.cluster.ClusterID {
229                                 backend = conn.local
230                         } else if backend = conn.remotes[clusterID]; backend == nil {
231                                 errs <- httpErrorf(http.StatusNotFound, "cannot execute federated list query: no proxy available for cluster %q", clusterID)
232                                 return
233                         }
234                         remoteOpts := opts
235                         if remoteOpts.Select != nil {
236                                 // We always need to select UUIDs to
237                                 // use the response, even if our
238                                 // caller doesn't.
239                                 remoteOpts.Select = append([]string{"uuid"}, remoteOpts.Select...)
240                         }
241                         for len(todo) > 0 {
242                                 if len(batch) > len(todo) {
243                                         // Reduce batch to just the todo's
244                                         batch = batch[:0]
245                                         for uuid := range todo {
246                                                 batch = append(batch, uuid)
247                                         }
248                                 }
249                                 remoteOpts.Filters = []arvados.Filter{{"uuid", "in", batch}}
250
251                                 done, err := fn(ctx, clusterID, backend, remoteOpts)
252                                 if err != nil {
253                                         errs <- httpErrorf(http.StatusBadGateway, "%s", err.Error())
254                                         return
255                                 }
256                                 progress := false
257                                 for _, uuid := range done {
258                                         if _, ok := todo[uuid]; ok {
259                                                 progress = true
260                                                 delete(todo, uuid)
261                                         }
262                                 }
263                                 if len(done) == 0 {
264                                         // Zero items == no more
265                                         // results exist, no need to
266                                         // get another page.
267                                         break
268                                 } else if !progress {
269                                         errs <- httpErrorf(http.StatusBadGateway, "cannot make progress in federated list query: cluster %q returned %d items but none had the requested UUIDs", clusterID, len(done))
270                                         return
271                                 }
272                         }
273                         errs <- nil
274                 }(clusterID, todo)
275         }
276
277         // Wait for all goroutines to return, then return the first
278         // non-nil error, if any.
279         var firstErr error
280         for range todoByRemote {
281                 if err := <-errs; err != nil && firstErr == nil {
282                         firstErr = err
283                         // Signal to any remaining fn() calls that
284                         // further effort is futile.
285                         cancel()
286                 }
287         }
288         return firstErr
289 }
290
291 func httpErrorf(code int, format string, args ...interface{}) error {
292         return httpserver.ErrorWithStatus(fmt.Errorf(format, args...), code)
293 }