/
svc.py
5058 lines (4504 loc) · 171 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
from __future__ import unicode_literals
import sys
import os
import signal
import logging
import datetime
import time
import lock
import json
import re
from resources import Resource
from resourceset import ResourceSet
from freezer import Freezer
import rcStatus
from rcGlobalEnv import rcEnv, get_osvc_paths, Storage
from rcUtilities import justcall, lazy, unset_lazy, vcall, is_string, try_decode, eval_expr, convert_bool
from rcConfigParser import RawConfigParser
import rcExceptions as ex
import rcLogger
import node
from rcScheduler import scheduler_fork, Scheduler, SchedOpts
from osvcd import Crypt
if sys.version_info[0] < 3:
BrokenPipeError = IOError
def signal_handler(*args):
"""
A signal handler raising the excSignal exception.
Args can be signum and frame, but we don't use them.
"""
raise ex.excSignal
DEFAULT_WAITLOCK = 60
DEFAULT_STATUS_GROUPS = [
"container",
"ip",
"disk",
"fs",
"share",
"sync",
"app",
"stonith",
"task",
]
CONFIG_DEFAULTS = {
'push_schedule': '00:00-06:00@361',
'sync_schedule': '04:00-06:00@121',
'comp_schedule': '00:00-06:00@361',
'status_schedule': '@9',
'monitor_schedule': '@1',
'resinfo_schedule': '@60',
'no_schedule': '',
}
ACTIONS_NO_STATUS_CHANGE = [
"autopush",
"clear",
"docker",
"frozen",
"get",
"json_config",
"json_status",
"json_disklist",
"json_devlist",
"logs",
"print_config",
"print_devlist",
"print_disklist",
"print_config_mtime",
"print_resource_status",
"print_schedule",
"print_status",
"push",
"push_resinfo",
"push_config",
"push_service_status",
"prstatus",
"scheduler",
"status",
"validate_config",
]
ACTIONS_ALLOW_ON_INVALID_NODE = [
"delete",
"edit_config",
"frozen",
"get",
"logs",
"print_config",
"set",
"unset",
"update",
"validate_config",
]
ACTIONS_NO_LOG = [
"delete",
"edit_config",
"get",
"group_status",
"logs",
"push",
"push_resinfo",
"push_config",
"push_service_status",
"resource_monitor",
"scheduler",
"set",
"status",
"unset",
"validate_config",
]
ACTIONS_NO_TRIGGER = [
"delete",
"dns_update",
"enable",
"disable",
"status",
"scheduler",
"pg_freeze",
"pg_thaw",
"pg_kill",
"logs",
"edit_config",
"push_resinfo",
"push",
"group_status",
"presync",
"postsync",
"resource_monitor",
]
ACTIONS_NO_LOCK = [
"docker",
"edit_config",
"freeze",
"frozen",
"get",
"logs",
"push",
"push_resinfo",
"push_config",
"push_service_status",
"run",
"scheduler",
"status",
"thaw",
"toc",
"validate_config",
]
DISK_TYPES = [
"disk.drbd",
"disk.gandi",
"disk.gce",
"disk.lock",
"disk.loop",
"disk.md",
"disk.rados",
"disk.raw",
"disk.vg",
"disk.zpool",
]
STATUS_TYPES = [
"app",
"container.amazon",
"container.docker",
"container.esx",
"container.hpvm",
"container.jail",
"container.kvm",
"container.lxc",
"container.ldom",
"container.openstack",
"container.ovm",
"container.srp",
"container.vbox",
"container.vcloud",
"container.vz",
"container.xen",
"container.zone",
"disk.drbd",
"disk.gandi",
"disk.gce",
"disk.lock",
"disk.loop",
"disk.md",
"disk.lv",
"disk.raw",
"disk.rados",
"disk.scsireserv",
"disk.vg",
"disk.zpool",
"fs",
"ip",
"ip.docker",
"share.nfs",
"sync.btrfs",
"sync.btrfssnap",
"sync.dcsckpt",
"sync.dcssnap",
"sync.dds",
"sync.docker",
"sync.evasnap",
"sync.hp3par",
"sync.hp3parsnap",
"sync.ibmdssnap",
"sync.necismsnap",
"sync.netapp",
"sync.nexenta",
"sync.rados",
"sync.rsync",
"sync.symclone",
"sync.symsnap",
"sync.symsrdfs",
"sync.s3",
"sync.zfs",
"stonith.callout",
"stonith.ilo",
"task",
]
ACTIONS_DO_MASTER_AND_SLAVE = [
"boot",
"migrate",
"prstart",
"prstop",
"restart",
"shutdown",
"start",
"startstandby",
"stop",
"stopstandby",
"switch",
]
ACTIONS_NEED_SNAP_TRIGGER = [
"sync_drp",
"sync_nodes",
"sync_resync",
"sync_update",
]
CLUSTER_TYPES = [
"failover",
"flex",
"autoflex",
]
os.environ['LANG'] = 'C'
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:
return
if self.options.master or self.options.slaves or self.options.slave is not None:
return
raise ex.excError("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):
try:
func(self)
except Exception as exc:
raise ex.excError(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:
return
if self.options.master or self.options.slaves or self.options.slave is not None:
return
raise ex.excError("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):
func(self)
return _func
class Svc(Crypt):
"""
A OpenSVC service class.
A service is a collection of resources.
It exposes operations methods like provision, unprovision, stop, start,
and sync.
"""
def __init__(self, svcname=None):
self.type = "hosted"
self.svcname = svcname
self.hostid = rcEnv.nodename
self.paths = Storage(
exe=os.path.join(rcEnv.paths.pathetc, self.svcname),
cf=os.path.join(rcEnv.paths.pathetc, self.svcname+'.conf'),
initd=os.path.join(rcEnv.paths.pathetc, self.svcname+'.d'),
alt_initd=os.path.join(rcEnv.paths.pathetc, self.svcname+'.dir'),
push_flag=os.path.join(rcEnv.paths.pathvar, self.svcname, 'last_pushed_config'),
run_flag=os.path.join(os.sep, "var", "run", "opensvc."+self.svcname),
)
self.resources_by_id = {}
self.encap_resources = {}
self.resourcesets = []
self.resourcesets_by_type = {}
self.disks = set()
self.devs = set()
self.ref_cache = {}
self.encap_json_status_cache = {}
self.rset_status_cache = None
self.lockfd = None
self.group_status_cache = None
self.abort_start_done = False
self.action_start_date = datetime.datetime.now()
self.ha = False
self.has_encap_resources = False
self.encap = False
self.action_rid = []
self.action_rid_before_depends = []
self.action_rid_depends = []
self.dependencies = {}
self.running_action = None
self.need_postsync = set()
self.service_monitor_set = False
# set by the builder
self.conf = os.path.join(rcEnv.paths.pathetc, svcname+".conf")
self.node = None
self.comment = ""
self.drp_type = ""
self.app = ""
self.drnoaction = False
self.clustertype = "failover"
self.show_disabled = False
self.svc_env = rcEnv.node_env
self.nodes = set([rcEnv.nodename])
self.ordered_nodes = [rcEnv.nodename]
self.drpnodes = set()
self.ordered_drpnodes = []
self.drpnode = ""
self.encapnodes = set()
self.flex_primary = ""
self.drp_flex_primary = ""
self.sync_dblogger = False
self.create_pg = False
self.disable_rollback = False
self.presync_done = False
self.presnap_trigger = None
self.postsnap_trigger = None
self.monitor_action = None
self.pre_monitor_action = None
self.disabled = False
self.anti_affinity = None
self.autostart_node = []
self.lock_timeout = DEFAULT_WAITLOCK
# merged by the cmdline parser
self.options = Storage(
color="auto",
slaves=False,
slave=None,
master=False,
cron=False,
force=False,
remote=False,
ignore_affinity=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=DEFAULT_WAITLOCK,
)
self.scsirelease = self.prstop
self.scsireserv = self.prstart
self.scsicheckreserv = self.prstatus
@lazy
def log(self):
return rcLogger.initLogger(self.svcname)
@lazy
def sched(self):
"""
Lazy init of the service scheduler.
"""
return Scheduler(
name=self.svcname,
config_defaults=CONFIG_DEFAULTS,
options=self.options,
config=self.config,
log=self.log,
svc=self,
scheduler_actions={
"compliance_auto": SchedOpts(
"DEFAULT",
fname=self.svcname+os.sep+"last_comp_check",
schedule_option="comp_schedule"
),
"push_service_status": SchedOpts(
"DEFAULT",
fname=self.svcname+os.sep+"last_push_service_status",
schedule_option="status_schedule"
),
},
)
@lazy
def dockerlib(self):
"""
Lazy allocator for the dockerlib object.
"""
import rcDocker
return rcDocker.DockerLib(self)
@lazy
def freezer(self):
"""
Lazy allocator for the freezer object.
"""
return Freezer(self.svcname)
@lazy
def compliance(self):
from compliance import Compliance
comp = Compliance(self)
return comp
def __lt__(self, other):
"""
Order by service name
"""
return self.svcname < other.svcname
def register_dependency(self, action, _from, _to):
if action not in self.dependencies:
self.dependencies[action] = {}
if _from not in self.dependencies[action]:
self.dependencies[action][_from] = set()
self.dependencies[action][_from].add(_to)
def action_rid_dependencies(self, action, rid):
if action in ("boot", "provision", "start"):
action = "start"
elif action in ("shutdown", "unprovision", "stop"):
action = "stop"
else:
return set()
if action not in self.dependencies:
return set()
if rid not in self.dependencies[action]:
return set()
return self.dependencies[action][rid]
def action_rid_dependency_of(self, action, rid):
if action in ("boot", "provision", "start"):
action = "start"
elif action in ("shutdown", "unprovision", "stop"):
action = "stop"
else:
return set()
if action not in self.dependencies:
return set()
dependency_of = set()
for _rid, dependencies in self.dependencies[action].items():
if rid in dependencies:
dependency_of.add(_rid)
return dependency_of
def print_schedule(self):
"""
The 'print schedule' node and service action entrypoint.
"""
return self.sched.print_schedule()
def scheduler(self):
"""
The service scheduler action entrypoint.
"""
self.options.cron = True
self.sync_dblogger = True
if not self.has_run_flag():
self.log.info("the scheduler is off during init")
return
for action in self.sched.scheduler_actions:
try:
if action == "sync_all":
# save the action logging to the collector if sync_all
# is not needed
self.sched_sync_all()
elif action.startswith("task#"):
self.run_task(action)
elif action == "compliance_auto":
self.compliance_auto()
else:
self.action(action)
except ex.MonitorAction as exc:
self.svcunlock()
self.action("toc")
except ex.excError as exc:
self.log.error(exc)
except:
self.save_exc()
def post_build(self):
"""
A method run after the service is done building.
Add resource-dependent tasks to the scheduler.
"""
if not self.encap:
self.sched.scheduler_actions["push_config"] = SchedOpts(
"DEFAULT",
fname=self.svcname+os.sep+"last_push_config",
schedule_option="push_schedule"
)
try:
monitor_schedule = self.conf_get_string_scope('DEFAULT', 'monitor_schedule')
except ex.OptNotFound:
monitor_schedule = None
if (self.ha and "flex" not in self.clustertype) or monitor_schedule is not None:
self.sched.scheduler_actions["resource_monitor"] = SchedOpts(
"DEFAULT",
fname=self.svcname+os.sep+"last_resource_monitor",
schedule_option="monitor_schedule"
)
syncs = []
for resource in self.get_resources("sync"):
syncs += [SchedOpts(
resource.rid,
fname=self.svcname+os.sep+"last_syncall_"+resource.rid,
schedule_option="sync_schedule"
)]
if len(syncs) > 0:
self.sched.scheduler_actions["sync_all"] = syncs
for resource in self.get_resources("task"):
self.sched.scheduler_actions[resource.rid] = SchedOpts(
resource.rid,
fname=self.svcname+os.sep+"last_"+resource.rid,
schedule_option="no_schedule"
)
self.sched.scheduler_actions["push_resinfo"] = SchedOpts(
"DEFAULT",
fname=self.svcname+os.sep+"last_push_resinfo",
schedule_option="resinfo_schedule"
)
def purge_status_last(self):
"""
Purge all service resources on-disk status caches.
"""
for rset in self.resourcesets:
rset.purge_status_last()
def get_subset_parallel(self, rtype):
"""
Return True if the resources of a resourceset can run an action in
parallel executing per-resource workers.
"""
rtype = rtype.split(".")[0]
subset_section = 'subset#' + rtype
if not self.config.has_section(subset_section):
return False
try:
return self.conf_get_boolean_scope(subset_section, "parallel")
except ex.OptNotFound:
return False
def __iadd__(self, other):
"""
Svc += ResourceSet
Svc += Resource
"""
if hasattr(other, 'resources'):
# new ResourceSet or ResourceSet-derived class
self.resourcesets.append(other)
self.resourcesets_by_type[other.type] = other
other.svc = self
return self
if other.subset is not None:
# the resource wants to be added to a specific resourceset
# for action grouping, parallel execution or sub-resource
# triggers
base_type = other.type.split(".")[0]
rtype = "%s:%s" % (base_type, other.subset)
else:
rtype = other.type
if rtype in self.resourcesets_by_type:
# the resource set already exists. add resource or resourceset.
self.resourcesets_by_type[rtype] += other
elif isinstance(other, Resource):
parallel = self.get_subset_parallel(rtype)
if hasattr(other, 'rset_class'):
rset = other.rset_class(type=rtype, resources=[other], parallel=parallel)
else:
rset = ResourceSet(type=rtype, resources=[other], parallel=parallel)
rset.rid = rtype
rset.svc = self
rset.pg_settings = self.get_pg_settings("subset#"+rtype)
self.__iadd__(rset)
else:
self.log.debug("unexpected object addition to the service: %s",
str(other))
if isinstance(other, Resource) and other.rid and "#" in other.rid:
other.pg_settings = self.get_pg_settings(other.rid)
self.resources_by_id[other.rid] = other
other.svc = self
if not other.disabled and hasattr(other, "on_add"):
other.on_add()
return self
def dblogger(self, action, begin, end, actionlogfile):
"""
Send to the collector the service status after an action, and
the action log.
"""
self.node.collector.call(
'end_action', self, action, begin, end, actionlogfile,
sync=self.sync_dblogger
)
g_vars, g_vals, r_vars, r_vals = self.svcmon_push_lists()
self.node.collector.call(
'svcmon_update_combo', g_vars, g_vals, r_vars, r_vals,
sync=self.sync_dblogger
)
os.unlink(actionlogfile)
try:
logging.shutdown()
except:
pass
def svclock(self, action=None, timeout=30, delay=1):
"""
Acquire the service action lock.
"""
suffix = None
if action in ACTIONS_NO_LOCK 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(rcEnv.paths.pathlock, self.svcname)
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:
lockfd = lock.lock(
timeout=timeout,
delay=delay,
lockfile=lockfile,
intent=action
)
except lock.lockTimeout as exc:
raise ex.excError("timed out waiting for lock %s: %s" % (details, str(exc)))
except lock.lockNoLockFile:
raise ex.excError("lock_nowait: set the 'lockfile' param %s" % details)
except lock.lockCreateError:
raise ex.excError("can not create lock file %s" % details)
except lock.lockAcquire as exc:
raise ex.excError("another action is currently running %s: %s" % (details, str(exc)))
except ex.excSignal:
raise ex.excError("interrupted by signal %s" % details)
except Exception as exc:
self.save_exc()
raise ex.excError("unexpected locking error %s: %s" % (details, str(exc)))
if lockfd is not None:
self.lockfd = lockfd
def svcunlock(self):
"""
Release the service action lock.
"""
lock.unlock(self.lockfd)
self.lockfd = None
@staticmethod
def setup_signal_handlers():
"""
Install signal handlers.
"""
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
def get_resource(self, rid):
"""
Return a resource object by id.
Return None if the rid is not found.
"""
if rid not in self.resources_by_id:
return
return self.resources_by_id[rid]
def get_resources(self, _type=None, strict=False, discard_disabled=True):
"""
Return the list of resources matching criteria.
"""
if _type is None:
rsets = self.resourcesets
else:
rsets = self.get_resourcesets(_type, strict=strict)
resources = []
for rset in rsets:
for resource in rset.resources:
if not self.encap and 'encap' in resource.tags:
continue
if discard_disabled and resource.disabled:
continue
resources.append(resource)
return resources
def get_resourcesets(self, _type, strict=False):
"""
Return the list of resourceset matching the specified types.
"""
if not isinstance(_type, list):
_types = [_type]
else:
_types = _type
rsets_by_type = {}
for rset in self.resourcesets:
if ':' in rset.type and rset.has_resource_with_types(_types, strict=strict):
# subset
rsets_by_type[rset.type] = rset
continue
rs_base_type = rset.type.split(".")[0]
if rset.type in _types:
# exact match
if rs_base_type not in rsets_by_type:
rsets_by_type[rs_base_type] = type(rset)(type=rs_base_type)
rsets_by_type[rs_base_type].svc = self
rsets_by_type[rs_base_type] += rset
elif rs_base_type in _types and not strict:
# group match
if rs_base_type not in rsets_by_type:
rsets_by_type[rs_base_type] = type(rset)(type=rs_base_type)
rsets_by_type[rs_base_type].svc = self
rsets_by_type[rs_base_type] += rset
rsets = list(rsets_by_type.values())
rsets.sort()
return rsets
def has_resourceset(self, _type, strict=False):
"""
Return True if the service has a resource set of the specified type.
"""
return len(self.get_resourcesets(_type, strict=strict)) > 0
def all_set_action(self, action=None, tags=None):
"""
Execute an action on all resources all resource sets.
"""
self.set_action(self.resourcesets, action=action, tags=tags)
def sub_set_action(self, _type=None, action=None, tags=None, xtags=None,
strict=False):
"""
Execute an action on all resources of the resource sets of the
specified type.
"""
rsets = self.get_resourcesets(_type, strict=strict)
self.set_action(rsets, action=action, tags=tags, xtags=xtags)
def need_snap_trigger(self, rsets, action):
"""
Return True if the action is a sync action and at least one of the
specified resource sets has a resource requiring a snapshot.
"""
if action not in ACTIONS_NEED_SNAP_TRIGGER:
return False
for rset in rsets:
for resource in rset.resources:
# avoid to run pre/post snap triggers when there is no
# resource flagged for snap and on drpnodes
if hasattr(resource, "snap") and resource.snap is True and \
rcEnv.nodename in self.nodes:
return True
return False
def set_action(self, rsets=None, action=None, tags=None, xtags=None):
"""
Call the action on all sets sorted resources.
If the sets define a pre_snap trigger run that before the action.
If the sets define a pre_<action> trigger run that before the action.
If the sets define a post_<action> trigger run that after the action.
"""
if rsets is None:
rsets = []
if tags is None:
tags = set()
if xtags is None:
xtags = set()
def do_trigger(when):
"""
Excecute a <when> trigger on each resource of the set,
if the action allows triggers.
If a trigger raises,
* excError, stop looping over the resources and propagate up
to the caller.
* excAbortAction, continue looping over the resources
* any other exception, save the traceback in the debug log
and stop looping over the resources and raise an excError
"""
for rset in rsets:
if action in ACTIONS_NO_TRIGGER or rset.all_skip(action):
break
try:
rset.log.debug("start %s %s_action", rset.type, when)
getattr(rset, when + "_action")(action)
except ex.excError:
raise
except ex.excAbortAction:
continue
except:
self.save_exc()
raise ex.excError
def do_snap_trigger(when):
"""
Execute the <when>snap trigger.
"""
if not need_snap:
return
trigger = getattr(self, when + "snap_trigger")
if trigger is None:
return
results = self.vcall(trigger)
if results[0] != 0:
raise ex.excError(results[2])
need_snap = self.need_snap_trigger(rsets, action)
# Multiple resourcesets of the same type need to be sorted
# so that the start and stop action happen in a predictible order.
# Sort alphanumerically on reseourceset type.
#
# Example, on start:
# app
# app.1
# app.2
# on stop:
# app.2
# app.1
# app
reverse = "stop" in action or action in ("rollback", "shutdown", "unprovision")
rsets = sorted(rsets, key=lambda x: x.type, reverse=reverse)
# snapshots are created in pre_action and destroyed in post_action
# place presnap and postsnap triggers around pre_action
do_snap_trigger("pre")
do_trigger("pre")
do_snap_trigger("post")
for rset in rsets:
self.log.debug('set_action: action=%s rset=%s', action, rset.type)
rset.action(action, tags=tags, xtags=xtags)
do_trigger("post")
def __str__(self):
"""
The Svc class print formatter.
"""
output = "Service %s available resources:" % self.svcname
for key in self.resourcesets_by_type:
output += " %s" % key
output += "\n"
for rset in self.resourcesets:
output += " [%s]" % str(rset)
return output
def status(self):
"""
Return the aggregate status a service.
"""
group_status = self.group_status()
return group_status["overall"].status
@lazy
def status_data_dump(self):
return os.path.join(rcEnv.paths.pathvar, self.svcname, "status.json")
def print_status_data(self, from_resource_status_cache=False):
"""
Return a structure containing hierarchical status of
the service.
"""
if not from_resource_status_cache and not self.options.refresh and os.path.exists(self.status_data_dump):
try:
with open(self.status_data_dump, 'r') as filep:
return json.load(filep)
except ValueError:
pass
now = time.time()
data = {
"updated": datetime.datetime.utcfromtimestamp(now).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
"mtime": now,
"resources": {},
"frozen": self.frozen(),
}
containers = self.get_resources('container')
if len(containers) > 0:
data['encap'] = {}
for container in containers:
if container.name is None or len(container.name) == 0:
# docker case
continue
try:
data['encap'][container.rid] = self.encap_json_status(container)
except:
data['encap'][container.rid] = {'resources': {}}
if hasattr(container, "vm_hostname"):
data['encap'][container.rid]["hostname"] = container.vm_hostname()
for rset in self.get_resourcesets(STATUS_TYPES, strict=True):
for resource in rset.resources:
(
rid,
rtype,
status,
label,
log,
monitor,
disable,
optional,