Merge branch '11557-acr-output-col-perms'
[arvados.git] / sdk / cwl / tests / test_job.py
1 import functools
2 import json
3 import logging
4 import mock
5 import os
6 import unittest
7 import copy
8 import StringIO
9
10 import arvados
11 import arvados_cwl
12 import cwltool.process
13 from arvados.errors import ApiError
14 from schema_salad.ref_resolver import Loader
15 from schema_salad.sourceline import cmap
16 from .mock_discovery import get_rootDesc
17 from .matcher import JsonDiffMatcher
18
19 if not os.getenv('ARVADOS_DEBUG'):
20     logging.getLogger('arvados.cwl-runner').setLevel(logging.WARN)
21     logging.getLogger('arvados.arv-run').setLevel(logging.WARN)
22
23 class TestJob(unittest.TestCase):
24
25     # The test passes no builder.resources
26     # Hence the default resources will apply: {'cores': 1, 'ram': 1024, 'outdirSize': 1024, 'tmpdirSize': 1024}
27     @mock.patch('arvados.commands.keepdocker.list_images_in_arv')
28     def test_run(self, list_images_in_arv):
29         for enable_reuse in (True, False):
30             runner = mock.MagicMock()
31             runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
32             runner.ignore_docker_for_reuse = False
33             runner.num_retries = 0
34             document_loader, avsc_names, schema_metadata, metaschema_loader = cwltool.process.get_schema("v1.0")
35
36             list_images_in_arv.return_value = [["zzzzz-4zz18-zzzzzzzzzzzzzzz"]]
37             runner.api.collections().get().execute.return_value = {"portable_data_hash": "99999999999999999999999999999993+99"}
38             # Simulate reused job from another project so that we can check is a can_read
39             # link is added.
40             runner.api.jobs().create().execute.return_value = {
41                 'state': 'Complete' if enable_reuse else 'Queued',
42                 'owner_uuid': 'zzzzz-tpzed-yyyyyyyyyyyyyyy' if enable_reuse else 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
43                 'uuid': 'zzzzz-819sb-yyyyyyyyyyyyyyy',
44                 'output': None,
45             }
46
47             tool = cmap({
48                 "inputs": [],
49                 "outputs": [],
50                 "baseCommand": "ls",
51                 "arguments": [{"valueFrom": "$(runtime.outdir)"}]
52             })
53             make_fs_access=functools.partial(arvados_cwl.CollectionFsAccess,
54                                          collection_cache=arvados_cwl.CollectionCache(runner.api, None, 0))
55             arvtool = arvados_cwl.ArvadosCommandTool(runner, tool, work_api="jobs", avsc_names=avsc_names,
56                                                      basedir="", make_fs_access=make_fs_access, loader=Loader({}))
57             arvtool.formatgraph = None
58             for j in arvtool.job({}, mock.MagicMock(), basedir="", make_fs_access=make_fs_access):
59                 j.run(enable_reuse=enable_reuse)
60                 runner.api.jobs().create.assert_called_with(
61                     body=JsonDiffMatcher({
62                         'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
63                         'runtime_constraints': {},
64                         'script_parameters': {
65                             'tasks': [{
66                                 'task.env': {'HOME': '$(task.outdir)', 'TMPDIR': '$(task.tmpdir)'},
67                                 'command': ['ls', '$(task.outdir)']
68                             }],
69                         },
70                         'script_version': 'master',
71                         'minimum_script_version': 'a3f2cb186e437bfce0031b024b2157b73ed2717d',
72                         'repository': 'arvados',
73                         'script': 'crunchrunner',
74                         'runtime_constraints': {
75                             'docker_image': 'arvados/jobs',
76                             'min_cores_per_node': 1,
77                             'min_ram_mb_per_node': 1024,
78                             'min_scratch_mb_per_node': 2048 # tmpdirSize + outdirSize
79                         }
80                     }),
81                     find_or_create=enable_reuse,
82                     filters=[['repository', '=', 'arvados'],
83                              ['script', '=', 'crunchrunner'],
84                              ['script_version', 'in git', 'a3f2cb186e437bfce0031b024b2157b73ed2717d'],
85                              ['docker_image_locator', 'in docker', 'arvados/jobs']]
86                 )
87                 if enable_reuse:
88                     runner.api.links().create.assert_called_with(
89                         body=JsonDiffMatcher({
90                             'link_class': 'permission',
91                             'name': 'can_read',
92                             "tail_uuid": "zzzzz-8i9sb-zzzzzzzzzzzzzzz",
93                             "head_uuid": "zzzzz-819sb-yyyyyyyyyyyyyyy",
94                         })
95                     )
96                     # Simulate an API excepction when trying to create a
97                     # sharing link on the job
98                     runner.api.links().create.side_effect = ApiError(
99                         mock.MagicMock(return_value={'status': 403}),
100                         'Permission denied')
101                     j.run(enable_reuse=enable_reuse)
102                     j.output_callback.assert_called_with({}, 'success')
103                 else:
104                     assert not runner.api.links().create.called
105
106     # The test passes some fields in builder.resources
107     # For the remaining fields, the defaults will apply: {'cores': 1, 'ram': 1024, 'outdirSize': 1024, 'tmpdirSize': 1024}
108     @mock.patch('arvados.commands.keepdocker.list_images_in_arv')
109     def test_resource_requirements(self, list_images_in_arv):
110         runner = mock.MagicMock()
111         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
112         runner.ignore_docker_for_reuse = False
113         runner.num_retries = 0
114         arvados_cwl.add_arv_hints()
115
116         list_images_in_arv.return_value = [["zzzzz-4zz18-zzzzzzzzzzzzzzz"]]
117         runner.api.collections().get().execute.return_vaulue = {"portable_data_hash": "99999999999999999999999999999993+99"}
118
119         document_loader, avsc_names, schema_metadata, metaschema_loader = cwltool.process.get_schema("v1.0")
120
121
122         tool = {
123             "inputs": [],
124             "outputs": [],
125             "hints": [{
126                 "class": "ResourceRequirement",
127                 "coresMin": 3,
128                 "ramMin": 3000,
129                 "tmpdirMin": 4000
130             }, {
131                 "class": "http://arvados.org/cwl#RuntimeConstraints",
132                 "keep_cache": 512,
133                 "outputDirType": "keep_output_dir"
134             }, {
135                 "class": "http://arvados.org/cwl#APIRequirement",
136             }],
137             "baseCommand": "ls"
138         }
139         make_fs_access=functools.partial(arvados_cwl.CollectionFsAccess,
140                                          collection_cache=arvados_cwl.CollectionCache(runner.api, None, 0))
141         arvtool = arvados_cwl.ArvadosCommandTool(runner, tool, work_api="jobs", avsc_names=avsc_names,
142                                                  make_fs_access=make_fs_access, loader=Loader({}))
143         arvtool.formatgraph = None
144         for j in arvtool.job({}, mock.MagicMock(), basedir="", make_fs_access=make_fs_access):
145             j.run()
146         runner.api.jobs().create.assert_called_with(
147             body=JsonDiffMatcher({
148                 'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
149                 'runtime_constraints': {},
150                 'script_parameters': {
151                     'tasks': [{
152                         'task.env': {'HOME': '$(task.outdir)', 'TMPDIR': '$(task.tmpdir)'},
153                         'task.keepTmpOutput': True,
154                         'command': ['ls']
155                     }]
156             },
157             'script_version': 'master',
158                 'minimum_script_version': 'a3f2cb186e437bfce0031b024b2157b73ed2717d',
159                 'repository': 'arvados',
160                 'script': 'crunchrunner',
161                 'runtime_constraints': {
162                     'docker_image': 'arvados/jobs',
163                     'min_cores_per_node': 3,
164                     'min_ram_mb_per_node': 3512,     # ramMin + keep_cache
165                     'min_scratch_mb_per_node': 5024, # tmpdirSize + outdirSize
166                     'keep_cache_mb_per_task': 512
167                 }
168             }),
169             find_or_create=True,
170             filters=[['repository', '=', 'arvados'],
171                      ['script', '=', 'crunchrunner'],
172                      ['script_version', 'in git', 'a3f2cb186e437bfce0031b024b2157b73ed2717d'],
173                      ['docker_image_locator', 'in docker', 'arvados/jobs']])
174
175     @mock.patch("arvados.collection.CollectionReader")
176     def test_done(self, reader):
177         api = mock.MagicMock()
178
179         runner = mock.MagicMock()
180         runner.api = api
181         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
182         runner.num_retries = 0
183         runner.ignore_docker_for_reuse = False
184
185         reader().open.return_value = StringIO.StringIO(
186             """2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.tmpdir)=/tmp/crunch-job-task-work/compute3.1/tmpdir
187 2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.outdir)=/tmp/crunch-job-task-work/compute3.1/outdir
188 2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.keep)=/keep
189         """)
190         api.collections().list().execute.side_effect = ({"items": []},
191                                                         {"items": [{"manifest_text": "XYZ"}]},
192                                                         {"items": []},
193                                                         {"items": [{"manifest_text": "ABC"}]})
194
195         arvjob = arvados_cwl.ArvadosJob(runner)
196         arvjob.name = "testjob"
197         arvjob.builder = mock.MagicMock()
198         arvjob.output_callback = mock.MagicMock()
199         arvjob.collect_outputs = mock.MagicMock()
200         arvjob.collect_outputs.return_value = {"out": "stuff"}
201
202         arvjob.done({
203             "state": "Complete",
204             "output": "99999999999999999999999999999993+99",
205             "log": "99999999999999999999999999999994+99",
206             "uuid": "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
207         })
208
209         api.collections().list.assert_has_calls([
210             mock.call(),
211             # Output collection check
212             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
213                           ['portable_data_hash', '=', '99999999999999999999999999999993+99'],
214                           ['name', '=', 'Output 9999999 of testjob']]),
215             mock.call().execute(num_retries=0),
216             mock.call(limit=1, filters=[['portable_data_hash', '=', '99999999999999999999999999999993+99']],
217                  select=['manifest_text']),
218             mock.call().execute(num_retries=0),
219             # Log collection's turn
220             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
221                           ['portable_data_hash', '=', '99999999999999999999999999999994+99'],
222                           ['name', '=', 'Log of zzzzz-8i9sb-zzzzzzzzzzzzzzz']]),
223             mock.call().execute(num_retries=0),
224             mock.call(limit=1, filters=[['portable_data_hash', '=', '99999999999999999999999999999994+99']],
225                  select=['manifest_text']),
226             mock.call().execute(num_retries=0)])
227
228         api.collections().create.assert_has_calls([
229             mock.call(ensure_unique_name=True,
230                       body={'portable_data_hash': '99999999999999999999999999999993+99',
231                             'manifest_text': 'XYZ',
232                             'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
233                             'name': 'Output 9999999 of testjob'}),
234             mock.call().execute(num_retries=0),
235             mock.call(ensure_unique_name=True,
236                       body={'portable_data_hash': '99999999999999999999999999999994+99',
237                             'manifest_text': 'ABC',
238                             'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
239                             'name': 'Log of zzzzz-8i9sb-zzzzzzzzzzzzzzz'}),
240             mock.call().execute(num_retries=0),
241         ])
242
243         arvjob.output_callback.assert_called_with({"out": "stuff"}, "success")
244
245     @mock.patch("arvados.collection.CollectionReader")
246     def test_done_use_existing_collection(self, reader):
247         api = mock.MagicMock()
248
249         runner = mock.MagicMock()
250         runner.api = api
251         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
252         runner.num_retries = 0
253
254         reader().open.return_value = StringIO.StringIO(
255             """2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.tmpdir)=/tmp/crunch-job-task-work/compute3.1/tmpdir
256 2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.outdir)=/tmp/crunch-job-task-work/compute3.1/outdir
257 2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.keep)=/keep
258         """)
259
260         api.collections().list().execute.side_effect = (
261             {"items": [{"uuid": "zzzzz-4zz18-zzzzzzzzzzzzzz2"}]},
262             {"items": [{"uuid": "zzzzz-4zz18-zzzzzzzzzzzzzz2"}]},
263         )
264
265         arvjob = arvados_cwl.ArvadosJob(runner)
266         arvjob.name = "testjob"
267         arvjob.builder = mock.MagicMock()
268         arvjob.output_callback = mock.MagicMock()
269         arvjob.collect_outputs = mock.MagicMock()
270         arvjob.collect_outputs.return_value = {"out": "stuff"}
271
272         arvjob.done({
273             "state": "Complete",
274             "output": "99999999999999999999999999999993+99",
275             "log": "99999999999999999999999999999994+99",
276             "uuid": "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
277         })
278
279         api.collections().list.assert_has_calls([
280             mock.call(),
281             # Output collection
282             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
283                                ['portable_data_hash', '=', '99999999999999999999999999999993+99'],
284                                ['name', '=', 'Output 9999999 of testjob']]),
285             mock.call().execute(num_retries=0),
286             # Log collection
287             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
288                                ['portable_data_hash', '=', '99999999999999999999999999999994+99'],
289                                ['name', '=', 'Log of zzzzz-8i9sb-zzzzzzzzzzzzzzz']]),
290             mock.call().execute(num_retries=0)
291         ])
292
293         self.assertFalse(api.collections().create.called)
294
295         arvjob.output_callback.assert_called_with({"out": "stuff"}, "success")
296
297
298 class TestWorkflow(unittest.TestCase):
299     # The test passes no builder.resources
300     # Hence the default resources will apply: {'cores': 1, 'ram': 1024, 'outdirSize': 1024, 'tmpdirSize': 1024}
301     @mock.patch("arvados.collection.Collection")
302     @mock.patch('arvados.commands.keepdocker.list_images_in_arv')
303     def test_run(self, list_images_in_arv, mockcollection):
304         arvados_cwl.add_arv_hints()
305
306         api = mock.MagicMock()
307         api._rootDesc = get_rootDesc()
308
309         runner = arvados_cwl.ArvCwlRunner(api)
310         self.assertEqual(runner.work_api, 'jobs')
311
312         list_images_in_arv.return_value = [["zzzzz-4zz18-zzzzzzzzzzzzzzz"]]
313         runner.api.collections().get().execute.return_vaulue = {"portable_data_hash": "99999999999999999999999999999993+99"}
314
315         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
316         runner.ignore_docker_for_reuse = False
317         runner.num_retries = 0
318         document_loader, avsc_names, schema_metadata, metaschema_loader = cwltool.process.get_schema("v1.0")
319
320         tool, metadata = document_loader.resolve_ref("tests/wf/scatter2.cwl")
321         metadata["cwlVersion"] = tool["cwlVersion"]
322
323         mockcollection().portable_data_hash.return_value = "99999999999999999999999999999999+118"
324
325         make_fs_access=functools.partial(arvados_cwl.CollectionFsAccess,
326                                          collection_cache=arvados_cwl.CollectionCache(runner.api, None, 0))
327         arvtool = arvados_cwl.ArvadosWorkflow(runner, tool, work_api="jobs", avsc_names=avsc_names,
328                                               basedir="", make_fs_access=make_fs_access, loader=document_loader,
329                                               makeTool=runner.arv_make_tool, metadata=metadata)
330         arvtool.formatgraph = None
331         it = arvtool.job({}, mock.MagicMock(), basedir="", make_fs_access=make_fs_access)
332         it.next().run()
333         it.next().run()
334
335         with open("tests/wf/scatter2_subwf.cwl") as f:
336             subwf = f.read()
337
338         runner.api.jobs().create.assert_called_with(
339             body=JsonDiffMatcher({
340                 'minimum_script_version': 'a3f2cb186e437bfce0031b024b2157b73ed2717d',
341                 'repository': 'arvados',
342                 'script_version': 'master',
343                 'script': 'crunchrunner',
344                 'script_parameters': {
345                     'tasks': [{'task.env': {
346                         'HOME': '$(task.outdir)',
347                         'TMPDIR': '$(task.tmpdir)'},
348                                'task.vwd': {
349                                    'workflow.cwl': '$(task.keep)/99999999999999999999999999999999+118/workflow.cwl',
350                                    'cwl.input.yml': '$(task.keep)/99999999999999999999999999999999+118/cwl.input.yml'
351                                },
352                     'command': [u'cwltool', u'--no-container', u'--move-outputs', u'--preserve-entire-environment', u'workflow.cwl#main', u'cwl.input.yml'],
353                     'task.stdout': 'cwl.output.json'}]},
354                 'runtime_constraints': {
355                     'min_scratch_mb_per_node': 2048,
356                     'min_cores_per_node': 1,
357                     'docker_image': 'arvados/jobs',
358                     'min_ram_mb_per_node': 1024
359                 },
360                 'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'}),
361             filters=[['repository', '=', 'arvados'],
362                      ['script', '=', 'crunchrunner'],
363                      ['script_version', 'in git', 'a3f2cb186e437bfce0031b024b2157b73ed2717d'],
364                      ['docker_image_locator', 'in docker', 'arvados/jobs']],
365             find_or_create=True)
366
367         mockcollection().open().__enter__().write.assert_has_calls([mock.call(subwf)])
368         mockcollection().open().__enter__().write.assert_has_calls([mock.call(
369 '''{
370   "sleeptime": 5
371 }''')])
372
373     def test_default_work_api(self):
374         arvados_cwl.add_arv_hints()
375
376         api = mock.MagicMock()
377         api._rootDesc = copy.deepcopy(get_rootDesc())
378         del api._rootDesc.get('resources')['jobs']['methods']['create']
379         runner = arvados_cwl.ArvCwlRunner(api)
380         self.assertEqual(runner.work_api, 'containers')