1 // Deals with parsing Collection responses from API Server.
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"
20 HeapProfileFilename string
23 // Collection representation
24 type Collection struct {
28 BlockDigestToSize map[blockdigest.BlockDigest]int
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
43 // GetCollectionsParams params
44 type GetCollectionsParams struct {
45 Client arvadosclient.ArvadosClient
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"`
59 // SdkCollectionList lists collections from api
60 type SdkCollectionList struct {
61 ItemsAvailable int `json:"items_available"`
62 Items []SdkCollectionInfo `json:"items"`
66 flag.StringVar(&HeapProfileFilename,
69 "File to write the heap profiles to. Leave blank to skip profiling.")
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)
85 defer heapProfile.Close()
87 err = pprof.WriteHeapProfile(heapProfile)
94 // GetCollectionsAndSummarize gets collections from api and summarizes
95 func GetCollectionsAndSummarize(params GetCollectionsParams) (results ReadCollections, err error) {
96 results, err = GetCollections(params)
101 results.Summarize(params.Logger)
103 log.Printf("Uuid to Size used: %v", results.OwnerToCollectionSize)
104 log.Printf("Read and processed %d collections",
105 len(results.UUIDToCollection))
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
110 // if !readCollections.ReadAllCollections {
111 // log.Fatalf("Did not read all collections")
117 // GetCollections gets collections from api
118 func GetCollections(params GetCollectionsParams) (results ReadCollections, err error) {
119 if ¶ms.Client == nil {
120 err = fmt.Errorf("params.Client passed to GetCollections() should " +
121 "contain a valid ArvadosClient, but instead it is nil.")
125 fieldsWanted := []string{"manifest_text",
131 sdkParams := arvadosclient.Dict{
132 "select": fieldsWanted,
133 "order": []string{"modified_at ASC"},
134 "filters": [][]string{[]string{"modified_at", ">=", "1900-01-01T00:00:00Z"}}}
136 if params.BatchSize > 0 {
137 sdkParams["limit"] = params.BatchSize
140 var defaultReplicationLevel int
142 var value interface{}
143 value, err = params.Client.Discovery("defaultCollectionReplication")
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)
157 initialNumberOfCollectionsAvailable, err :=
158 util.NumberItemsAvailable(params.Client, "collections")
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)
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
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
184 // Write the heap profile for examining memory usage
185 err = WriteHeapProfile()
190 // Get next batch of collections.
191 var collections SdkCollectionList
192 err = params.Client.List("collections", sdkParams, &collections)
197 // Process collection and update our date filter.
198 latestModificationDate, maxManifestSize, totalManifestSize, err := ProcessCollections(params.Logger,
200 defaultReplicationLevel,
201 results.UUIDToCollection)
205 sdkParams["filters"].([][]string)[0][2] = latestModificationDate.Format(time.RFC3339)
208 previousTotalCollections = totalCollections
209 totalCollections = len(results.UUIDToCollection)
211 log.Printf("%d collections read, %d new in last batch, "+
212 "%s latest modified date, %.0f %d %d avg,max,total manifest size",
214 totalCollections-previousTotalCollections,
215 sdkParams["filters"].([][]string)[0][2],
216 float32(totalManifestSize)/float32(totalCollections),
217 maxManifestSize, totalManifestSize)
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
230 // Make one final API request to verify that we have processed all collections available up to the latest modification date
231 sdkParams["filters"].([][]string)[0][1] = "<="
232 sdkParams["limit"] = 0
233 err = params.Client.List("collections", sdkParams, &collections)
237 finalNumberOfCollectionsAvailable, err :=
238 util.NumberItemsAvailable(params.Client, "collections")
242 if totalCollections < finalNumberOfCollectionsAvailable {
243 err = fmt.Errorf("API server indicates a total of %d collections "+
244 "available up to %v, but we only retrieved %d. "+
245 "Refusing to continue as this could indicate an "+
246 "otherwise undetected failure.",
247 finalNumberOfCollectionsAvailable,
248 sdkParams["filters"].([][]string)[0][2],
253 // Write the heap profile for examining memory usage
254 err = WriteHeapProfile()
259 // StrCopy returns a newly allocated string.
260 // It is useful to copy slices so that the garbage collector can reuse
261 // the memory of the longer strings they came from.
262 func StrCopy(s string) string {
263 return string([]byte(s))
266 // ProcessCollections read from api server
267 func ProcessCollections(arvLogger *logger.Logger,
268 receivedCollections []SdkCollectionInfo,
269 defaultReplicationLevel int,
270 UUIDToCollection map[string]Collection,
272 latestModificationDate time.Time,
273 maxManifestSize, totalManifestSize uint64,
276 for _, sdkCollection := range receivedCollections {
277 collection := Collection{UUID: StrCopy(sdkCollection.UUID),
278 OwnerUUID: StrCopy(sdkCollection.OwnerUUID),
279 ReplicationLevel: sdkCollection.Redundancy,
280 BlockDigestToSize: make(map[blockdigest.BlockDigest]int)}
282 if sdkCollection.ModifiedAt.IsZero() {
284 "Arvados SDK collection returned with unexpected zero "+
285 "modification date. This probably means that either we failed to "+
286 "parse the modification date or the API server has changed how "+
287 "it returns modification dates: %+v",
292 if sdkCollection.ModifiedAt.After(latestModificationDate) {
293 latestModificationDate = sdkCollection.ModifiedAt
296 if collection.ReplicationLevel == 0 {
297 collection.ReplicationLevel = defaultReplicationLevel
300 manifest := manifest.Manifest{Text: sdkCollection.ManifestText}
301 manifestSize := uint64(len(sdkCollection.ManifestText))
303 if _, alreadySeen := UUIDToCollection[collection.UUID]; !alreadySeen {
304 totalManifestSize += manifestSize
306 if manifestSize > maxManifestSize {
307 maxManifestSize = manifestSize
310 blockChannel := manifest.BlockIterWithDuplicates()
311 for block := range blockChannel {
312 if storedSize, stored := collection.BlockDigestToSize[block.Digest]; stored && storedSize != block.Size {
314 "Collection %s contains multiple sizes (%d and %d) for block %s",
320 collection.BlockDigestToSize[block.Digest] = block.Size
322 if manifest.Err != nil {
327 collection.TotalSize = 0
328 for _, size := range collection.BlockDigestToSize {
329 collection.TotalSize += size
331 UUIDToCollection[collection.UUID] = collection
333 // Clear out all the manifest strings that we don't need anymore.
334 // These hopefully form the bulk of our memory usage.
336 sdkCollection.ManifestText = ""
342 // Summarize the collections read
343 func (readCollections *ReadCollections) Summarize(arvLogger *logger.Logger) {
344 readCollections.OwnerToCollectionSize = make(map[string]int)
345 readCollections.BlockToDesiredReplication = make(map[blockdigest.DigestWithSize]int)
346 numCollections := len(readCollections.UUIDToCollection)
347 readCollections.CollectionUUIDToIndex = make(map[string]int, numCollections)
348 readCollections.CollectionIndexToUUID = make([]string, 0, numCollections)
349 readCollections.BlockToCollectionIndices = make(map[blockdigest.DigestWithSize][]int)
351 for _, coll := range readCollections.UUIDToCollection {
352 collectionIndex := len(readCollections.CollectionIndexToUUID)
353 readCollections.CollectionIndexToUUID =
354 append(readCollections.CollectionIndexToUUID, coll.UUID)
355 readCollections.CollectionUUIDToIndex[coll.UUID] = collectionIndex
357 readCollections.OwnerToCollectionSize[coll.OwnerUUID] =
358 readCollections.OwnerToCollectionSize[coll.OwnerUUID] + coll.TotalSize
360 for block, size := range coll.BlockDigestToSize {
361 locator := blockdigest.DigestWithSize{Digest: block, Size: uint32(size)}
362 readCollections.BlockToCollectionIndices[locator] =
363 append(readCollections.BlockToCollectionIndices[locator],
365 storedReplication := readCollections.BlockToDesiredReplication[locator]
366 if coll.ReplicationLevel > storedReplication {
367 readCollections.BlockToDesiredReplication[locator] =
368 coll.ReplicationLevel
373 if arvLogger != nil {
374 arvLogger.Update(func(p map[string]interface{}, e map[string]interface{}) {
375 collectionInfo := logger.GetOrCreateMap(p, "collection_info")
376 // Since maps are shallow copied, we run a risk of concurrent
377 // updates here. By copying results.OwnerToCollectionSize into
378 // the log, we're assuming that it won't be updated.
379 collectionInfo["owner_to_collection_size"] =
380 readCollections.OwnerToCollectionSize
381 collectionInfo["distinct_blocks_named"] =
382 len(readCollections.BlockToDesiredReplication)