15954: Move PortableDataHash func to sdk/go/arvados.
[arvados.git] / sdk / go / arvados / collection.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package arvados
6
7 import (
8         "bufio"
9         "crypto/md5"
10         "fmt"
11         "regexp"
12         "strings"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/blockdigest"
16 )
17
18 // Collection is an arvados#collection resource.
19 type Collection struct {
20         UUID                      string                 `json:"uuid"`
21         Etag                      string                 `json:"etag"`
22         OwnerUUID                 string                 `json:"owner_uuid"`
23         TrashAt                   *time.Time             `json:"trash_at"`
24         ManifestText              string                 `json:"manifest_text"`
25         UnsignedManifestText      string                 `json:"unsigned_manifest_text"`
26         Name                      string                 `json:"name"`
27         CreatedAt                 time.Time              `json:"created_at"`
28         ModifiedAt                time.Time              `json:"modified_at"`
29         ModifiedByClientUUID      string                 `json:"modified_by_client_uuid"`
30         ModifiedByUserUUID        string                 `json:"modified_by_user_uuid"`
31         PortableDataHash          string                 `json:"portable_data_hash"`
32         ReplicationConfirmed      *int                   `json:"replication_confirmed"`
33         ReplicationConfirmedAt    *time.Time             `json:"replication_confirmed_at"`
34         ReplicationDesired        *int                   `json:"replication_desired"`
35         StorageClassesDesired     []string               `json:"storage_classes_desired"`
36         StorageClassesConfirmed   []string               `json:"storage_classes_confirmed"`
37         StorageClassesConfirmedAt *time.Time             `json:"storage_classes_confirmed_at"`
38         DeleteAt                  *time.Time             `json:"delete_at"`
39         IsTrashed                 bool                   `json:"is_trashed"`
40         Properties                map[string]interface{} `json:"properties"`
41         WritableBy                []string               `json:"writable_by,omitempty"`
42         FileCount                 int                    `json:"file_count"`
43         FileSizeTotal             int64                  `json:"file_size_total"`
44         Version                   int                    `json:"version"`
45         PreserveVersion           bool                   `json:"preserve_version"`
46         CurrentVersionUUID        string                 `json:"current_version_uuid"`
47         Description               string                 `json:"description"`
48 }
49
50 func (c Collection) resourceName() string {
51         return "collection"
52 }
53
54 // SizedDigests returns the hash+size part of each data block
55 // referenced by the collection.
56 func (c *Collection) SizedDigests() ([]SizedDigest, error) {
57         manifestText := c.ManifestText
58         if manifestText == "" {
59                 manifestText = c.UnsignedManifestText
60         }
61         if manifestText == "" && c.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
62                 // TODO: Check more subtle forms of corruption, too
63                 return nil, fmt.Errorf("manifest is missing")
64         }
65         var sds []SizedDigest
66         scanner := bufio.NewScanner(strings.NewReader(manifestText))
67         scanner.Buffer(make([]byte, 1048576), len(manifestText))
68         for scanner.Scan() {
69                 line := scanner.Text()
70                 tokens := strings.Split(line, " ")
71                 if len(tokens) < 3 {
72                         return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
73                 }
74                 for _, token := range tokens[1:] {
75                         if !blockdigest.LocatorPattern.MatchString(token) {
76                                 // FIXME: ensure it's a file token
77                                 break
78                         }
79                         // FIXME: shouldn't assume 32 char hash
80                         if i := strings.IndexRune(token[33:], '+'); i >= 0 {
81                                 token = token[:33+i]
82                         }
83                         sds = append(sds, SizedDigest(token))
84                 }
85         }
86         return sds, scanner.Err()
87 }
88
89 type CollectionList struct {
90         Items          []Collection `json:"items"`
91         ItemsAvailable int          `json:"items_available"`
92         Offset         int          `json:"offset"`
93         Limit          int          `json:"limit"`
94 }
95
96 var (
97         blkRe = regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
98         tokRe = regexp.MustCompile(` ?[^ ]*`)
99 )
100
101 // PortableDataHash computes the portable data hash of the given
102 // manifest.
103 func PortableDataHash(mt string) string {
104         h := md5.New()
105         size := 0
106         _ = tokRe.ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
107                 if m := blkRe.Find(tok); m != nil {
108                         // write hash+size, ignore remaining block hints
109                         tok = m
110                 }
111                 n, err := h.Write(tok)
112                 if err != nil {
113                         panic(err)
114                 }
115                 size += n
116                 return nil
117         })
118         return fmt.Sprintf("%x+%d", h.Sum(nil), size)
119 }