18947: Refactor keep-web as arvados-server command.
[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         "bytes"
9         "crypto/md5"
10         "fmt"
11         "regexp"
12         "strings"
13         "time"
14
15         "git.arvados.org/arvados.git/sdk/go/blockdigest"
16 )
17
18 var (
19         UUIDMatch = regexp.MustCompile(`^[a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}$`).MatchString
20         PDHMatch  = regexp.MustCompile(`^[0-9a-f]{32}\+\d+$`).MatchString
21 )
22
23 // Collection is an arvados#collection resource.
24 type Collection struct {
25         UUID                      string                 `json:"uuid"`
26         Etag                      string                 `json:"etag"`
27         OwnerUUID                 string                 `json:"owner_uuid"`
28         TrashAt                   *time.Time             `json:"trash_at"`
29         ManifestText              string                 `json:"manifest_text"`
30         UnsignedManifestText      string                 `json:"unsigned_manifest_text"`
31         Name                      string                 `json:"name"`
32         CreatedAt                 time.Time              `json:"created_at"`
33         ModifiedAt                time.Time              `json:"modified_at"`
34         ModifiedByClientUUID      string                 `json:"modified_by_client_uuid"`
35         ModifiedByUserUUID        string                 `json:"modified_by_user_uuid"`
36         PortableDataHash          string                 `json:"portable_data_hash"`
37         ReplicationConfirmed      *int                   `json:"replication_confirmed"`
38         ReplicationConfirmedAt    *time.Time             `json:"replication_confirmed_at"`
39         ReplicationDesired        *int                   `json:"replication_desired"`
40         StorageClassesDesired     []string               `json:"storage_classes_desired"`
41         StorageClassesConfirmed   []string               `json:"storage_classes_confirmed"`
42         StorageClassesConfirmedAt *time.Time             `json:"storage_classes_confirmed_at"`
43         DeleteAt                  *time.Time             `json:"delete_at"`
44         IsTrashed                 bool                   `json:"is_trashed"`
45         Properties                map[string]interface{} `json:"properties"`
46         WritableBy                []string               `json:"writable_by,omitempty"`
47         FileCount                 int                    `json:"file_count"`
48         FileSizeTotal             int64                  `json:"file_size_total"`
49         Version                   int                    `json:"version"`
50         PreserveVersion           bool                   `json:"preserve_version"`
51         CurrentVersionUUID        string                 `json:"current_version_uuid"`
52         Description               string                 `json:"description"`
53 }
54
55 func (c Collection) resourceName() string {
56         return "collection"
57 }
58
59 // SizedDigests returns the hash+size part of each data block
60 // referenced by the collection.
61 //
62 // Zero-length blocks are not included.
63 func (c *Collection) SizedDigests() ([]SizedDigest, error) {
64         manifestText := []byte(c.ManifestText)
65         if len(manifestText) == 0 {
66                 manifestText = []byte(c.UnsignedManifestText)
67         }
68         if len(manifestText) == 0 && c.PortableDataHash != "d41d8cd98f00b204e9800998ecf8427e+0" {
69                 // TODO: Check more subtle forms of corruption, too
70                 return nil, fmt.Errorf("manifest is missing")
71         }
72         sds := make([]SizedDigest, 0, len(manifestText)/40)
73         for _, line := range bytes.Split(manifestText, []byte{'\n'}) {
74                 if len(line) == 0 {
75                         continue
76                 }
77                 tokens := bytes.Split(line, []byte{' '})
78                 if len(tokens) < 3 {
79                         return nil, fmt.Errorf("Invalid stream (<3 tokens): %q", line)
80                 }
81                 for _, token := range tokens[1:] {
82                         if !blockdigest.LocatorPattern.Match(token) {
83                                 // FIXME: ensure it's a file token
84                                 break
85                         }
86                         if bytes.HasPrefix(token, []byte("d41d8cd98f00b204e9800998ecf8427e+0")) {
87                                 // Exclude "empty block" placeholder
88                                 continue
89                         }
90                         // FIXME: shouldn't assume 32 char hash
91                         if i := bytes.IndexRune(token[33:], '+'); i >= 0 {
92                                 token = token[:33+i]
93                         }
94                         sds = append(sds, SizedDigest(string(token)))
95                 }
96         }
97         return sds, nil
98 }
99
100 type CollectionList struct {
101         Items          []Collection `json:"items"`
102         ItemsAvailable int          `json:"items_available"`
103         Offset         int          `json:"offset"`
104         Limit          int          `json:"limit"`
105 }
106
107 var (
108         blkRe = regexp.MustCompile(`^ [0-9a-f]{32}\+\d+`)
109         tokRe = regexp.MustCompile(` ?[^ ]*`)
110 )
111
112 // PortableDataHash computes the portable data hash of the given
113 // manifest.
114 func PortableDataHash(mt string) string {
115         h := md5.New()
116         size := 0
117         _ = tokRe.ReplaceAllFunc([]byte(mt), func(tok []byte) []byte {
118                 if m := blkRe.Find(tok); m != nil {
119                         // write hash+size, ignore remaining block hints
120                         tok = m
121                 }
122                 n, err := h.Write(tok)
123                 if err != nil {
124                         panic(err)
125                 }
126                 size += n
127                 return nil
128         })
129         return fmt.Sprintf("%x+%d", h.Sum(nil), size)
130 }
131
132 // CollectionIDFromDNSName returns a UUID or PDH if s begins with a
133 // UUID or URL-encoded PDH; otherwise "".
134 func CollectionIDFromDNSName(s string) string {
135         // Strip domain.
136         if i := strings.IndexRune(s, '.'); i >= 0 {
137                 s = s[:i]
138         }
139         // Names like {uuid}--collections.example.com serve the same
140         // purpose as {uuid}.collections.example.com but can reduce
141         // cost/effort of using [additional] wildcard certificates.
142         if i := strings.Index(s, "--"); i >= 0 {
143                 s = s[:i]
144         }
145         if UUIDMatch(s) {
146                 return s
147         }
148         if pdh := strings.Replace(s, "-", "+", 1); PDHMatch(pdh) {
149                 return pdh
150         }
151         return ""
152 }