Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[arvados.git] / services / fuse / tests / test_mount.py
1 import unittest
2 import arvados
3 import arvados_fuse as fuse
4 import threading
5 import time
6 import os
7 import llfuse
8 import tempfile
9 import shutil
10 import subprocess
11 import glob
12 import run_test_server
13 import json
14
15 class MountTestBase(unittest.TestCase):
16     def setUp(self):
17         self.keeptmp = tempfile.mkdtemp()
18         os.environ['KEEP_LOCAL_STORE'] = self.keeptmp
19         self.mounttmp = tempfile.mkdtemp()
20         run_test_server.run(False)
21         run_test_server.authorize_with("admin")
22         self.api = api = fuse.SafeApi(arvados.config)
23
24     def make_mount(self, root_class, *root_args):
25         operations = fuse.Operations(os.getuid(), os.getgid())
26         operations.inodes.add_entry(root_class(
27                 llfuse.ROOT_INODE, operations.inodes, self.api, 0, *root_args))
28         llfuse.init(operations, self.mounttmp, [])
29         threading.Thread(None, llfuse.main).start()
30         # wait until the driver is finished initializing
31         operations.initlock.wait()
32
33     def tearDown(self):
34         run_test_server.stop()
35
36         # llfuse.close is buggy, so use fusermount instead.
37         #llfuse.close(unmount=True)
38         count = 0
39         success = 1
40         while (count < 9 and success != 0):
41           success = subprocess.call(["fusermount", "-u", self.mounttmp])
42           time.sleep(0.5)
43           count += 1
44
45         os.rmdir(self.mounttmp)
46         shutil.rmtree(self.keeptmp)
47
48     def assertDirContents(self, subdir, expect_content):
49         path = self.mounttmp
50         if subdir:
51             path = os.path.join(path, subdir)
52         self.assertEqual(sorted(expect_content), sorted(os.listdir(path)))
53
54
55 class FuseMountTest(MountTestBase):
56     def setUp(self):
57         super(FuseMountTest, self).setUp()
58
59         cw = arvados.CollectionWriter()
60
61         cw.start_new_file('thing1.txt')
62         cw.write("data 1")
63         cw.start_new_file('thing2.txt')
64         cw.write("data 2")
65         cw.start_new_stream('dir1')
66
67         cw.start_new_file('thing3.txt')
68         cw.write("data 3")
69         cw.start_new_file('thing4.txt')
70         cw.write("data 4")
71
72         cw.start_new_stream('dir2')
73         cw.start_new_file('thing5.txt')
74         cw.write("data 5")
75         cw.start_new_file('thing6.txt')
76         cw.write("data 6")
77
78         cw.start_new_stream('dir2/dir3')
79         cw.start_new_file('thing7.txt')
80         cw.write("data 7")
81
82         cw.start_new_file('thing8.txt')
83         cw.write("data 8")
84
85         cw.start_new_stream('edgecases')
86         for f in ":/./../.../-/*/\x01\\/ ".split("/"):
87             cw.start_new_file(f)
88             cw.write('x')
89
90         for f in ":/../.../-/*/\x01\\/ ".split("/"):
91             cw.start_new_stream('edgecases/dirs/' + f)
92             cw.start_new_file('x/x')
93             cw.write('x')
94
95         self.testcollection = cw.finish()
96         self.api.collections().create(body={"manifest_text":cw.manifest_text()}).execute()
97
98     def runTest(self):
99         self.make_mount(fuse.CollectionDirectory, self.testcollection)
100
101         self.assertDirContents(None, ['thing1.txt', 'thing2.txt',
102                                       'edgecases', 'dir1', 'dir2'])
103         self.assertDirContents('dir1', ['thing3.txt', 'thing4.txt'])
104         self.assertDirContents('dir2', ['thing5.txt', 'thing6.txt', 'dir3'])
105         self.assertDirContents('dir2/dir3', ['thing7.txt', 'thing8.txt'])
106         self.assertDirContents('edgecases',
107                                "dirs/:/_/__/.../-/*/\x01\\/ ".split("/"))
108         self.assertDirContents('edgecases/dirs',
109                                ":/__/.../-/*/\x01\\/ ".split("/"))
110
111         files = {'thing1.txt': 'data 1',
112                  'thing2.txt': 'data 2',
113                  'dir1/thing3.txt': 'data 3',
114                  'dir1/thing4.txt': 'data 4',
115                  'dir2/thing5.txt': 'data 5',
116                  'dir2/thing6.txt': 'data 6',
117                  'dir2/dir3/thing7.txt': 'data 7',
118                  'dir2/dir3/thing8.txt': 'data 8'}
119
120         for k, v in files.items():
121             with open(os.path.join(self.mounttmp, k)) as f:
122                 self.assertEqual(v, f.read())
123
124
125 class FuseNoAPITest(MountTestBase):
126     def setUp(self):
127         super(FuseNoAPITest, self).setUp()
128         keep = arvados.keep.KeepClient(local_store=self.keeptmp)
129         self.file_data = "API-free text\n"
130         self.file_loc = keep.put(self.file_data)
131         self.coll_loc = keep.put(". {} 0:{}:api-free.txt\n".format(
132                 self.file_loc, len(self.file_data)))
133
134     def runTest(self):
135         self.make_mount(fuse.MagicDirectory)
136         self.assertDirContents(self.coll_loc, ['api-free.txt'])
137         with open(os.path.join(
138                 self.mounttmp, self.coll_loc, 'api-free.txt')) as keep_file:
139             actual = keep_file.read(-1)
140         self.assertEqual(self.file_data, actual)
141
142
143 class FuseMagicTest(MountTestBase):
144     def setUp(self):
145         super(FuseMagicTest, self).setUp()
146
147         cw = arvados.CollectionWriter()
148
149         cw.start_new_file('thing1.txt')
150         cw.write("data 1")
151
152         self.testcollection = cw.finish()
153         self.api.collections().create(body={"manifest_text":cw.manifest_text()}).execute()
154
155     def runTest(self):
156         self.make_mount(fuse.MagicDirectory)
157
158         mount_ls = os.listdir(self.mounttmp)
159         self.assertIn('README', mount_ls)
160         self.assertFalse(any(arvados.util.keep_locator_pattern.match(fn) or
161                              arvados.util.uuid_pattern.match(fn)
162                              for fn in mount_ls),
163                          "new FUSE MagicDirectory lists Collection")
164         self.assertDirContents(self.testcollection, ['thing1.txt'])
165         self.assertDirContents(os.path.join('by_id', self.testcollection),
166                                ['thing1.txt'])
167         mount_ls = os.listdir(self.mounttmp)
168         self.assertIn('README', mount_ls)
169         self.assertIn(self.testcollection, mount_ls)
170         self.assertIn(self.testcollection,
171                       os.listdir(os.path.join(self.mounttmp, 'by_id')))
172
173         files = {}
174         files[os.path.join(self.mounttmp, self.testcollection, 'thing1.txt')] = 'data 1'
175
176         for k, v in files.items():
177             with open(os.path.join(self.mounttmp, k)) as f:
178                 self.assertEqual(v, f.read())
179
180
181 class FuseTagsTest(MountTestBase):
182     def runTest(self):
183         self.make_mount(fuse.TagsDirectory)
184
185         d1 = os.listdir(self.mounttmp)
186         d1.sort()
187         self.assertEqual(['foo_tag'], d1)
188
189         d2 = os.listdir(os.path.join(self.mounttmp, 'foo_tag'))
190         d2.sort()
191         self.assertEqual(['zzzzz-4zz18-fy296fx3hot09f7'], d2)
192
193         d3 = os.listdir(os.path.join(self.mounttmp, 'foo_tag', 'zzzzz-4zz18-fy296fx3hot09f7'))
194         d3.sort()
195         self.assertEqual(['foo'], d3)
196
197
198 class FuseTagsUpdateTest(MountTestBase):
199     def tag_collection(self, coll_uuid, tag_name):
200         return self.api.links().create(
201             body={'link': {'head_uuid': coll_uuid,
202                            'link_class': 'tag',
203                            'name': tag_name,
204         }}).execute()
205
206     def runTest(self):
207         operations = fuse.Operations(os.getuid(), os.getgid())
208         e = operations.inodes.add_entry(fuse.TagsDirectory(llfuse.ROOT_INODE, operations.inodes, self.api, 0, poll_time=1))
209
210         llfuse.init(operations, self.mounttmp, [])
211         t = threading.Thread(None, lambda: llfuse.main())
212         t.start()
213
214         # wait until the driver is finished initializing
215         operations.initlock.wait()
216         self.assertIn('foo_tag', os.listdir(self.mounttmp))
217
218         bar_uuid = run_test_server.fixture('collections')['bar_file']['uuid']
219         self.tag_collection(bar_uuid, 'fuse_test_tag')
220         time.sleep(1)
221         self.assertIn('fuse_test_tag', os.listdir(self.mounttmp))
222         self.assertDirContents('fuse_test_tag', [bar_uuid])
223
224         baz_uuid = run_test_server.fixture('collections')['baz_file']['uuid']
225         l = self.tag_collection(baz_uuid, 'fuse_test_tag')
226         time.sleep(1)
227         self.assertDirContents('fuse_test_tag', [bar_uuid, baz_uuid])
228
229         self.api.links().delete(uuid=l['uuid']).execute()
230         time.sleep(1)
231         self.assertDirContents('fuse_test_tag', [bar_uuid])
232
233
234 class FuseSharedTest(MountTestBase):
235     def runTest(self):
236         self.make_mount(fuse.SharedDirectory,
237                         self.api.users().current().execute()['uuid'])
238
239         # shared_dirs is a list of the directories exposed
240         # by fuse.SharedDirectory (i.e. any object visible
241         # to the current user)
242         shared_dirs = os.listdir(self.mounttmp)
243         shared_dirs.sort()
244         self.assertIn('FUSE User', shared_dirs)
245
246         # fuse_user_objs is a list of the objects owned by the FUSE
247         # test user (which present as files in the 'FUSE User'
248         # directory)
249         fuse_user_objs = os.listdir(os.path.join(self.mounttmp, 'FUSE User'))
250         fuse_user_objs.sort()
251         self.assertEqual(['Empty collection.link',                # permission link on collection
252                           'FUSE Test Project',                    # project owned by user
253                           'collection #1 owned by FUSE',          # collection owned by user
254                           'collection #2 owned by FUSE',          # collection owned by user
255                           'pipeline instance owned by FUSE.pipelineInstance',  # pipeline instance owned by user
256                       ], fuse_user_objs)
257
258         # test_proj_files is a list of the files in the FUSE Test Project.
259         test_proj_files = os.listdir(os.path.join(self.mounttmp, 'FUSE User', 'FUSE Test Project'))
260         test_proj_files.sort()
261         self.assertEqual(['collection in FUSE project',
262                           'pipeline instance in FUSE project.pipelineInstance',
263                           'pipeline template in FUSE project.pipelineTemplate'
264                       ], test_proj_files)
265
266         # Double check that we can open and read objects in this folder as a file,
267         # and that its contents are what we expect.
268         with open(os.path.join(
269                 self.mounttmp,
270                 'FUSE User',
271                 'FUSE Test Project',
272                 'pipeline template in FUSE project.pipelineTemplate')) as f:
273             j = json.load(f)
274             self.assertEqual("pipeline template in FUSE project", j['name'])
275
276
277 class FuseHomeTest(MountTestBase):
278     def runTest(self):
279         self.make_mount(fuse.ProjectDirectory,
280                         self.api.users().current().execute())
281
282         d1 = os.listdir(self.mounttmp)
283         self.assertIn('Unrestricted public data', d1)
284
285         d2 = os.listdir(os.path.join(self.mounttmp, 'Unrestricted public data'))
286         self.assertEqual(['GNU General Public License, version 3'], d2)
287
288         d3 = os.listdir(os.path.join(self.mounttmp, 'Unrestricted public data', 'GNU General Public License, version 3'))
289         self.assertEqual(["GNU_General_Public_License,_version_3.pdf"], d3)
290
291
292 class FuseUnitTest(unittest.TestCase):
293     def test_sanitize_filename(self):
294         acceptable = [
295             "foo.txt",
296             ".foo",
297             "..foo",
298             "...",
299             "foo...",
300             "foo..",
301             "foo.",
302             "-",
303             "\x01\x02\x03",
304             ]
305         unacceptable = [
306             "f\00",
307             "\00\00",
308             "/foo",
309             "foo/",
310             "//",
311             ]
312         for f in acceptable:
313             self.assertEqual(f, fuse.sanitize_filename(f))
314         for f in unacceptable:
315             self.assertNotEqual(f, fuse.sanitize_filename(f))
316             # The sanitized filename should be the same length, though.
317             self.assertEqual(len(f), len(fuse.sanitize_filename(f)))
318         # Special cases
319         self.assertEqual("_", fuse.sanitize_filename(""))
320         self.assertEqual("_", fuse.sanitize_filename("."))
321         self.assertEqual("__", fuse.sanitize_filename(".."))