4705: Refactor mount creation in FUSE tests.
[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 FuseMagicTest(MountTestBase):
126     def setUp(self):
127         super(FuseMagicTest, self).setUp()
128
129         cw = arvados.CollectionWriter()
130
131         cw.start_new_file('thing1.txt')
132         cw.write("data 1")
133
134         self.testcollection = cw.finish()
135         self.api.collections().create(body={"manifest_text":cw.manifest_text()}).execute()
136
137     def runTest(self):
138         self.make_mount(fuse.MagicDirectory)
139
140         mount_ls = os.listdir(self.mounttmp)
141         self.assertIn('README', mount_ls)
142         self.assertFalse(any(arvados.util.keep_locator_pattern.match(fn) or
143                              arvados.util.uuid_pattern.match(fn)
144                              for fn in mount_ls),
145                          "new FUSE MagicDirectory lists Collection")
146         self.assertDirContents(self.testcollection, ['thing1.txt'])
147         self.assertDirContents(os.path.join('by_id', self.testcollection),
148                                ['thing1.txt'])
149         mount_ls = os.listdir(self.mounttmp)
150         self.assertIn('README', mount_ls)
151         self.assertIn(self.testcollection, mount_ls)
152         self.assertIn(self.testcollection,
153                       os.listdir(os.path.join(self.mounttmp, 'by_id')))
154
155         files = {}
156         files[os.path.join(self.mounttmp, self.testcollection, 'thing1.txt')] = 'data 1'
157
158         for k, v in files.items():
159             with open(os.path.join(self.mounttmp, k)) as f:
160                 self.assertEqual(v, f.read())
161
162
163 class FuseTagsTest(MountTestBase):
164     def runTest(self):
165         self.make_mount(fuse.TagsDirectory)
166
167         d1 = os.listdir(self.mounttmp)
168         d1.sort()
169         self.assertEqual(['foo_tag'], d1)
170
171         d2 = os.listdir(os.path.join(self.mounttmp, 'foo_tag'))
172         d2.sort()
173         self.assertEqual(['zzzzz-4zz18-fy296fx3hot09f7'], d2)
174
175         d3 = os.listdir(os.path.join(self.mounttmp, 'foo_tag', 'zzzzz-4zz18-fy296fx3hot09f7'))
176         d3.sort()
177         self.assertEqual(['foo'], d3)
178
179
180 class FuseTagsUpdateTest(MountTestBase):
181     def tag_collection(self, coll_uuid, tag_name):
182         return self.api.links().create(
183             body={'link': {'head_uuid': coll_uuid,
184                            'link_class': 'tag',
185                            'name': tag_name,
186         }}).execute()
187
188     def runTest(self):
189         operations = fuse.Operations(os.getuid(), os.getgid())
190         e = operations.inodes.add_entry(fuse.TagsDirectory(llfuse.ROOT_INODE, operations.inodes, self.api, 0, poll_time=1))
191
192         llfuse.init(operations, self.mounttmp, [])
193         t = threading.Thread(None, lambda: llfuse.main())
194         t.start()
195
196         # wait until the driver is finished initializing
197         operations.initlock.wait()
198         self.assertIn('foo_tag', os.listdir(self.mounttmp))
199
200         bar_uuid = run_test_server.fixture('collections')['bar_file']['uuid']
201         self.tag_collection(bar_uuid, 'fuse_test_tag')
202         time.sleep(1)
203         self.assertIn('fuse_test_tag', os.listdir(self.mounttmp))
204         self.assertDirContents('fuse_test_tag', [bar_uuid])
205
206         baz_uuid = run_test_server.fixture('collections')['baz_file']['uuid']
207         l = self.tag_collection(baz_uuid, 'fuse_test_tag')
208         time.sleep(1)
209         self.assertDirContents('fuse_test_tag', [bar_uuid, baz_uuid])
210
211         self.api.links().delete(uuid=l['uuid']).execute()
212         time.sleep(1)
213         self.assertDirContents('fuse_test_tag', [bar_uuid])
214
215
216 class FuseSharedTest(MountTestBase):
217     def runTest(self):
218         self.make_mount(fuse.SharedDirectory,
219                         self.api.users().current().execute()['uuid'])
220
221         # shared_dirs is a list of the directories exposed
222         # by fuse.SharedDirectory (i.e. any object visible
223         # to the current user)
224         shared_dirs = os.listdir(self.mounttmp)
225         shared_dirs.sort()
226         self.assertIn('FUSE User', shared_dirs)
227
228         # fuse_user_objs is a list of the objects owned by the FUSE
229         # test user (which present as files in the 'FUSE User'
230         # directory)
231         fuse_user_objs = os.listdir(os.path.join(self.mounttmp, 'FUSE User'))
232         fuse_user_objs.sort()
233         self.assertEqual(['Empty collection.link',                # permission link on collection
234                           'FUSE Test Project',                    # project owned by user
235                           'collection #1 owned by FUSE',          # collection owned by user
236                           'collection #2 owned by FUSE',          # collection owned by user
237                           'pipeline instance owned by FUSE.pipelineInstance',  # pipeline instance owned by user
238                       ], fuse_user_objs)
239
240         # test_proj_files is a list of the files in the FUSE Test Project.
241         test_proj_files = os.listdir(os.path.join(self.mounttmp, 'FUSE User', 'FUSE Test Project'))
242         test_proj_files.sort()
243         self.assertEqual(['collection in FUSE project',
244                           'pipeline instance in FUSE project.pipelineInstance',
245                           'pipeline template in FUSE project.pipelineTemplate'
246                       ], test_proj_files)
247
248         # Double check that we can open and read objects in this folder as a file,
249         # and that its contents are what we expect.
250         with open(os.path.join(
251                 self.mounttmp,
252                 'FUSE User',
253                 'FUSE Test Project',
254                 'pipeline template in FUSE project.pipelineTemplate')) as f:
255             j = json.load(f)
256             self.assertEqual("pipeline template in FUSE project", j['name'])
257
258
259 class FuseHomeTest(MountTestBase):
260     def runTest(self):
261         self.make_mount(fuse.ProjectDirectory,
262                         self.api.users().current().execute())
263
264         d1 = os.listdir(self.mounttmp)
265         self.assertIn('Unrestricted public data', d1)
266
267         d2 = os.listdir(os.path.join(self.mounttmp, 'Unrestricted public data'))
268         self.assertEqual(['GNU General Public License, version 3'], d2)
269
270         d3 = os.listdir(os.path.join(self.mounttmp, 'Unrestricted public data', 'GNU General Public License, version 3'))
271         self.assertEqual(["GNU_General_Public_License,_version_3.pdf"], d3)
272
273
274 class FuseUnitTest(unittest.TestCase):
275     def test_sanitize_filename(self):
276         acceptable = [
277             "foo.txt",
278             ".foo",
279             "..foo",
280             "...",
281             "foo...",
282             "foo..",
283             "foo.",
284             "-",
285             "\x01\x02\x03",
286             ]
287         unacceptable = [
288             "f\00",
289             "\00\00",
290             "/foo",
291             "foo/",
292             "//",
293             ]
294         for f in acceptable:
295             self.assertEqual(f, fuse.sanitize_filename(f))
296         for f in unacceptable:
297             self.assertNotEqual(f, fuse.sanitize_filename(f))
298             # The sanitized filename should be the same length, though.
299             self.assertEqual(len(f), len(fuse.sanitize_filename(f)))
300         # Special cases
301         self.assertEqual("_", fuse.sanitize_filename(""))
302         self.assertEqual("_", fuse.sanitize_filename("."))
303         self.assertEqual("__", fuse.sanitize_filename(".."))