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