716ef34e26098771c44f99c46aeea593ce3e87fb
[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         fs.byIDLock.Lock()
157         n := fs.byID[id]
158         if n != nil {
159                 // Avoid the extra remote API lookup if we already
160                 // have a singleton for this ID.
161                 fs.byIDLock.Unlock()
162                 return &hardlink{inode: n, parent: parent, name: id}, nil
163         }
164         fs.byIDLock.Unlock()
165
166         if strings.Contains(id, "-4zz18-") || pdhRegexp.MatchString(id) {
167                 node, err := fs.collectionSingleton(id)
168                 if os.IsNotExist(err) {
169                         return nil, nil
170                 } else if err != nil {
171                         return nil, err
172                 }
173                 return &hardlink{inode: node, parent: parent, name: id}, nil
174         } else if strings.Contains(id, "-j7d0g-") || strings.Contains(id, "-tpzed-") {
175                 proj, err := fs.getProject(id)
176                 if os.IsNotExist(err) {
177                         return nil, nil
178                 } else if err != nil {
179                         return nil, err
180                 }
181                 node := fs.projectSingleton(id, proj)
182                 return &hardlink{inode: node, parent: parent, name: id}, nil
183         } else {
184                 return nil, nil
185         }
186 }
187
188 func (fs *customFileSystem) projectSingleton(uuid string, proj *Group) inode {
189         fs.byIDLock.Lock()
190         defer fs.byIDLock.Unlock()
191         if n := fs.byID[uuid]; n != nil {
192                 return n
193         }
194         name := uuid
195         if name == "" {
196                 // special case uuid=="" implements the "home project"
197                 // (owner_uuid == current user uuid)
198                 name = "home"
199         }
200         var projLoading sync.Mutex
201         n := &lookupnode{
202                 stale:   fs.Stale,
203                 loadOne: func(parent inode, name string) (inode, error) { return fs.projectsLoadOne(parent, uuid, name) },
204                 loadAll: func(parent inode) ([]inode, error) { return fs.projectsLoadAll(parent, uuid) },
205                 treenode: treenode{
206                         fs:     fs,
207                         parent: fs.byIDRoot,
208                         inodes: make(map[string]inode),
209                         fileinfo: fileinfo{
210                                 name:    name,
211                                 modTime: time.Now(),
212                                 mode:    0755 | os.ModeDir,
213                                 sys: func() interface{} {
214                                         projLoading.Lock()
215                                         defer projLoading.Unlock()
216                                         if proj != nil {
217                                                 return proj
218                                         }
219                                         g, err := fs.getProject(uuid)
220                                         if err != nil {
221                                                 return err
222                                         }
223                                         proj = g
224                                         return proj
225                                 },
226                         },
227                 },
228         }
229         fs.byID[uuid] = n
230         return n
231 }
232
233 func (fs *customFileSystem) getProject(uuid string) (*Group, error) {
234         var g Group
235         err := fs.RequestAndDecode(&g, "GET", "arvados/v1/groups/"+uuid, nil, nil)
236         if statusErr, ok := err.(interface{ HTTPStatus() int }); ok && statusErr.HTTPStatus() == http.StatusNotFound {
237                 return nil, os.ErrNotExist
238         } else if err != nil {
239                 return nil, err
240         }
241         return &g, err
242 }
243
244 func (fs *customFileSystem) collectionSingleton(id string) (inode, error) {
245         fs.byIDLock.Lock()
246         if n := fs.byID[id]; n != nil {
247                 fs.byIDLock.Unlock()
248                 return n, nil
249         }
250         fs.byIDLock.Unlock()
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         fs.byIDLock.Lock()
264         defer fs.byIDLock.Unlock()
265         if n := fs.byID[id]; n != nil {
266                 return n, nil
267         }
268         fs.byID[id] = cfs
269         fs.byIDRoot.Child(id, func(inode) (inode, error) { return cfs, nil })
270         return cfs, nil
271 }
272
273 func (fs *customFileSystem) getCollection(id string) (*Collection, error) {
274         var coll Collection
275         err := fs.RequestAndDecode(&coll, "GET", "arvados/v1/collections/"+id, nil, nil)
276         if statusErr, ok := err.(interface{ HTTPStatus() int }); ok && statusErr.HTTPStatus() == http.StatusNotFound {
277                 return nil, os.ErrNotExist
278         } else if err != nil {
279                 return nil, err
280         }
281         if len(id) != 27 {
282                 // This means id is a PDH, and controller/railsapi
283                 // returned one of (possibly) many collections with
284                 // that PDH. Even if controller returns more fields
285                 // besides PDH and manifest text (which are equal for
286                 // all matching collections), we don't want to expose
287                 // them (e.g., through Sys()).
288                 coll = Collection{
289                         PortableDataHash: coll.PortableDataHash,
290                         ManifestText:     coll.ManifestText,
291                 }
292         }
293         return &coll, nil
294 }
295
296 // vdirnode wraps an inode by rejecting (with ErrInvalidOperation)
297 // calls that add/replace children directly, instead calling a
298 // create() func when a non-existing child is looked up.
299 //
300 // create() can return either a new node, which will be added to the
301 // treenode, or nil for ENOENT.
302 type vdirnode struct {
303         treenode
304         create func(parent inode, name string) (inode, error)
305 }
306
307 func (vn *vdirnode) Child(name string, replace func(inode) (inode, error)) (inode, error) {
308         return vn.treenode.Child(name, func(existing inode) (inode, error) {
309                 if existing == nil && vn.create != nil {
310                         newnode, err := vn.create(vn, name)
311                         if err != nil {
312                                 return nil, err
313                         }
314                         if newnode != nil {
315                                 newnode.SetParent(vn, name)
316                                 existing = newnode
317                                 vn.treenode.fileinfo.modTime = time.Now()
318                         }
319                 }
320                 if replace == nil {
321                         return existing, nil
322                 } else if tryRepl, err := replace(existing); err != nil {
323                         return existing, err
324                 } else if tryRepl != existing {
325                         return existing, ErrInvalidOperation
326                 } else {
327                         return existing, nil
328                 }
329         })
330 }
331
332 // A hardlink can be used to mount an existing node at an additional
333 // point in the same filesystem.
334 type hardlink struct {
335         inode
336         parent inode
337         name   string
338 }
339
340 func (hl *hardlink) Sync() error {
341         if node, ok := hl.inode.(syncer); ok {
342                 return node.Sync()
343         } else {
344                 return ErrInvalidOperation
345         }
346 }
347
348 func (hl *hardlink) SetParent(parent inode, name string) {
349         hl.Lock()
350         defer hl.Unlock()
351         hl.parent = parent
352         hl.name = name
353 }
354
355 func (hl *hardlink) Parent() inode {
356         hl.RLock()
357         defer hl.RUnlock()
358         return hl.parent
359 }
360
361 func (hl *hardlink) FileInfo() os.FileInfo {
362         fi := hl.inode.FileInfo()
363         if fi, ok := fi.(fileinfo); ok {
364                 fi.name = hl.name
365                 return fi
366         }
367         return fi
368 }