Merge branch '19954-permission-dedup-doc'
[arvados.git] / sdk / go / arvados / fs_site.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         "net/http"
9         "os"
10         "strings"
11         "sync"
12         "time"
13 )
14
15 type CustomFileSystem interface {
16         FileSystem
17         MountByID(mount string)
18         MountProject(mount, uuid string)
19         MountUsers(mount string)
20         ForwardSlashNameSubstitution(string)
21 }
22
23 type customFileSystem struct {
24         fileSystem
25         root *vdirnode
26         thr  *throttle
27
28         staleThreshold time.Time
29         staleLock      sync.Mutex
30
31         forwardSlashNameSubstitution string
32
33         byID     map[string]inode
34         byIDLock sync.Mutex
35         byIDRoot *treenode
36 }
37
38 func (c *Client) CustomFileSystem(kc keepClient) CustomFileSystem {
39         root := &vdirnode{}
40         fs := &customFileSystem{
41                 root: root,
42                 fileSystem: fileSystem{
43                         fsBackend: keepBackend{apiClient: c, keepClient: kc},
44                         root:      root,
45                         thr:       newThrottle(concurrentWriters),
46                 },
47         }
48         root.treenode = treenode{
49                 fs:     fs,
50                 parent: root,
51                 fileinfo: fileinfo{
52                         name:    "/",
53                         mode:    os.ModeDir | 0755,
54                         modTime: time.Now(),
55                 },
56                 inodes: make(map[string]inode),
57         }
58         fs.byID = map[string]inode{}
59         fs.byIDRoot = &treenode{
60                 fs:     fs,
61                 parent: root,
62                 inodes: make(map[string]inode),
63                 fileinfo: fileinfo{
64                         name:    "_internal_by_id",
65                         modTime: time.Now(),
66                         mode:    0755 | os.ModeDir,
67                 },
68         }
69         return fs
70 }
71
72 func (fs *customFileSystem) MountByID(mount string) {
73         fs.root.treenode.Lock()
74         defer fs.root.treenode.Unlock()
75         fs.root.treenode.Child(mount, func(inode) (inode, error) {
76                 return &vdirnode{
77                         treenode: treenode{
78                                 fs:     fs,
79                                 parent: fs.root,
80                                 inodes: make(map[string]inode),
81                                 fileinfo: fileinfo{
82                                         name:    mount,
83                                         modTime: time.Now(),
84                                         mode:    0755 | os.ModeDir,
85                                 },
86                         },
87                         create: fs.newCollectionOrProjectHardlink,
88                 }, nil
89         })
90 }
91
92 func (fs *customFileSystem) MountProject(mount, uuid string) {
93         fs.root.treenode.Lock()
94         defer fs.root.treenode.Unlock()
95         fs.root.treenode.Child(mount, func(inode) (inode, error) {
96                 return fs.newProjectDir(fs.root, mount, uuid, nil), nil
97         })
98 }
99
100 func (fs *customFileSystem) MountUsers(mount string) {
101         fs.root.treenode.Lock()
102         defer fs.root.treenode.Unlock()
103         fs.root.treenode.Child(mount, func(inode) (inode, error) {
104                 return &lookupnode{
105                         stale:   fs.Stale,
106                         loadOne: fs.usersLoadOne,
107                         loadAll: fs.usersLoadAll,
108                         treenode: treenode{
109                                 fs:     fs,
110                                 parent: fs.root,
111                                 inodes: make(map[string]inode),
112                                 fileinfo: fileinfo{
113                                         name:    mount,
114                                         modTime: time.Now(),
115                                         mode:    0755 | os.ModeDir,
116                                 },
117                         },
118                 }, nil
119         })
120 }
121
122 func (fs *customFileSystem) ForwardSlashNameSubstitution(repl string) {
123         fs.forwardSlashNameSubstitution = repl
124 }
125
126 // SiteFileSystem returns a FileSystem that maps collections and other
127 // Arvados objects onto a filesystem layout.
128 //
129 // This is experimental: the filesystem layout is not stable, and
130 // there are significant known bugs and shortcomings. For example,
131 // writes are not persisted until Sync() is called.
132 func (c *Client) SiteFileSystem(kc keepClient) CustomFileSystem {
133         fs := c.CustomFileSystem(kc)
134         fs.MountByID("by_id")
135         fs.MountUsers("users")
136         return fs
137 }
138
139 func (fs *customFileSystem) Sync() error {
140         return fs.byIDRoot.Sync()
141 }
142
143 // Stale returns true if information obtained at time t should be
144 // considered stale.
145 func (fs *customFileSystem) Stale(t time.Time) bool {
146         fs.staleLock.Lock()
147         defer fs.staleLock.Unlock()
148         return !fs.staleThreshold.Before(t)
149 }
150
151 func (fs *customFileSystem) newNode(name string, perm os.FileMode, modTime time.Time) (node inode, err error) {
152         return nil, ErrInvalidOperation
153 }
154
155 func (fs *customFileSystem) newCollectionOrProjectHardlink(parent inode, id string) (inode, error) {
156         if strings.Contains(id, "-4zz18-") || pdhRegexp.MatchString(id) {
157                 node, err := fs.collectionSingleton(id)
158                 if os.IsNotExist(err) {
159                         return nil, nil
160                 } else if err != nil {
161                         return nil, err
162                 }
163                 return &hardlink{inode: node, parent: parent, name: id}, nil
164         } else if strings.Contains(id, "-j7d0g-") || strings.Contains(id, "-tpzed-") {
165                 fs.byIDLock.Lock()
166                 node := fs.byID[id]
167                 fs.byIDLock.Unlock()
168                 if node == nil {
169                         // Look up the project synchronously before
170                         // calling projectSingleton (otherwise we
171                         // wouldn't detect a nonexistent project until
172                         // it's too late to return ErrNotExist).
173                         proj, err := fs.getProject(id)
174                         if os.IsNotExist(err) {
175                                 return nil, nil
176                         } else if err != nil {
177                                 return nil, err
178                         }
179                         node = fs.projectSingleton(id, proj)
180                 }
181                 return &hardlink{inode: node, parent: parent, name: id}, nil
182         } else {
183                 return nil, nil
184         }
185 }
186
187 func (fs *customFileSystem) projectSingleton(uuid string, proj *Group) inode {
188         fs.byIDLock.Lock()
189         defer fs.byIDLock.Unlock()
190         if n := fs.byID[uuid]; n != nil {
191                 return n
192         }
193         name := uuid
194         if name == "" {
195                 // special case uuid=="" implements the "home project"
196                 // (owner_uuid == current user uuid)
197                 name = "home"
198         }
199         var projLoading sync.Mutex
200         n := &lookupnode{
201                 stale:   fs.Stale,
202                 loadOne: func(parent inode, name string) (inode, error) { return fs.projectsLoadOne(parent, uuid, name) },
203                 loadAll: func(parent inode) ([]inode, error) { return fs.projectsLoadAll(parent, uuid) },
204                 treenode: treenode{
205                         fs:     fs,
206                         parent: fs.byIDRoot,
207                         inodes: make(map[string]inode),
208                         fileinfo: fileinfo{
209                                 name:    name,
210                                 modTime: time.Now(),
211                                 mode:    0755 | os.ModeDir,
212                                 sys: func() interface{} {
213                                         projLoading.Lock()
214                                         defer projLoading.Unlock()
215                                         if proj != nil {
216                                                 return proj
217                                         }
218                                         g, err := fs.getProject(uuid)
219                                         if err != nil {
220                                                 return err
221                                         }
222                                         proj = g
223                                         return proj
224                                 },
225                         },
226                 },
227         }
228         fs.byID[uuid] = n
229         return n
230 }
231
232 func (fs *customFileSystem) getProject(uuid string) (*Group, error) {
233         var g Group
234         err := fs.RequestAndDecode(&g, "GET", "arvados/v1/groups/"+uuid, nil, nil)
235         if statusErr, ok := err.(interface{ HTTPStatus() int }); ok && statusErr.HTTPStatus() == http.StatusNotFound {
236                 return nil, os.ErrNotExist
237         } else if err != nil {
238                 return nil, err
239         }
240         return &g, err
241 }
242
243 func (fs *customFileSystem) collectionSingleton(id string) (inode, error) {
244         // Return existing singleton, if we have it
245         fs.byIDLock.Lock()
246         existing := fs.byID[id]
247         fs.byIDLock.Unlock()
248         if existing != nil {
249                 return existing, nil
250         }
251
252         coll, err := fs.getCollection(id)
253         if err != nil {
254                 return nil, err
255         }
256         newfs, err := coll.FileSystem(fs, fs)
257         if err != nil {
258                 return nil, err
259         }
260         cfs := newfs.(*collectionFileSystem)
261         cfs.SetParent(fs.byIDRoot, id)
262
263         // Check again in case another goroutine has added a node to
264         // fs.byID since we checked above.
265         fs.byIDLock.Lock()
266         defer fs.byIDLock.Unlock()
267         if existing = fs.byID[id]; existing != nil {
268                 // Other goroutine won the race. Discard the node we
269                 // just made, and return the race winner.
270                 return existing, nil
271         }
272         // We won the race. Save the new node in fs.byID and
273         // fs.byIDRoot.
274         fs.byID[id] = cfs
275         fs.byIDRoot.Lock()
276         defer fs.byIDRoot.Unlock()
277         fs.byIDRoot.Child(id, func(inode) (inode, error) { return cfs, nil })
278         return cfs, nil
279 }
280
281 func (fs *customFileSystem) getCollection(id string) (*Collection, error) {
282         var coll Collection
283         err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, nil)
284         if statusErr, ok := err.(interface{ HTTPStatus() int }); ok && statusErr.HTTPStatus() == http.StatusNotFound {
285                 return nil, os.ErrNotExist
286         } else if err != nil {
287                 return nil, err
288         }
289         if len(id) != 27 {
290                 // This means id is a PDH, and controller/railsapi
291                 // returned one of (possibly) many collections with
292                 // that PDH. Even if controller returns more fields
293                 // besides PDH and manifest text (which are equal for
294                 // all matching collections), we don't want to expose
295                 // them (e.g., through Sys()).
296                 coll = Collection{
297                         PortableDataHash: coll.PortableDataHash,
298                         ManifestText:     coll.ManifestText,
299                 }
300         }
301         return &coll, nil
302 }
303
304 // vdirnode wraps an inode by rejecting (with ErrInvalidOperation)
305 // calls that add/replace children directly, instead calling a
306 // create() func when a non-existing child is looked up.
307 //
308 // create() can return either a new node, which will be added to the
309 // treenode, or nil for ENOENT.
310 type vdirnode struct {
311         treenode
312         create func(parent inode, name string) (inode, error)
313 }
314
315 func (vn *vdirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
316         return vn.treenode.Child(name, func(existing inode) (inode, error) {
317                 if existing == nil && vn.create != nil {
318                         newnode, err := vn.create(vn, name)
319                         if err != nil {
320                                 return nil, err
321                         }
322                         if newnode != nil {
323                                 newnode.SetParent(vn, name)
324                                 existing = newnode
325                                 vn.treenode.fileinfo.modTime = time.Now()
326                         }
327                 }
328                 if replace == nil {
329                         return existing, nil
330                 } else if tryRepl, err := replace(existing); err != nil {
331                         return existing, err
332                 } else if tryRepl != existing {
333                         return existing, ErrInvalidOperation
334                 } else {
335                         return existing, nil
336                 }
337         })
338 }
339
340 // A hardlink can be used to mount an existing node at an additional
341 // point in the same filesystem.
342 type hardlink struct {
343         inode
344         parent inode
345         name   string
346 }
347
348 // If the wrapped inode is a filesystem, rootnode returns the wrapped
349 // fs's rootnode, otherwise inode itself. This allows
350 // (*fileSystem)Rename() to lock the root node of a hardlink-wrapped
351 // filesystem.
352 func (hl *hardlink) rootnode() inode {
353         if node, ok := hl.inode.(interface{ rootnode() inode }); ok {
354                 return node.rootnode()
355         } else {
356                 return hl.inode
357         }
358 }
359
360 func (hl *hardlink) Sync() error {
361         if node, ok := hl.inode.(syncer); ok {
362                 return node.Sync()
363         } else {
364                 return ErrInvalidOperation
365         }
366 }
367
368 func (hl *hardlink) SetParent(parent inode, name string) {
369         hl.Lock()
370         defer hl.Unlock()
371         hl.parent = parent
372         hl.name = name
373 }
374
375 func (hl *hardlink) Parent() inode {
376         hl.RLock()
377         defer hl.RUnlock()
378         return hl.parent
379 }
380
381 func (hl *hardlink) FileInfo() os.FileInfo {
382         fi := hl.inode.FileInfo()
383         if fi, ok := fi.(fileinfo); ok {
384                 fi.name = hl.name
385                 return fi
386         }
387         return fi
388 }