This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
test_executor.py
1014 lines (819 loc) · 49.2 KB
/
test_executor.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 errno
import functools
import json
import logging
import subprocess
import time
import unittest
from unittest.mock import patch
from threading import Event, Timer
import os
import pymesos as pm
import pytest
import cook
import cook.config as cc
import cook.executor as ce
import cook.subprocess as cs
import tests.utils as tu
def sleep_and_set_stop_signal_task(stop_signal, wait_seconds):
"""Waits for wait_seconds seconds before setting stop_signal."""
timer = Timer(wait_seconds, stop_signal.set)
timer.daemon = True
timer.start()
def make_task_env(env_dict):
environment = []
for (key, value) in env_dict.items():
environment.append({'type': 'VALUE', 'name': key, 'value': str(value)})
return {'executor': {'command': {'environment': {'variables': environment}}}}
class ExecutorTest(unittest.TestCase):
def test_get_task_id(self):
task_id = tu.get_random_task_id()
task = {'task_id': {'value': task_id}}
self.assertEqual(task_id, ce.get_task_id(task))
def test_get_task_id_missing_value(self):
with self.assertRaises(KeyError):
ce.get_task_id({'task_id': {}})
def test_get_task_id_empty_dictionary(self):
with self.assertRaises(KeyError):
ce.get_task_id({})
def test_create_status_running(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
status_updater = ce.StatusUpdater(driver, task_id)
actual_status = status_updater.create_status(cook.TASK_RUNNING)
expected_status = {'task_id': {'value': task_id},
'state': cook.TASK_RUNNING}
tu.assert_status(self, expected_status, actual_status)
def test_update_status(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
status_updater = ce.StatusUpdater(driver, task_id)
task_state = "TEST_TASK_STATE"
self.assertTrue(status_updater.update_status(cook.TASK_STARTING))
self.assertTrue(status_updater.update_status(task_state))
self.assertTrue(status_updater.update_status(cook.TASK_RUNNING, reason='Running'))
self.assertTrue(status_updater.update_status(cook.TASK_FAILED, reason='Termination'))
self.assertFalse(status_updater.update_status(cook.TASK_FINISHED))
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': task_state},
{'task_id': {'value': task_id}, 'reason': 'Running', 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'reason': 'Termination', 'state': cook.TASK_FAILED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
def test_send_message(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
expected_message = {'task-id': task_id, 'message': 'test-message'}
result = ce.send_message(driver, tu.fake_os_error_handler, expected_message)
self.assertTrue(result)
self.assertEqual(1, len(driver.messages))
actual_encoded_message = driver.messages[0]
tu.assert_message(self, expected_message, actual_encoded_message)
def test_send_message_handles_os_error_memory(self):
exception_handler_calls = []
exception_handler = functools.partial(tu.store_exception_handler, exception_handler_calls)
exception = OSError(errno.ENOMEM, 'Out of memory')
driver = tu.ErrorMesosExecutorDriver(exception)
task_id = tu.get_random_task_id()
message = {'task-id': task_id, 'message': 'test-message'}
result = ce.send_message(driver, exception_handler, message)
self.assertEqual([exception], exception_handler_calls)
self.assertFalse(result)
self.assertEqual(1, len(driver.messages))
def test_send_message_handles_os_error_non_memory(self):
exception_handler_calls = []
exception_handler = functools.partial(tu.store_exception_handler, exception_handler_calls)
exception = OSError(errno.EACCES, 'Permission denied')
driver = tu.ErrorMesosExecutorDriver(exception)
task_id = tu.get_random_task_id()
message = {'task-id': task_id, 'message': 'test-message'}
result = ce.send_message(driver, exception_handler, message)
self.assertEqual([], exception_handler_calls)
self.assertFalse(result)
self.assertEqual(1, len(driver.messages))
def test_send_message_handles_generic_exception(self):
exception_handler_calls = []
exception_handler = functools.partial(tu.store_exception_handler, exception_handler_calls)
exception = Exception('Generic Exception')
driver = tu.ErrorMesosExecutorDriver(exception)
task_id = tu.get_random_task_id()
message = {'task-id': task_id, 'message': 'test-message'}
result = ce.send_message(driver, exception_handler, message)
self.assertEqual([], exception_handler_calls)
self.assertFalse(result)
self.assertEqual(1, len(driver.messages))
def test_os_error_handler_functools_partial(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
status_updater = ce.StatusUpdater(driver, task_id)
stop_signal = Event()
inner_os_error_handler = functools.partial(ce.os_error_handler, stop_signal, status_updater)
inner_os_error_handler(OSError(errno.ENOMEM, 'No Memory'))
self.assertTrue(stop_signal.isSet())
expected_statuses = [{'task_id': {'value': task_id},
'reason': cook.REASON_CONTAINER_LIMITATION_MEMORY,
'state': cook.TASK_FAILED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
def test_os_error_handler_no_memory(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
status_updater = ce.StatusUpdater(driver, task_id)
stop_signal = Event()
os_error = OSError(errno.ENOMEM, 'No Memory')
ce.os_error_handler(stop_signal, status_updater, os_error)
self.assertTrue(stop_signal.isSet())
expected_statuses = [{'task_id': {'value': task_id},
'reason': cook.REASON_CONTAINER_LIMITATION_MEMORY,
'state': cook.TASK_FAILED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
def test_os_error_handler_no_permission(self):
driver = tu.FakeMesosExecutorDriver()
task_id = tu.get_random_task_id()
status_updater = ce.StatusUpdater(driver, task_id)
stop_signal = Event()
os_error = OSError(errno.EPERM, 'No Permission')
ce.os_error_handler(stop_signal, status_updater, os_error)
self.assertTrue(stop_signal.isSet())
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_FAILED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
def test_launch_task(self):
task_id = tu.get_random_task_id()
command = 'echo "Hello World"; echo "Error Message" >&2'
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
process = ce.launch_task(task, os.environ)
self.assertIsNotNone(process)
for _ in range(100):
if cs.is_process_running(process):
time.sleep(0.01)
if process.poll() is None:
process.kill()
tu.close_sys_outputs()
self.assertEqual(0, process.poll())
with open(stdout_name) as f:
stdout_content = f.read()
self.assertTrue("Hello World\n" in stdout_content)
with open(stderr_name) as f:
stderr_content = f.read()
self.assertTrue("Error Message\n" in stderr_content)
finally:
tu.cleanup_output(stdout_name, stderr_name)
def test_launch_task_interactive_output(self):
task_id = tu.get_random_task_id()
command = 'echo "Start"; echo "Hello"; sleep 100; echo "World"; echo "Done"; '
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
process = ce.launch_task(task, os.environ)
self.assertIsNotNone(process)
# let the process run for up to 50 seconds
for _ in range(5000):
if cs.is_process_running(process):
time.sleep(0.01)
with open(stdout_name) as f:
stdout_content = f.read()
if 'Start' in stdout_content and 'Hello' in stdout_content:
break
try:
with open(stdout_name) as f:
stdout_content = f.read()
logging.info('Contents of stdout: {}'.format(stdout_content))
self.assertTrue("Start" in stdout_content)
self.assertTrue("Hello" in stdout_content)
self.assertFalse("World" in stdout_content)
self.assertFalse("Done" in stdout_content)
finally:
if process.poll() is None:
logging.info('Killing launched process')
process.kill()
finally:
tu.cleanup_output(stdout_name, stderr_name)
def test_launch_task_no_command(self):
task_id = tu.get_random_task_id()
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': ''}).encode('utf8'))}
process = ce.launch_task(task, os.environ)
self.assertIsNone(process)
def test_launch_task_handle_exception(self):
task_id = tu.get_random_task_id()
task = {'task_id': {'value': task_id}}
process = ce.launch_task(task, os.environ)
self.assertIsNone(process)
def test_await_process_completion_normal(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
command = 'sleep 2'
process = subprocess.Popen(command, preexec_fn=os.setpgrp, shell=True)
shutdown_grace_period_ms = 1000
stop_signal = Event()
ce.await_process_completion(process, stop_signal, shutdown_grace_period_ms)
self.assertFalse(stop_signal.isSet())
self.assertEqual(0, process.returncode)
finally:
tu.cleanup_output(stdout_name, stderr_name)
def test_await_process_completion_killed(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
command = 'sleep 100'
process = subprocess.Popen(command, preexec_fn=os.setpgrp, shell=True)
shutdown_grace_period_ms = 2000
stop_signal = Event()
sleep_and_set_stop_signal_task(stop_signal, 2)
ce.await_process_completion(process, stop_signal, shutdown_grace_period_ms)
self.assertTrue(process.returncode < 0)
finally:
tu.cleanup_output(stdout_name, stderr_name)
def test_get_task_state(self):
self.assertEqual(cook.TASK_FINISHED, ce.get_task_state(0))
self.assertEqual(cook.TASK_FAILED, ce.get_task_state(1))
self.assertEqual(cook.TASK_KILLED, ce.get_task_state(-1))
def test_retrieve_process_environment(self):
self.assertEqual({'EXECUTOR_PROGRESS_OUTPUT_FILE': 'stdout'},
ce.retrieve_process_environment(cc.ExecutorConfig(), make_task_env({}), {}))
self.assertEqual({'CUSTOM_PROGRESS_OUTPUT_FILE': 'stdout',
'FOO': 'BAR',
'MESOS_SANDBOX': '/path/to/sandbox',
'PROGRESS_OUTPUT_FILE': 'executor.progress'},
ce.retrieve_process_environment(
cc.ExecutorConfig(progress_output_env_variable='CUSTOM_PROGRESS_OUTPUT_FILE'),
make_task_env({}),
{'FOO': 'BAR',
'MESOS_SANDBOX': '/path/to/sandbox',
'PROGRESS_OUTPUT_FILE': 'executor.progress'}))
self.assertEqual({'CUSTOM_PROGRESS_OUTPUT_FILE': 'custom.progress',
'EXECUTOR_PROGRESS_OUTPUT_FILE_ENV': 'CUSTOM_PROGRESS_OUTPUT_FILE'},
ce.retrieve_process_environment(
cc.ExecutorConfig(progress_output_env_variable='CUSTOM_PROGRESS_OUTPUT_FILE',
progress_output_name='custom.progress'),
make_task_env({}),
{'CUSTOM_PROGRESS_OUTPUT_FILE': 'executor.progress',
'EXECUTOR_PROGRESS_OUTPUT_FILE_ENV': 'CUSTOM_PROGRESS_OUTPUT_FILE'}))
self.assertEqual({'CUSTOM_PROGRESS_OUTPUT_FILE': 'custom.progress',
'EXECUTOR_PROGRESS_OUTPUT_FILE_ENV': 'CUSTOM_PROGRESS_OUTPUT_FILE',
'PROGRESS_OUTPUT_FILE': 'stdout'},
ce.retrieve_process_environment(
cc.ExecutorConfig(progress_output_env_variable='CUSTOM_PROGRESS_OUTPUT_FILE',
progress_output_name='custom.progress'),
make_task_env({}),
{'CUSTOM_PROGRESS_OUTPUT_FILE': 'executor.progress',
'EXECUTOR_PROGRESS_OUTPUT_FILE_ENV': 'CUSTOM_PROGRESS_OUTPUT_FILE',
'PROGRESS_OUTPUT_FILE': 'stdout'}))
self.assertEqual({'EXECUTOR_PROGRESS_OUTPUT_FILE': 'stdout',
'MY_RESET_VAR': 'myval',
'ANOTHER_VAR': 'another'},
ce.retrieve_process_environment(
cc.ExecutorConfig(reset_vars=['MY_RESET_VAR', 'ANOTHER_RESET_VAR', 'A_MISSING_VAR']),
make_task_env({'MY_RESET_VAR': 'myval'}),
{'MY_RESET_VAR': 'badval',
'ANOTHER_VAR': 'another',
'ANOTHER_RESET_VAR': 'get rid of me'}))
def manage_task_runner(self, command, assertions_fn, stop_signal=None, task_id=None, config=None, driver=None):
if driver is None:
driver = tu.FakeMesosExecutorDriver()
if stop_signal is None:
stop_signal = Event()
if task_id is None:
task_id = tu.get_random_task_id()
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
completed_signal = Event()
if config is None:
sandbox_directory = '/location/to/task/sandbox/{}'.format(task_id)
mesos_directory = '/mesos/directory/{}'.format(task_id)
config = cc.ExecutorConfig(max_message_length=300,
mesos_directory = mesos_directory,
progress_output_name=stdout_name,
progress_regex_string='\^\^\^\^JOB-PROGRESS:\s+([0-9]*\.?[0-9]+)($|\s+.*)',
progress_sample_interval_ms=100,
sandbox_directory=sandbox_directory)
else:
sandbox_directory = config.sandbox_directory
mesos_directory = config.mesos_directory
try:
ce.manage_task(driver, task, stop_signal, completed_signal, config)
self.assertTrue(completed_signal.isSet())
assertions_fn(driver, task_id, sandbox_directory, mesos_directory)
finally:
tu.cleanup_output(stdout_name, stderr_name)
def run_command_in_manage_task_runner(self, command, assertions, wait_time_secs):
stop_signal = Event()
sleep_and_set_stop_signal_task(stop_signal, wait_time_secs)
self.manage_task_runner(command, assertions, stop_signal=stop_signal)
stop_signal.set()
def test_manage_task_environment_output(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
with open(stdout_name) as f:
file_contents = f.read()
self.assertTrue('FEE=FIE' in file_contents)
self.assertTrue('FOO=BAR' in file_contents)
self.assertTrue('PROGRESS_OUTPUT_FILE=foobar' in file_contents)
command = 'env | sort'
current_environ = os.environ
try:
os.environ = {'FOO': 'BAR', 'FEE': 'FIE', 'PROGRESS_OUTPUT_FILE': 'foobar'}
self.manage_task_runner(command, assertions)
finally:
os.environ = current_environ
def test_manage_task_successful_exit(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
command = 'echo "Hello World"'
self.manage_task_runner(command, assertions)
def test_manage_task_empty_command(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id},
'state': cook.TASK_STARTING},
{'task_id': {'value': task_id},
'reason': cook.REASON_TASK_INVALID,
'state': cook.TASK_ERROR}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
tu.assert_messages(self, [expected_message_0], [], driver.messages)
command = ''
self.manage_task_runner(command, assertions)
def test_manage_task_involved_command_successful_exit(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_core_messages = [{'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'},
{'exit-code': 0, 'task-id': task_id}]
expected_progress_messages = [{'progress-message': 'line count is 20',
'progress-percent': 90, 'progress-sequence': 1, 'task-id': task_id}]
tu.assert_messages(self, expected_core_messages, expected_progress_messages, driver.messages)
test_file_name = tu.ensure_directory('build/file.' + tu.get_random_task_id())
command = ('mkdir -p build; touch {0}; for i in $(seq 20); do echo $i >> {0}; done; '
'LINE_COUNT=`wc -l < {0} | tr -d \'[:space:]\'`; cat {0}; rm -rfv {0}; '
'echo "^^^^JOB-PROGRESS: 90 line count is $LINE_COUNT"'.format(test_file_name))
self.manage_task_runner(command, assertions)
def test_manage_task_successful_exit_despite_faulty_driver(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_core_messages = [{'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'},
{'exit-code': 0, 'task-id': task_id}]
expected_progress_messages = [{'progress-message': 'ninety percent',
'progress-percent': 90, 'progress-sequence': 1, 'task-id': task_id},
# retried because the previous send fails
{'progress-message': 'ninety percent',
'progress-percent': 90, 'progress-sequence': 1, 'task-id': task_id}]
tu.assert_messages(self, expected_core_messages, expected_progress_messages, driver.messages)
test_file_name = tu.ensure_directory('build/file.' + tu.get_random_task_id())
command = ('echo "^^^^JOB-PROGRESS: 90 ninety percent"'.format(test_file_name))
socket_error = OSError('socket.error') # socket.error is an alias of OSError
self.manage_task_runner(command, assertions, driver=tu.ErrorMesosExecutorDriver(socket_error))
def test_manage_task_successful_exit_with_progress_message(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_core_messages = [{'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'},
{'exit-code': 0, 'task-id': task_id}]
expected_progress_messages = [{'progress-message': 'Fifty percent',
'progress-percent': 50, 'progress-sequence': 1, 'task-id': task_id},
{'progress-message': 'Fifty-five percent',
'progress-percent': 55, 'progress-sequence': 2, 'task-id': task_id}]
tu.assert_messages(self, expected_core_messages, expected_progress_messages, driver.messages)
command = 'echo "Hello World"; ' \
'echo "^^^^JOB-PROGRESS: 50 Fifty percent"; ' \
'sleep 0.1; ' \
'echo "^^^^JOB-PROGRESS: 54.8 Fifty-five percent"; ' \
'sleep 0.1; ' \
'echo "Exiting..."; ' \
'exit 0'
self.manage_task_runner(command, assertions)
def test_manage_task_erroneous_exit(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FAILED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 1, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
command = 'echo "Hello World"; exit 1'
self.manage_task_runner(command, assertions)
# FIXME - remove the xfail mark once the issue with this test crashing is resolved:
# https://github.com/twosigma/Cook/issues/678
@pytest.mark.xfail
@unittest.skip('This test crashes occasionally')
def test_manage_task_terminated(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_KILLED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': -15, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
command = 'sleep 100'
self.run_command_in_manage_task_runner(command, assertions, 2)
# FIXME - remove the xfail mark once the issue with this test crashing is resolved:
# https://github.com/twosigma/Cook/issues/856
@pytest.mark.xfail
@unittest.skip('This test fails occasionally')
def test_manage_task_random_binary_output(self):
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_core_messages = [{'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'},
{'exit-code': 0, 'task-id': task_id}]
expected_progress_messages = [{'progress-message': '',
'progress-percent': 50, 'progress-sequence': 1, 'task-id': task_id}]
tu.assert_messages(self, expected_core_messages, expected_progress_messages, driver.messages)
stdout_name = tu.ensure_directory('build/stdout.' + str(task_id))
if not os.path.isfile(stdout_name):
self.fail('{} does not exist.'.format(stdout_name))
stop_signal = Event()
sleep_and_set_stop_signal_task(stop_signal, 60)
# progress string in file with binary data will be ignored
command = 'echo "Hello"; ' \
'head -c 1000 /dev/random; ' \
'echo "force newline stage-1"; ' \
'echo "^^^^JOB-PROGRESS: 50 `head -c 50 /dev/random`"; ' \
'echo "force newline stage-2"; ' \
'echo "Done"'
self.manage_task_runner(command, assertions, stop_signal=stop_signal)
stop_signal.set()
def test_manage_task_long_output_single_line(self):
num_iterations = 100000
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
stdout_name = tu.ensure_directory('build/stdout.' + str(task_id))
if os.path.isfile(stdout_name):
with open(stdout_name) as f:
file_contents = f.read()
self.assertEqual(num_iterations * 25, file_contents.count('X'))
else:
self.fail('{} does not exist.'.format(stdout_name))
stderr_name = tu.ensure_directory('build/stderr.' + str(task_id))
if os.path.isfile(stderr_name):
with open(stderr_name) as f:
file_contents = f.read()
self.assertEqual(num_iterations * 25, file_contents.count('X'))
else:
self.fail('{} does not exist.'.format(stderr_name))
command = 'for i in `seq {}`; ' \
'do printf "XXXXXXXXXXXXXXXXXXXXXXXXX"; printf "XXXXXXXXXXXXXXXXXXXXXXXXX" >&2; done; ' \
'echo "Done."'.format(num_iterations)
self.run_command_in_manage_task_runner(command, assertions, 60)
def test_manage_task_long_output_multiple_lines(self):
num_iterations = 100000
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
stdout_name = tu.ensure_directory('build/stdout.' + str(task_id))
if os.path.isfile(stdout_name):
with open(stdout_name) as f:
file_contents = f.read()
self.assertEqual(num_iterations * 25, file_contents.count('X'))
else:
self.fail('{} does not exist.'.format(stdout_name))
stderr_name = tu.ensure_directory('build/stderr.' + str(task_id))
if os.path.isfile(stderr_name):
with open(stderr_name) as f:
file_contents = f.read()
self.assertEqual(num_iterations * 25, file_contents.count('X'))
else:
self.fail('{} does not exist.'.format(stderr_name))
command = 'for i in `seq {}`; ' \
'do printf "XXXXXXXXXXXXXXXXXXXXXXXXX\\n"; printf "XXXXXXXXXXXXXXXXXXXXXXXXX\\n" >&2; done; ' \
'echo "Done."'.format(num_iterations)
self.run_command_in_manage_task_runner(command, assertions, 60)
def test_manage_task_long_progress_output(self):
num_iterations = 100000
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
logging.info('Messages: {}'.format(driver.messages))
self.assertLess(2, len(driver.messages))
actual_encoded_message_0 = driver.messages[0]
expected_message_0 = {'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'}
tu.assert_message(self, expected_message_0, actual_encoded_message_0)
found_exit_message = False
for index in range(1, len(driver.messages)):
actual_encoded_message = driver.messages[index]
actual_message = tu.parse_message(actual_encoded_message)
if 'exit-code' in actual_message:
found_exit_message = True
expected_message = {'exit-code': 0, 'task-id': task_id}
tu.assert_message(self, expected_message, actual_encoded_message)
break
self.assertTrue(found_exit_message)
stderr_name = tu.ensure_directory('build/stderr.' + str(task_id))
if os.path.isfile(stderr_name):
with open(stderr_name) as f:
file_contents = f.read()
self.assertEqual(num_iterations * 25, file_contents.count('X'))
else:
self.fail('{} does not exist.'.format(stderr_name))
stop_signal = Event()
sleep_and_set_stop_signal_task(stop_signal, 60)
# one order magnitude smaller than non-progress long tests above
command = 'for i in `seq {}`; ' \
'do printf "^^^^JOB-PROGRESS: 50 Fifty\\n"; printf "XXXXXXXXXXXXXXXXXXXXXXXXX\\n" >&2; done; ' \
'echo "Done."'.format(num_iterations)
self.run_command_in_manage_task_runner(command, assertions, 60)
def test_manage_task_progress_in_progress_stderr_and_stdout_progress(self):
max_message_length = 35
def assertions(driver, task_id, sandbox_directory, mesos_directory):
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_core_messages = [{'sandbox-directory': mesos_directory, 'task-id': task_id, 'type': 'directory'},
{'exit-code': 0, 'task-id': task_id}]
expected_progress_messages = [{'progress-message': 'Fifty percent in progress file',
'progress-percent': 50, 'progress-sequence': 1, 'task-id': task_id},
{'progress-message': 'Fifty-five percent in stdout',
'progress-percent': 55, 'progress-sequence': 2, 'task-id': task_id},
{'progress-message': 'Sixty percent in stderr',
'progress-percent': 60, 'progress-sequence': 3, 'task-id': task_id},
{'progress-message': 'Sixty-five percent in stdout wit...',
'progress-percent': 65, 'progress-sequence': 4, 'task-id': task_id}]
tu.assert_messages(self, expected_core_messages, expected_progress_messages, driver.messages)
stop_signal = Event()
sleep_and_set_stop_signal_task(stop_signal, 60)
task_id = tu.get_random_task_id()
progress_name = tu.ensure_directory('build/progress.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
config = tu.FakeExecutorConfig({'max_bytes_read_per_line': 1024,
'max_message_length': max_message_length,
'mesos_directory': '/mesos/directory/for/{}'.format(task_id),
'progress_output_env_variable': 'DEFAULT_PROGRESS_FILE_ENV_VARIABLE',
'progress_output_name': progress_name,
'progress_regex_string': '\^\^\^\^JOB-PROGRESS:\s+([0-9]*\.?[0-9]+)($|\s+.*)',
'progress_sample_interval_ms': 10,
'reset_vars': [],
'sandbox_directory': '/sandbox/directory/for/{}'.format(task_id),
'shutdown_grace_period_ms': 60000,
'stderr_file': stderr_name,
'stdout_file': stdout_name})
command = 'echo "Hello World"; ' \
'echo "^^^^JOB-PROGRESS: 50 Fifty percent in progress file" >> {}; ' \
'sleep 0.25; ' \
'echo "^^^^JOB-PROGRESS: 55 Fifty-five percent in stdout" >> {}; ' \
'sleep 0.25; ' \
'echo "^^^^JOB-PROGRESS: 60 Sixty percent in stderr" >> {}; ' \
'sleep 0.25; ' \
'echo "^^^^JOB-PROGRESS: 65 Sixty-five percent in stdout with a long message" >> {}; ' \
'sleep 0.25; ' \
'echo "Exiting..."; ' \
'exit 0'.format(progress_name, stdout_name, stderr_name, stdout_name)
try:
self.manage_task_runner(command, assertions, stop_signal=stop_signal, task_id=task_id, config=config)
stop_signal.set()
finally:
tu.cleanup_file(progress_name)
def test_executor_launch_task(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
output_name = tu.ensure_directory('build/output.' + str(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
config = cc.ExecutorConfig()
stop_signal = Event()
executor = ce.CookExecutor(stop_signal, config)
driver = tu.FakeMesosExecutorDriver()
command = 'echo "Start" >> {}; sleep 0.1; echo "Done." >> {}; '.format(output_name, output_name)
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
executor.launchTask(driver, task)
executor.await_completion()
logging.info('Task completed')
if os.path.isfile(output_name):
with open(output_name) as f:
file_contents = f.read()
self.assertTrue('Start' in file_contents)
self.assertTrue('Done' in file_contents)
else:
self.fail('{} does not exist.'.format(stderr_name))
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': '', 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
finally:
tu.cleanup_output(stdout_name, stderr_name)
tu.cleanup_file(output_name)
def test_executor_launch_task_and_disconnect_no_checkpointing(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
output_name = tu.ensure_directory('build/output.' + str(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
config = cc.ExecutorConfig()
stop_signal = Event()
executor = ce.CookExecutor(stop_signal, config)
driver = tu.FakeMesosExecutorDriver()
command = 'echo "Start" >> {}; sleep 100; echo "Done." >> {}; '.format(output_name, output_name)
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
executor.launchTask(driver, task)
# let the process run for up to 10 seconds
for _ in range(1000):
time.sleep(0.01)
if os.path.isfile(output_name):
with open(output_name) as f:
content = f.read()
if 'Start' in content:
break
executor.disconnected(driver)
self.assertTrue(executor.disconnect_signal.isSet())
self.assertTrue(executor.stop_signal.isSet())
executor.await_completion()
logging.info('Task completed')
if os.path.isfile(output_name):
with open(output_name) as f:
file_contents = f.read()
self.assertTrue('Start' in file_contents)
self.assertTrue('Done' not in file_contents)
else:
self.fail('{} does not exist.'.format(stderr_name))
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_KILLED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': '', 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': -15, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
finally:
tu.cleanup_output(stdout_name, stderr_name)
tu.cleanup_file(output_name)
def test_executor_reregistration(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
output_name = tu.ensure_directory('build/output.' + str(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
config = cc.ExecutorConfig(checkpoint=1, recovery_timeout='5mins')
stop_signal = Event()
executor = ce.CookExecutor(stop_signal, config)
driver = tu.FakeMesosExecutorDriver()
agent_info = {'id': {'value': 'agent'}}
command = 'echo "Start" >> {}; sleep 30; echo "Done." >> {}; '.format(output_name, output_name)
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
executor.launchTask(driver, task)
# let the process run for up to 10 seconds
for _ in range(1000):
time.sleep(0.01)
if os.path.isfile(output_name):
with open(output_name) as f:
content = f.read()
if 'Start' in content:
break
self.assertEqual(None, executor.reregister_signal)
executor.disconnected(driver)
self.assertFalse(executor.disconnect_signal.isSet())
self.assertFalse(executor.stop_signal.isSet())
old_reregister_signal = executor.reregister_signal
executor.reregistered(driver, agent_info)
self.assertTrue(old_reregister_signal.isSet())
self.assertEqual(None, executor.reregister_signal)
executor.await_completion()
logging.info('Task completed')
if os.path.isfile(output_name):
with open(output_name) as f:
file_contents = f.read()
self.assertTrue('Start' in file_contents)
self.assertTrue('Done' in file_contents)
else:
self.fail('{} does not exist.'.format(stderr_name))
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_FINISHED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': '', 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': 0, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
finally:
tu.cleanup_output(stdout_name, stderr_name)
tu.cleanup_file(output_name)
def test_executor_reregistration_timeout(self):
task_id = tu.get_random_task_id()
stdout_name = tu.ensure_directory('build/stdout.{}'.format(task_id))
stderr_name = tu.ensure_directory('build/stderr.{}'.format(task_id))
output_name = tu.ensure_directory('build/output.' + str(task_id))
tu.redirect_stdout_to_file(stdout_name)
tu.redirect_stderr_to_file(stderr_name)
try:
config = cc.ExecutorConfig(checkpoint=1, recovery_timeout='5secs')
stop_signal = Event()
executor = ce.CookExecutor(stop_signal, config)
driver = tu.FakeMesosExecutorDriver()
agent_info = {'id': {'value': 'agent'}}
command = 'echo "Start" >> {}; sleep 30; echo "Done." >> {}; '.format(output_name, output_name)
task = {'task_id': {'value': task_id},
'data': pm.encode_data(json.dumps({'command': command}).encode('utf8'))}
executor.launchTask(driver, task)
# let the process run for up to 10 seconds
for _ in range(1000):
time.sleep(0.01)
if os.path.isfile(output_name):
with open(output_name) as f:
content = f.read()
if 'Start' in content:
break
executor.disconnected(driver)
self.assertFalse(executor.disconnect_signal.isSet())
self.assertFalse(executor.stop_signal.isSet())
executor.await_completion()
logging.info('Task completed')
self.assertFalse(executor.reregister_signal.isSet())
self.assertTrue(executor.disconnect_signal.isSet())
self.assertTrue(executor.stop_signal.isSet())
if os.path.isfile(output_name):
with open(output_name) as f:
file_contents = f.read()
self.assertTrue('Start' in file_contents)
self.assertFalse('Done' in file_contents)
else:
self.fail('{} does not exist.'.format(stderr_name))
expected_statuses = [{'task_id': {'value': task_id}, 'state': cook.TASK_STARTING},
{'task_id': {'value': task_id}, 'state': cook.TASK_RUNNING},
{'task_id': {'value': task_id}, 'state': cook.TASK_KILLED}]
tu.assert_statuses(self, expected_statuses, driver.statuses)
expected_message_0 = {'sandbox-directory': '', 'task-id': task_id, 'type': 'directory'}
expected_message_1 = {'exit-code': -15, 'task-id': task_id}
tu.assert_messages(self, [expected_message_0, expected_message_1], [], driver.messages)
finally:
tu.cleanup_output(stdout_name, stderr_name)
tu.cleanup_file(output_name)
@patch('os._exit')