-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathtest_endpointmanager_unit.py
More file actions
2443 lines (1905 loc) · 82.5 KB
/
test_endpointmanager_unit.py
File metadata and controls
2443 lines (1905 loc) · 82.5 KB
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 fcntl
import json
import logging
import os
import pathlib
import pwd
import queue
import random
import re
import signal
import sys
import time
import typing as t
import uuid
from collections import namedtuple
from concurrent.futures import Future
from unittest import mock
import pika
import pytest as pytest
import yaml
from globus_compute_common.messagepack import unpack
from globus_compute_common.messagepack.message_types import EPStatusReport
from globus_compute_endpoint.endpoint.config import (
ManagerEndpointConfig,
UserEndpointConfig,
)
from globus_compute_endpoint.endpoint.config.config import MINIMUM_HEARTBEAT
from globus_compute_endpoint.endpoint.endpoint import Endpoint
from globus_compute_endpoint.endpoint.rabbit_mq import (
CommandQueueSubscriber,
ResultPublisher,
)
from globus_compute_endpoint.endpoint.utils import _redact_url_creds
from globus_sdk import UserApp
from pytest_mock import MockFixture
try:
import pyprctl
except AttributeError:
pytest.skip(allow_module_level=True)
else:
# these imports also import pyprctl later
from globus_compute_endpoint.endpoint.endpoint_manager import (
EndpointManager,
InvalidUserError,
MappedPosixIdentity,
)
_MOCK_BASE = "globus_compute_endpoint.endpoint.endpoint_manager."
# SPoA for "good/happy-path" exit codes
_GOOD_EC = 88
_GOOD_UNPRIVILEGED_EC = 84
_mock_rootuser_rec = pwd.struct_passwd(
("root", "", 0, 0, "Mock Root User", "/mock_root", "/bin/false")
)
_mock_localuser_rec = pwd.struct_passwd(
(
"a_local_user",
"",
12345,
67890,
"Mock Regular User",
"/usr/home/...",
"/bin/false",
)
)
_ep_info_known_keys = (
"posix_ppid",
"globus_candidate_identities",
"globus_matched_identity",
)
class MockPamError(Exception):
def __init__(self, *a, **k):
pass
def mock_ensure_compute_dir():
return pathlib.Path(_mock_localuser_rec.pw_dir) / ".globus_compute"
@pytest.fixture
def mock_log():
with mock.patch(f"{_MOCK_BASE}log", spec=logging.Logger) as m:
m.getEffectiveLevel.return_value = logging.DEBUG
yield m
@pytest.fixture
def conf_dir(fs, request):
conf_dir = pathlib.Path(f"/{request.node.name}/mock_endpoint")
conf_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
g_and_o_perms = (conf_dir.stat().st_mode | 0o00) & 0o77 # get G and O perms
assert g_and_o_perms == 0, "Tests should work with protective permissions"
yield conf_dir
if conf_dir.exists():
g_and_o_perms = (conf_dir.stat().st_mode | 0o00) & 0o77 # get G and O perms
assert g_and_o_perms == 0, "Code should not change permissions"
@pytest.fixture
def identity_map_path(conf_dir):
im_path = conf_dir / "some_identity_mapping_configuration.json"
im_path.write_text("[]")
yield im_path
@pytest.fixture
def mock_conf(identity_map_path):
yield ManagerEndpointConfig()
@pytest.fixture
def mock_conf_root(identity_map_path):
yield ManagerEndpointConfig(identity_mapping_config_path=identity_map_path)
@pytest.fixture(autouse=True)
def user_conf_template(conf_dir) -> pathlib.Path:
template = Endpoint.user_config_template_path(conf_dir)
template.write_text("""
heartbeat_period: {{ heartbeat }}
engine:
type: GlobusComputeEngine
provider:
type: LocalProvider
init_blocks: 1
min_blocks: 0
max_blocks: 1
""")
return template
@pytest.fixture(autouse=True)
def mock_setproctitle(mocker, randomstring):
orig_proc_title = randomstring()
mock_spt = mocker.patch(f"{_MOCK_BASE}setproctitle")
mock_spt.getproctitle.return_value = orig_proc_title
yield mock_spt, orig_proc_title
@pytest.fixture
def mock_reg_info(ep_uuid) -> str:
yield {
"endpoint_id": ep_uuid,
"command_queue_info": {"connection_url": "", "queue": ""},
"result_queue_info": {
"connection_url": "",
"queue": "",
"queue_publish_kwargs": {},
},
"heartbeat_queue_info": {
"connection_url": "",
"queue": "",
"queue_publish_kwargs": {},
},
}
@pytest.fixture(autouse=True)
def mock_app(mocker: MockFixture) -> UserApp:
_app = mock.Mock(spec=UserApp)
mocker.patch(f"{_MOCK_BASE}get_globus_app_with_scopes", return_value=_app)
return _app
@pytest.fixture
def mock_close_fds():
with mock.patch(f"{_MOCK_BASE}close_all_fds") as m:
yield m
@pytest.fixture
def mock_client(mocker, ep_uuid, mock_reg_info):
mock_gcc = mock.Mock()
mock_gcc.register_endpoint.return_value = mock_reg_info
mocker.patch(f"{_MOCK_BASE}Client", return_value=mock_gcc)
yield ep_uuid, mock_gcc
@pytest.fixture
def mock_auth_client(mocker):
mock_ac = mock.Mock()
mocker.patch(f"{_MOCK_BASE}ComputeAuthClient", return_value=mock_ac)
yield mock_ac
@pytest.fixture(autouse=True)
def mock_pim(request):
if "no_mock_pim" in request.keywords:
yield
return
with mock.patch(f"{_MOCK_BASE}PosixIdentityMapper") as mock_pim:
mock_pim.return_value = mock_pim
yield mock_pim
@pytest.fixture
def mock_props():
yield pika.BasicProperties(
content_type="application/json",
content_encoding="utf-8",
timestamp=round(time.time()),
expiration="10000",
)
@pytest.fixture
def epmanager_as_user(
mocker,
conf_dir,
mock_close_fds,
mock_client,
mock_auth_client,
mock_conf,
mock_reg_info,
):
mock_os = mocker.patch(f"{_MOCK_BASE}os")
mock_os.getuid.return_value = _mock_localuser_rec.pw_uid
mock_os.getgid.return_value = _mock_localuser_rec.pw_gid
mock_os.getppid.return_value = 3333
mock_os.getpid.return_value = 44444444
mock_os.fork.return_value = 0
mock_os.pipe.return_value = 40, 41
mock_os.dup2.side_effect = (0, 1, 2, AssertionError("dup2: unexpected?"))
mock_os.open.side_effect = (4, 5, AssertionError("open: unexpected?"))
mock_pwd = mocker.patch(f"{_MOCK_BASE}pwd")
mock_pwd.getpwnam.side_effect = AssertionError(
"getpwnam: unprivileged should not care"
)
mock_pwd.getpwuid.side_effect = (
_mock_localuser_rec, # Initial "who am I?"
_mock_localuser_rec, # Registration's get_metadata()
AssertionError("getpwuid: should not request user in event loop!"),
)
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=False)
ep_uuid, _ = mock_client
# Needed to mock the pipe buffer size
mocker.patch.object(fcntl, "fcntl", return_value=8192)
ident = "some_identity_uuid"
mock_auth_client.userinfo.return_value = {"identity_set": [{"sub": ident}]}
mock_conf.identity_mapping_config_path = None
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
assert em.identity_mapper is None
em._command_queue = mock.Mock()
em._command_stop_event.set()
yield conf_dir, mock_conf, mock_client, mock_os, mock_pwd, em
assert em.identity_mapper is None
em.request_shutdown(None, None)
@pytest.fixture
def epmanager_as_root(
mocker,
conf_dir,
mock_close_fds,
mock_conf_root,
mock_client,
mock_auth_client,
mock_pim,
mock_reg_info,
):
mock_os = mocker.patch(f"{_MOCK_BASE}os")
mock_os.getppid.return_value = 1111
mock_os.getpid.return_value = 22222222
mock_os.getuid.return_value = 0
mock_os.getgid.return_value = 0
mock_os.setuid.side_effect = PermissionError("[unit test] Operation not permitted")
mock_os.fork.return_value = 0
mock_os.pipe.return_value = 40, 41
mock_os.dup2.side_effect = (0, 1, 2, AssertionError("dup2: unexpected?"))
mock_os.open.side_effect = (4, 5, AssertionError("open: unexpected?"))
mock_os.environ = {"Some": "test", "environ": "with", "debug": "1"}
mock_pwd = mocker.patch(f"{_MOCK_BASE}pwd")
mock_pwd.getpwnam.side_effect = (
_mock_localuser_rec,
AssertionError("getpwnam: Test whoops!"),
)
mock_pwd.getpwuid.side_effect = (
_mock_rootuser_rec,
_mock_localuser_rec,
_mock_localuser_rec,
AssertionError("getpwuid: Test whoops!"),
)
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=True)
mocker.patch(f"{_MOCK_BASE}ensure_compute_dir", side_effect=mock_ensure_compute_dir)
ep_uuid, _ = mock_client
# Needed to mock the pipe buffer size
mocker.patch.object(fcntl, "fcntl", return_value=8192)
ident = "epmanager_some_identity"
mock_auth_client.userinfo.return_value = {"identity_set": [{"sub": ident}]}
em = EndpointManager(conf_dir, ep_uuid, mock_conf_root, mock_reg_info)
em._command = mock.Mock(spec=CommandQueueSubscriber)
em._heartbeat_publisher = mock.Mock(spec=ResultPublisher)
yield conf_dir, mock_conf_root, mock_client, mock_os, mock_pwd, em
if em.identity_mapper:
em.identity_mapper.stop_watching()
em.request_shutdown(None, None)
@pytest.fixture
def ident():
return "successful_exec_some_identity"
@pytest.fixture
def command_payload(ident):
return {
"globus_username": "a@example.com",
"globus_effective_identity": 1,
"globus_identity_set": [{"sub": ident}],
"command": "cmd_start_endpoint",
"kwargs": {
"name": "some_ep_name",
"user_opts": {"heartbeat": 10},
"amqp_creds": {},
"user_runtime": {
"python": {
"version": "3.4.2",
},
"globus_compute_sdk_version": "2.90.2",
},
},
}
@pytest.fixture
def successful_exec_from_mocked_root(
epmanager_as_root,
mock_auth_client,
user_conf_template,
mock_props,
ident,
command_payload,
):
conf_dir, mock_conf, mock_client, mock_os, mock_pwd, em = epmanager_as_root
mock_auth_client.userinfo.return_value = {"identity_set": [{"sub": ident}]}
queue_item = (1, mock_props, json.dumps(command_payload).encode())
em.identity_mapper = mock.Mock()
em.identity_mapper.map_identities.return_value = [
[{ident: ["typicalglobusname@somehost.org"]}]
]
em._command_queue = mock.Mock()
em._command_stop_event.set()
em._command_queue.get.side_effect = [queue_item, queue.Empty()]
yield mock_os, conf_dir, mock_conf, mock_client, mock_pwd, em
@pytest.fixture
def successful_exec_from_mocked_user(
epmanager_as_user,
mock_auth_client,
user_conf_template,
mock_props,
ident,
command_payload,
):
conf_dir, mock_conf, mock_client, mock_os, mock_pwd, em = epmanager_as_user
mock_auth_client.userinfo.return_value = {"identity_set": [{"sub": ident}]}
queue_item = (1, mock_props, json.dumps(command_payload).encode())
em._command_queue = mock.Mock()
em._command_stop_event.set()
em._command_queue.get.side_effect = [queue_item, queue.Empty()]
yield mock_os, conf_dir, mock_conf, mock_client, mock_pwd, em
def _create_pam_handle_mock():
try:
# attempt to play nice with systems that do not have PAM installed, and
# rely on those that do to test with spec=PamHandle
from globus_compute_endpoint.pam import PamHandle
_has_pam = True
except ImportError:
_has_pam = False
def _create_mock():
# work with other fixtures (namely fs), that don't like multiple attempts to
# import; do the work once and cache it via closure
while True:
if _has_pam:
yield mock.MagicMock(spec=PamHandle)
else:
yield mock.MagicMock()
return _create_mock()
create_pam_handle_mock = _create_pam_handle_mock()
@pytest.fixture
def mock_pamh():
m = next(create_pam_handle_mock)
m.return_value = m
m.__enter__.return_value = m
yield m
@pytest.fixture
def mock_pam(mock_pamh):
with mock.patch(f"{_MOCK_BASE}_import_pam") as m:
m.return_value = m
m.PamHandle = mock_pamh
m.PamError = MockPamError
yield m
@pytest.fixture
def mock_ctl():
with mock.patch(f"{_MOCK_BASE}_import_pyprctl") as m:
m.return_value = m
yield m
@pytest.mark.parametrize("env", (None, "blar", "local", "production"))
def test_sets_process_title(
randomstring,
conf_dir,
mock_conf,
mock_client,
mock_setproctitle,
env,
mock_reg_info,
):
mock_spt, orig_proc_title = mock_setproctitle
ep_uuid, mock_gcc = mock_client
mock_conf.environment = env
EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
assert mock_spt.setproctitle.called, "Sanity check"
a, *_ = mock_spt.setproctitle.call_args
assert a[0].startswith(
"Globus Compute Endpoint"
), "Expect easily identifiable process name"
assert "*(" in a[0], "Expected asterisk as subtle clue of 'manager process'"
assert f"{ep_uuid}, {conf_dir.name}" in a[0], "Can find process by conf"
if env:
assert f" - {env}" in a[0], "Expected environment name in title"
else:
assert " - " not in a[0], "Default is not 'do not show env' for prod"
assert a[0].endswith(f"[{orig_proc_title}]"), "Save original cmdline for debugging"
@pytest.mark.parametrize("custom_template_path", (True, False))
@pytest.mark.parametrize("custom_schema_path", (True, False))
def test_sets_user_config_template_and_schema_path(
mock_client: t.Tuple[uuid.UUID, mock.Mock],
conf_dir: pathlib.Path,
mock_conf: ManagerEndpointConfig,
custom_template_path: bool,
custom_schema_path: bool,
mock_reg_info,
):
ep_uuid, _ = mock_client
template_path = Endpoint.user_config_template_path(conf_dir)
if custom_template_path:
template_path = conf_dir / "my_template.yaml.j2"
schema_path = Endpoint.user_config_schema_path(conf_dir)
if custom_schema_path:
schema_path = conf_dir / "my_schema.json"
template_path.touch()
schema_path.write_text("{}")
mock_conf.user_config_template_path = template_path
mock_conf.user_config_schema_path = schema_path
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
assert em.user_config_template_path == template_path
assert em.user_config_schema_path == schema_path
def test_mismatched_id_gracefully_exits(
mock_log, randomstring, conf_dir, mock_conf, mock_client, mock_reg_info
):
wrong_uuid, mock_gcc = mock_client
ep_uuid = str(uuid.uuid4())
assert wrong_uuid != ep_uuid, "Verify test setup"
with pytest.raises(SystemExit) as pyexc:
EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
assert pyexc.value.code == os.EX_SOFTWARE, "Expected meaningful exit code"
assert mock_log.error.called
a = mock_log.error.call_args[0][0]
assert "mismatched endpoint" in a
assert f"Expected: {ep_uuid}" in a
assert f"received: {wrong_uuid}" in a
@pytest.mark.parametrize(
"received_data",
(
(False, {"command_queue_info": {"connection_url": ""}}),
(False, {"command_queue_info": {"queue": ""}}),
(False, {"heartbeat_queue_info": {"connection_url": ""}}),
(False, {"heartbeat_queue_info": {"queue": ""}}),
(
False,
{
"typo-ed_cqi": {"connection_url": "", "queue": ""},
"heartbeat_queue_info": {"connection_url": "", "queue": ""},
},
),
(
True,
{
"command_queue_info": {"connection_url": "", "queue": ""},
"heartbeat_queue_info": {
"connection_url": "",
"queue": "",
"queue_publish_kwargs": {},
},
},
),
),
)
def test_handles_invalid_reg_info(
mock_log, randomstring, conf_dir, mock_conf, mock_client, received_data
):
ep_uuid, mock_gcc = mock_client
received_data[1]["endpoint_id"] = ep_uuid
should_succeed, mock_gcc.register_endpoint.return_value = received_data
if not should_succeed:
with pytest.raises(SystemExit) as pyexc:
EndpointManager(conf_dir, ep_uuid, mock_conf, received_data[1])
assert pyexc.value.code == os.EX_DATAERR, "Expected meaningful exit code"
assert mock_log.error.called
a = mock_log.error.call_args[0][0]
assert "Invalid or unexpected" in a
else:
# "null" test
EndpointManager(conf_dir, ep_uuid, mock_conf, received_data[1])
def test_records_user_ep_as_running(successful_exec_from_mocked_root):
mock_os, *_, em = successful_exec_from_mocked_root
mock_os.fork.return_value = 1
em._event_loop()
uep_rec = em._children.pop(1)
assert uep_rec.ep_name == "some_ep_name"
def test_caches_start_cmd_args_if_ep_already_running(
mocker, successful_exec_from_mocked_root, command_payload
):
*_, em = successful_exec_from_mocked_root
child_pid = random.randrange(1, 32768 + 1)
mock_uep = mocker.MagicMock()
mock_uep.ep_name = "some_ep_name"
em._children[child_pid] = mock_uep
em._event_loop()
assert child_pid in em._children
cached_args = em._cached_cmd_start_args.pop(child_pid)
assert cached_args is not None
mpi, args, kwargs = cached_args
assert mpi.local_user_record == _mock_localuser_rec
assert args == []
assert kwargs == command_payload["kwargs"]
def test_writes_endpoint_uuid(epmanager_as_root):
conf_dir, _mock_conf, mock_client, *_ = epmanager_as_root
_ep_uuid, mock_gcc = mock_client
returned_uuid = mock_gcc.register_endpoint.return_value["endpoint_id"]
ep_json_path = conf_dir / "endpoint.json"
assert ep_json_path.exists()
ep_data = json.loads(ep_json_path.read_text())
assert ep_data["endpoint_id"] == returned_uuid
def test_log_contains_sentinel_lines(
mocker, mock_log, epmanager_as_root, noop, reset_signals
):
*_, em = epmanager_as_root
mocker.patch(f"{_MOCK_BASE}os")
em._event_loop = noop
em.start()
uuid_pat = r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
beg_re_sentinel = re.compile(r"\n\n=+ Endpoint Manager begins: ")
beg_re_uuid = re.compile(rf"\n\n=+ Endpoint Manager begins: {uuid_pat}\n")
end_re_sentinel = re.compile(r"\n-+ Endpoint Manager ends: ")
end_re_uuid = re.compile(rf"\n-+ Endpoint Manager ends: {uuid_pat}\n\n")
log_str = "\n".join(a[0] for a, _ in mock_log.info.call_args_list)
assert log_str.startswith("\n\n"), "Expect visual separation for log trawlers"
assert beg_re_sentinel.search(log_str) is not None, "Expected visual begin sentinel"
assert beg_re_uuid.search(log_str) is not None, "Expected begin sentinel has EP id"
assert "\nShutdown complete.\n" in log_str
assert end_re_sentinel.search(log_str) is not None, "Expected visual end sentinel"
assert end_re_uuid.search(log_str) is not None, "Expected end sentinel has EP id"
def test_title_changes_for_shutdown(
mocker, epmanager_as_root, noop, mock_setproctitle, reset_signals
):
*_, em = epmanager_as_root
mock_spt, orig_proc_title = mock_setproctitle
em._event_loop = noop
mocker.patch(f"{_MOCK_BASE}os")
mock_spt.reset_mock()
assert not mock_spt.setproctitle.called, "Verify test setup"
em.start()
assert mock_spt.setproctitle.called
a = mock_spt.setproctitle.call_args[0][0]
assert a.startswith("[shutdown in progress]"), "Let admin know action in progress"
assert a.endswith(orig_proc_title)
def test_children_signaled_at_shutdown(
mocker, epmanager_as_root, randomstring, noop, reset_signals
):
*_, em = epmanager_as_root
em._event_loop = mock.Mock()
em.wait_for_children = noop
mock_os = mocker.patch(f"{_MOCK_BASE}os")
mock_time = mocker.patch(f"{_MOCK_BASE}time")
mock_time.monotonic.side_effect = [0, 10, 20, 30] # don't _actually_ wait.
mock_os.getuid.side_effect = ["us"] # fail if called more than once; intentional
mock_os.getgid.side_effect = ["us"] # fail if called more than once; intentional
mock_os.getpgid = lambda pid: pid
expected = []
for _ in range(random.randrange(0, 10)):
uid, gid, pid = tuple(random.randint(1, 2**30) for _ in range(3))
uname = randomstring()
expected.append((uid, gid, uname, "some process command line"))
mock_rec = mocker.MagicMock()
mock_rec.uid, mock_rec.gid = uid, gid
em._children[pid] = mock_rec
gid_expected_calls = (
a
for b in zip(
((gid, gid, -1) for _uid, gid, *_ in expected),
[("us", "us", -1)] * len(expected), # return to root gid after signal
)
for a in b
)
uid_expected_calls = (
a
for b in zip(
((uid, uid, -1) for uid, _gid, *_ in expected),
[("us", "us", -1)] * len(expected), # return to root uid after signal
)
for a in b
)
# test that SIGTERM, *then* SIGKILL sent
killpg_expected_calls = [(pid, signal.SIGTERM) for pid in em._children]
killpg_expected_calls.extend((pid, signal.SIGKILL) for pid in em._children)
em.start()
assert em._event_loop.called, "Verify test setup"
resgid = mock_os.setresgid.call_args_list
resuid = mock_os.setresuid.call_args_list
killpg = mock_os.killpg.call_args_list[1:]
for setgid_call, exp_args in zip(resgid, gid_expected_calls):
assert setgid_call[0] == exp_args, "Signals only sent by _same_ user, NOT root"
for setuid_call, exp_args in zip(resuid, uid_expected_calls):
assert setuid_call[0] == exp_args, "Signals only sent by _same_ user, NOT root"
for killpg_call, exp_args in zip(killpg, killpg_expected_calls):
assert killpg_call[0] == exp_args, "Expected SIGTERM, *then* SIGKILL"
def test_restarts_running_endpoint_with_cached_args(epmanager_as_root, mock_log):
*_, mock_os, _mock_pwd, em = epmanager_as_root
child_pid = random.randrange(1, 32768 + 1)
mapped_posix = MappedPosixIdentity(_mock_localuser_rec, [], None)
args_tup = (
mapped_posix,
[],
{"name": "some_ep_name", "user_opts": {"heartbeat": 10}},
)
mock_os.waitpid.side_effect = [(child_pid, -1), (0, -1)]
mock_os.waitstatus_to_exitcode.return_value = 0
em._cached_cmd_start_args[child_pid] = args_tup
em.cmd_start_endpoint = mock.Mock()
em.wait_for_children()
a, _k = mock_log.info.call_args
assert "using cached arguments to start" in a[0]
assert em.cmd_start_endpoint.call_args.args == args_tup
def test_no_cached_args_means_no_restart(epmanager_as_root, mocker, mock_log):
*_, em = epmanager_as_root
child_pid = random.randrange(1, 32768 + 1)
mock_os = mocker.patch(f"{_MOCK_BASE}os")
mock_os.waitpid.side_effect = [(child_pid, -1), (0, -1)]
mock_os.waitstatus_to_exitcode.return_value = 0
em.cmd_start_endpoint = mock.Mock()
em.wait_for_children()
a, _k = mock_log.info.call_args
assert "stopped normally" in a[0], "Verify happy path"
assert not em.cmd_start_endpoint.called
def test_emits_endpoint_id_if_isatty(mocker, mock_log, epmanager_as_root):
*_, em = epmanager_as_root
mocker.patch.object(em, "_install_signal_handlers", side_effect=Exception)
mock_sys = mocker.patch(f"{_MOCK_BASE}sys")
mock_sys.stdout.isatty.return_value = True
mock_sys.stderr.isatty.return_value = True
with pytest.raises(Exception):
em.start()
assert mock_log.info.called, "Always emitted to log"
a = mock_log.info.call_args[0][0]
assert em._endpoint_uuid_str in a
assert mock_sys.stdout.write.called
assert not mock_sys.stderr.write.called, "Expect ID not emitted twice"
written = "".join(a[0] for a, _ in mock_sys.stdout.write.call_args_list)
assert em._endpoint_uuid_str in written
mock_log.reset_mock()
mock_sys.reset_mock()
mock_sys.stdout.isatty.return_value = False
mock_sys.stderr.isatty.return_value = True
with pytest.raises(Exception):
em.start()
assert mock_log.info.called, "Always emitted to log"
a = mock_log.info.call_args[0][0]
assert em._endpoint_uuid_str in a
assert not mock_sys.stdout.write.called, "Expect ID not emitted twice"
assert mock_sys.stderr.write.called
written = "".join(a[0] for a, _ in mock_sys.stderr.write.call_args_list)
assert em._endpoint_uuid_str in written
mock_log.reset_mock()
mock_sys.reset_mock()
mock_sys.stdout.isatty.return_value = False
mock_sys.stderr.isatty.return_value = False
with pytest.raises(Exception):
em.start()
assert mock_log.info.called, "Always emitted to log"
a = mock_log.info.call_args[0][0]
assert em._endpoint_uuid_str in a
assert not mock_sys.stdout.write.called
assert not mock_sys.stderr.write.called
def test_as_root_and_no_identity_mapper_configuration_allowed(
mocker, mock_client, conf_dir, mock_conf, mock_reg_info
):
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=True)
ep_uuid, _ = mock_client
mock_conf.identity_mapping_config_path = None
EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
def test_no_identity_mapper_if_unprivileged(
mocker, conf_dir, mock_conf_root, mock_client, mock_reg_info
):
mock_privilege = mocker.patch(f"{_MOCK_BASE}is_privileged")
mock_privilege.return_value = True
em = EndpointManager(conf_dir, None, mock_conf_root, mock_reg_info)
assert em.identity_mapper is not None
em.identity_mapper.stop_watching()
mock_privilege.return_value = False
em = EndpointManager(conf_dir, None, mock_conf_root, mock_reg_info)
assert em.identity_mapper is None
def test_unprivileged_warns_if_identity_conf_specified(
mocker, mock_log, conf_dir, mock_conf, mock_conf_root, mock_client, mock_reg_info
):
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=False)
em = EndpointManager(conf_dir, None, mock_conf, mock_reg_info)
assert em.identity_mapper is None
assert not mock_log.warning.called
em = EndpointManager(conf_dir, None, mock_conf_root, mock_reg_info)
assert em.identity_mapper is None
a, _ = mock_log.warning.call_args
assert "specified, but process is not privileged" in a[0]
assert "identity mapping configuration will be ignored" in a[0]
def test_quits_if_not_privileged_and_no_identity_set(
mocker, mock_log, mock_client, mock_auth_client, epmanager_as_root
):
*_, em = epmanager_as_root
em.identity_mapper = None
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=False)
mock_auth_client.userinfo.return_value = {"identity_set": []}
assert em._time_to_stop is False, "Verify test setup"
em._event_loop()
assert em._time_to_stop
a, _ = mock_log.error.call_args
assert "Failed to determine identity set" in a[0]
assert "try `whoami` command" in a[0], "Expected suggested action"
def test_clean_exit_on_identity_collection_error(
mocker, mock_log, mock_client, mock_auth_client, epmanager_as_root
):
*_, em = epmanager_as_root
em.identity_mapper = None
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=False)
mock_auth_client.userinfo.return_value = {"not_identity_set": None}
assert em._time_to_stop is False, "Verify test setup"
em._event_loop()
# handle potential Python version differences
ke = KeyError("identity_set")
expected_exc_text = f"({type(ke).__name__}) {ke}"
assert em._time_to_stop
a, _ = mock_log.error.call_args
assert expected_exc_text in a[0]
assert "Failed to determine identity set" in a[0]
assert "try `whoami` command" in a[0], "Expected suggested action"
a, k = mock_log.debug.call_args
assert "failed to determine identities" in a[0]
assert "exc_info" in k
@pytest.mark.no_mock_pim
def test_as_root_gracefully_handles_unreadable_identity_mapper_conf(
mocker, mock_log, conf_dir, mock_conf_root, identity_map_path
):
mock_print = mocker.patch(f"{_MOCK_BASE}print")
mocker.patch(f"{_MOCK_BASE}is_privileged", return_value=True)
ep_uuid = str(uuid.uuid1())
reg_info = {
"endpoint_id": ep_uuid,
"command_queue_info": {"connection_url": 1, "queue": 1},
}
identity_map_path.chmod(mode=0o000)
with pytest.raises(SystemExit) as pyt_exc:
EndpointManager(conf_dir, ep_uuid, mock_conf_root, reg_info)
assert pyt_exc.value.code == os.EX_NOPERM
assert mock_log.error.called
assert mock_print.called
for a in (mock_log.error.call_args[0][0], mock_print.call_args[0][0]):
assert "PermissionError" in a
identity_map_path.chmod(mode=0o644)
identity_map_path.write_text("[{asfg")
with pytest.raises(SystemExit) as pyt_exc:
EndpointManager(conf_dir, ep_uuid, mock_conf_root, reg_info)
assert pyt_exc.value.code == os.EX_CONFIG
assert mock_log.error.called
assert mock_print.called
for a in (mock_log.error.call_args[0][0], mock_print.call_args[0][0]):
assert "Unable to read identity mapping" in a
def test_iterates_even_if_no_commands(mocker, epmanager_as_root):
*_, em = epmanager_as_root
em._command_stop_event.set()
em._event_loop() # subtest is that it iterates and doesn't block
em._time_to_stop = False
em._command_queue = mock.Mock()
em._command_queue.get.side_effect = queue.Empty()
em._event_loop()
assert em._command_queue.get.called
@pytest.mark.parametrize("hb", (-100, -5, 0, 0.1, 4, 7, 11, None))
def test_heartbeat_period_minimum(conf_dir, mock_conf, hb, ep_uuid, mock_reg_info):
if hb is not None:
mock_conf._heartbeat_period = hb
assert mock_conf.heartbeat_period == hb, "Avoid config setter"
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
exp_hb = 30.0 if hb is None else max(MINIMUM_HEARTBEAT, hb)
assert exp_hb == em._heartbeat_period, "Expected a reasonable minimum heartbeat"
def test_send_heartbeat_verifies_thread(mock_conf, conf_dir, ep_uuid, mock_reg_info):
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
f = em.send_heartbeat()
exc = f.exception()
assert "publisher is not running" in str(exc)
def test_send_heartbeat_honors_shutdown(mock_conf, conf_dir, ep_uuid, mock_reg_info):
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
em._heartbeat_period = random.randint(1, 10000)
em._heartbeat_publisher = mock.Mock(spec=ResultPublisher)
em.send_heartbeat()
a, _ = em._heartbeat_publisher.publish.call_args
epsr: EPStatusReport = unpack(a[0])
assert epsr.global_state["heartbeat_period"] == em._heartbeat_period
em.send_heartbeat(shutting_down=True)
a, _ = em._heartbeat_publisher.publish.call_args
epsr: EPStatusReport = unpack(a[0])
assert epsr.global_state["heartbeat_period"] == 0
def test_send_heartbeat_shares_exception(
mock_log, mock_conf, conf_dir, ep_uuid, mock_reg_info, randomstring
):
exc_text = randomstring()
em = EndpointManager(conf_dir, ep_uuid, mock_conf, mock_reg_info)
em._heartbeat_publisher = mock.Mock(spec=ResultPublisher)
em._heartbeat_publisher.publish.return_value = Future()
f = em.send_heartbeat()
mock_log.error.reset_mock()
f.set_exception(MemoryError(exc_text))
assert mock_log.error.called
a, _ = mock_log.error.call_args
assert exc_text in str(a[0])
def test_sends_heartbeat_at_shutdown(epmanager_as_root, noop, reset_signals):
*_, em = epmanager_as_root
hb_fut = mock.Mock(spec=Future)
em.send_heartbeat = mock.Mock(spec=EndpointManager.send_heartbeat)
em.send_heartbeat.return_value = hb_fut
em._event_loop = noop
em.start()
assert hb_fut.result.called
a, _ = hb_fut.result.call_args
assert isinstance(a[0], int), "Expected *some* timeout value for sending a HB"
_, k = em.send_heartbeat.call_args
assert k["shutting_down"] is True