/
svc.py
5869 lines (5262 loc) · 193 KB
/
svc.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
"""
The module defining the Svc class.
"""
from __future__ import print_function, unicode_literals
import hashlib
import itertools
import logging
import os
import signal
import shutil
import sys
import tempfile
import time
from errno import ECONNREFUSED
import core.exceptions as ex
import core.logger
import core.status
import utilities.lock
from core.comm import Crypt, DEFAULT_DAEMON_TIMEOUT
from core.configfile import move_config_file
from core.contexts import want_context
from core.extconfig import ExtConfigMixin
from core.freezer import Freezer
from core.node import Node
from core.objects.pg import PgMixin
from core.resource import Resource
from core.resourceset import ResourceSet
from core.scheduler import SchedOpts, Scheduler, sched_action
from env import Env, Paths
from utilities.converters import *
from utilities.drivers import driver_import, rtypes_with_callable
from utilities.fcache import fcache
from utilities.files import makedirs
from utilities.lazy import lazy, set_lazy, unset_all_lazy, unset_lazy
from utilities.naming import (fmt_path, resolve_path, svc_pathcf, svc_pathetc,
svc_pathlog, svc_pathtmp, svc_pathvar, new_id, factory, split_path)
from utilities.proc import (action_triggers, drop_option, find_editor,
init_locale, justcall, lcall, vcall)
from utilities.storage import Storage
from utilities.string import is_string
if six.PY2:
BrokenPipeError = IOError
def signal_handler(*args):
"""
A signal handler raising the Signal exception.
Args can be signum and frame, but we don't use them.
"""
raise ex.Signal
# Actions with a special handling of remote/peer relaying
ACTION_NO_ASYNC = [
"add",
"clear",
"edit_config",
"logs",
"print_config",
"print_status",
]
KIND_ACTION_NO_ASYNC = ["ccfg"]
ACTION_ANY_NODE = (
"decode",
"delete",
"eval",
"gen_cert",
"get",
"keys",
"validate_config",
"set",
"unset",
)
ACTION_ASYNC = {
"abort": {
"target": "aborted",
"progress": "aborting",
},
"delete": {
"target": "deleted",
"progress": "deleting",
"local": True,
"kinds": ["svc", "vol", "usr", "sec", "cfg"],
},
"freeze": {
"target": "frozen",
"progress": "freezing",
"local": True,
"kinds": ["svc", "vol"],
},
"giveback": {
"target": "placed",
"progress": "placing",
"kinds": ["svc"],
},
"move": {
"target": "placed@",
"progress": "placing@",
"kinds": ["svc"],
},
"provision": {
"target": "provisioned",
"progress": "provisioning",
"local": True,
"kinds": ["svc", "vol"],
},
"purge": {
"target": "purged",
"progress": "purging",
"local": True,
"kinds": ["svc", "vol", "usr", "sec", "cfg"],
},
"restart": {
"target": "restarted",
"progress": "restarting",
"local": True,
},
"shutdown": {
"target": "shutdown",
"progress": "shutting",
"local": True,
"kinds": ["svc", "vol"],
},
"start": {
"target": "started",
"progress": "starting",
"local": True,
"kinds": ["svc", "vol"],
},
"stop": {
"target": "stopped",
"progress": "stopping",
"local": True,
"kinds": ["svc", "vol"],
},
"switch": {
"target": "placed@",
"progress": "placing@",
"kinds": ["svc", "vol"],
},
"takeover": {
"target": "placed@",
"progress": "placing@",
"kinds": ["svc", "vol"],
},
"toc": {
"progress": "tocing",
"local": True,
"kinds": ["svc", "vol"],
},
"thaw": {
"target": "thawed",
"progress": "thawing",
"local": True,
"kinds": ["svc", "vol"],
},
"unprovision": {
"target": "unprovisioned",
"progress": "unprovisioning",
"local": True,
"kinds": ["svc", "vol"],
},
}
TOP_STATUS_GROUPS = [
"overall",
"avail",
"optional",
]
DEFAULT_STATUS_GROUPS = [
"ip",
"volume",
"disk",
"fs",
"share",
"container",
"app",
"sync",
"task",
]
CONFIG_DEFAULTS = {
'sync#i0_schedule': '@60',
'sync_schedule': '~04:00-06:00',
'comp_schedule': '~00:00-06:00',
'status_schedule': '@9',
'monitor_schedule': '@1',
'resinfo_schedule': '@60',
'no_schedule': '',
}
ACTIONS_NO_STATUS_CHANGE = [
"abort",
"clear",
"decode",
"docker",
"eval",
"frozen",
"get",
"giveback",
"json_config",
"json_status",
"json_devs",
"json_exposed_devs",
"json_sub_devs",
"json_base_devs",
"logs",
"oci",
"podman",
"pg_pids",
"print_config",
"print_devs",
"print_exposed_devs",
"print_sub_devs",
"print_base_devs",
"print_config_mtime",
"print_resource_status",
"print_resinfo",
"print_schedule",
"print_status",
"push_resinfo",
"push_status",
"push_config",
"push_encap_config",
"prstatus",
"resource_monitor",
"status",
"validate_config",
]
#
# don't refresh the status at the end of these actions because
# we need a Svc rebuild to produce an accurate status dump.
# osvcd will refresh the status due to cf_mtime>status_mtime.
#
ACTIONS_CF_CHANGE = [
"edit_config",
"scale",
"set",
"unset",
]
ACTIONS_ALLOW_ON_INVALID_NODE = [
"abort",
"clear",
"delete",
"disable",
"edit_config",
"eval",
"frozen",
"freeze",
"get",
"logs",
"print_config",
"print_status",
"set",
"status",
"thaw",
"unset",
"update",
"validate_config",
]
ACTIONS_NO_LOG = [
"delete",
"edit_config",
"eval",
"get",
"group_status",
"install_secrets",
"logs",
"push_resinfo",
"push_status",
"push_config",
"push_encap_config",
"service_status",
"resource_monitor",
"set",
"status",
"unset",
"validate_config",
]
ACTIONS_NO_TRIGGER = [
"abort",
"clear",
"delete",
"disable",
"dns_update",
"edit_config",
"enable",
"group_status",
"install_secrets",
"logs",
"pg_freeze",
"pg_thaw",
"pg_kill",
"postsync",
"push_encap_config",
"push_config",
"push_resinfo",
"push_status",
"presync",
"resource_monitor",
"set_provisioned",
"set_unprovisioned",
"status",
]
ACTIONS_LOCK_COMPAT = {
"postsync": ["sync_all", "sync_nodes", "sync_drp", "sync_update", "sync_resync"],
}
ACTIONS_NO_LOCK = [
"abort",
"clear",
"docker",
"edit_config",
"enter",
"freeze",
"frozen",
"eval",
"get",
"logs",
"oci",
"podman",
"push_resinfo",
"push_status",
"push_config",
"push_encap_config",
"run",
"status",
"set_provisioned",
"set_unprovisioned",
"thaw",
"validate_config",
]
START_GROUPS = [
"ip",
"sync.netapp",
"sync.nexenta",
"sync.symclone",
"sync.symsnap",
"sync.symsrdfs",
"sync.hp3par",
"sync.ibmdssnap",
"volume",
"disk",
"fs",
"share",
"container",
"app",
"task",
]
STOP_GROUPS = [
"task",
"app",
"container",
"share",
"fs",
"sync.btrfssnap",
"disk",
"volume",
"ip",
]
ACTIONS_DO_MASTER = [
"clear",
"freeze",
"install_secrets",
"set_provisioned",
"set_unprovisioned",
"run",
"thaw",
"toc",
]
ACTIONS_DO_MASTER_AND_SLAVE = [
"boot",
"migrate",
"pg_update",
"provision",
"prstart",
"prstop",
"restart",
"shutdown",
"start",
"startstandby",
"stop",
"toc",
"unprovision"
]
ACTIONS_NEED_SNAP_TRIGGER = [
"sync_drp",
"sync_nodes",
"sync_resync",
"sync_update",
]
TOPOLOGIES = [
"failover",
"flex",
"span",
]
DRV_GRP_XLATE = {
"drbd": ["disk", "drbd"],
"vdisk": ["disk", "vdisk"],
"vmdg": ["disk", "ldom"],
"pool": ["disk", "zpool"],
"zpool": ["disk", "zpool"],
"loop": ["disk", "loop"],
"md": ["disk", "md"],
"zvol": ["disk", "zvol"],
"lv": ["disk", "lv"],
"raw": ["disk", "raw"],
"vxdg": ["disk", "vxdg"],
"vxvol": ["disk", "vxvol"],
}
init_locale()
def _slave_action(func):
def need_specifier(self):
"""
Raise an exception if --master or --slave(s) need to be set
"""
if self.command_is_scoped():
return
if self.running_action in ACTIONS_DO_MASTER_AND_SLAVE + ACTIONS_DO_MASTER:
return
if self.options.master or self.options.slaves or self.options.slave is not None:
return
raise ex.Error("specify either --master, --slave(s) or both (%s)" % func.__name__)
def _func(self):
if self.encap or not self.has_encap_resources:
return
if self.command_is_scoped() and \
len(set(self.action_rid) & set(self.encap_resources.keys())) == 0:
self.log.info("skip action on slaves: no encap resources are selected")
return
need_specifier(self)
if self.options.slaves or \
self.options.slave is not None or \
(not self.options.master and
not self.options.slaves and
self.options.slave is None and
self.running_action in ACTIONS_DO_MASTER_AND_SLAVE):
try:
func(self)
except Exception as exc:
raise ex.Error(str(exc))
return _func
def _master_action(func):
def need_specifier(self):
"""
Raise an exception if --master or --slave(s) need to be set
"""
if self.encap:
return
if not self.has_encap_resources:
return
if self.command_is_scoped():
return
if self.running_action in ACTIONS_DO_MASTER_AND_SLAVE + ACTIONS_DO_MASTER:
return
if self.options.master or self.options.slaves or self.options.slave is not None:
return
raise ex.Error("specify either --master, --slave(s) or both (%s)" % func.__name__)
def _func(self):
need_specifier(self)
if self.options.master or \
(not self.options.master and
not self.options.slaves and
self.options.slave is None
and self.running_action in ACTIONS_DO_MASTER_AND_SLAVE + ACTIONS_DO_MASTER):
func(self)
return _func
class ObjPaths(object):
def __init__(self, path, name, cf):
self.name = name
self.path = path
nsetc = svc_pathetc(path)
if cf:
self.cf = cf
else:
self.cf = svc_pathcf(path)
self.initd = os.path.join(nsetc, name+'.d')
self.alt_initd = os.path.join(nsetc, name+'.dir')
@property
def tmp_cf(self):
nstmp = svc_pathtmp(self.path)
return os.path.join(nstmp, self.name+".conf.tmp")
class BaseSvc(Crypt, ExtConfigMixin):
kind = "base"
def __init__(self, name=None, namespace=None, node=None, cf=None, cd=None, volatile=False, log=None, log_handlers=None):
self.log_handlers = log_handlers
self.raw_cd = cd
ExtConfigMixin.__init__(self, default_status_groups=DEFAULT_STATUS_GROUPS)
self.name = name
self.namespace = namespace.strip("/") if namespace else None
self.node = node
self.hostid = Env.nodename
self.volatile = volatile
self.path = fmt_path(self.name, self.namespace, self.kind)
self.prev_env = None
if log:
self.set_lazy("log", log)
self.paths = ObjPaths(self.path, name, cf)
self.reset_resources()
self.encap_json_status_cache = {}
self.rset_status_cache = None
self.lockfd = None
self.abort_start_done = False
self.action_start_date = datetime.datetime.now()
self.action_rid = []
self.action_rid_before_depends = []
self.action_rid_depends = []
self.dependencies = {}
self.running_action = None
self.presync_done = False
self.stats_data = {}
self.stats_updated = 0
# needed for kw scoping
self.nodes = set([Env.nodename])
self.drpnodes = set()
self.encapnodes = set()
self.flex_primary = ""
self.drp_flex_primary = ""
# real values for kw needed by scoping
self.init_nodes()
# merged by the cmdline parser
self.options = Storage(
color="auto",
local=False,
slaves=False,
slave=None,
master=False,
cron=False,
follow=False,
force=False,
remote=False,
debug=False,
disable_rollback=False,
show_disabled=None,
moduleset="",
module="",
ruleset_date="",
dry_run=False,
refresh=False,
rid=None,
tags=None,
subsets=None,
discard=False,
recover=False,
waitlock=None,
wait=False,
)
def reset_resources(self):
self.init_resources_errors = 0
self.resources_initialized = False
self.resources_by_id = {}
self.encap_resources = {}
self.resourcesets_by_id = {}
self.has_encap_resources = False
def get_node(self):
"""
helper for the comm module to find the Node(), for accessing
its configuration.
"""
if self.node is None:
self.node = Node()
return self.node
def init_nodes(self):
"""
Called from __init__, and on node labels change by entities
holding long-lived BaseSvc objects.
"""
if want_context():
return
try:
ordered_encapnodes = self.oget("DEFAULT", "encapnodes") or []
self.encapnodes = set(ordered_encapnodes)
except (AttributeError, ValueError):
ordered_encapnodes = []
self.encapnodes = set()
try:
self.ordered_nodes = self.oget("DEFAULT", "nodes") or []
except (AttributeError, ValueError):
self.ordered_nodes = [Env.nodename]
if self.encap and Env.nodename not in self.ordered_nodes:
self.ordered_nodes = [Env.nodename]
try:
self.ordered_drpnodes = self.oget("DEFAULT", "drpnodes") or []
except (AttributeError, ValueError):
self.ordered_drpnodes = []
try:
self.drpnode = self.oget("DEFAULT", "drpnode") or ""
except (AttributeError, ValueError):
self.drpnode = ""
if self.drpnode and self.drpnode not in self.ordered_drpnodes:
self.ordered_drpnodes.insert(0, self.drpnode)
self.nodes = set(self.ordered_nodes)
self.drpnodes = set(self.ordered_drpnodes)
self.flex_primary = self.get_flex_primary()
self.drp_flex_primary = self.get_drp_flex_primary()
@lazy
def monitor_action(self):
return "none"
@lazy
def fullname(self):
return "%s.%s.%s.%s" % (
self.name,
self.namespace if self.namespace else "root",
self.kind,
self.node.cluster_name
)
@lazy
def var_d(self):
var_d = svc_pathvar(self.path)
if not self.volatile:
makedirs(var_d)
return var_d
@lazy
def log_d(self):
log_d = svc_pathlog(self.path)
if not self.volatile:
makedirs(log_d)
return log_d
@lazy
def loggerpath(self):
return Env.nodename+"."+self.path.replace("/", ".")
@lazy
def log(self): # pylint: disable=method-hidden
extra = {
"path": self.path,
"node": Env.nodename,
"sid": Env.session_uuid,
"cron": self.options.cron,
}
return logging.LoggerAdapter(self.logger, extra)
@lazy
def logger(self): # pylint: disable=method-hidden
if self.volatile:
handlers = ["stream"]
else:
handlers = self.log_handlers
log_file = os.path.join(self.log_d, self.name+".log")
return core.logger.initLogger(self.loggerpath, log_file, handlers=handlers)
@lazy
def compliance(self):
from core.compliance import Compliance
comp = Compliance(self)
return comp
@lazy
def sched(self):
"""
Lazy init of the service scheduler.
"""
return Scheduler(
config_defaults=CONFIG_DEFAULTS,
options=self.options,
svc=self,
scheduler_actions={},
configure_method="configure_scheduler",
)
@lazy
def orchestrate(self):
return "no"
@lazy
def disable_rollback(self):
return True
@lazy
def show_disabled(self):
return True
@lazy
def encap(self):
return False
@lazy
def freezer(self):
"""
Lazy allocator for the freezer object.
"""
return Freezer(self.path)
@lazy
def id(self):
"""
return object id:
When object has no id a new id is created and if object is not volatile
the object config file is updated.
id should not be called on deleted object else new empty object will be created
"""
try:
return self.conf_get("DEFAULT", "id")
except ex.OptNotFound as exc:
new_id = self.new_id()
if not self.volatile:
self._set("DEFAULT", "id", new_id, validation=False)
return new_id
@staticmethod
def new_id():
return new_id()
@lazy
def peers(self):
if Env.nodename in self.nodes:
return self.nodes
elif Env.nodename in self.drpnodes:
return self.drpnodes
else:
return []
@lazy
def ordered_peers(self):
if Env.nodename in self.nodes:
return self.ordered_nodes
elif Env.nodename in self.drpnodes:
return self.ordered_drpnodes
else:
return []
@lazy
def placement(self):
return "nodes order"
@lazy
def topology(self):
return "span"
@lazy
def svc_env(self):
val = self.oget("DEFAULT", "env")
if val is None:
return self.node.env
return val
@lazy
def lock_timeout(self):
return self.oget("DEFAULT", "lock_timeout")
@lazy
def priority(self):
prio = self.oget("DEFAULT", "priority")
if prio is None:
return Env.default_priority
return prio
@lazy
def cd(self):
if self.raw_cd is not None:
return self.raw_cd
return self.parse_config_file(self.paths.cf)
def cd_clear_caches(self):
self.raw_cd = None
self.unset_lazy("cd")
@lazy
def disabled(self):
return self.oget("DEFAULT", "disable")
def svclock(self, action=None, timeout=30, delay=1):
"""
Acquire the service action lock.
"""
if want_context():
return
suffix = None
if action == "toc" and self.monitor_action in ("reboot", "crash"):
return
if (action not in ACTION_NO_ASYNC and self.options.node is not None and self.options.node != "") or \
action in ACTIONS_NO_LOCK or \
self.options.nolock or \
action.startswith("collector") or \
self.lockfd is not None:
# explicitly blacklisted or
# no need to serialize requests or
# already acquired
return
if action.startswith("compliance"):
# compliance modules are allowed to execute actions on the service
# so give them their own lock
suffix = "compliance"
elif action.startswith("sync"):
suffix = "sync"
lockfile = os.path.join(self.var_d, "lock.generic")
if suffix is not None:
lockfile = ".".join((lockfile, suffix))
details = "(timeout %d, delay %d, action %s, lockfile %s)" % \
(timeout, delay, action, lockfile)
self.log.debug("acquire service lock %s", details)
# try an immmediate lock acquire and see if the running action is
# compatible
if action in ACTIONS_LOCK_COMPAT:
try:
lockfd = utilities.lock.lock(
timeout=0,
delay=delay,
lockfile=lockfile,
intent=action
)
if lockfd is not None:
self.lockfd = lockfd
return
except utilities.lock.LockTimeout as exc:
if exc.intent in ACTIONS_LOCK_COMPAT[action]:
return
# not compatible, continue with the normal acquire
except Exception:
pass
try:
lockfd = utilities.lock.lock(
timeout=timeout,
delay=delay,
lockfile=lockfile,
intent=action
)
except utilities.lock.LockTimeout as exc:
raise ex.Error("timed out waiting for lock %s: %s" % (details, str(exc)))
except utilities.lock.LockNoLockFile:
raise ex.Error("lock_nowait: set the 'lockfile' param %s" % details)
except utilities.lock.LockCreateError:
raise ex.Error("can not create lock file %s" % details)
except utilities.lock.LockAcquire as exc:
raise ex.Error("another action is currently running %s: %s" % (details, str(exc)))
except ex.Signal:
raise ex.Error("interrupted by signal %s" % details)
except Exception as exc:
self.save_exc()
raise ex.Error("unexpected locking error %s: %s" % (details, str(exc)))
if lockfd is not None:
self.lockfd = lockfd
def svcunlock(self):
"""
Release the service action lock.
"""
utilities.lock.unlock(self.lockfd)
self.lockfd = None
@staticmethod
def setup_signal_handlers():
"""
Install signal handlers.
"""
try:
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
except ValueError:
# signal only works in main thread
pass
def systemd_join_agent_service(self):
from utilities.systemd import systemd_system, systemd_join
if os.environ.get("OSVC_ACTION_ORIGIN") == "daemon" or not systemd_system():
return
systemd_join("opensvc-agent.service")
def action(self, action, options=None):
self.systemd_join_agent_service()
try:
options = self.prepare_options(action, options)
ret = self.async_action(action)
if ret is not None:
return ret
except ex.Error as exc:
msg = str(exc)
if msg:
self.log.error(msg)
return 1
except ex.AbortAction as exc:
msg = str(exc)
if msg:
self.log.info(msg)
return 0
except ex.AlreadyDone as exc:
# so do_svcs_action() can decide not to wait for the
# service to reach the global_expect
return -1
self.allow_on_this_node(action)
try:
return self._action(action, options=options)
except utilities.lock.LOCK_EXCEPTIONS as exc:
raise ex.Error(str(exc))
def barrier_sanity_check(self, barrier):
"""
Raise if the barrier (--upto <barrier> or --downto <barrier>) does not
match any resource, to avoid a full start when the user makes a typo
in the barrier selector.
"""
if barrier is None:
return
if self.get_resource(barrier):
return
if self.get_resources(barrier):
return
raise ex.Error("barrier '%s' does not match any resource" % barrier)
@sched_action
def _action(self, action, options=None):
"""
Filter resources on which the service action must act.
Abort if the service is frozen, or if --cluster is not set on a HA
service.
Set up the environment variables.
Finally do the service action either in logged or unlogged mode.
"""
self.barrier_sanity_check(self.options.upto)
self.barrier_sanity_check(self.options.downto)
try:
self.action_rid_before_depends = self.options_to_rids(options, action)
except ex.AbortAction as exc:
self.log.error(exc)
return 1
depends = set()
for rid in self.action_rid_before_depends:
depends |= self.action_rid_dependencies(action, rid) - set(self.action_rid_before_depends)
self.action_rid = set(self.action_rid_before_depends)
if len(depends) > 0:
self.log.info("add rid %s to satisfy dependencies" % ", ".join(depends))
self.action_rid |= depends
self.action_rid = list(self.action_rid)
self.action_rid_depends = list(depends)
self.action_start_date = datetime.datetime.now()
if self.node is None:
self.node = Node()
if action not in ACTIONS_NO_STATUS_CHANGE and \
'compliance' not in action and \
'collector' not in action and \
not options.dry_run and \
not action.startswith("oci") and \
not action.startswith("docker") and \
not action.startswith("podman"):
#
# here we know we will run a resource state-changing action
# purge the resource status file cache, so that we don't take
# decision on outdated information
#