Merge branch '10346-rearrange-api-docs' closes #10346
[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
168         arvjob.done({
169             "state": "Complete",
170             "output": "99999999999999999999999999999993+99",
171             "log": "99999999999999999999999999999994+99",
172             "uuid": "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
173         })
174
175         api.collections().list.assert_has_calls([
176             mock.call(),
177             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
178                           ['portable_data_hash', '=', '99999999999999999999999999999993+99'],
179                           ['name', '=', 'Output 9999999 of testjob']]),
180             mock.call().execute(num_retries=0),
181             mock.call(limit=1, filters=[['portable_data_hash', '=', '99999999999999999999999999999993+99']],
182                  select=['manifest_text']),
183             mock.call().execute(num_retries=0)])
184
185         api.collections().create.assert_called_with(
186             ensure_unique_name=True,
187             body={'portable_data_hash': '99999999999999999999999999999993+99',
188                   'manifest_text': 'XYZ',
189                   'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz',
190                   'name': 'Output 9999999 of testjob'})
191
192     @mock.patch("arvados.collection.CollectionReader")
193     def test_done_use_existing_collection(self, reader):
194         api = mock.MagicMock()
195
196         runner = mock.MagicMock()
197         runner.api = api
198         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
199         runner.num_retries = 0
200
201         reader().open.return_value = StringIO.StringIO(
202             """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
203 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
204 2016-11-02_23:12:18 c97qk-8i9sb-cryqw2blvzy4yaj 13358 0 stderr 2016/11/02 23:12:18 crunchrunner: $(task.keep)=/keep
205         """)
206
207         api.collections().list().execute.side_effect = ({"items": [{"uuid": "zzzzz-4zz18-zzzzzzzzzzzzzz2"}]},)
208
209         arvjob = arvados_cwl.ArvadosJob(runner)
210         arvjob.name = "testjob"
211         arvjob.builder = mock.MagicMock()
212         arvjob.output_callback = mock.MagicMock()
213         arvjob.collect_outputs = mock.MagicMock()
214
215         arvjob.done({
216             "state": "Complete",
217             "output": "99999999999999999999999999999993+99",
218             "log": "99999999999999999999999999999994+99",
219             "uuid": "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
220         })
221
222         api.collections().list.assert_has_calls([
223             mock.call(),
224             mock.call(filters=[['owner_uuid', '=', 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'],
225                                ['portable_data_hash', '=', '99999999999999999999999999999993+99'],
226                                ['name', '=', 'Output 9999999 of testjob']]),
227             mock.call().execute(num_retries=0)])
228
229         self.assertFalse(api.collections().create.called)
230
231
232 class TestWorkflow(unittest.TestCase):
233     # The test passes no builder.resources
234     # Hence the default resources will apply: {'cores': 1, 'ram': 1024, 'outdirSize': 1024, 'tmpdirSize': 1024}
235     @mock.patch("arvados.collection.Collection")
236     @mock.patch('arvados.commands.keepdocker.list_images_in_arv')
237     def test_run(self, list_images_in_arv, mockcollection):
238         arvados_cwl.add_arv_hints()
239
240         api = mock.MagicMock()
241         api._rootDesc = get_rootDesc()
242
243         runner = arvados_cwl.ArvCwlRunner(api)
244         self.assertEqual(runner.work_api, 'jobs')
245
246         list_images_in_arv.return_value = [["zzzzz-4zz18-zzzzzzzzzzzzzzz"]]
247         runner.api.collections().get().execute.return_vaulue = {"portable_data_hash": "99999999999999999999999999999993+99"}
248
249         runner.project_uuid = "zzzzz-8i9sb-zzzzzzzzzzzzzzz"
250         runner.ignore_docker_for_reuse = False
251         runner.num_retries = 0
252         document_loader, avsc_names, schema_metadata, metaschema_loader = cwltool.process.get_schema("v1.0")
253
254         tool, metadata = document_loader.resolve_ref("tests/wf/scatter2.cwl")
255         metadata["cwlVersion"] = tool["cwlVersion"]
256
257         mockcollection().portable_data_hash.return_value = "99999999999999999999999999999999+118"
258
259         make_fs_access=functools.partial(arvados_cwl.CollectionFsAccess, api_client=runner.api)
260         arvtool = arvados_cwl.ArvadosWorkflow(runner, tool, work_api="jobs", avsc_names=avsc_names,
261                                               basedir="", make_fs_access=make_fs_access, loader=document_loader,
262                                               makeTool=runner.arv_make_tool, metadata=metadata)
263         arvtool.formatgraph = None
264         it = arvtool.job({}, mock.MagicMock(), basedir="", make_fs_access=make_fs_access)
265         it.next().run()
266         it.next().run()
267
268         with open("tests/wf/scatter2_subwf.cwl") as f:
269             subwf = f.read()
270
271         runner.api.jobs().create.assert_called_with(
272             body={
273                 'minimum_script_version': '9e5b98e8f5f4727856b53447191f9c06e3da2ba6',
274                 'repository': 'arvados',
275                 'script_version': 'master',
276                 'script': 'crunchrunner',
277                 'script_parameters': {
278                     'tasks': [{'task.env': {
279                         'HOME': '$(task.outdir)',
280                         'TMPDIR': '$(task.tmpdir)'},
281                                'task.vwd': {
282                                    'workflow.cwl': '$(task.keep)/99999999999999999999999999999999+118/workflow.cwl',
283                                    'cwl.input.yml': '$(task.keep)/99999999999999999999999999999999+118/cwl.input.yml'
284                                },
285                     'command': [u'cwltool', u'--no-container', u'--move-outputs', u'--preserve-entire-environment', u'workflow.cwl#main', u'cwl.input.yml'],
286                     'task.stdout': 'cwl.output.json'}]},
287                 'runtime_constraints': {
288                     'min_scratch_mb_per_node': 2048,
289                     'min_cores_per_node': 1,
290                     'docker_image': 'arvados/jobs:'+arvados_cwl.__version__,
291                     'min_ram_mb_per_node': 1024
292                 },
293                 'owner_uuid': 'zzzzz-8i9sb-zzzzzzzzzzzzzzz'},
294             filters=[['repository', '=', 'arvados'],
295                      ['script', '=', 'crunchrunner'],
296                      ['script_version', 'in git', '9e5b98e8f5f4727856b53447191f9c06e3da2ba6'],
297                      ['docker_image_locator', 'in docker', 'arvados/jobs:'+arvados_cwl.__version__]],
298             find_or_create=True)
299
300         mockcollection().open().__enter__().write.assert_has_calls([mock.call(subwf)])
301         mockcollection().open().__enter__().write.assert_has_calls([mock.call('{sleeptime: 5}')])
302
303     def test_default_work_api(self):
304         arvados_cwl.add_arv_hints()
305
306         api = mock.MagicMock()
307         api._rootDesc = copy.deepcopy(get_rootDesc())
308         del api._rootDesc.get('resources')['jobs']['methods']['create']
309         runner = arvados_cwl.ArvCwlRunner(api)
310         self.assertEqual(runner.work_api, 'containers')