/
monitor.py
4152 lines (3848 loc) · 160 KB
/
monitor.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
"""
Monitor Thread
"""
import codecs
import json
import logging
import os
import re
import shutil
import sys
import tempfile
import threading
import time
from itertools import chain
import daemon.shared as shared
from core.freezer import Freezer
from env import Env
from foreign.six.moves import queue
from utilities.naming import (factory, fmt_path, list_services,
resolve_path, split_path, svc_pathcf,
svc_pathvar)
from utilities.files import makedirs, fsum
from utilities.cache import purge_cache
from utilities.storage import Storage
STARTED_STATES = [
"n/a",
"up",
]
STOPPED_STATES = [
"n/a",
"down",
"stdby up",
"stdby down",
"unknown", # slavers with deleted slaves
None, # base-kind services
]
SHUTDOWN_STATES = [
"n/a",
"down",
"stdby down",
"unknown", # slavers with deleted slaves
None, # base-kind services
]
ORCHESTRATE_STATES = (
"ready",
"idle",
"wait children",
"wait parents",
"wait sync",
"wait leader",
"wait non-leader",
)
ABORT_STATES = (
("thaw failed", "thawed"),
("freeze failed", "frozen"),
("start failed", "started"),
("stop failed", "stopped"),
("stop failed", "purged"),
("stop failed", "unprovisioned"),
("shutdown failed", "shutdown"),
("delete failed", "deleted"),
("unprovision failed", "unprovisioned"),
("provision failed", "provisioned"),
("place failed", "placed"),
("purge failed", "purged"),
)
NON_LEADER_ABORT_STATES = (
("stop failed", "placed@"),
("stop failed", "placed"),
)
LEADER_ABORT_STATES = (
("start failed", "placed"),
("start failed", "placed@"),
)
ETC_NS_SKIP = len(os.path.join(Env.paths.pathetcns, ""))
#import cProfile
#import pstats
#pr = cProfile.Profile()
#def start_profile():
# pr.enable()
#def stop_profile():
# pr.disable()
# ps = pstats.Stats(pr).sort_stats(2)
# ps.print_stats()
class Defer(Exception):
"""
Raised from orchestration routines to signal the condition to
start the next step are not satisfied yet.
"""
pass
class MonitorObjectOrchestratorManualMixin(object):
def object_orchestrator_manual(self, svc, smon, status):
"""
Take actions to meet global expect target, set by user or by
object_orchestrator_auto()
"""
if smon.global_expect is None:
return
instance = self.get_service_instance(svc.path, Env.nodename)
kwargs = dict(svc=svc, smon=smon, status=status, instance=instance)
try:
base_global_expect, target = smon.global_expect.split("@", 1)
fnname = "_oom_{ge}_at".format(ge=base_global_expect)
kwargs["target"] = target
except Exception:
fnname = "_oom_{ge}".format(ge=smon.global_expect)
try:
fn = getattr(self, fnname)
except AttributeError:
self.log.warning("unsupported global expect on %s: %s",
svc.path, smon.global_expect)
self.set_smon(global_expect="unset")
return
try:
fn(**kwargs)
except Defer as exc:
self.log.debug("%s %s defer %s", svc.path, fnname, exc.args[0])
def _oom_frozen(self, svc=None, smon=None, status=None, instance=None):
if not self.instance_frozen(svc.path):
self.event("instance_freeze", {
"reason": "target",
"path": svc.path,
"monitor": smon,
})
self.service_freeze(svc.path)
def _oom_thawed(self, svc=None, smon=None, status=None, instance=None):
if self.instance_frozen(svc.path):
self.event("instance_thaw", {
"reason": "target",
"path": svc.path,
"monitor": smon,
})
self.service_thaw(svc.path)
def _oom_shutdown(self, svc=None, smon=None, status=None, instance=None):
def step_wait_children():
if not self.children_down(svc):
self.set_smon(svc.path, status="wait children")
raise Defer("wait: children are not stopped yet")
elif smon.status == "wait children":
self.set_smon(svc.path, status="idle")
def step_freeze():
if self.instance_frozen(svc.path):
return
self.event("instance_freeze", {
"reason": "target",
"path": svc.path,
})
self.service_freeze(svc.path)
raise Defer("freeze: action started")
def step_shutdown():
if self.is_instance_shutdown(instance):
return
thawed_on = self.service_instances_thawed(svc.path)
if thawed_on:
self.duplog("info", "service %(path)s still has thawed "
"instances on nodes %(thawed_on)s, delay "
"shutdown",
path=svc.path,
thawed_on=", ".join(thawed_on))
else:
self.service_shutdown(svc.path)
step_wait_children()
step_freeze()
step_shutdown()
def _oom_stopped(self, svc=None, smon=None, status=None, instance=None):
def step_wait_children():
if not self.children_down(svc):
self.set_smon(svc.path, status="wait children")
raise Defer("wait: children are not stopped yet")
elif smon.status == "wait children":
self.set_smon(svc.path, status="idle")
def step_freeze():
if self.instance_frozen(svc.path):
return
self.log.info("freeze service %s", svc.path)
self.event("instance_freeze", {
"reason": "target",
"path": svc.path,
})
self.service_freeze(svc.path)
raise Defer("freeze: action started")
def step_stop():
if instance.avail in STOPPED_STATES:
return
thawed_on = self.service_instances_thawed(svc.path)
if thawed_on:
self.duplog("info", "service %(path)s still has thawed instances "
"on nodes %(thawed_on)s, delay stop",
path=svc.path,
thawed_on=", ".join(thawed_on))
else:
self.event("instance_stop", {
"reason": "target",
"path": svc.path,
})
self.service_stop(svc.path)
step_wait_children()
step_freeze()
step_stop()
def _oom_started(self, svc=None, smon=None, status=None, instance=None):
def step_wait_parents():
if not self.parents_available(svc):
self.set_smon(svc.path, status="wait parents")
raise Defer("wait: parents are not started yet")
elif smon.status == "wait parents":
self.set_smon(svc.path, status="idle")
def step_thaw():
if not self.instance_frozen(svc.path):
return
self.event("instance_thaw", {
"reason": "target",
"path": svc.path,
})
self.service_thaw(svc.path)
raise Defer("thaw: action started")
def step_start():
if status in STARTED_STATES:
return
agg = self.get_service_agg(svc.path)
if agg.frozen != "thawed":
raise Defer("start: instance is not thawed yet")
self.object_orchestrator_auto(svc, smon, status)
raise Defer("start: action started")
step_thaw()
step_wait_parents()
step_start()
def _oom_unprovisioned(self, svc=None, smon=None, status=None, instance=None):
def step_wait_status():
if smon.status not in ("unprovisioning", "stopping"):
return
raise Defer("wait: incompatible monitor status: %s" % smon.status)
def step_wait_done():
if svc.path in shared.SERVICES and not self.instance_unprovisioned(instance):
return
if smon.status != "idle":
self.set_smon(svc.path, status="idle")
raise Defer("wait: instance does not exist or already unprovisioned")
def step_set_wait_children():
if self.children_unprovisioned(svc):
return
self.set_smon(svc.path, status="wait children")
raise Defer("wait: set wait children")
def step_stop():
if instance.avail in STOPPED_STATES:
return
self.event("instance_stop", {
"reason": "target",
"path": svc.path,
})
self.service_stop(svc.path, force=True)
raise Defer("stop: action started")
def step_wait_stopped():
agg = self.get_service_agg(svc.path)
if agg.avail in STOPPED_STATES:
return
raise Defer("wait: local instance not stopped yet")
def step_wait_children():
if smon.status != "wait children":
return
if self.children_unprovisioned(svc):
return
raise Defer("wait: children are not unprovisioned yet")
def step_wait_non_leader():
if smon.status != "wait non-leader":
return
if self.leader_last(svc, provisioned=False, silent=True):
return
self.log.info("service %s still waiting non leaders", svc.path)
raise Defer("wait: non-leader instances are not unprovisioned yet")
def step_set_wait_non_leader():
leader = self.leader_last(svc, provisioned=False)
if leader:
return leader
self.set_smon(svc.path, status="wait non-leader")
raise Defer("wait: set wait non-leader")
def step_unprovision():
self.event("instance_unprovision", {
"reason": "target",
"path": svc.path,
})
self.service_unprovision(svc, leader)
step_wait_status()
step_wait_done()
step_set_wait_children()
step_stop()
step_wait_stopped()
step_wait_children()
leader = step_wait_non_leader() # pylint: disable=assignment-from-none
step_set_wait_non_leader()
step_unprovision()
def _oom_provisioned(self, svc=None, smon=None, status=None, instance=None):
def step_wait_parents():
if smon.status == "wait parents":
if not self.parents_available(svc):
raise Defer("wait: parents not available")
def step_wait_leader():
if smon.status == "wait leader":
if not self.leader_first(svc, provisioned=True, silent=True):
raise Defer("wait: leader not provisioned yet")
def step_wait_sync():
if smon.status == "wait sync":
if not self.min_instances_reached(svc):
raise Defer("wait: the object configuration is not synced yet")
def step_provision():
if self.instance_provisioned(instance):
self.set_smon(svc.path, status="idle")
raise Defer("provision: instance already provisioned")
if not self.min_instances_reached(svc):
self.set_smon(svc.path, status="wait sync")
raise Defer("provision: set wait sync")
if self.is_natural_leader(svc) and not self.parents_available(svc):
self.set_smon(svc.path, status="wait parents")
raise Defer("provision: set wait parents")
if not self.leader_first(svc, provisioned=True):
self.set_smon(svc.path, status="wait leader")
raise Defer("provision: set wait leader")
self.event("instance_provision", {
"reason": "target",
"path": svc.path,
})
self.service_provision(svc)
raise Defer("provision: action started")
step_wait_parents()
step_wait_leader()
step_wait_sync()
step_provision()
def _oom_deleted(self, svc=None, smon=None, status=None, instance=None):
def step_wait_children():
if self.children_down(svc):
if smon.status == "wait children":
self.set_smon(svc.path, status="idle")
return
self.set_smon(svc.path, status="wait children")
raise Defer("wait: children are not down yet")
def step_delete():
if svc.path not in shared.SERVICES:
raise Defer("delete: object does not exist")
self.event("instance_delete", {
"reason": "target",
"path": svc.path,
})
self.service_delete(svc.path)
raise Defer("delete: action started")
step_wait_children()
step_delete()
def _oom_purged(self, svc=None, smon=None, status=None, instance=None):
def step_wait_status():
if smon.status not in ("purging", "deleting", "stopping"):
return
raise Defer("wait: incompatible monitor status: %s" % smon.status)
def step_wait_children():
if self.children_unprovisioned(svc):
return
self.set_smon(svc.path, status="wait children")
raise Defer("wait: children are not unprovisioned yet")
def step_stop():
if instance.avail in STOPPED_STATES:
return
self.event("instance_stop", {
"reason": "target",
"path": svc.path,
})
self.service_stop(svc.path, force=True)
raise Defer("stop: action started")
def step_purge():
agg = self.get_service_agg(svc.path)
if agg.avail not in STOPPED_STATES:
raise Defer("purge: object is not stopped")
if smon.status == "wait children":
if not self.children_unprovisioned(svc):
raise Defer("purge: waiting children")
elif smon.status == "wait non-leader":
if not self.leader_last(svc, provisioned=False, silent=True, deleted=True):
raise Defer("purge: waiting non-leader")
leader = self.leader_last(svc, provisioned=False, deleted=True)
if not leader:
self.set_smon(svc.path, status="wait non-leader")
raise Defer("purge: wait non-leader")
if svc.path in shared.SERVICES and svc.kind not in ("vol", "svc"):
# base services do not implement the purge action
self.event("instance_delete", {
"reason": "target",
"path": svc.path,
})
self.service_delete(svc.path)
raise Defer("purge: delete action started")
if svc.path not in shared.SERVICES or not instance:
if smon.status != "idle":
self.set_smon(svc.path, status="idle")
raise Defer("purge: object or instance does not exist")
self.event("instance_purge", {
"reason": "target",
"path": svc.path,
})
self.service_purge(svc, leader)
raise Defer("purge: action started")
step_wait_status()
step_wait_children()
step_stop()
step_purge()
def _oom_aborted(self, svc=None, smon=None, status=None, instance=None):
if smon.local_expect in (None, "started"):
return
self.event("instance_abort", {
"reason": "target",
"path": svc.path,
})
self.set_smon(svc.path, local_expect="unset")
def _oom_placed(self, svc=None, smon=None, status=None, instance=None):
"""
Flex start new instances before stopping the old.
Failover stop old instance before stopping the new.
"""
# refresh smon for placement attr change caused by a clear
smon = self.get_service_monitor(svc.path)
def step_thaw():
if not self.instance_frozen(svc.path):
return
self.event("instance_thaw", {
"reason": "target",
"path": svc.path,
})
self.service_thaw(svc.path)
raise Defer("thaw: action started")
def step_stop():
if smon.placement == "leader":
return
if not self.has_leader(svc):
raise Defer("stop: no peer node can takeover")
if instance.avail in STOPPED_STATES:
raise Defer("stop: local instance already stopped")
if svc.topology == "flex" and not self.leaders_started(svc.path):
raise Defer("start: flex leader instances not started")
self.event("instance_stop", {
"reason": "target",
"path": svc.path,
})
self.service_stop(svc.path)
raise Defer("stop: action started")
def step_start():
if instance.avail in STARTED_STATES:
return
if svc.topology == "failover" and not self.non_leaders_stopped(svc.path):
raise Defer("start: failover non-leader instances not stopped")
agg = self.get_service_agg(svc.path)
if agg.placement in ("optimal", "n/a") and agg.avail == "up":
raise Defer("start: aggregate placement is optimal and avail up")
self.object_orchestrator_auto(svc, smon, status)
raise Defer("start: action started")
step_thaw()
step_stop()
step_start()
def _oom_placed_at(self, svc=None, smon=None, status=None, instance=None, target=None):
"""
Flex start new instances before stopping the old.
Failover stop old instance before stopping the new.
"""
target = target.split(",")
candidates = self.placement_candidates(
svc, discard_frozen=False,
discard_overloaded=False,
discard_unprovisioned=False,
discard_constraints_violation=False,
discard_start_failed=False,
discard_affinities=False,
)
def step_thaw():
if not self.instance_frozen(svc.path):
return
self.event("instance_thaw", {
"reason": "target",
"path": svc.path,
})
self.service_thaw(svc.path)
raise Defer("thaw: action started")
def step_stop():
if Env.nodename in target:
return
if instance.avail in STOPPED_STATES:
return
if svc.topology == "flex" and not self.instances_started(svc.path, set(svc.peers) & set(target)):
raise Defer("stop: flex destination instances not started")
if smon.status == "stop failed":
raise Defer("stop: local instance blocking mon status (%s)" % smon.status)
if not (set(target) & set(candidates)):
raise Defer("stop: no candidate to takeover")
self.event("instance_stop", {
"reason": "target",
"path": svc.path,
})
self.service_stop(svc.path)
raise Defer("stop: action started")
def step_wait_parents():
dep = self.parents_available(svc)
if not dep and instance.avail not in STARTED_STATES:
self.set_smon(svc.path, status="wait parents")
raise Defer("wait: parents are not started yet")
if smon.status == "wait parents":
if dep or instance.avail in STARTED_STATES:
self.set_smon(svc.path, status="idle")
def step_start():
if Env.nodename not in target:
return
if instance.avail in STARTED_STATES:
return
if svc.topology == "failover" and not self.instances_stopped(svc.path, set(svc.peers) - set(target)):
raise Defer("start: failover source instances not stopped")
if Env.nodename not in target:
raise Defer("start: not a target")
if instance.avail not in STOPPED_STATES + ["warn"]:
raise Defer("start: local instance not stopped or warn")
if smon.status in ("start failed", "place failed"):
raise Defer("start: local instance blocking mon status (%s)" % smon.status)
self.event("instance_start", {
"reason": "target",
"path": svc.path,
})
err_status="place failed" if smon.global_expect == "placed" else "start failed"
self.service_start(svc.path, err_status=err_status)
raise Defer("start: action started")
step_thaw()
step_stop()
step_wait_parents()
step_start()
class Monitor(shared.OsvcThread, MonitorObjectOrchestratorManualMixin):
"""
The monitoring thread collecting local service states and taking decisions.
"""
name = "monitor"
monitor_period = 0.5
arbitrators_check_period = 60
max_shortloops = 30
default_stdby_nb_restart = 2
arbitrators_data = None
last_arbitrator_ping = 0
def __init__(self):
shared.OsvcThread.__init__(self)
self._shutdown = False
self.compat = True
self.last_node_data = None
self.init_steps = set()
def init(self):
self.set_tid()
self.log = logging.LoggerAdapter(logging.getLogger(Env.nodename+".osvcd.monitor"), {"node": Env.nodename, "component": self.name})
self.event("monitor_started")
self.startup = time.time()
self.rejoin_grace_period_expired = False
self.shortloops = 0
self.unfreeze_when_all_nodes_joined = False
self.node_frozen = self.freezer.node_frozen()
self.init_data()
if os.environ.get("OPENSVC_AGENT_UPGRADE"):
if not self.node_frozen:
self.event("node_freeze", data={"reason": "upgrade"})
self.unfreeze_when_all_nodes_joined = True
self.freezer.node_freeze()
self.node_frozen = self.freezer.node_frozen()
last_boot_id = shared.NODE.last_boot_id()
boot_id = shared.NODE.asset.get_boot_id()
try:
# align float precision (py2/3 use different precision for mtime)
last_boot_id = "%.02f" % float(last_boot_id)
boot_id = "%.02f" % float(boot_id)
except (TypeError, ValueError):
pass
self.log.info("boot id %s, last %s", boot_id, last_boot_id)
self.wait_listener()
if last_boot_id in (None, boot_id):
self.services_init_status()
else:
self.kern_freeze()
self.services_init_boot()
shared.NODE.write_boot_id()
self.dump_nodes_info()
# send a first message without service status, so the peers know
# we are in init state.
self.update_hb_data()
def wait_listener(self):
while True:
lsnr = shared.THREADS.get("listener")
if lsnr and lsnr.stage == "ready":
break
time.sleep(0.2)
def init_data(self):
self._update_cluster_data()
shared.GEN = 0
initial_data = {
"compat": shared.COMPAT_VERSION,
"api": shared.API_VERSION,
"agent": shared.NODE.agent_version,
"monitor": {
"status": "init",
"status_updated": time.time(),
},
"labels": shared.NODE.labels,
"targets": shared.NODE.targets,
"services": {
"status": {},
"config": {},
},
"gen": {
},
"config": {
"csum": shared.NODE.nodeconf_csum(),
},
}
self.node_data.set([], initial_data)
for nodename in self.cluster_nodes:
self.nodes_data.setnx([nodename], {})
def run(self):
try:
self.init()
except Exception as exc:
self.log.exception(exc)
raise
try:
while True:
self.do()
if self.stopped():
self.join_threads()
self.kill_procs()
sys.exit(0)
except Exception as exc:
self.log.exception(exc)
def transition_count(self):
count = 0
for path, smon in self.iter_local_services_monitors():
if smon.status and smon.status != "scaling" and smon.status.endswith("ing"):
count += 1
return count
def set_next(self, timeout):
"""
Set the shortloop counter to the value meaning the long loop will
be run at most in <timeout> seconds.
"""
target = self.max_shortloops - (timeout // self.monitor_period)
if target < 0:
target = 0
elif target < self.shortloops:
return
self.shortloops = target
def add_service(self, path):
name, namespace, kind = split_path(path)
svc = factory(kind)(name, namespace, node=shared.NODE, log_handlers=[])
svc.configure_scheduler()
shared.SERVICES[path] = svc
return svc
def reconfigure(self):
"""
The node config references may have changed, update the services objects.
"""
self._update_cluster_data()
shared.NODE.unset_lazy("labels")
self.node_data.set(["labels"], shared.NODE.labels)
self.node_data.set(["config"], {"csum": shared.NODE.nodeconf_csum()})
self.on_nodes_info_change()
for path in [p for p in shared.SERVICES]:
try:
self.add_service(path)
except Exception as exc:
continue
def do(self):
terminated = self.janitor_procs() + self.janitor_threads()
changed = self.merge_rx()
changed |= self.mon_changed()
if self.get_node_monitor().status == "init" and self.services_have_init_status():
self.set_nmon(status="rejoin")
self.rejoin_grace_period_expired = False
if terminated == 0 and not changed and self.shortloops < self.max_shortloops:
self.shortloops += 1
if self.shortloops == self.max_shortloops:
# we're very idle, take time to ...
self.update_completions()
with shared.MON_TICKER:
shared.MON_TICKER.wait(self.monitor_period)
return
self.node_frozen = self.freezer.node_frozen()
if changed:
with shared.MON_TICKER:
#self.log.debug("woken for:")
#for idx, reason in enumerate(shared.MON_CHANGED):
# self.log.debug("%d. %s", idx, reason)
self.unset_mon_changed()
self.shortloops = 0
self.reload_config()
if self._shutdown:
if len(self.procs) == 0:
self.stop()
else:
self.update_cluster_data()
self.orchestrator()
self.update_hb_data()
shared.wake_collector()
#########################################################################
#
# Service config exchange
#
#########################################################################
def sync_services_conf(self):
"""
For each service, decide if we have an outdated configuration file
and fetch the most recent one if needed.
"""
confs = self.get_services_configs()
for path, data in confs.items():
try:
shared.SERVICES[path]
new_service = False
except KeyError:
new_service = True
if self.has_instance_with(path, global_expect=["purged", "deleted"]):
continue
if Env.nodename not in data:
# need to check if we should have this config ?
new_service = True
if new_service:
ref_conf = Storage({
"csum": "",
"updated": 0,
})
ref_nodename = Env.nodename
else:
ref_conf = data[Env.nodename]
ref_nodename = Env.nodename
for nodename, conf in data.items():
if Env.nodename == nodename:
continue
if new_service and Env.nodename not in conf.get("scope", []):
# we are not a service node
continue
if conf.csum != ref_conf.csum and \
conf.updated > ref_conf.updated:
ref_conf = conf
ref_nodename = nodename
if not new_service and ref_conf.scope and Env.nodename not in ref_conf.scope:
smon = self.get_service_monitor(path)
if not smon or smon.status == "deleting":
continue
self.log.info("node %s has the most recent %s config, "
"which no longer defines %s as a node.",
ref_nodename, path, Env.nodename)
#self.event("instance_stop", {
# "reason": "relayout",
# "path": svc.path,
#})
#self.service_stop(path, force=True)
self.service_delete(path)
continue
if ref_nodename == Env.nodename:
# we already have the most recent version
continue
try:
svc = shared.SERVICES[path]
if Env.nodename in svc.nodes and ref_nodename in svc.drpnodes:
# don't fetch drp config from prd nodes
continue
except KeyError:
pass
self.log.info("node %s has the most recent %s config",
ref_nodename, path)
self.fetch_service_config(path, ref_nodename)
if new_service:
self.init_new_service(path)
else:
self.service_status_fallback(path)
def init_new_service(self, path):
try:
self.add_service(path)
except Exception as exc:
self.log.error("unbuildable service %s fetched: %s", path, exc)
return
try:
svc = shared.SERVICES[path]
if svc.kind == "svc":
self.event("instance_freeze", {
"reason": "install",
"path": svc.path,
})
Freezer(path).freeze()
if not os.path.exists(svc.paths.cf):
return
self.service_status_fallback(svc.path)
except Exception:
# can happen when deleting the service
pass
def fetch_service_config(self, path, nodename):
"""
Fetch and install the most recent service configuration file, using
the remote node listener.
"""
req = {
"action": "object_config",
"options": {
"path": path,
},
}
resp = self.daemon_get(req, server=nodename)
if resp is None:
self.log.error("unable to fetch service %s config from node %s: "
"received %s", path, nodename, resp)
return
status = resp.get("status", 1)
if status == 2:
# peer is deleting this service
self.log.info(resp.get("error", ""))
return
elif status != 0:
self.log.error("unable to fetch service %s config from node %s: "
"received %s", path, nodename, resp)
return
with tempfile.NamedTemporaryFile(dir=Env.paths.pathtmp, delete=False) as filep:
tmpfpath = filep.name
try:
with codecs.open(tmpfpath, "w", "utf-8") as filep:
filep.write(resp["data"])
with shared.SERVICES_LOCK:
if path in shared.SERVICES:
svc = shared.SERVICES[path]
else:
svc = None
if svc:
try:
results = svc._validate_config(path=filep.name)
except Exception as exc:
self.log.error("service %s fetched config validation "
"error: %s", path, exc)
return
else:
results = {"errors": 0}
if results["errors"] == 0:
dst = svc_pathcf(path)
makedirs(os.path.dirname(dst))
shutil.copy(filep.name, dst)
mtime = resp.get("mtime")
if mtime:
os.utime(dst, (mtime, mtime))
else:
self.log.error("the service %s config fetched from node %s is "
"not valid", path, nodename)
return
try:
svc = self.add_service(path)
svc.postinstall()
except Exception as exc:
self.log.error("service %s postinstall failed: %s", path, exc)
finally:
os.unlink(tmpfpath)
self.event("service_config_installed", {
"path": path,
"from": nodename
})
#########################################################################
#
# Node and Service Commands
#
#########################################################################
def generic_callback(self, path, **kwargs):
self.set_smon(path, **kwargs)
self.update_hb_data()
def node_stonith(self, node):
proc = self.node_command(["stonith", "--node", node])
# make sure we won't redo the stonith for another service
for path, smon in self.iter_local_services_monitors():
if smon.stonith == node:
self.set_smon(path, stonith="unset")
# wait for 10sec before giving up
for step in range(10):
ret = proc.poll()
if ret is not None:
return ret
time.sleep(1)
# timeout, free the caller
self.push_proc(proc=proc)
def service_startstandby_resources(self, path, rids, slave=None):
self.set_smon(path, "restarting")
cmd = ["startstandby", "--rid", ",".join(rids)]
if slave:
cmd += ["--slave", slave]
proc = self.service_command(path, cmd)
self.push_proc(
proc=proc,
on_success="service_start_resources_on_success",
on_success_args=[path, rids],
on_success_kwargs={"slave": slave},
on_error="generic_callback",
on_error_args=[path],
on_error_kwargs={"status": "idle"},
)
def service_start_resources(self, path, rids, slave=None):
self.set_smon(path, "restarting")
cmd = ["start", "--rid", ",".join(rids)]
if slave:
cmd += ["--slave", slave]
proc = self.service_command(path, cmd)
self.push_proc(
proc=proc,
on_success="service_start_resources_on_success",
on_success_args=[path, rids],
on_success_kwargs={"slave": slave},
on_error="generic_callback",
on_error_args=[path],
on_error_kwargs={"status": "idle"},
)
def service_start_resources_on_success(self, path, rids, slave=None):
self.set_smon(path, status="idle")
self.update_hb_data()
changed = False
for rid in rids:
instance = self.get_service_instance(path, Env.nodename)
if instance is None:
self.reset_smon_retries(path, rid)
changed = True
continue
if slave is None:
res = instance.get("resources", {}).get(rid, {})
if res.get("status") not in ("up", "stdby up"):
self.log.error("%s start returned success but resource is "