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