/
node.py
5364 lines (4889 loc) · 184 KB
/
node.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
# -*- coding: utf8 -*-
"""
This module implements the Node class.
The node
* handles communications with the collector
* holds the list of services
* has a scheduler
"""
from __future__ import absolute_import, division, print_function
import datetime
import fnmatch
import json
import logging
import os
import re
import shlex
import sys
import time
from errno import ECONNREFUSED, EPIPE
from multiprocessing import Process
import foreign.six as six
import core.exceptions as ex
import core.logger
import core.objects.builder
from core.capabilities import capabilities
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.network import NetworksMixin
from core.scheduler import SchedOpts, Scheduler, sched_action
from env import Env
from utilities.loop_delay import delay
from utilities.naming import (ANSI_ESCAPE, factory, fmt_path, glob_services_config,
is_service, new_id, paths_data,
resolve_path, split_path, strip_path, svc_pathetc,
validate_kind, validate_name, validate_ns_name,
object_path_glob)
from utilities.render.command import format_command
from utilities.selector import selector_config_match, selector_parse_fragment, selector_parse_op_fragment
from utilities.cache import purge_cache_expired
from utilities.converters import print_duration, print_size, convert_duration
from utilities.drivers import driver_import
from utilities.lazy import (lazy, lazy_initialized, set_lazy, unset_all_lazy,
unset_lazy)
from utilities.lock import LOCK_EXCEPTIONS
from utilities.proc import call, justcall, vcall, which, check_privs, daemon_process_running, drop_option, find_editor, \
init_locale, does_call_cmd_need_shell, get_call_cmd_from_str
from utilities.files import assert_file_exists, assert_file_is_root_only_writeable, makedirs
from utilities.render.color import formatter
from utilities.storage import Storage
from utilities.string import bdecode, base64encode
try:
from foreign.six.moves.urllib.request import Request, urlopen
from foreign.six.moves.urllib.error import HTTPError
from foreign.six.moves.urllib.parse import urlencode
except ImportError:
# pylint false positive
pass
if six.PY2:
BrokenPipeError = IOError
init_locale()
DEFAULT_STATUS_GROUPS = [
"hb",
"arbitrator",
]
ACTION_ANY_NODE = (
"collector_cli",
"delete",
"eval",
"get",
"set",
"unset",
"wait",
)
ACTION_ASYNC = {
"freeze": {
"target": "frozen",
"progress": "freezing",
},
"thaw": {
"target": "thawed",
"progress": "thawing",
},
}
ACTIONS_CUSTOM_REMOTE = (
"drain",
"ls",
"logs",
"ping",
"events",
"daemon_mutex_status",
"daemon_stats",
"daemon_status",
"daemon_blacklist_status",
"daemon_join",
"daemon_rejoin",
"daemon_relay_status",
"stonith",
)
ACTIONS_NOWAIT_RESULT = (
"delete",
"eval",
"get",
"set",
"unset",
"reboot",
"shutdown",
"updatepkg",
"updateclumgr",
"updatecomp",
"daemon_restart",
)
ACTIONS_NO_PARALLEL = [
"edit_config",
"get",
"print_config",
"print_resource_status",
"print_schedule",
"print_status",
]
ACTIONS_NO_MULTIPLE_SERVICES = [
"print_resource_status",
]
CONFIG_DEFAULTS = {
"push_schedule": "~00:00-06:00",
"sync_schedule": "~04:00-06:00",
"comp_schedule": "~02:00-06:00",
"collect_stats_schedule": "@10",
"no_schedule": "",
}
UNPRIVILEGED_ACTIONS = [
"collector_cli",
]
STATS_INTERVAL = 30
class Node(Crypt, ExtConfigMixin, NetworksMixin):
"""
Defines a cluster node. It contain list of Svc.
Implements node-level actions and checks.
"""
def __str__(self):
return self.nodename
def __init__(self, log_handlers=None):
ExtConfigMixin.__init__(self, default_status_groups=DEFAULT_STATUS_GROUPS)
self.listener = None
self.clouds = None
self.paths = Storage(
reboot_flag=os.path.join(Env.paths.pathvar, "REBOOT_FLAG"),
last_boot_id=os.path.join(Env.paths.pathvar, "node", "last_boot_id"),
tmp_cf=os.path.join(Env.paths.pathvar, "node.conf.tmp"),
cf=Env.paths.nodeconf,
)
self.services = None
self.options = Storage(
cron=False,
syncrpc=False,
force=False,
debug=False,
stats_dir=None,
begin=None,
end=None,
moduleset="",
module="",
node=None,
ruleset_date="",
objects=[],
format=None,
user=None,
api=None,
resource=[],
mac=None,
broadcast=None,
param=None,
value=None,
extra_argv=[],
)
self.stats_data = {}
self.stats_updated = 0
log_file = os.path.join(Env.paths.pathlog, "node.log")
self.logger = core.logger.initLogger(Env.nodename, log_file, handlers=log_handlers)
extra = {"node": Env.nodename, "sid": Env.session_uuid}
self.log = logging.LoggerAdapter(self.logger, extra)
def get_node(self):
"""
helper for the comm module to find the Node(), for accessing
its configuration.
"""
return self
@lazy
def cd(self):
configs = []
if os.path.exists(Env.paths.clusterconf):
configs.append(Env.paths.clusterconf)
if os.path.exists(Env.paths.nodeconf):
configs.append(Env.paths.nodeconf)
return self.parse_config_file(configs)
def cd_clear_caches(self):
self.raw_cd = None
self.unset_lazy("cd")
@lazy
def private_cd(self):
return self.parse_config_file(self.paths.cf)
@lazy
def kwstore(self):
from .nodedict import KEYS
return KEYS
@lazy
def devnull(self):
return os.open(os.devnull, os.O_RDWR)
@lazy
def var_d(self):
var_d = os.path.join(Env.paths.pathvar, "node")
makedirs(var_d)
return var_d
@property
def svcs(self):
if self.services is None:
return None
return list(self.services.values())
@lazy
def freezer(self):
"""
Lazy allocator for the freezer object.
"""
return Freezer("node")
@lazy
def sched(self):
"""
Lazy initialization of the node Scheduler object.
"""
return Scheduler(
config_defaults=CONFIG_DEFAULTS,
options=self.options,
node=self,
scheduler_actions={
"checks": [SchedOpts(
"checks",
req_collector=True,
)],
"dequeue_actions": [SchedOpts(
"dequeue_actions",
schedule_option="no_schedule",
req_collector=True,
)],
"pushstats": [SchedOpts(
"stats",
req_collector=True,
)],
"collect_stats": [SchedOpts(
"stats_collection",
schedule_option="collect_stats_schedule"
)],
"pushpkg": [SchedOpts(
"packages",
req_collector=True,
)],
"pushpatch": [SchedOpts(
"patches",
req_collector=True,
)],
"pushasset": [SchedOpts(
"asset",
req_collector=True,
)],
"pushnsr": [SchedOpts(
"nsr",
schedule_option="no_schedule",
req_collector=True,
)],
"pushhp3par": [SchedOpts(
"hp3par",
schedule_option="no_schedule",
req_collector=True,
)],
"pushemcvnx": [SchedOpts(
"emcvnx",
schedule_option="no_schedule",
req_collector=True,
)],
"pushcentera": [SchedOpts(
"centera",
schedule_option="no_schedule",
req_collector=True,
)],
"pushnetapp": [SchedOpts(
"netapp",
schedule_option="no_schedule",
req_collector=True,
)],
"pushibmds": [SchedOpts(
"ibmds",
schedule_option="no_schedule",
req_collector=True,
)],
"pushfreenas": [SchedOpts(
"freenas",
schedule_option="no_schedule",
req_collector=True,
)],
"pushxtremio": [SchedOpts(
"xtremio",
schedule_option="no_schedule",
req_collector=True,
)],
"pushpure": [SchedOpts(
"pure",
schedule_option="no_schedule",
req_collector=True,
)],
"pushgcedisks": [SchedOpts(
"gcedisks",
schedule_option="no_schedule",
req_collector=True,
)],
"pushhcs": [SchedOpts(
"hcs",
schedule_option="no_schedule",
req_collector=True,
)],
"pushhds": [SchedOpts(
"hds",
schedule_option="no_schedule",
req_collector=True,
)],
"pushnecism": [SchedOpts(
"necism",
schedule_option="no_schedule",
req_collector=True,
)],
"pusheva": [SchedOpts(
"eva",
schedule_option="no_schedule",
req_collector=True,
)],
"pushibmsvc": [SchedOpts(
"ibmsvc",
schedule_option="no_schedule",
req_collector=True,
)],
"pushvioserver": [SchedOpts(
"vioserver",
schedule_option="no_schedule",
req_collector=True,
)],
"pushsym": [SchedOpts(
"sym",
schedule_option="no_schedule",
req_collector=True,
)],
"pushbrocade": [SchedOpts(
"brocade", schedule_option="no_schedule",
req_collector=True,
)],
"pushdisks": [SchedOpts(
"disks",
req_collector=True,
)],
"sysreport": [SchedOpts(
"sysreport",
req_collector=True,
)],
"compliance_auto": [SchedOpts(
"compliance",
fname="last_comp_check",
schedule_option="comp_schedule",
req_collector=True,
)],
"rotate_root_pw": [SchedOpts(
"rotate_root_pw",
fname="last_rotate_root_pw",
schedule_option="no_schedule",
req_collector=True,
)],
"auto_reboot": [SchedOpts(
"reboot",
fname="last_auto_reboot",
schedule_option="no_schedule"
)]
},
)
@lazy
def collector(self):
"""
Lazy initialization of the node Collector object.
"""
self.log.debug("initialize node::collector")
from core.collector.rpc import CollectorRpc
return CollectorRpc(node=self)
@lazy
def nodename(self):
"""
Lazy initialization of the node name.
"""
return Env.nodename
@lazy
def compliance(self):
from core.compliance import Compliance
comp = Compliance(self)
return comp
def check_privs(self, action):
"""
Raise if the action requires root privileges but the current
running user is not root.
"""
if action in UNPRIVILEGED_ACTIONS:
return
check_privs()
@lazy
def quorum(self):
try:
return self.conf_get("cluster", "quorum")
except ex.OptNotFound as exc:
return exc.default
@lazy
def dns(self):
try:
return self.conf_get("cluster", "dns")
except ex.OptNotFound as exc:
return exc.default
@lazy
def env(self):
try:
return self.conf_get("node", "env")
except ex.OptNotFound as exc:
return exc.default
def get_min_avail(self, keyword, metric, limit=100):
total = self.stats().get(metric) # mb
if total in (0, None):
return 0
try:
val = self.conf_get("node", keyword)
except ex.OptNotFound as exc:
val = exc.default
if str(val).endswith("%"):
val = int(val.rstrip("%"))
else:
val = val // 1024 // 1024 # b > mb
val = int(val/total*100)
if val > limit:
# unreasonable
val = limit
return val
@lazy
def min_avail_mem(self):
return self.get_min_avail("min_avail_mem", "mem_total", 50)
@lazy
def min_avail_swap(self):
return self.get_min_avail("min_avail_swap", "swap_total", 100)
@lazy
def max_parallel(self):
try:
return self.conf_get("node", "max_parallel")
except ex.OptNotFound as exc:
return self.default_max_parallel()
def default_max_parallel(self):
nr = int(self.asset.get_cpu_threads()["value"])
if nr == 0:
nr = int(self.asset.get_cpu_cores()["value"])
return max(2, nr//2)
@lazy
def dnsnodes(self):
if not self.dns:
return []
from socket import gethostbyaddr
nodes = []
for ip in self.dns:
try:
data = gethostbyaddr(ip)
names = [data[0]] + data[1]
except Exception as exc:
names = []
for node in names:
if node in self.cluster_nodes:
nodes.append(node)
break
return nodes
@lazy
def arbitrators(self):
arbitrators = []
for section in self.conf_sections("arbitrator"):
data = {
"id": section,
}
try:
data["name"] = self.conf_get(section, "name")
except Exception:
continue
try:
data["secret"] = self.conf_get(section, "secret")
except Exception:
continue
try:
data["timeout"] = self.conf_get(section, "timeout")
except ex.OptNotFound as exc:
data["timeout"] = exc.default
arbitrators.append(data)
return arbitrators
@staticmethod
def split_url(url, default_app=None):
"""
Split a node.conf node.dbopensvc style url into a
(protocol, host, port, app) tuple.
"""
if url == 'None':
return 'https', '127.0.0.1', '443', '/'
# transport
if url.startswith('https'):
transport = 'https'
url = url.replace('https://', '')
elif url.startswith('http'):
transport = 'http'
url = url.replace('http://', '')
else:
transport = 'https'
elements = url.split('/')
if len(elements) < 1:
raise ex.Error("url %s should have at least one slash")
# app
if len(elements) > 1:
app = elements[1]
else:
app = default_app
# host/port
subelements = elements[0].split(':')
if len(subelements) == 1:
host = subelements[0]
if transport == 'http':
port = '80'
else:
port = '443'
elif len(subelements) == 2:
host = subelements[0]
port = subelements[1]
else:
raise ex.Error("too many columns in %s" % ":".join(subelements))
return transport, host, port, app
@lazy
def collector_env(self):
"""
Return the collector connection elements parsed from the node config
node.uuid, node.dbopensvc and node.dbcompliance as a Storage().
"""
data = Storage()
url = self.oget("node", "dbopensvc")
if url:
try:
(
data.dbopensvc_transport,
data.dbopensvc_host,
data.dbopensvc_port,
data.dbopensvc_app
) = self.split_url(url, default_app="feed")
data.dbopensvc = "%s://%s:%s/%s/default/call/xmlrpc" % (
data.dbopensvc_transport,
data.dbopensvc_host,
data.dbopensvc_port,
data.dbopensvc_app
)
except ex.Error as exc:
self.log.error("malformed dbopensvc url: %s (%s)",
url, str(exc))
else:
data.dbopensvc_transport = None
data.dbopensvc_host = None
data.dbopensvc_port = None
data.dbopensvc_app = None
data.dbopensvc = None
url = self.oget("node", "dbcompliance")
if url:
try:
(
data.dbcompliance_transport,
data.dbcompliance_host,
data.dbcompliance_port,
data.dbcompliance_app
) = self.split_url(url, default_app="init")
data.dbcompliance = "%s://%s:%s/%s/compliance/call/xmlrpc" % (
data.dbcompliance_transport,
data.dbcompliance_host,
data.dbcompliance_port,
data.dbcompliance_app
)
except ex.Error as exc:
self.log.error("malformed dbcompliance url: %s (%s)",
url, str(exc))
else:
data.dbcompliance_transport = data.dbopensvc_transport
data.dbcompliance_host = data.dbopensvc_host
data.dbcompliance_port = data.dbopensvc_port
data.dbcompliance_app = "init"
data.dbcompliance = "%s://%s:%s/%s/compliance/call/xmlrpc" % (
data.dbcompliance_transport,
data.dbcompliance_host,
data.dbcompliance_port,
data.dbcompliance_app
)
node_uuid = self.oget("node", "uuid")
if node_uuid:
data.uuid = node_uuid
else:
data.uuid = ""
return data
def call(self, *args, **kwargs):
"""
Wrap utilities call function, setting the node logger.
"""
kwargs["log"] = self.log
return call(*args, **kwargs)
def vcall(self, *args, **kwargs):
"""
Wrap utilities vcall function, setting the node logger.
"""
kwargs["log"] = self.log
return vcall(*args, **kwargs)
@staticmethod
def filter_ns(paths, namespace):
if not namespace:
return paths
if namespace == "root":
return [path for path in paths if split_path(path)[1] is None]
return [path for path in paths if split_path(path)[1] == namespace]
def svcs_selector(self, selector, namespace=None, local=False):
"""
Given a selector string, return a list of service names.
This exposed method only aggregates ORed elements.
"""
# fully qualified name
path = is_service(selector, namespace, local=local)
if path:
self.options.single_service = True
paths = self.filter_ns([path], namespace)
return paths
if not local and os.environ.get("OSVC_ACTION_ORIGIN") != "daemon":
# the daemon always submits actions with simple, local selector.
# avoid round trips.
try:
data = self._daemon_object_selector(selector, namespace, kind=os.environ.get("OSVC_KIND"))
if isinstance(data, list):
return data
except Exception as exc:
print(exc, file=sys.stderr)
# fallback to local lookup
pass
# full listing and namespace full listing
if selector is None:
# only svc kind by default
selector = "*"
# fnmatch on names and service config/status filtering
try:
paths = self._svcs_selector(selector, namespace)
finally:
del self.services
self.services = None
paths = self.filter_ns(paths, namespace)
return paths
def _svcs_selector(self, selector, namespace=None):
if want_context():
raise ex.Error("daemon is unreachable")
self.build_services()
paths = [svc.path for svc in self.svcs]
paths = self.filter_ns(paths, namespace)
if "," in selector:
ored_selectors = selector.split(",")
else:
ored_selectors = [selector]
result = []
for _selector in ored_selectors:
for path in self.__svcs_selector(_selector, paths, namespace=namespace):
if path not in result:
result.append(path)
if len(result) == 0 and not re.findall(r"[,+*=^:~><]", selector):
raise ex.Error("object not found")
return result
def __svcs_selector(self, selector, paths, namespace=None):
"""
Given a selector string, return a list of service names.
This method only intersect the ANDed elements.
"""
if selector in (None, ""):
return []
path = is_service(selector, namespace, local=True)
if path:
return [path]
if "+" in selector:
anded_selectors = selector.split("+")
else:
anded_selectors = [selector]
if selector in (None, ""):
result = paths
else:
result = None
for _selector in anded_selectors:
_paths = self.___svcs_selector(_selector, paths, namespace)
if result is None:
result = _paths
else:
common = set(result) & set(_paths)
result = [name for name in result if name in common]
return result
def ___svcs_selector(self, selector, paths, namespace):
"""
Given a basic selector string (no AND nor OR), return a list of service
names.
"""
pds = paths_data(paths)
kind = os.environ.get("OSVC_KIND")
if kind:
pds = [pd for pd in pds if pd["kind"] == kind]
paths = [pd["display"] for pd in pds]
negate, selector, elts = selector_parse_fragment(selector)
if len(elts) == 1:
return object_path_glob(selector, pds=pds, namespace=namespace, kind=kind, negate=negate)
try:
param, op, value = selector_parse_op_fragment(elts)
except ValueError:
return []
# config keyword match
result = []
for svc in self.svcs:
ret = selector_config_match(svc, param, op, value)
if ret ^ negate:
result.append(svc.path)
return result
def build_services(self, *args, **kwargs):
"""
Instanciate a Svc objects for each requested services and add it to
the node.
"""
if self.svcs is not None and \
('paths' not in kwargs or
(isinstance(kwargs['paths'], list) and len(kwargs['paths']) == 0)):
return
if 'paths' in kwargs and \
isinstance(kwargs['paths'], list) and \
len(kwargs['paths']) > 0 and \
self.svcs is not None:
paths_request = set(kwargs['paths'])
paths_actual = set([s.path for s in self.svcs])
if len(paths_request-paths_actual) == 0:
return
self.services = {}
if want_context():
# build volatile objects
for path in kwargs['paths']:
name, namespace, kind = split_path(path)
self += factory(kind)(name, namespace=namespace, volatile=True,
cf=os.devnull, node=self)
return
kwargs["node"] = self
svcs, errors = core.objects.builder.build_services(*args, **kwargs)
if 'paths' in kwargs:
self.check_build_errors(kwargs['paths'], svcs, errors)
opt_status = kwargs.get("status")
for svc in svcs:
if opt_status is not None and not svc.status() in opt_status:
continue
self += svc
@staticmethod
def check_build_errors(paths, svcs, errors):
"""
Raise error if the service builder did not return a Svc object for
each service we requested.
"""
if isinstance(paths, list):
n_args = len(paths)
else:
n_args = 1
n_svcs = len(svcs)
if n_svcs == n_args:
return 0
msg = ""
if n_args > 1:
msg += "%d services validated out of %d\n" % (n_svcs, n_args)
if len(errors) == 1:
msg += errors[0]
else:
msg += "\n".join(["- "+err for err in errors])
if n_args == 0 and not msg:
return 0
raise ex.Error(msg)
def rebuild_services(self, paths):
"""
Delete the list of Svc objects in the Node object and create a new one.
Args:
paths: add only Svc objects for services specified
"""
del self.services
self.services = None
self.build_services(paths=paths, node=self)
def close(self):
"""
Stop the node class workers
"""
if lazy_initialized(self, "devnull"):
os.close(self.devnull)
import gc
import threading
gc.collect()
for thr in threading.enumerate():
if thr.name == 'QueueFeederThread' and thr.ident is not None:
thr.join(1)
def make_temp_config(self):
"""
Copy the current service configuration file to a temporary
location for edition.
If the temp file already exists, propose the --discard
or --recover options.
"""
import shutil
if os.path.exists(self.paths.tmp_cf):
if self.options.recover:
pass
elif self.options.discard:
shutil.copy(Env.paths.nodeconf, self.paths.tmp_cf)
else:
self.edit_config_diff()
print("%s exists: node conf is already being edited. Set "
"--discard to edit from the current configuration, "
"or --recover to open the unapplied config" %
self.paths.tmp_cf, file=sys.stderr)
raise ex.Error
else:
shutil.copy(Env.paths.nodeconf, self.paths.tmp_cf)
return self.paths.tmp_cf
def edit_config_diff(self):
"""
Display the diff between the current config and the pending
unvalidated config.
"""
from subprocess import call
def diff_capable(opts):
cmd = ["diff"] + opts + [Env.paths.nodeconf, self.paths.cf]
cmd_results = justcall(cmd)
if cmd_results[2] == 0:
return True
return False
if not os.path.exists(self.paths.tmp_cf):
return
if diff_capable(["-u", "--color"]):
cmd = ["diff", "-u", "--color", Env.paths.nodeconf, self.paths.tmp_cf]
elif diff_capable(["-u"]):
cmd = ["diff", "-u", Env.paths.nodeconf, self.paths.tmp_cf]
else:
cmd = ["diff", Env.paths.nodeconf, self.paths.tmp_cf]
call(cmd)
def nodeconf_csum(self):
from utilities.files import fsum
return fsum(Env.paths.nodeconf)
def edit_config(self):
"""
Execute an editor on the node configuration file.
When the editor exits, validate the new configuration file.
If validation pass, install the new configuration,
else keep the previous configuration in place and offer the
user the --recover or --discard choices for its next edit
config action.
"""
try:
editor = find_editor()
except ex.Error as err:
print(err, file=sys.stderr)
return 1
from utilities.files import fsum
path = self.make_temp_config()
os.system(' '.join((editor, path)))
if fsum(path) == self.nodeconf_csum():
os.unlink(path)
return 0
results = self._validate_config(path=path)
if results["errors"] == 0:
try:
move_config_file(path, Env.paths.nodeconf)
finally:
try:
os.unlink(path)
except Exception:
pass
else:
print("your changes were not applied because of the errors "
"reported above. you can use the edit config command "
"with --recover to try to fix your changes or with "
"--discard to restart from the live config")
return results["errors"] + results["warnings"]
def purge_status_last(self):
"""
Purge the cached status of each and every services and resources.
"""
for svc in self.svcs:
svc.purge_status_last()
def __iadd__(self, svc):
"""
Implement the Node() += Svc() operation, setting the node backpointer
in the added service, storing the service in a list
"""
if not hasattr(svc, "path"):
return self
if self.services is None:
self.services = {}
self.services[svc.path] = svc
return self
def action(self, action, options=None):
"""
The node action wrapper.
Looks up which method to handle the action (some are not implemented
in the Node class), and call the handling method.
"""
try:
self.async_action(action)
except ex.AbortAction:
return 0
try:
return self._action(action, options)
except LOCK_EXCEPTIONS as exc: