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