This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
/
test_basic.py
2881 lines (2604 loc) · 166 KB
/
test_basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import json
import logging
import math
import operator
import os
import re
import subprocess
import time
import unittest
import uuid
from collections import Counter
from datetime import datetime
from urllib.parse import urlparse
import dateutil.parser
import pytest
from pytz import utc
from retrying import retry
from tests.cook import reasons, mesos
from tests.cook import util
@pytest.mark.timeout(util.DEFAULT_TEST_TIMEOUT_SECS) # individual test timeout
class CookTest(util.CookTest):
@classmethod
def setUpClass(cls):
cls.cook_url = util.retrieve_cook_url()
util.init_cook_session(cls.cook_url)
def setUp(self):
self.cook_url = type(self).cook_url
self.mesos_url = util.retrieve_mesos_url()
self.logger = logging.getLogger(__name__)
self.cors_origin = os.getenv('COOK_ALLOWED_ORIGIN', 'http://cors.example.com')
def test_scheduler_info(self):
info = util.scheduler_info(self.cook_url)
info_details = json.dumps(info, sort_keys=True)
self.assertIn('authentication-scheme', info, info_details)
self.assertIn('commit', info, info_details)
self.assertIn('start-time', info, info_details)
self.assertIn('version', info, info_details)
self.assertEqual(len(info), 4, info_details)
try:
dateutil.parser.parse(info['start-time'])
except:
self.fail(f"Unable to parse start time: {info_details}")
def test_basic_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
job_uuid, resp = util.submit_job(self.cook_url, executor=job_executor_type)
self.assertEqual(resp.status_code, 201, msg=resp.content)
self.assertEqual(resp.content, str.encode(f"submitted jobs {job_uuid}"))
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
self.assertIn('success', [i['status'] for i in job['instances']], json.dumps(job, indent=2))
self.assertEqual(False, job['disable_mea_culpa_retries'])
instance = job['instances'][0]
if instance['executor'] == 'cook':
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
else:
self.logger.info(f'Exit code not checked because cook executor was not used for {instance}')
def test_output_url(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
job_uuid, resp = util.submit_job(self.cook_url, command='sleep 600', executor=job_executor_type)
try:
self.assertTrue(len(util.wait_for_output_url(self.cook_url, job_uuid)['output_url']) > 0)
job = util.query_jobs(self.cook_url, True, uuid=[job_uuid]).json()[0]
if util.should_expect_sandbox_directory_for_job(job):
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
finally:
util.kill_jobs(self.cook_url, [job_uuid], assert_response=False)
@unittest.skipUnless(util.docker_tests_enabled(),
'Requires setting the COOK_TEST_DOCKER_IMAGE environment variable')
def test_docker_fields(self):
docker_image = util.docker_image()
self.assertIsNotNone(docker_image)
container = {'type': 'docker',
'docker': {'image': docker_image,
'network': 'HOST',
'force-pull-image': False,
'parameters': [{'key': 'foo', 'value': 'bar'},
{'key': 'baz', 'value': 'qux'}]},
'volumes': [{'host-path': '/var/lib/abc'},
{'mode': 'RW',
'host-path': '/var/lib/def'},
{'host-path': '/var/lib/ghi',
'container-path': '/var/lib/jkl'},
{'mode': 'RW',
'host-path': '/var/lib/mno',
'container-path': '/var/lib/pqr'}]}
job_uuid, resp = util.submit_job(self.cook_url, container=container)
self.assertEqual(resp.status_code, 201, msg=resp.content)
self.assertEqual(resp.content, str.encode(f"submitted jobs {job_uuid}"))
job = util.load_job(self.cook_url, job_uuid)
container = job['container']
docker = container['docker']
volumes = container['volumes']
self.assertEqual('DOCKER', container['type'])
self.assertEqual(docker_image, docker['image'])
self.assertEqual('HOST', docker['network'])
self.assertEqual(False, docker['force-pull-image'])
self.assertEqual(2, len(docker['parameters']))
self.assertEqual('bar', next(p['value'] for p in docker['parameters'] if p['key'] == 'foo'))
self.assertEqual('qux', next(p['value'] for p in docker['parameters'] if p['key'] == 'baz'))
self.assertLessEqual(4, len(volumes))
self.assertIn({'host-path': '/var/lib/abc'}, volumes)
self.assertIn({'mode': 'RW',
'host-path': '/var/lib/def'}, volumes)
self.assertIn({'host-path': '/var/lib/ghi',
'container-path': '/var/lib/jkl'}, volumes)
self.assertIn({'mode': 'RW',
'host-path': '/var/lib/mno',
'container-path': '/var/lib/pqr'}, volumes)
def test_no_cook_executor_on_subsequent_instances(self):
settings = util.settings(self.cook_url)
retry_limit = util.get_in(settings, 'executor', 'retry-limit')
max_job_retries = util.get_in(settings, 'task-constraints', 'retry-limit')
if retry_limit is None or retry_limit is 0:
pytest.skip('Cook executor is not configured (retry-limit is None)')
elif retry_limit * 2 > max_job_retries:
pytest.skip(f'Cannot set max_retries to {retry_limit * 2}, configured maximum is {max_job_retries}')
else:
self.logger.debug(f'Cook executor retry limit is {retry_limit}')
num_hosts = len(util.get_mesos_state(self.mesos_url)['slaves'])
if retry_limit >= num_hosts:
pytest.skip(f'Skipping test as not enough agents to verify Mesos executor on subsequent '
f'instances (agents = {num_hosts}, retry limit = {retry_limit})')
# Should launch many instances
job_uuid, resp = util.submit_job(self.cook_url, command='exit 1', max_retries=retry_limit * 2)
self.assertEqual(resp.status_code, 201, msg=resp.content)
try:
# Try to get more than retry_limit instances
util.wait_until(lambda: util.load_job(self.cook_url, job_uuid),
lambda job: len(job['instances']) > retry_limit)
except BaseException as e:
self.logger.debug(f"Didn't reach desired instance count: {e}")
job = util.load_job(self.cook_url, job_uuid)
self.logger.debug(f"Num job instances is {len(job['instances'])}")
job_instances = sorted(job['instances'], key=operator.itemgetter('start_time'))
for i, job_instance in enumerate(job_instances):
message = f'Trailing instance {i}: {json.dumps(job_instance, sort_keys=True)}'
self.assertNotEqual('success', job_instance['status'], message)
if retry_limit >= len(job_instances):
self.logger.debug('Not enough instances to verify Mesos executor on subsequent instances')
else:
later_job_instances = job_instances[retry_limit:]
for i, job_instance in enumerate(later_job_instances):
message = f'Trailing instance {i}: {json.dumps(job_instance, sort_keys=True)}'
self.assertEqual('mesos', job_instance['executor'], message)
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_disable_mea_culpa(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
self.assertEqual('cook', job_executor_type)
uuid, resp = util.submit_job(self.cook_url, command='sleep 30', env={'EXECUTOR_TEST_EXIT': '1'},
disable_mea_culpa_retries=True, executor=job_executor_type)
try:
instance = util.wait_for_instance(self.cook_url, uuid)
self.assertEqual('cook', instance['executor'])
job = util.wait_for_job(self.cook_url, uuid, 'completed')
msg = json.dumps(job, indent=2)
self.assertEqual(job['state'], 'failed', msg)
self.assertEqual(job['retries_remaining'], 0, msg)
instances = job['instances']
instance = instances[0]
self.assertEqual(1, len(instances), msg)
self.assertEqual('Mesos executor terminated', instance['reason_string'], msg)
self.assertTrue(instance['reason_mea_culpa'], msg)
finally:
util.kill_jobs(self.cook_url, [uuid])
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_mea_culpa_retries(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
self.assertEqual('cook', job_executor_type)
uuid, resp = util.submit_job(self.cook_url, command='sleep 30', env={'EXECUTOR_TEST_EXIT': '1'}, executor=job_executor_type)
try:
instance = util.wait_for_instance(self.cook_url, uuid)
self.assertEqual('cook', instance['executor'])
job = util.wait_until(lambda: util.load_job(self.cook_url, uuid),
lambda job: len(job['instances']) > 1 and any(
[i['status'] == 'failed' for i in job['instances']]))
self.assertEqual(job['retries_remaining'], 1, json.dumps(job, indent=2))
failed_instances = [i for i in job['instances'] if i['status'] == 'failed']
self.assertTrue(len(failed_instances) != 0, json.dumps(job, indent=2))
for instance in failed_instances:
msg = json.dumps(instance, indent=2)
self.assertEqual('failed', instance['status'], msg)
self.assertEqual('Mesos executor terminated', instance['reason_string'], msg)
self.assertTrue(instance['reason_mea_culpa'], msg)
finally:
util.kill_jobs(self.cook_url, [uuid])
def test_compute_cluster(self):
settings_dict = util.settings(self.cook_url)
# For now, we only have one compute cluster. This could be wrong with future
# refactors, but for now, this is the only compute cluster we have, so we should
# expect it.
expected_compute_cluster = settings_dict['compute-clusters'][0]['config']['compute-cluster-name']
expected_mesos_framework = settings_dict['compute-clusters'][0]['config']['framework-id']
job_uuid, resp = util.submit_job(self.cook_url)
try:
self.assertIsNotNone(expected_compute_cluster)
self.assertEqual(resp.status_code, 201, msg=resp.content)
instance = util.wait_for_instance(self.cook_url, job_uuid)
message = repr(instance)
self.assertIsNotNone(instance['compute-cluster'], message)
self.assertEqual('mesos', instance['compute-cluster']['type'], message)
self.assertEqual(expected_compute_cluster, instance['compute-cluster']['name'], message)
self.assertEqual(expected_mesos_framework, instance['compute-cluster']['mesos']['framework-id'], message)
finally:
util.kill_jobs(self.cook_url, [job_uuid])
def test_executor_flag(self):
job_uuid, resp = util.submit_job(self.cook_url, executor='cook')
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.load_job(self.cook_url, job_uuid)
self.assertEqual('cook', job['executor'])
job_uuid, resp = util.submit_job(self.cook_url, executor='mesos')
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.load_job(self.cook_url, job_uuid)
self.assertEqual('mesos', job['executor'])
def test_job_environment_cook_job_and_instance_uuid_only(self):
command = 'echo "Job environment:" && env && echo "Checking environment variables..." && ' \
'if [ ${#COOK_JOB_GROUP_UUID} -ne 0 ]; then echo "COOK_JOB_GROUP_UUID env is present"; exit 1; ' \
'else echo "COOK_JOB_GROUP_UUID env is missing as expected"; fi && ' \
'if [ ${#COOK_JOB_UUID} -eq 0 ]; then echo "COOK_JOB_UUID env is missing"; exit 1; ' \
'else echo "COOK_JOB_UUID env is present as expected"; fi && ' \
'if [ ${#COOK_INSTANCE_UUID} -eq 0 ]; then echo "COOK_INSTANCE_UUID env is missing"; exit 1; ' \
'else echo "COOK_INSTANCE_UUID env is present as expected"; fi'
job_uuid, resp = util.submit_job(self.cook_url, command=command)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
self.assertEqual(1, len(job['instances']))
message = json.dumps(job['instances'][0], sort_keys=True)
self.assertEqual('success', job['instances'][0]['status'], message)
def test_job_environment_cook_job_and_instance_and_group_uuid(self):
command = 'echo "Job environment:" && env && echo "Checking environment variables..." && ' \
'if [ ${#COOK_JOB_GROUP_UUID} -eq 0 ]; then echo "COOK_JOB_GROUP_UUID env is missing"; exit 1; ' \
'else echo "COOK_JOB_GROUP_UUID env is present as expected"; fi && ' \
'if [ ${#COOK_JOB_UUID} -eq 0 ]; then echo "COOK_JOB_UUID env is missing"; exit 1; ' \
'else echo "COOK_JOB_UUID env is present as expected"; fi && ' \
'if [ ${#COOK_INSTANCE_UUID} -eq 0 ]; then echo "COOK_INSTANCE_UUID env is missing"; exit 1; ' \
'else echo "COOK_INSTANCE_UUID env is present as expected"; fi'
group_uuid = str(uuid.uuid4())
job_uuid, resp = util.submit_job(self.cook_url, command=command, group=group_uuid)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
self.assertEqual(1, len(job['instances']))
message = json.dumps(job['instances'][0], sort_keys=True)
self.assertEqual('success', job['instances'][0]['status'], message)
def test_failing_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
job_uuid, resp = util.submit_job(self.cook_url, command='exit 1', executor=job_executor_type)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
self.assertEqual(1, len(job['instances']), job['instances'])
instance = job['instances'][0]
message = json.dumps(instance, sort_keys=True)
self.assertEqual('failed', instance['status'], message)
self.assertFalse(instance['reason_mea_culpa'], message)
if util.should_expect_sandbox_directory(instance):
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
if instance['executor'] == 'cook':
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(1, instance['exit_code'], message)
else:
self.logger.info(f'Exit code not checked because cook executor was not used for {instance}')
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_progress_update_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
progress_file_env = util.retrieve_progress_file_env(self.cook_url)
line = util.progress_line(self.cook_url, 25, f'Twenty-five percent in ${{{progress_file_env}}}', True)
command = f'{line}; sleep 1; exit 0'
job_uuid, resp = util.submit_job(self.cook_url, command=command,
env={progress_file_env: 'progress.txt'},
executor=job_executor_type, max_runtime=60000)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
message = json.dumps(job['instances'], sort_keys=True)
self.assertIn('success', (i['status'] for i in job['instances']), message)
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
self.assertEqual('cook', instance['executor'])
util.sleep_for_publish_interval(self.cook_url)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
self.assertEqual(25, instance['progress'], message)
self.assertEqual('Twenty-five percent in progress.txt', instance['progress_message'], message)
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_configurable_progress_update_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
command = 'echo "message: 25 Twenty-five percent" > progress_file.txt; sleep 1; exit 0'
job_uuid, resp = util.submit_job(self.cook_url, command=command, executor=job_executor_type, max_runtime=60000,
progress_output_file='progress_file.txt',
progress_regex_string='message: (\d*) (.*)')
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
message = json.dumps(job, sort_keys=True)
self.assertEqual('progress_file.txt', job['progress_output_file'], message)
self.assertEqual('message: (\d*) (.*)', job['progress_regex_string'], message)
self.assertEqual('success', job['state'], message)
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid, 'success')
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
self.assertEqual('cook', instance['executor'])
util.sleep_for_publish_interval(self.cook_url)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
self.assertEqual(25, instance['progress'], message)
self.assertEqual('Twenty-five percent', instance['progress_message'], message)
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_multiple_progress_updates_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
line_1 = util.progress_line(self.cook_url, 25, 'Twenty-five percent', True)
line_2 = util.progress_line(self.cook_url, 50, 'Fifty percent', True)
line_3 = util.progress_line(self.cook_url, '', 'Sixty percent invalid format', True)
line_4 = util.progress_line(self.cook_url, 75, 'Seventy-five percent', True)
line_5 = util.progress_line(self.cook_url, '', 'Eighty percent invalid format', True)
command = f'{line_1} && sleep 2 && {line_2} && sleep 2 && ' \
f'{line_3} && sleep 2 && {line_4} && sleep 2 && ' \
f'{line_5} && sleep 2 && echo "Done" && sleep 10 && exit 0'
job_uuid, resp = util.submit_job(self.cook_url, command=command, executor=job_executor_type, max_runtime=60000)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
message = json.dumps(job, sort_keys=True)
self.assertEqual('success', job['state'], message)
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid, 'success')
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
self.assertEqual('cook', instance['executor'])
util.sleep_for_publish_interval(self.cook_url)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
self.assertEqual(75, instance['progress'], message)
self.assertEqual('Seventy-five percent', instance['progress_message'], message)
@unittest.skipUnless(util.is_cook_executor_in_use() and not (util.docker_tests_enabled() and util.continuous_integration()),
'Test assumes the Cook Executor is in use. Fails on travis with docker')
def test_multiple_progress_updates_submit_stdout(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
line_1 = util.progress_line(self.cook_url, 25, 'Twenty-five percent')
line_2 = util.progress_line(self.cook_url, 50, 'Fifty percent')
line_3 = util.progress_line(self.cook_url, '', 'Sixty percent invalid format')
line_4 = util.progress_line(self.cook_url, 75, 'Seventy-five percent')
line_5 = util.progress_line(self.cook_url, '', 'Eighty percent invalid format')
command = f'echo "{line_1}" && sleep 2 && echo "{line_2}" && sleep 2 && ' \
f'echo "{line_3}" && sleep 2 && echo "{line_4}" && sleep 2 && ' \
f'echo "{line_5}" && sleep 2 && echo "Done" && exit 0'
job_uuid, resp = util.submit_job(self.cook_url, command=command, executor=job_executor_type, max_runtime=60000)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
message = json.dumps(job, sort_keys=True)
self.assertEqual('success', job['state'], message)
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid, 'success')
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
self.assertEqual('cook', instance['executor'])
util.sleep_for_publish_interval(self.cook_url)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
self.assertEqual(75, instance['progress'], message)
self.assertEqual('Seventy-five percent', instance['progress_message'], message)
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_multiple_rapid_progress_updates_submit(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
def progress_string(a):
return util.progress_line(self.cook_url, a, f'{a}%', True)
items = list(range(1, 100, 4)) + list(range(99, 40, -4)) + list(range(40, 81, 2))
command = ''.join([f'{progress_string(a)} && ' for a in items]) + 'echo "Done" && sleep 10 && exit 0'
job_uuid, resp = util.submit_job(self.cook_url, command=command, executor=job_executor_type, max_runtime=60000)
self.assertEqual(201, resp.status_code, msg=resp.content)
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
message = json.dumps(job, sort_keys=True)
self.assertEqual('success', job['state'], message)
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid, 'success')
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
self.assertEqual('cook', instance['executor'])
util.sleep_for_publish_interval(self.cook_url)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertEqual(0, instance['exit_code'], message)
self.assertEqual(80, instance['progress'], message)
self.assertEqual('80%', instance['progress_message'], message)
def test_max_runtime_exceeded(self):
job_executor_type = util.get_job_executor_type(self.cook_url)
settings_timeout_interval_minutes = util.get_in(util.settings(self.cook_url), 'task-constraints',
'timeout-interval-minutes')
# the value needs to be a little more than 2 times settings_timeout_interval_minutes to allow
# at least two runs of the lingering task killer
job_sleep_seconds = (2 * settings_timeout_interval_minutes * 60) + 15
job_sleep_ms = job_sleep_seconds * 1000
max_runtime_ms = 5000
assert max_runtime_ms < job_sleep_ms
# schedule a job that will go over its max_runtime time limit
job_uuid, resp = util.submit_job(self.cook_url,
command=f'sleep {job_sleep_seconds}',
executor=job_executor_type, max_runtime=max_runtime_ms)
try:
self.assertEqual(201, resp.status_code, msg=resp.content)
# We wait for the job to start running, and only then start waiting for the max-runtime timeout,
# otherwise we could get a false-negative on wait-for-job 'completed' because of a scheduling delay.
# We wait for the 'end_time' attribute separately because there is another small delay
# between the job being killed and that attribute being set.
# Having three separate waits also disambiguates the root cause of a wait-timeout failure.
util.wait_for_job(self.cook_url, job_uuid, 'running')
util.wait_for_job(self.cook_url, job_uuid, 'completed', job_sleep_ms)
job = util.wait_for_end_time(self.cook_url, job_uuid)
job_details = f"Job details: {json.dumps(job, sort_keys=True)}"
self.assertEqual(1, len(job['instances']), job_details)
instance = job['instances'][0]
# did the job fail as expected?
self.assertEqual('failed', instance['status'], job_details)
# We currently have three possible reason codes that we can observe
# due to a race in the scheduler. See issue #515 on GitHub for more details.
allowed_reasons = [
# observed status update from when Cook killed the job
reasons.MAX_RUNTIME_EXCEEDED,
# observed status update received when exit code appears
reasons.CMD_NON_ZERO_EXIT,
# cook killed the job during setup, so the executor had an error
reasons.EXECUTOR_UNREGISTERED]
self.assertIn(instance['reason_code'], allowed_reasons, job_details)
# was the actual running time consistent with running over time and being killed?
actual_running_time_ms = instance['end_time'] - instance['start_time']
self.assertGreater(actual_running_time_ms, max_runtime_ms, job_details)
self.assertGreater(job_sleep_ms, actual_running_time_ms, job_details)
# verify additional fields set when the cook executor is used
if instance['executor'] == 'cook':
instance = util.wait_for_sandbox_directory(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertIsNotNone(instance['output_url'], message)
self.assertIsNotNone(instance['sandbox_directory'], message)
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
message = json.dumps(instance, sort_keys=True)
self.assertNotEqual(0, instance['exit_code'], message)
else:
self.logger.info(f'Exit code not checked because cook executor was not used for {instance}')
finally:
util.kill_jobs(self.cook_url, [job_uuid])
@staticmethod
def memory_limit_python_command():
"""Generates a python command that incrementally allocates large strings that cause the python process to
request more memory than it is allocated."""
command = 'python3 -c ' \
'"import resource; ' \
' import sys; ' \
' sys.stdout.write(\'Starting...\\n\'); ' \
' one_mb = 1024 * 1024; ' \
' [sys.stdout.write(' \
' \'progress: {} iter-{}.{}-mem-{}mB-{}\\n\'.format(' \
' i, ' \
' i, ' \
' len(\' \' * (i * 50 * one_mb)), ' \
' int(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / one_mb), ' \
' sys.stdout.flush())) ' \
' for i in range(100)]; ' \
' sys.stdout.write(\'Done.\\n\'); "'
return command
@staticmethod
def memory_limit_script_command():
"""Generates a script command that incrementally allocates large strings that cause the process to
request more memory than it is allocated."""
command = 'random_string() { ' \
' base64 /dev/urandom | tr -d \'/+\' | dd bs=1048576 count=1024 2>/dev/null; ' \
'}; ' \
'R="$(random_string)"; ' \
'V=""; ' \
'echo "Length of R is ${#R}" ; ' \
'for p in `seq 0 99`; do ' \
' for i in `seq 1 10`; do ' \
' V="${V}.${R}"; ' \
' echo "progress: ${p} ${p}-percent iter-${i}" ; ' \
' done ; ' \
' echo "Length of V is ${#V}" ; ' \
'done'
return command
def memory_limit_exceeded_helper(self, command, executor_type):
"""Given a command that needs more memory than it is allocated, when the command is submitted to cook,
the job should be killed by Mesos as it exceeds its memory limits."""
job_uuid, resp = util.submit_job(self.cook_url, command=command, executor=executor_type, mem=128)
self.assertEqual(201, resp.status_code, msg=resp.content)
instance = util.wait_for_instance(self.cook_url, job_uuid)
self.logger.debug('instance: %s' % instance)
job = instance['parent']
try:
job = util.wait_for_job(self.cook_url, job_uuid, 'completed')
job_details = f"Job details: {json.dumps(job, sort_keys=True)}"
self.assertEqual('failed', job['state'], job_details)
self.assertLessEqual(1, len(job['instances']), job_details)
instance = job['instances'][-1]
instance_details = json.dumps(instance, sort_keys=True)
self.logger.debug('instance: %s' % instance)
# did the job fail as expected?
self.assertEqual(executor_type, instance['executor'], instance_details)
self.assertEqual('failed', instance['status'], instance_details)
# Mesos chooses to kill the task (exit code 137) or kill the executor with a memory limit exceeded message
if 2002 == instance['reason_code']:
self.assertEqual('Container memory limit exceeded', instance['reason_string'], instance_details)
elif 99003 == instance['reason_code']:
# If the command was killed, it will have exited with either:
# 137 (Fatal error signal of 128 + SIGKILL)
# -9 (Negative return values are the signal number which was used to kill the process)
self.assertEqual('Command exited non-zero', instance['reason_string'], instance_details)
if executor_type == 'cook':
instance = util.wait_for_exit_code(self.cook_url, job_uuid)
self.logger.info(f'Exit code: {instance["exit_code"]}')
self.assertIn(instance['exit_code'], [137, -9], instance_details)
else:
self.fail('Unknown reason code {}, details {}'.format(instance['reason_code'], instance_details))
finally:
mesos.dump_sandbox_files(util.session, instance, job)
util.kill_jobs(self.cook_url, [job_uuid])
@pytest.mark.memlimit
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_memory_limit_exceeded_cook_python(self):
command = self.memory_limit_python_command()
self.memory_limit_exceeded_helper(command, 'cook')
@pytest.mark.memlimit
def test_memory_limit_exceeded_mesos_python(self):
command = self.memory_limit_python_command()
self.memory_limit_exceeded_helper(command, 'mesos')
@pytest.mark.memlimit
@unittest.skipUnless(util.is_cook_executor_in_use(), 'Test assumes the Cook Executor is in use')
def test_memory_limit_exceeded_cook_script(self):
command = self.memory_limit_script_command()
self.memory_limit_exceeded_helper(command, 'cook')
@pytest.mark.memlimit
def test_memory_limit_exceeded_mesos_script(self):
command = self.memory_limit_script_command()
self.memory_limit_exceeded_helper(command, 'mesos')
def test_get_job(self):
# schedule a job
job_spec = util.minimal_job()
resp = util.session.post('%s/rawscheduler' % self.cook_url, json={'jobs': [job_spec]})
self.assertEqual(201, resp.status_code, msg=resp.content)
# query for the same job & ensure the response has what it's supposed to have
job = util.wait_for_job(self.cook_url, job_spec['uuid'], 'completed')
self.assertEqual(job_spec['mem'], job['mem'])
self.assertEqual(job_spec['max_retries'], job['max_retries'])
self.assertEqual(job_spec['name'], job['name'])
self.assertEqual(job_spec['priority'], job['priority'])
self.assertEqual(job_spec['uuid'], job['uuid'])
self.assertEqual(job_spec['cpus'], job['cpus'])
self.assertTrue('labels' in job)
self.assertEqual(9223372036854775807, job['max_runtime'])
# 9223372036854775807 is MAX_LONG(ish), the default value for max_runtime
self.assertEqual('success', job['state'])
self.assertTrue('env' in job)
self.assertTrue('framework_id' in job)
self.assertTrue('ports' in job)
self.assertTrue('instances' in job)
self.assertEqual('completed', job['status'])
self.assertTrue(isinstance(job['submit_time'], int))
self.assertTrue('uris' in job)
self.assertTrue('retries_remaining' in job)
instance = job['instances'][0]
self.assertTrue(isinstance(instance['start_time'], int))
self.assertTrue('executor_id' in instance)
self.assertTrue('hostname' in instance)
self.assertTrue('slave_id' in instance)
self.assertTrue(isinstance(instance['preempted'], bool))
self.assertTrue(isinstance(instance['end_time'], int))
self.assertTrue(isinstance(instance['backfilled'], bool))
self.assertTrue('ports' in instance)
self.assertEqual('completed', job['status'])
self.assertTrue('task_id' in instance)
def determine_user(self):
job_uuid, resp = util.submit_job(self.cook_url)
self.assertEqual(resp.status_code, 201)
return util.get_user(self.cook_url, job_uuid)
def test_list_jobs_by_state(self):
# schedule a bunch of jobs in hopes of getting jobs into different statuses
job_specs = [util.minimal_job(command=f"sleep {i}") for i in range(1, 20)]
try:
_, resp = util.submit_jobs(self.cook_url, job_specs)
self.assertEqual(resp.status_code, 201)
# let some jobs get scheduled
time.sleep(10)
user = self.determine_user()
for state in ['waiting', 'running', 'completed']:
resp = util.list_jobs(self.cook_url, user=user, state=state)
self.assertEqual(200, resp.status_code, msg=resp.content)
jobs = resp.json()
for job in jobs:
self.assertEquals(state, job['status'])
finally:
util.kill_jobs(self.cook_url, job_specs)
def test_list_jobs_by_time(self):
# schedule two jobs with different submit times
job_specs = [util.minimal_job() for _ in range(2)]
request_body = {'jobs': [job_specs[0]]}
resp = util.session.post('%s/rawscheduler' % self.cook_url, json=request_body)
self.assertEqual(resp.status_code, 201)
time.sleep(5)
request_body = {'jobs': [job_specs[1]]}
resp = util.session.post('%s/rawscheduler' % self.cook_url, json=request_body)
self.assertEqual(resp.status_code, 201)
submit_times = [util.load_job(self.cook_url, job_spec['uuid'])['submit_time'] for job_spec in job_specs]
user = self.determine_user()
# start-ms and end-ms are exclusive
# query where start-ms and end-ms are the submit times of jobs 1 & 2 respectively
resp = util.list_jobs(self.cook_url, user=user, state='waiting+running+completed',
start_ms=submit_times[0] - 1, end_ms=submit_times[1] + 1)
self.assertEqual(200, resp.status_code, msg=resp.content)
jobs = resp.json()
self.assertTrue(util.contains_job_uuid(jobs, job_specs[0]['uuid']))
self.assertTrue(util.contains_job_uuid(jobs, job_specs[1]['uuid']))
# query just for job 1
resp = util.list_jobs(self.cook_url, user=user, state='waiting+running+completed',
start_ms=submit_times[0] - 1, end_ms=submit_times[1])
self.assertEqual(200, resp.status_code, msg=resp.content)
jobs = resp.json()
self.assertTrue(util.contains_job_uuid(jobs, job_specs[0]['uuid']))
self.assertFalse(util.contains_job_uuid(jobs, job_specs[1]['uuid']))
# query just for job 2
resp = util.list_jobs(self.cook_url, user=user, state='waiting+running+completed',
start_ms=submit_times[0] + 1, end_ms=submit_times[1] + 1)
self.assertEqual(200, resp.status_code, msg=resp.content)
jobs = resp.json()
self.assertFalse(util.contains_job_uuid(jobs, job_specs[0]['uuid']))
self.assertTrue(util.contains_job_uuid(jobs, job_specs[1]['uuid']))
# query for neither
resp = util.list_jobs(self.cook_url, user=user, state='waiting+running+completed',
start_ms=submit_times[0] + 1, end_ms=submit_times[1])
self.assertEqual(200, resp.status_code, msg=resp.content)
jobs = resp.json()
self.assertFalse(util.contains_job_uuid(jobs, job_specs[0]['uuid']))
self.assertFalse(util.contains_job_uuid(jobs, job_specs[1]['uuid']))
def test_list_jobs_by_completion_state(self):
name = str(uuid.uuid4())
job_uuid_1, resp = util.submit_job(self.cook_url, command='true', name=name, max_retries=2)
self.assertEqual(201, resp.status_code)
job_uuid_2, resp = util.submit_job(self.cook_url, command='false', name=name)
self.assertEqual(201, resp.status_code)
job_uuid_3, resp = util.submit_job(self.cook_url, command='true', name=name, max_retries=2)
self.assertEqual(201, resp.status_code)
user = self.determine_user()
start = util.wait_for_job(self.cook_url, job_uuid_1, 'completed')['submit_time']
end = util.wait_for_job(self.cook_url, job_uuid_2, 'completed')['submit_time'] + 1
# Test the various combinations of states
resp = util.list_jobs(self.cook_url, user=user, state='completed', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='success+failed', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='completed+success+failed', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='completed+failed', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='completed+success', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='success', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='running+waiting+success', start_ms=start, end_ms=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='failed', start_ms=start, end_ms=end)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.list_jobs(self.cook_url, user=user, state='running+waiting+failed', start_ms=start, end_ms=end)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
# Test with failed and a specified limit
resp = util.list_jobs(self.cook_url, user=user, state='failed', start_ms=start, end_ms=end, limit=1, name=name)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
# Test with success and a specified limit
start = end - 1
end = util.wait_for_job(self.cook_url, job_uuid_3, 'completed')['submit_time'] + 1
resp = util.list_jobs(self.cook_url, user=user, state='success', start_ms=start, end_ms=end, limit=1, name=name)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
def test_list_jobs_by_completion_state_with_jobs_endpoint(self):
name = str(uuid.uuid4())
job_uuid_1, resp = util.submit_job(self.cook_url, command='true', name=name, max_retries=2)
self.assertEqual(201, resp.status_code)
job_uuid_2, resp = util.submit_job(self.cook_url, command='false', name=name)
self.assertEqual(201, resp.status_code)
job_uuid_3, resp = util.submit_job(self.cook_url, command='true', name=name, max_retries=2)
self.assertEqual(201, resp.status_code)
user = self.determine_user()
start = util.wait_for_job(self.cook_url, job_uuid_1, 'completed')['submit_time']
end = util.wait_for_job(self.cook_url, job_uuid_2, 'completed')['submit_time'] + 1
# Assert the job states
job_1 = util.load_job(self.cook_url, job_uuid_1)
job_2 = util.load_job(self.cook_url, job_uuid_2)
self.logger.info(job_1)
self.logger.info(job_2)
self.assertEqual('success', job_1['state'])
self.assertEqual('failed', job_2['state'])
# Test the various combinations of states
resp = util.jobs(self.cook_url, user=user, state='completed', start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['success', 'failed'], start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['completed', 'success', 'failed'], start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['completed', 'failed'], start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['completed', 'success'], start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state='success', start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['running', 'waiting', 'success'], start=start, end=end)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state='failed', start=start, end=end)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
resp = util.jobs(self.cook_url, user=user, state=['running', 'waiting', 'failed'], start=start, end=end)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
# Test with failed and a specified limit
resp = util.jobs(self.cook_url, user=user, state='failed', start=start, end=end, limit=1, name=name)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
# Test with success and a specified limit
start = end - 1
job_3 = util.wait_for_job(self.cook_url, job_uuid_3, 'completed')
self.logger.info(job_3)
self.assertEqual('success', job_3['state'])
end = job_3['submit_time'] + 1
resp = util.jobs(self.cook_url, user=user, state='success', start=start, end=end, limit=1, name=name)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
def test_list_jobs_by_name(self):
job_uuid_1, resp = util.submit_job(self.cook_url, name='foo-bar-baz_qux')
self.assertEqual(201, resp.status_code)
job_uuid_2, resp = util.submit_job(self.cook_url, name='')
self.assertEqual(201, resp.status_code)
job_uuid_3, resp = util.submit_job(self.cook_url, name='.')
self.assertEqual(201, resp.status_code)
job_uuid_4, resp = util.submit_job(self.cook_url, name='foo-bar-baz__')
self.assertEqual(201, resp.status_code)
job_uuid_5, resp = util.submit_job(self.cook_url, name='ff')
self.assertEqual(201, resp.status_code)
job_uuid_6, resp = util.submit_job(self.cook_url, name='a')
self.assertEqual(201, resp.status_code)
user = self.determine_user()
any_state = 'running+waiting+completed'
resp = util.list_jobs(self.cook_url, user=user, state=any_state)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='*')
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='foo-bar-baz_qux')
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='foo-bar-baz_*')
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='f*')
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='*.*')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='foo-bar-baz__*')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='ff*')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='a*')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertTrue(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
resp = util.list_jobs(self.cook_url, user=user, state=any_state, name='a-z0-9_-')
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_1), job_uuid_1)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_2), job_uuid_2)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_3), job_uuid_3)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_4), job_uuid_4)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_5), job_uuid_5)
self.assertFalse(util.contains_job_uuid(resp.json(), job_uuid_6), job_uuid_6)
def test_list_jobs_by_pool(self):
# Submit two jobs to each active pool -- one that will be
# running or waiting for a while, and another that will complete
jobs = []
name = str(uuid.uuid4())
pools, _ = util.active_pools(self.cook_url)
start = util.current_milli_time()
sleep_command = 'sleep 600'
for pool in pools:
pool_name = pool['name']
job_uuid, resp = util.submit_job(self.cook_url, pool=pool_name, name=name, command=sleep_command)
self.assertEqual(201, resp.status_code)
jobs.append(util.load_job(self.cook_url, job_uuid))
job_uuid, resp = util.submit_job(self.cook_url, pool=pool_name, name=name, command='exit 0')
self.assertEqual(201, resp.status_code)
jobs.append(util.wait_for_job(self.cook_url, job_uuid, 'completed'))
end = util.current_milli_time() + 1
try:
completed = ['completed']
active = ['running', 'waiting']
user = self.determine_user()
# List jobs for each pool
for pool in pools:
pool_name = pool['name']
# List running / waiting
job_uuid = next(j['uuid'] for j in jobs if j['pool'] == pool_name and j['command'] == sleep_command)
resp = util.jobs(self.cook_url, user=user, state=active,
start=start, end=end, name=name, pool=pool_name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(1, len(resp.json()))
self.assertEqual(job_uuid, resp.json()[0]['uuid'])
resp = util.jobs(self.cook_url, headers={'x-cook-pool': pool_name}, user=user,
state=active, start=start, end=end, name=name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(1, len(resp.json()))
self.assertEqual(job_uuid, resp.json()[0]['uuid'])
# List completed
job_uuid = next(j['uuid'] for j in jobs if j['pool'] == pool_name and j['command'] == 'exit 0')
resp = util.jobs(self.cook_url, user=user, state=completed,
start=start, end=end, name=name, pool=pool_name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(1, len(resp.json()), json.dumps(resp.json(), indent=2))
self.assertEqual(job_uuid, resp.json()[0]['uuid'])
resp = util.jobs(self.cook_url, headers={'x-cook-pool': pool_name}, user=user,
state=completed, start=start, end=end, name=name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(1, len(resp.json()), json.dumps(resp.json(), indent=2))
self.assertEqual(job_uuid, resp.json()[0]['uuid'])
# List all states
job_uuids = [j['uuid'] for j in jobs if j['pool'] == pool_name]
resp = util.jobs(self.cook_url, user=user, state=completed + active,
start=start, end=end, name=name, pool=pool_name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(2, len(resp.json()), json.dumps(resp.json(), indent=2))
self.assertEqual(sorted(job_uuids), sorted(j['uuid'] for j in resp.json()))
resp = util.jobs(self.cook_url, headers={'x-cook-pool': pool_name}, user=user,
state=completed + active, start=start, end=end, name=name)
self.assertEqual(200, resp.status_code, resp.text)
self.assertEqual(2, len(resp.json()), json.dumps(resp.json(), indent=2))
self.assertEqual(sorted(job_uuids), sorted(j['uuid'] for j in resp.json()))
if len(pools) > 0:
# List running / waiting with no pool should return all running / waiting
resp = util.jobs(self.cook_url, user=user, state=active, start=start, end=end, name=name)
job_uuids = [j['uuid'] for j in jobs if j['command'] == sleep_command]
self.assertEqual(200, resp.status_code)
self.assertEqual(sorted(job_uuids), sorted([j['uuid'] for j in resp.json()]))
# List completed with no pool should return all completed
resp = util.jobs(self.cook_url, user=user, state=completed, start=start, end=end, name=name)
job_uuids = [j['uuid'] for j in jobs if j['command'] == 'exit 0']
self.assertEqual(200, resp.status_code)