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