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