-
Notifications
You must be signed in to change notification settings - Fork 46
/
test_process_dispatcher.py
1549 lines (1159 loc) · 59.5 KB
/
test_process_dispatcher.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 shutil
import tempfile
import uuid
import unittest
import time
import os
from mock import Mock, patch, DEFAULT
from nose.plugins.attrib import attr
from pyon.net.endpoint import RPCClient
from pyon.service.service import BaseService
from pyon.util.containers import DotDict, get_safe
from pyon.util.unit_test import PyonTestCase
from pyon.util.int_test import IonIntegrationTestCase
from pyon.core.exception import NotFound, BadRequest, Conflict, IonException
from pyon.public import log
from pyon.core import bootstrap
from interface.services.cei.iprocess_dispatcher_service import ProcessDispatcherServiceClient
from interface.objects import ProcessDefinition, ProcessSchedule, ProcessTarget,\
ProcessStateEnum, ProcessQueueingMode, ProcessRestartMode, ProcessDefinitionType
from interface.services.icontainer_agent import ContainerAgentClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from ion.services.cei.process_dispatcher_service import ProcessDispatcherService,\
PDLocalBackend, PDNativeBackend, get_dashi, get_pd_dashi_name, PDDashiHandler,\
Notifier
from ion.services.cei.test import ProcessStateWaiter
try:
from epu.states import InstanceState
from epu.processdispatcher.engines import domain_id_from_engine
from epu.dashiproc.epumanagement import EPUManagementClient
_HAS_EPU = True
except ImportError:
InstanceState = None
domain_id_from_engine = None
EPUManagementClient = None
_HAS_EPU = False
# NOTE: much of the Process Dispatcher functionality is tested directly in the
# epu repository where the code resides. This file only attempts to test the
# Pyon interface itself as well as some integration testing to validate
# communication.
@attr('UNIT', group='cei')
class ProcessDispatcherServiceLocalTest(PyonTestCase):
"""Tests the local backend of the PD
"""
def setUp(self):
self.pd_service = ProcessDispatcherService()
self.pd_service.container = DotDict()
self.pd_service.container['spawn_process'] = Mock()
self.pd_service.container['id'] = 'mock_container_id'
self.pd_service.container['proc_manager'] = DotDict()
self.pd_service.container['resource_registry'] = Mock()
self.pd_service.container.proc_manager['terminate_process'] = Mock()
self.pd_service.container.proc_manager['procs'] = {}
self.mock_cc_spawn = self.pd_service.container.spawn_process
self.mock_cc_terminate = self.pd_service.container.proc_manager.terminate_process
self.mock_cc_procs = self.pd_service.container.proc_manager.procs
self.pd_service.init()
self.assertIsInstance(self.pd_service.backend, PDLocalBackend)
self.pd_service.backend.rr = self.mock_rr = Mock()
self.pd_service.backend.event_pub = self.mock_event_pub = Mock()
def test_create_schedule(self):
backend = self.pd_service.backend
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
self.mock_rr.read.return_value = proc_def
self.mock_cc_spawn.return_value = '123'
pid = self.pd_service.create_process("fake-process-def-id")
# not used for anything in local mode
proc_schedule = DotDict()
configuration = {"some": "value"}
if backend.SPAWN_DELAY:
with patch("gevent.spawn_later") as mock_gevent:
self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertTrue(mock_gevent.called)
self.assertEqual(mock_gevent.call_args[0][0], backend.SPAWN_DELAY)
self.assertEqual(mock_gevent.call_args[0][1], backend._inner_spawn)
spawn_args = mock_gevent.call_args[0][2:]
# now call the delayed spawn directly
backend._inner_spawn(*spawn_args)
else:
self.pd_service.schedule_process("fake-process-def-id", proc_schedule,
configuration, pid)
self.assertTrue(pid.startswith(proc_def.name) and pid != proc_def.name)
self.assertEqual(self.mock_cc_spawn.call_count, 1)
call_args, call_kwargs = self.mock_cc_spawn.call_args
self.assertFalse(call_args)
# name should be def name followed by a uuid
name = call_kwargs['name']
assert name.startswith(proc_def['name'])
self.assertEqual(len(call_kwargs), 5)
self.assertEqual(call_kwargs['module'], 'my_module')
self.assertEqual(call_kwargs['cls'], 'class')
self.assertEqual(call_kwargs['process_id'], pid)
called_config = call_kwargs['config']
self.assertEqual(called_config, configuration)
# PENDING followed by RUNNING
self.assertEqual(self.mock_event_pub.publish_event.call_count, 2)
process = self.pd_service.read_process(pid)
self.assertEqual(process.process_id, pid)
self.assertEqual(process.process_state, ProcessStateEnum.RUNNING)
def test_read_process_notfound(self):
with self.assertRaises(NotFound):
self.pd_service.read_process("processid")
def test_schedule_process_notfound(self):
proc_schedule = DotDict()
configuration = {}
self.mock_rr.read.side_effect = NotFound()
with self.assertRaises(NotFound):
self.pd_service.schedule_process("not-a-real-process-id",
proc_schedule, configuration)
self.mock_rr.read.assert_called_once_with("not-a-real-process-id")
def test_local_cancel(self):
pid = self.pd_service.create_process("fake-process-def-id")
ok = self.pd_service.cancel_process(pid)
self.assertTrue(ok)
self.mock_cc_terminate.assert_called_once_with(pid)
class FakeDashiNotFoundError(Exception):
pass
class FakeDashiBadRequestError(Exception):
pass
class FakeDashiWriteConflictError(Exception):
pass
@attr('UNIT', group='cei')
class ProcessDispatcherServiceDashiHandlerTest(PyonTestCase):
"""Tests the dashi frontend of the PD
"""
def setUp(self):
self.mock_backend = DotDict()
self.mock_backend['create_definition'] = Mock()
self.mock_backend['read_definition'] = Mock()
self.mock_backend['read_definition_by_name'] = Mock()
self.mock_backend['update_definition'] = Mock()
self.mock_backend['delete_definition'] = Mock()
self.mock_backend['create'] = Mock()
self.mock_backend['schedule'] = Mock()
self.mock_backend['read_process'] = Mock()
self.mock_backend['list'] = Mock()
self.mock_backend['cancel'] = Mock()
self.mock_backend['set_system_boot'] = Mock()
self.mock_dashi = DotDict()
self.mock_dashi['handle'] = Mock()
self.mock_pyon_dashi_exc_map = {
NotFound: FakeDashiNotFoundError,
BadRequest: FakeDashiBadRequestError,
Conflict: FakeDashiWriteConflictError
}
self.pd_dashi_handler = PDDashiHandler(self.mock_backend, self.mock_dashi)
def test_process_definitions(self):
definition_id = "hello"
definition_type = ProcessDefinitionType.PYON_STREAM
executable = {'class': 'SomeThing', 'module': 'some.module'}
name = "whataname"
description = "describing stuff"
self.pd_dashi_handler.create_definition(definition_id, definition_type,
executable, name, description)
self.assertEqual(self.mock_backend.create_definition.call_count, 1)
self.pd_dashi_handler.describe_definition(definition_id)
self.assertEqual(self.mock_backend.read_definition.call_count, 1)
self.pd_dashi_handler.describe_definition(definition_name=name)
self.assertEqual(self.mock_backend.read_definition_by_name.call_count, 1)
self.pd_dashi_handler.update_definition(definition_id, definition_type,
executable, name, description)
self.assertEqual(self.mock_backend.update_definition.call_count, 1)
self.pd_dashi_handler.remove_definition(definition_id)
self.assertEqual(self.mock_backend.delete_definition.call_count, 1)
with patch('ion.services.cei.process_dispatcher_service._PYON_DASHI_EXC_MAP',
self.mock_pyon_dashi_exc_map):
with self.assertRaises(FakeDashiBadRequestError):
self.pd_dashi_handler.list_definitions()
# need to specify either definition id or name
with self.assertRaises(FakeDashiBadRequestError):
self.pd_dashi_handler.describe_definition()
def test_exception_map(self):
# only testing one of the handlers. assuming they all share the decorator
with patch('ion.services.cei.process_dispatcher_service._PYON_DASHI_EXC_MAP',
self.mock_pyon_dashi_exc_map):
self.mock_backend.read_definition.side_effect = NotFound()
with self.assertRaises(FakeDashiNotFoundError):
self.pd_dashi_handler.describe_definition("some-def")
self.mock_backend.read_definition.side_effect = Conflict()
with self.assertRaises(FakeDashiWriteConflictError):
self.pd_dashi_handler.describe_definition("some-def")
self.mock_backend.read_definition.side_effect = BadRequest()
with self.assertRaises(FakeDashiBadRequestError):
self.pd_dashi_handler.describe_definition("some-def")
# try with an unmapped IonException. should get passed through directly
self.mock_backend.read_definition.side_effect = IonException()
with self.assertRaises(IonException):
self.pd_dashi_handler.describe_definition("some-def")
def test_schedule(self):
self.mock_backend['read_definition'].return_value = ProcessDefinition()
upid = 'myupid'
name = 'myname'
definition_id = 'something'
queueing_mode = 'RESTART_ONLY'
restart_mode = 'ABNORMAL'
self.pd_dashi_handler.schedule_process(upid, definition_id,
queueing_mode=queueing_mode, restart_mode=restart_mode, name=name)
self.assertEqual(self.mock_backend.schedule.call_count, 1)
args, kwargs = self.mock_backend.schedule.call_args
passed_schedule = args[2]
assert passed_schedule.queueing_mode == ProcessQueueingMode.RESTART_ONLY
assert passed_schedule.restart_mode == ProcessRestartMode.ABNORMAL
passed_name = args[4]
assert passed_name == name
def test_schedule_by_name(self):
pdef = ProcessDefinition()
pdef._id = "someprocessid"
self.mock_backend['read_definition_by_name'].return_value = pdef
upid = 'myupid'
definition_name = 'something'
queueing_mode = 'RESTART_ONLY'
restart_mode = 'ABNORMAL'
self.pd_dashi_handler.schedule_process(upid, definition_name=definition_name,
queueing_mode=queueing_mode, restart_mode=restart_mode)
self.mock_backend.read_definition_by_name.assert_called_once_with(definition_name)
self.assertFalse(self.mock_backend.read_definition.call_count)
self.assertEqual(self.mock_backend.schedule.call_count, 1)
args, kwargs = self.mock_backend.schedule.call_args
passed_schedule = args[2]
assert passed_schedule.queueing_mode == ProcessQueueingMode.RESTART_ONLY
assert passed_schedule.restart_mode == ProcessRestartMode.ABNORMAL
def test_set_system_boot(self):
self.pd_dashi_handler.set_system_boot(False)
self.mock_backend.set_system_boot.assert_called_once_with(False)
@attr('UNIT', group='cei')
class ProcessDispatcherServiceNativeTest(PyonTestCase):
"""Tests the Pyon backend of the PD
"""
def setUp(self):
self.pd_service = ProcessDispatcherService()
self.pd_service.container = DotDict()
self.pd_service.container['spawn_process'] = Mock()
self.pd_service.container['id'] = 'mock_container_id'
self.pd_service.container['proc_manager'] = DotDict()
self.pd_service.container['resource_registry'] = Mock()
self.pd_service.container.proc_manager['terminate_process'] = Mock()
self.pd_service.container.proc_manager['procs'] = {}
pdcfg = dict(dashi_uri="amqp://hello", dashi_exchange="123",
static_resources=True, backend="native")
self.pd_service.CFG = DotDict()
self.pd_service.CFG['processdispatcher'] = pdcfg
self.mock_dashi = Mock()
with patch.multiple('ion.services.cei.process_dispatcher_service',
get_dashi=DEFAULT, ProcessDispatcherCore=DEFAULT,
get_processdispatcher_store=DEFAULT, EngineRegistry=DEFAULT,
PDMatchmaker=DEFAULT, PDDoctor=DEFAULT) as mocks:
mocks['get_dashi'].return_value = self.mock_dashi
mocks['get_processdispatcher_store'].return_value = self.mock_store = Mock()
mocks['ProcessDispatcherCore'].return_value = self.mock_core = Mock()
mocks['PDMatchmaker'].return_value = self.mock_matchmaker = Mock()
mocks['PDDoctor'].return_value = self.mock_doctor = Mock()
mocks['EngineRegistry'].return_value = self.mock_engineregistry = Mock()
self.pd_service.init()
# replace the core and matchmaker with mocks
self.pd_service.backend.beat_subscriber = self.mock_beat_subscriber = Mock()
self.assertIsInstance(self.pd_service.backend, PDNativeBackend)
self.pd_service.backend.rr = self.mock_rr = Mock()
self.event_pub = Mock()
self.pd_service.backend.event_pub = self.event_pub
self.pd_service.start()
self.assertEqual(self.mock_dashi.handle.call_count, 1)
self.mock_matchmaker.start_election.assert_called_once_with()
self.mock_beat_subscriber.start.assert_called_once_with()
def test_create_schedule(self):
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class', 'url': 'myurl'}
mock_read_definition = Mock()
mock_read_definition.return_value = proc_def
self.pd_service.backend.read_definition = mock_read_definition
pid = self.pd_service.create_process("fake-process-def-id")
proc_schedule = DotDict()
proc_schedule['target'] = DotDict()
proc_schedule.target['constraints'] = {"hats": 4}
proc_schedule.target['node_exclusive'] = None
proc_schedule.target['execution_engine_id'] = None
configuration = {"some": "value"}
pid2 = self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertTrue(pid.startswith(proc_def.name) and pid != proc_def.name)
self.assertEqual(pid, pid2)
self.assertTrue(pid.startswith(proc_def.name) and pid != proc_def.name)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
def test_schedule_haagent_name(self):
haa_proc_def = DotDict()
haa_proc_def['name'] = "haagent"
haa_proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
payload_proc_def = DotDict()
payload_proc_def['name'] = "payload_process"
payload_proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
proc_defs = {"haa_proc_def_id": haa_proc_def,
"payload_proc_def_id": payload_proc_def}
read_definition_mock = Mock()
read_definition_mock.side_effect = proc_defs.get
self.pd_service.backend.read_definition = read_definition_mock
# not used for anything in local mode
proc_schedule = DotDict()
configuration = {"highavailability": {"process_definition_id": "payload_proc_def_id"}}
self.pd_service.schedule_process("haa_proc_def_id", proc_schedule, configuration)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
name = self.mock_core.schedule_process.call_args[1]['name']
self.assertTrue(name.startswith("payload_process-ha"))
# now try with scheduling by process definition name instead of ID
self.mock_core.schedule_process.reset_mock()
configuration = {"highavailability": {"process_definition_name": "payload_process"}}
self.pd_service.schedule_process("haa_proc_def_id", proc_schedule, configuration)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
name = self.mock_core.schedule_process.call_args[1]['name']
self.assertTrue(name.startswith("payload_process-ha"))
def test_queueing_mode_default(self):
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
mock_read_definition = Mock()
mock_read_definition.return_value = proc_def
self.pd_service.backend.read_definition = mock_read_definition
pid = self.pd_service.create_process("fake-process-def-id")
proc_schedule = ProcessSchedule()
configuration = {"some": "value"}
self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
call_args, call_kwargs = self.mock_core.schedule_process.call_args
self.assertEqual(call_kwargs['queueing_mode'], "ALWAYS")
def test_queueing_mode(self):
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
mock_read_definition = Mock()
mock_read_definition.return_value = proc_def
self.pd_service.backend.read_definition = mock_read_definition
pid = self.pd_service.create_process("fake-process-def-id")
pyon_queueing_mode = ProcessQueueingMode.NEVER
core_queueing_mode = "NEVER"
proc_schedule = ProcessSchedule()
proc_schedule.queueing_mode = pyon_queueing_mode
configuration = {"some": "value"}
self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
call_args, call_kwargs = self.mock_core.schedule_process.call_args
self.assertEqual(call_kwargs['queueing_mode'], core_queueing_mode)
def test_restart_mode(self):
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
mock_read_definition = Mock()
mock_read_definition.return_value = proc_def
self.pd_service.backend.read_definition = mock_read_definition
pid = self.pd_service.create_process("fake-process-def-id")
pyon_restart_mode = ProcessRestartMode.ABNORMAL
core_restart_mode = "ABNORMAL"
proc_schedule = ProcessSchedule()
proc_schedule.restart_mode = pyon_restart_mode
configuration = {"some": "value"}
self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
call_args, call_kwargs = self.mock_core.schedule_process.call_args
self.assertEqual(call_kwargs['restart_mode'], core_restart_mode)
def test_node_exclusive_eeid(self):
proc_def = DotDict()
proc_def['name'] = "someprocess"
proc_def['executable'] = {'module': 'my_module', 'class': 'class'}
mock_read_definition = Mock()
mock_read_definition.return_value = proc_def
self.pd_service.backend.read_definition = mock_read_definition
pid = self.pd_service.create_process("fake-process-def-id")
node_exclusive = "someattr"
ee_id = "some_ee"
proc_schedule = ProcessSchedule()
proc_schedule.target.node_exclusive = node_exclusive
proc_schedule.target.execution_engine_id = ee_id
configuration = {"some": "value"}
self.pd_service.schedule_process("fake-process-def-id",
proc_schedule, configuration, pid)
self.assertEqual(self.mock_core.schedule_process.call_count, 1)
call_args, call_kwargs = self.mock_core.schedule_process.call_args
self.assertEqual(call_kwargs['execution_engine_id'], ee_id)
self.assertEqual(call_kwargs['node_exclusive'], node_exclusive)
def test_cancel(self):
ok = self.pd_service.cancel_process("process-id")
self.assertTrue(ok)
self.assertEqual(self.mock_core.terminate_process.call_count, 1)
def test_definitions(self):
executable = {'module': 'my_module', 'class': 'class'}
definition = ProcessDefinition(name="someprocess", executable=executable)
pd_id = self.pd_service.create_process_definition(definition)
assert self.mock_core.create_definition.called
self.assertTrue(pd_id)
assert self.mock_rr.create.called_once_with(definition, object_id=pd_id)
self.mock_core.describe_definition.return_value = dict(name="someprocess",
executable=executable)
definition2 = self.pd_service.read_process_definition("someprocess")
assert self.mock_core.describe_definition.called
self.assertEqual(definition2.name, "someprocess")
self.assertEqual(definition2.executable, executable)
self.pd_service.delete_process_definition("someprocess")
assert self.mock_core.remove_definition.called
assert self.mock_rr.delete.called_once_with(pd_id)
def test_read_process(self):
self.mock_core.describe_process.return_value = dict(upid="processid",
state="500-RUNNING")
proc = self.pd_service.read_process("processid")
assert self.mock_core.describe_process.called
self.assertEqual(proc.process_id, "processid")
self.assertEqual(proc.process_state, ProcessStateEnum.RUNNING)
self.assertEqual(proc.process_configuration, {})
def test_read_process_notfound(self):
self.mock_core.describe_process.return_value = None
with self.assertRaises(NotFound):
self.pd_service.read_process("processid")
assert self.mock_core.describe_process.called
def test_read_process_with_config(self):
config = {"hats": 4}
self.mock_core.describe_process.return_value = dict(upid="processid",
state="500-RUNNING", configuration=config)
proc = self.pd_service.read_process("processid")
assert self.mock_core.describe_process.called
self.assertEqual(proc.process_id, "processid")
self.assertEqual(proc.process_state, ProcessStateEnum.RUNNING)
self.assertEqual(proc.process_configuration, config)
def test_list_processes(self):
core_procs = [dict(upid="processid", state="500-RUNNING")]
self.mock_core.describe_processes.return_value = core_procs
procs = self.pd_service.list_processes()
proc = procs[0]
self.assertEqual(proc.process_id, "processid")
self.assertEqual(proc.process_state, ProcessStateEnum.RUNNING)
class TestProcess(BaseService):
"""Test process to deploy via PD
"""
name = __name__ + "test"
def on_init(self):
self.i = 0
self.response = self.CFG.test_response
self.restart = get_safe(self.CFG, "process.start_mode") == "RESTART"
def count(self):
self.i += 1
return self.i
def query(self):
return self.response
def is_restart(self):
return self.restart
def get_process_name(self, pid=None):
if pid is None:
return
proc = self.container.proc_manager.procs.get(pid)
if proc is None:
return
return proc._proc_name
# a copy to use in process definitions for testing process->engine map functionality
TestProcessForProcessEngineMap = TestProcess
class TestProcessThatCrashes(BaseService):
"""Test process to deploy via PD
"""
name = __name__ + "test"
def on_init(self):
raise Exception("I died :(")
class TestClient(RPCClient):
def __init__(self, to_name=None, node=None, **kwargs):
to_name = to_name or __name__ + "test"
RPCClient.__init__(self, to_name=to_name, node=node, **kwargs)
def count(self, headers=None, timeout=None):
return self.request({}, op='count', headers=headers, timeout=timeout)
def query(self, headers=None, timeout=None):
return self.request({}, op='query', headers=headers, timeout=timeout)
def get_process_name(self, pid=None, headers=None, timeout=None):
return self.request({'pid': pid}, op='get_process_name', headers=headers, timeout=timeout)
def is_restart(self, headers=None, timeout=None):
return self.request({}, op='is_restart', headers=headers, timeout=timeout)
@attr('INT', group='cei')
class ProcessDispatcherServiceIntTest(IonIntegrationTestCase):
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2cei.yml')
self.rr_cli = ResourceRegistryServiceClient()
self.pd_cli = ProcessDispatcherServiceClient(node=self.container.node)
self.process_definition = ProcessDefinition(name='test_process')
self.process_definition.executable = {'module': 'ion.services.cei.test.test_process_dispatcher',
'class': 'TestProcess'}
self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)
self.waiter = ProcessStateWaiter()
def tearDown(self):
self.waiter.stop()
def test_create_schedule_cancel(self):
process_schedule = ProcessSchedule()
process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS
proc_name = 'myreallygoodname'
pid = self.pd_cli.create_process(self.process_definition_id)
self.waiter.start(pid)
pid2 = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={}, process_id=pid, name=proc_name)
self.assertEqual(pid, pid2)
# verifies L4-CI-CEI-RQ141 and L4-CI-CEI-RQ142
self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)
proc = self.pd_cli.read_process(pid)
self.assertEqual(proc.process_id, pid)
self.assertEqual(proc.process_configuration, {})
self.assertEqual(proc.process_state, ProcessStateEnum.RUNNING)
# make sure process is readable directly from RR (mirrored)
# verifies L4-CI-CEI-RQ63
# verifies L4-CI-CEI-RQ64
proc = self.rr_cli.read(pid)
self.assertEqual(proc.process_id, pid)
# now try communicating with the process to make sure it is really running
test_client = TestClient()
for i in range(5):
self.assertEqual(i + 1, test_client.count(timeout=10))
# verifies L4-CI-CEI-RQ147
# check the process name was set in container
got_proc_name = test_client.get_process_name(pid=pid2)
self.assertEqual(proc_name, got_proc_name)
# kill the process and start it again
self.pd_cli.cancel_process(pid)
self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)
pid2 = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={}, process_id=pid)
self.assertEqual(pid, pid2)
self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)
for i in range(5):
self.assertEqual(i + 1, test_client.count(timeout=10))
# kill the process for good
self.pd_cli.cancel_process(pid)
self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)
def test_schedule_with_config(self):
process_schedule = ProcessSchedule()
process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS
pid = self.pd_cli.create_process(self.process_definition_id)
self.waiter.start(pid)
# verifies L4-CI-CEI-RQ66
# feed in a string that the process will return -- verifies that
# configuration actually makes it to the instantiated process
test_response = uuid.uuid4().hex
configuration = {"test_response": test_response}
pid2 = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration=configuration, process_id=pid)
self.assertEqual(pid, pid2)
self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING)
test_client = TestClient()
# verifies L4-CI-CEI-RQ139
# assure that configuration block (which can contain inputs, outputs,
# and arbitrary config) 1) makes it to the process and 2) is returned
# in process queries
self.assertEqual(test_client.query(), test_response)
proc = self.pd_cli.read_process(pid)
self.assertEqual(proc.process_id, pid)
self.assertEqual(proc.process_configuration, configuration)
# kill the process for good
self.pd_cli.cancel_process(pid)
self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED)
def test_schedule_bad_config(self):
process_schedule = ProcessSchedule()
# a non-JSON-serializable IonObject
o = ProcessTarget()
with self.assertRaises(BadRequest) as ar:
self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={"bad": o})
self.assertTrue(ar.exception.message.startswith("bad configuration"))
def test_cancel_notfound(self):
with self.assertRaises(NotFound):
self.pd_cli.cancel_process("not-a-real-process-id")
def test_create_invalid_definition(self):
# create process definition missing module and class
# verifies L4-CI-CEI-RQ137
executable = dict(url="http://somewhere.com/something.py")
definition = ProcessDefinition(name="test_process", executable=executable)
with self.assertRaises(BadRequest):
self.pd_cli.create_process_definition(definition)
@unittest.skipIf(_HAS_EPU is False, 'epu dependency not available')
@unittest.skipUnless(os.getenv('CEI_LAUNCH_TEST', False), 'Skip test while not in CEI LAUNCH mode')
@unittest.skipUnless(os.getenv('CEI_LAUNCHINT_TEST', False), 'Skip Test that messes up the database')
@attr('LAUNCHINT', group='cei')
class ProcessDispatcherServiceDestructiveLaunchIntTest(IonIntegrationTestCase):
"""ProcessDispatcherServiceDestructiveLaunchIntTest
These tests cause the pd to request more VMs, which can cause problems in
a test environment. Also, they require two extra engines to be started. To run
the tests, add the following to your launch yml file:
test_one_spare_slot:
base_need: 1
replicas: 1
slots: 1
spare_slots: 1
test_maximum_of_one:
base_need: 1
replicas: 1
slots: 1
maximum_vms: 1
"""
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2cei.yml')
from pyon.public import CFG
import dashi
uri = "amqp://%s:%s@%s:%s" % (
CFG.server.amqp.username, CFG.server.amqp.password,
CFG.server.amqp.host, "5672")
exchange = CFG.dashi.exchange
sysname = CFG.dashi.sysname
self.dashi = dashi.DashiConnection("test", uri, exchange, sysname=sysname)
self.rr_cli = ResourceRegistryServiceClient()
self.pd_cli = ProcessDispatcherServiceClient(node=self.container.node)
self.epum_cli = EPUManagementClient(self.dashi, "epu_management_service")
self.proc_prefix = 'test_launchint_process'
self.process_definition = ProcessDefinition(name=self.proc_prefix)
self.process_definition.executable = {'module': 'ion.services.cei.test.test_process_dispatcher',
'class': 'TestProcess'}
self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)
self.waiter = ProcessStateWaiter()
self.waiter.start()
def tearDown(self):
procs = self.pd_cli.list_processes()
for process in procs:
if process.process_id.startswith(self.proc_prefix) and process.process_state <= ProcessStateEnum.RUNNING:
print "Killing process %s" % process.process_id
self.pd_cli.cancel_process(process.process_id)
self.waiter.stop()
def assert_available_instances(self, engine, n, timeout=240):
start_time = time.time()
while True:
domain = self.epum_cli.describe_domain("pd_domain_%s" % engine)
available_instances = []
for instance in domain.get('instances', []):
state = instance['state']
if state == '600-RUNNING':
available_instances.append(instance)
try:
self.assertEqual(len(available_instances), n)
break
except AssertionError:
if start_time + timeout > time.time():
time.sleep(1)
continue
else:
raise
def test_spare_slots(self):
engine = "test_one_spare_slot"
self.assert_available_instances(engine, 1)
target = ProcessTarget(execution_engine_id=engine)
process_schedule = ProcessSchedule()
process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS
process_schedule.target = target
pid = self.pd_cli.create_process(self.process_definition_id)
self.pd_cli.schedule_process(
self.process_definition_id, process_schedule, process_id=pid)
self.waiter.await_state_event(pid, ProcessStateEnum.RUNNING, timeout=60)
self.assert_available_instances(engine, 2)
time.sleep(20)
self.pd_cli.cancel_process(pid)
self.waiter.await_state_event(pid, ProcessStateEnum.TERMINATED, timeout=120)
time.sleep(20)
self.assert_available_instances(engine, 1)
def test_maximum_vms(self):
engine = "test_maximum_of_one"
self.assert_available_instances(engine, 1)
target = ProcessTarget(execution_engine_id=engine)
process_schedule = ProcessSchedule()
process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS
process_schedule.target = target
pid0 = self.pd_cli.create_process(self.process_definition_id)
pid1 = self.pd_cli.create_process(self.process_definition_id)
self.pd_cli.schedule_process(
self.process_definition_id, process_schedule, process_id=pid0)
self.pd_cli.schedule_process(
self.process_definition_id, process_schedule, process_id=pid1)
self.waiter.await_state_event(pid0, ProcessStateEnum.RUNNING, timeout=60)
assertion_error = None
try:
self.assert_available_instances(engine, 2)
except AssertionError as e:
assertion_error = e
assert assertion_error is not None, "Engine started 2 VMs, when maximum is 1"
self.pd_cli.cancel_process(pid0)
self.pd_cli.cancel_process(pid1)
self.waiter.await_state_event(pid0, ProcessStateEnum.TERMINATED, timeout=120)
@unittest.skipIf(_HAS_EPU is False, 'epu dependency not available')
@unittest.skipUnless(os.getenv('CEI_LAUNCH_TEST', False), 'Skip if not in CEI LAUNCH mode')
@unittest.skipIf(os.getenv('PYCC_MODE', False), 'Skip if in PYCC mode')
@attr('INT', group='cei')
class ProcessDispatcherServiceLaunchIntTest(IonIntegrationTestCase):
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2cei.yml')
self.rr_cli = ResourceRegistryServiceClient()
self.pd_cli = ProcessDispatcherServiceClient(node=self.container.node)
self.waiter = ProcessStateWaiter()
def tearDown(self):
self.waiter.stop()
def test_restart_throttling(self):
process_definition = ProcessDefinition(name='test_process')
process_definition.executable = {'module': 'ion.services.cei.test.test_process_dispatcher',
'class': 'TestProcessThatCrashes'}
process_definition_id = self.pd_cli.create_process_definition(process_definition)
process_schedule = ProcessSchedule()
process_schedule.queueing_mode = ProcessQueueingMode.ALWAYS
process_schedule.restart_mode = ProcessRestartMode.ALWAYS
pid = self.pd_cli.create_process(process_definition_id)
self.waiter.start(pid)
# feed in a string that the process will return -- verifies that
# configuration actually makes it to the instantiated process
configuration = {'process': {'minimum_time_between_starts': 15}}
pid2 = self.pd_cli.schedule_process(process_definition_id,
process_schedule, configuration=configuration, process_id=pid)
self.assertEqual(pid, pid2)
# The process hits PENDING right away
self.waiter.await_state_event(pid, ProcessStateEnum.PENDING)
# Then crashes on init, and restarts quickly once (see TestProcessThatCrashes impl above)
self.waiter.await_state_event(pid, ProcessStateEnum.REQUESTED)
requested_at = time.time()
self.waiter.await_state_event(pid, ProcessStateEnum.PENDING)
pending_at = time.time()
wait_time = pending_at - requested_at
assert wait_time < 2.0, "Process should restart quickly, not be throttled"
# Now the process schould be throttled, and restart more slowly
self.waiter.await_state_event(pid, ProcessStateEnum.REQUESTED)
requested_at = time.time()
self.waiter.await_state_event(pid, ProcessStateEnum.WAITING)
self.waiter.await_state_event(pid, ProcessStateEnum.PENDING)
pending_at = time.time()
wait_time = pending_at - requested_at
assert wait_time > 10.0, "Process should take more than 10s to start, throttled"
# We check again for good measure
self.waiter.await_state_event(pid, ProcessStateEnum.REQUESTED)
requested_at = time.time()
self.waiter.await_state_event(pid, ProcessStateEnum.WAITING)
self.waiter.await_state_event(pid, ProcessStateEnum.PENDING)
pending_at = time.time()
wait_time = pending_at - requested_at