Merge branch '7937-ignored-error' refs #7937
[arvados.git] / services / datamanager / collection / collection.go
1 // Deals with parsing Collection responses from API Server.
2
3 package collection
4
5 import (
6         "flag"
7         "fmt"
8         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
9         "git.curoverse.com/arvados.git/sdk/go/blockdigest"
10         "git.curoverse.com/arvados.git/sdk/go/logger"
11         "git.curoverse.com/arvados.git/sdk/go/manifest"
12         "git.curoverse.com/arvados.git/sdk/go/util"
13         "log"
14         "os"
15         "runtime/pprof"
16         "time"
17 )
18
19 var (
20         HeapProfileFilename string
21 )
22
23 // Collection representation
24 type Collection struct {
25         UUID              string
26         OwnerUUID         string
27         ReplicationLevel  int
28         BlockDigestToSize map[blockdigest.BlockDigest]int
29         TotalSize         int
30 }
31
32 // ReadCollections holds information about collections from API server
33 type ReadCollections struct {
34         ReadAllCollections        bool
35         UUIDToCollection          map[string]Collection
36         OwnerToCollectionSize     map[string]int
37         BlockToDesiredReplication map[blockdigest.DigestWithSize]int
38         CollectionUUIDToIndex     map[string]int
39         CollectionIndexToUUID     []string
40         BlockToCollectionIndices  map[blockdigest.DigestWithSize][]int
41 }
42
43 // GetCollectionsParams params
44 type GetCollectionsParams struct {
45         Client    arvadosclient.ArvadosClient
46         Logger    *logger.Logger
47         BatchSize int
48 }
49
50 // SdkCollectionInfo holds collection info from api
51 type SdkCollectionInfo struct {
52         UUID         string    `json:"uuid"`
53         OwnerUUID    string    `json:"owner_uuid"`
54         Redundancy   int       `json:"redundancy"`
55         ModifiedAt   time.Time `json:"modified_at"`
56         ManifestText string    `json:"manifest_text"`
57 }
58
59 // SdkCollectionList lists collections from api
60 type SdkCollectionList struct {
61         ItemsAvailable int                 `json:"items_available"`
62         Items          []SdkCollectionInfo `json:"items"`
63 }
64
65 func init() {
66         flag.StringVar(&HeapProfileFilename,
67                 "heap-profile",
68                 "",
69                 "File to write the heap profiles to. Leave blank to skip profiling.")
70 }
71
72 // WriteHeapProfile writes the heap profile to a file for later review.
73 // Since a file is expected to only contain a single heap profile this
74 // function overwrites the previously written profile, so it is safe
75 // to call multiple times in a single run.
76 // Otherwise we would see cumulative numbers as explained here:
77 // https://groups.google.com/d/msg/golang-nuts/ZyHciRglQYc/2nh4Ndu2fZcJ
78 func WriteHeapProfile() error {
79         if HeapProfileFilename != "" {
80                 heapProfile, err := os.Create(HeapProfileFilename)
81                 if err != nil {
82                         return err
83                 }
84
85                 defer heapProfile.Close()
86
87                 err = pprof.WriteHeapProfile(heapProfile)
88                 return err
89         }
90
91         return nil
92 }
93
94 // GetCollectionsAndSummarize gets collections from api and summarizes
95 func GetCollectionsAndSummarize(params GetCollectionsParams) (results ReadCollections, err error) {
96         results, err = GetCollections(params)
97         if err != nil {
98                 return
99         }
100
101         results.Summarize(params.Logger)
102
103         log.Printf("Uuid to Size used: %v", results.OwnerToCollectionSize)
104         log.Printf("Read and processed %d collections",
105                 len(results.UUIDToCollection))
106
107         // TODO(misha): Add a "readonly" flag. If we're in readonly mode,
108         // lots of behaviors can become warnings (and obviously we can't
109         // write anything).
110         // if !readCollections.ReadAllCollections {
111         //      log.Fatalf("Did not read all collections")
112         // }
113
114         return
115 }
116
117 // GetCollections gets collections from api
118 func GetCollections(params GetCollectionsParams) (results ReadCollections, err error) {
119         if &params.Client == nil {
120                 err = fmt.Errorf("params.Client passed to GetCollections() should " +
121                         "contain a valid ArvadosClient, but instead it is nil.")
122                 return
123         }
124
125         fieldsWanted := []string{"manifest_text",
126                 "owner_uuid",
127                 "uuid",
128                 "redundancy",
129                 "modified_at"}
130
131         sdkParams := arvadosclient.Dict{
132                 "select":  fieldsWanted,
133                 "order":   []string{"modified_at ASC"},
134                 "filters": [][]string{[]string{"modified_at", ">=", "1900-01-01T00:00:00Z"}}}
135
136         if params.BatchSize > 0 {
137                 sdkParams["limit"] = params.BatchSize
138         }
139
140         var defaultReplicationLevel int
141         {
142                 var value interface{}
143                 value, err = params.Client.Discovery("defaultCollectionReplication")
144                 if err != nil {
145                         return
146                 }
147
148                 defaultReplicationLevel = int(value.(float64))
149                 if defaultReplicationLevel <= 0 {
150                         err = fmt.Errorf("Default collection replication returned by arvados SDK "+
151                                 "should be a positive integer but instead it was %d.",
152                                 defaultReplicationLevel)
153                         return
154                 }
155         }
156
157         initialNumberOfCollectionsAvailable, err :=
158                 util.NumberItemsAvailable(params.Client, "collections")
159         if err != nil {
160                 return
161         }
162         // Include a 1% margin for collections added while we're reading so
163         // that we don't have to grow the map in most cases.
164         maxExpectedCollections := int(
165                 float64(initialNumberOfCollectionsAvailable) * 1.01)
166         results.UUIDToCollection = make(map[string]Collection, maxExpectedCollections)
167
168         if params.Logger != nil {
169                 params.Logger.Update(func(p map[string]interface{}, e map[string]interface{}) {
170                         collectionInfo := logger.GetOrCreateMap(p, "collection_info")
171                         collectionInfo["num_collections_at_start"] = initialNumberOfCollectionsAvailable
172                         collectionInfo["batch_size"] = params.BatchSize
173                         collectionInfo["default_replication_level"] = defaultReplicationLevel
174                 })
175         }
176
177         // These values are just for getting the loop to run the first time,
178         // afterwards they'll be set to real values.
179         previousTotalCollections := -1
180         totalCollections := 0
181         for totalCollections > previousTotalCollections {
182                 // We're still finding new collections
183
184                 // Write the heap profile for examining memory usage
185                 err = WriteHeapProfile()
186                 if err != nil {
187                         return
188                 }
189
190                 // Get next batch of collections.
191                 var collections SdkCollectionList
192                 err = params.Client.List("collections", sdkParams, &collections)
193                 if err != nil {
194                         return
195                 }
196
197                 // Process collection and update our date filter.
198                 latestModificationDate, maxManifestSize, totalManifestSize, err := ProcessCollections(params.Logger,
199                         collections.Items,
200                         defaultReplicationLevel,
201                         results.UUIDToCollection)
202                 if err != nil {
203                         return results, err
204                 }
205                 sdkParams["filters"].([][]string)[0][2] = latestModificationDate.Format(time.RFC3339)
206
207                 // update counts
208                 previousTotalCollections = totalCollections
209                 totalCollections = len(results.UUIDToCollection)
210
211                 log.Printf("%d collections read, %d new in last batch, "+
212                         "%s latest modified date, %.0f %d %d avg,max,total manifest size",
213                         totalCollections,
214                         totalCollections-previousTotalCollections,
215                         sdkParams["filters"].([][]string)[0][2],
216                         float32(totalManifestSize)/float32(totalCollections),
217                         maxManifestSize, totalManifestSize)
218
219                 if params.Logger != nil {
220                         params.Logger.Update(func(p map[string]interface{}, e map[string]interface{}) {
221                                 collectionInfo := logger.GetOrCreateMap(p, "collection_info")
222                                 collectionInfo["collections_read"] = totalCollections
223                                 collectionInfo["latest_modified_date_seen"] = sdkParams["filters"].([][]string)[0][2]
224                                 collectionInfo["total_manifest_size"] = totalManifestSize
225                                 collectionInfo["max_manifest_size"] = maxManifestSize
226                         })
227                 }
228         }
229
230         // Write the heap profile for examining memory usage
231         err = WriteHeapProfile()
232
233         return
234 }
235
236 // StrCopy returns a newly allocated string.
237 // It is useful to copy slices so that the garbage collector can reuse
238 // the memory of the longer strings they came from.
239 func StrCopy(s string) string {
240         return string([]byte(s))
241 }
242
243 // ProcessCollections read from api server
244 func ProcessCollections(arvLogger *logger.Logger,
245         receivedCollections []SdkCollectionInfo,
246         defaultReplicationLevel int,
247         UUIDToCollection map[string]Collection,
248 ) (
249         latestModificationDate time.Time,
250         maxManifestSize, totalManifestSize uint64,
251         err error,
252 ) {
253         for _, sdkCollection := range receivedCollections {
254                 collection := Collection{UUID: StrCopy(sdkCollection.UUID),
255                         OwnerUUID:         StrCopy(sdkCollection.OwnerUUID),
256                         ReplicationLevel:  sdkCollection.Redundancy,
257                         BlockDigestToSize: make(map[blockdigest.BlockDigest]int)}
258
259                 if sdkCollection.ModifiedAt.IsZero() {
260                         err = fmt.Errorf(
261                                 "Arvados SDK collection returned with unexpected zero "+
262                                         "modification date. This probably means that either we failed to "+
263                                         "parse the modification date or the API server has changed how "+
264                                         "it returns modification dates: %+v",
265                                 collection)
266                         return
267                 }
268
269                 if sdkCollection.ModifiedAt.After(latestModificationDate) {
270                         latestModificationDate = sdkCollection.ModifiedAt
271                 }
272
273                 if collection.ReplicationLevel == 0 {
274                         collection.ReplicationLevel = defaultReplicationLevel
275                 }
276
277                 manifest := manifest.Manifest{Text: sdkCollection.ManifestText}
278                 manifestSize := uint64(len(sdkCollection.ManifestText))
279
280                 if _, alreadySeen := UUIDToCollection[collection.UUID]; !alreadySeen {
281                         totalManifestSize += manifestSize
282                 }
283                 if manifestSize > maxManifestSize {
284                         maxManifestSize = manifestSize
285                 }
286
287                 blockChannel := manifest.BlockIterWithDuplicates()
288                 for block := range blockChannel {
289                         if storedSize, stored := collection.BlockDigestToSize[block.Digest]; stored && storedSize != block.Size {
290                                 log.Printf(
291                                         "Collection %s contains multiple sizes (%d and %d) for block %s",
292                                         collection.UUID,
293                                         storedSize,
294                                         block.Size,
295                                         block.Digest)
296                         }
297                         collection.BlockDigestToSize[block.Digest] = block.Size
298                 }
299                 if manifest.Err != nil {
300                         err = manifest.Err
301                         return
302                 }
303
304                 collection.TotalSize = 0
305                 for _, size := range collection.BlockDigestToSize {
306                         collection.TotalSize += size
307                 }
308                 UUIDToCollection[collection.UUID] = collection
309
310                 // Clear out all the manifest strings that we don't need anymore.
311                 // These hopefully form the bulk of our memory usage.
312                 manifest.Text = ""
313                 sdkCollection.ManifestText = ""
314         }
315
316         return
317 }
318
319 // Summarize the collections read
320 func (readCollections *ReadCollections) Summarize(arvLogger *logger.Logger) {
321         readCollections.OwnerToCollectionSize = make(map[string]int)
322         readCollections.BlockToDesiredReplication = make(map[blockdigest.DigestWithSize]int)
323         numCollections := len(readCollections.UUIDToCollection)
324         readCollections.CollectionUUIDToIndex = make(map[string]int, numCollections)
325         readCollections.CollectionIndexToUUID = make([]string, 0, numCollections)
326         readCollections.BlockToCollectionIndices = make(map[blockdigest.DigestWithSize][]int)
327
328         for _, coll := range readCollections.UUIDToCollection {
329                 collectionIndex := len(readCollections.CollectionIndexToUUID)
330                 readCollections.CollectionIndexToUUID =
331                         append(readCollections.CollectionIndexToUUID, coll.UUID)
332                 readCollections.CollectionUUIDToIndex[coll.UUID] = collectionIndex
333
334                 readCollections.OwnerToCollectionSize[coll.OwnerUUID] =
335                         readCollections.OwnerToCollectionSize[coll.OwnerUUID] + coll.TotalSize
336
337                 for block, size := range coll.BlockDigestToSize {
338                         locator := blockdigest.DigestWithSize{Digest: block, Size: uint32(size)}
339                         readCollections.BlockToCollectionIndices[locator] =
340                                 append(readCollections.BlockToCollectionIndices[locator],
341                                         collectionIndex)
342                         storedReplication := readCollections.BlockToDesiredReplication[locator]
343                         if coll.ReplicationLevel > storedReplication {
344                                 readCollections.BlockToDesiredReplication[locator] =
345                                         coll.ReplicationLevel
346                         }
347                 }
348         }
349
350         if arvLogger != nil {
351                 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
352                         collectionInfo := logger.GetOrCreateMap(p, "collection_info")
353                         // Since maps are shallow copied, we run a risk of concurrent
354                         // updates here. By copying results.OwnerToCollectionSize into
355                         // the log, we're assuming that it won't be updated.
356                         collectionInfo["owner_to_collection_size"] =
357                                 readCollections.OwnerToCollectionSize
358                         collectionInfo["distinct_blocks_named"] =
359                                 len(readCollections.BlockToDesiredReplication)
360                 })
361         }
362
363         return
364 }