forked from oceanbase/obdeploy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_deploy.py
1884 lines (1594 loc) · 71.1 KB
/
_deploy.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: utf-8
# OceanBase Deploy.
# Copyright (C) 2021 OceanBase
#
# This file is part of OceanBase Deploy.
#
# OceanBase Deploy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OceanBase Deploy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OceanBase Deploy. If not, see <https://www.gnu.org/licenses/>.
from __future__ import absolute_import, division, print_function
from collections.abc import Iterable, Iterator
import os
import re
import sys
import getpass
import hashlib
from copy import deepcopy
from enum import Enum
from datetime import datetime
from ruamel.yaml.comments import CommentedMap
import _errno as err
from tool import ConfigUtil, FileUtil, YamlLoader, OrderedDict, COMMAND_ENV
from _manager import Manager
from _stdio import SafeStdio
from _environ import ENV_BASE_DIR
yaml = YamlLoader()
DEFAULT_CONFIG_PARSER_MANAGER = None
ENV = 'env'
class ParserError(Exception):
pass
class UserConfig(object):
DEFAULT = {
'username': getpass.getuser(),
'password': None,
'key_file': None,
'port': 22,
'timeout': 300
}
def __init__(self, username=None, password=None, key_file=None, port=None, timeout=None):
self.username = username if username else self.DEFAULT['username']
self.password = password
self.key_file = key_file if key_file else self.DEFAULT['key_file']
self.port = port if port else self.DEFAULT['port']
self.timeout = timeout if timeout else self.DEFAULT['timeout']
def __str__(self):
return '%s' % self.username
def __repr__(self):
return '<UserConfig: %s>' % self.__str__()
class ServerConfig(object):
def __init__(self, ip, name=None):
self.ip = ip
self._name = name
@property
def name(self):
return self._name if self._name else self.ip
def __str__(self):
return '%s(%s)' % (self._name, self.ip) if self._name else self.ip
def __repr__(self):
return '<%s>' % self.__str__()
def __hash__(self):
return hash(self.__str__())
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.ip == other.ip and self.name == other.name
if isinstance(other, dict):
return self.ip == other['ip'] and self.name == other['name']
class ServerConfigFlyweightFactory(object):
_CACHE = {}
@staticmethod
def get_instance(ip, name=None):
server = ServerConfig(ip, name)
_key = server.__str__()
if _key not in ServerConfigFlyweightFactory._CACHE:
ServerConfigFlyweightFactory._CACHE[_key] = server
return ServerConfigFlyweightFactory._CACHE[_key]
class RsyncConfig(object):
RSYNC = 'runtime_dependencies'
SOURCE_PATH = 'src_path'
TARGET_PATH = 'target_path'
class InnerConfigItem(str):
pass
class InnerConfigKey(object):
keyword_symbol = "$_"
@classmethod
def is_keyword(cls, s):
return s.startswith(cls.keyword_symbol)
@classmethod
def to_keyword(cls, key):
return "{}{}".format(cls.keyword_symbol, key)
@classmethod
def keyword_to_str(cls, _keyword):
return str(_keyword.replace(cls.keyword_symbol, '', 1))
class ComponentInnerConfig(dict):
COMPONENT_GLOBAL_ATTRS = InnerConfigKey.to_keyword('component_global_attrs')
def __init__(self, component_name, config):
super(ComponentInnerConfig, self).__init__()
self.component_name = component_name
c_config = {}
for server in config:
i_config = {}
s_config = config[server]
for key in s_config:
i_config[InnerConfigItem(key)] = s_config[key]
c_config[server] = i_config
self.update(c_config)
def __iter__(self):
keys = self.keys()
servers = []
for key in keys:
if key != self.COMPONENT_GLOBAL_ATTRS:
servers.append(key)
return iter(servers)
def update_server_config(self, server, key, value):
self._update_config(server, key, value)
def update_attr(self, key, value):
self._update_config(self.COMPONENT_GLOBAL_ATTRS, key, value)
def del_server_config(self, server, key):
self._del_config(server, key)
def del_attr(self, key):
self._del_config(self.COMPONENT_GLOBAL_ATTRS, key)
def get_attr(self, key):
return self._get_config(self.COMPONENT_GLOBAL_ATTRS, key)
def _update_config(self, item, key, value):
if not self.__contains__(item):
self[item] = {}
if not InnerConfigKey.is_keyword(key):
key = InnerConfigKey.to_keyword(key)
self[item][key] = value
def _del_config(self, item, key):
if not self.__contains__(item):
return
if not InnerConfigKey.is_keyword(key):
key = InnerConfigKey.to_keyword(key)
if key in self[item]:
del self[item][key]
def _get_config(self, item, key):
if not self.__contains__(item):
return
if not InnerConfigKey.is_keyword(key):
key = InnerConfigKey.to_keyword(key)
return self[item].get(key)
class InnerConfigKeywords(object):
DEPLOY_INSTALL_MODE = 'deploy_install_mode'
DEPLOY_BASE_DIR = 'deploy_base_dir'
class InnerConfig(object):
def __init__(self, path, yaml_loader):
self.path = path
self.yaml_loader = yaml_loader
self.config = {}
self._load()
def _load(self):
self.config = {}
try:
with FileUtil.open(self.path, 'rb') as f:
config = self.yaml_loader.load(f)
for component_name in config:
if InnerConfigKey.is_keyword(component_name):
self.config[InnerConfigItem(component_name)] = config[component_name]
else:
self.config[component_name] = ComponentInnerConfig(component_name, config[component_name])
except:
pass
def _dump(self):
try:
stdio = self.yaml_loader.stdio if self.yaml_loader else None
with FileUtil.open(self.path, 'w', stdio=stdio) as f:
self.yaml_loader.dump(self.config, f)
return True
except:
pass
return False
def dump(self):
return self._dump()
def get_component_config(self, component_name):
return self.config.get(component_name, {})
def get_server_config(self, component_name, server):
return self.get_component_config(component_name).get(server, {})
def get_global_config(self, key, default=None):
key = InnerConfigKey.to_keyword(key)
return self.config.get(key, default)
def update_global_config(self, key, value):
self.config[InnerConfigKey.to_keyword(key)] = value
def update_component_config(self, component_name, config):
self.config[component_name] = {}
for server in config:
c_config = {}
data = config[server]
for key in data:
if not isinstance(key, InnerConfigItem):
key = InnerConfigItem(key)
c_config[key] = data[key]
self.config[component_name][server] = c_config
if ComponentInnerConfig.COMPONENT_GLOBAL_ATTRS in config:
self.config[component_name][ComponentInnerConfig.COMPONENT_GLOBAL_ATTRS] = config[ComponentInnerConfig.COMPONENT_GLOBAL_ATTRS]
class ConfigParser(object):
STYLE = ''
INNER_CONFIG_MAP = {}
PREFIX = '$_'
META_KEYS = ['version', 'tag', 'release', 'package_hash']
@classmethod
def _is_inner_item(cls, key):
return isinstance(key, InnerConfigItem) and key.startswith(cls.PREFIX)
@classmethod
def extract_inner_config(cls, cluster_config, config):
return {}
@staticmethod
def _get_server(server_data):
if isinstance(server_data, dict):
ip = ConfigUtil.get_value_from_dict(server_data, 'ip', transform_func=str)
name = ConfigUtil.get_value_from_dict(server_data, 'name', transform_func=str)
else:
ip = server_data
name = None
if not re.match(r'^((25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}(25[0-5]|2[0-4]\d|[01]?\d{1,2})$', ip) \
and not re.match(r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$', ip):
raise Exception('Invalid ip address {}'.format(ip))
return ServerConfigFlyweightFactory.get_instance(ip, name)
@classmethod
def _get_servers(cls, servers_data):
servers = []
for server_data in servers_data:
servers.append(cls._get_server(server_data))
return servers
@classmethod
def _to_cluster_config(cls, component_name, config, added_servers=None):
raise NotImplementedError
@classmethod
def merge_config(cls, component_name, config, new_config):
raise NotImplementedError
@classmethod
def to_cluster_config(cls, component_name, config, added_servers=None):
cluster_config = cls._to_cluster_config(component_name, config, added_servers)
cluster_config.set_include_file(config.get('include', ''))
cluster_config.parser = cls
return cluster_config
@classmethod
def _from_cluster_config(cls, conf, cluster_config):
raise NotImplementedError
@classmethod
def from_cluster_config(cls, cluster_config):
if not cls.STYLE:
raise NotImplementedError('undefined Style ConfigParser')
conf = CommentedMap()
conf['style'] = cls.STYLE
if cluster_config.origin_package_hash:
conf['package_hash'] = cluster_config.origin_package_hash
if cluster_config.origin_version:
conf['version'] = cluster_config.origin_version
if cluster_config.origin_tag:
conf['tag'] = cluster_config.origin_tag
if cluster_config.origin_release:
conf['release'] = cluster_config.origin_release
if cluster_config.depends:
conf['depends'] = list(cluster_config.depends)
conf = cls._from_cluster_config(conf, cluster_config)
inner_config = cls.extract_inner_config(cluster_config, conf)
return {
'inner_config': inner_config,
'config': conf
}
@classmethod
def get_server_src_conf(cls, cluster_config, component_config, server):
if server.name not in component_config:
component_config[server.name] = {}
return component_config[server.name]
@classmethod
def get_global_src_conf(cls, cluster_config, component_config):
if 'global' not in component_config:
component_config['global'] = {}
return component_config['global']
class DefaultConfigParser(ConfigParser):
STYLE = 'default'
@classmethod
def _to_cluster_config(cls, component_name, conf, added_servers=None):
servers = cls._get_servers(conf.get('servers', []))
cluster_config = ClusterConfig(
servers,
component_name,
ConfigUtil.get_value_from_dict(conf, 'version', None, str),
ConfigUtil.get_value_from_dict(conf, 'tag', None, str),
ConfigUtil.get_value_from_dict(conf, 'release', None, str),
ConfigUtil.get_value_from_dict(conf, 'package_hash', None, str)
)
if added_servers:
cluster_config.added_servers = added_servers
if 'global' in conf:
cluster_config.set_global_conf(conf['global'])
if RsyncConfig.RSYNC in conf:
cluster_config.set_rsync_list(conf[RsyncConfig.RSYNC])
if ENV in conf:
cluster_config.set_environments(conf[ENV])
for server in servers:
if server.name in conf:
cluster_config.add_server_conf(server, conf[server.name])
return cluster_config
@classmethod
def merge_config(cls, component_name, config, new_config):
unmergeable_keys = cls.META_KEYS + ['global', RsyncConfig.RSYNC, ENV]
for key in unmergeable_keys:
assert key not in new_config, Exception('{} is not allowed to be set in additional conf'.format(key))
servers = cls._get_servers(config.get('servers', []))
merge_servers = cls._get_servers(new_config.get('servers', []))
for server in merge_servers:
assert server not in servers, Exception('{} is already in cluster'.format(server))
config['servers'] = config.get('servers', []) + new_config.get('servers', [])
merge_server_names = [server.name for server in merge_servers]
for key in merge_server_names:
if key in new_config:
config[key] = new_config[key]
return cls.to_cluster_config(component_name, config, merge_servers)
@classmethod
def extract_inner_config(cls, cluster_config, config):
inner_config = cluster_config.get_inner_config()
for server in cluster_config.servers:
if server.name not in inner_config:
inner_config[server.name] = {}
global_config = config.get('global', {})
keys = list(global_config.keys())
for key in keys:
if cls._is_inner_item(key):
for server in cluster_config.servers:
inner_config[server.name][key] = global_config[key]
del global_config[key]
for server in cluster_config.servers:
if server.name not in config:
continue
server_config = config[server.name]
keys = list(server_config.keys())
for key in keys:
if cls._is_inner_item(key):
inner_config[server.name][key] = server_config[key]
del server_config[key]
return inner_config
@classmethod
def _from_cluster_config(cls, conf, cluster_config):
conf['servers'] = []
for server in cluster_config.servers:
if server.name == server.ip:
conf['servers'].append(server.name)
else:
conf['servers'].append({'name': server.name, 'ip': server.ip})
if cluster_config.get_original_global_conf():
conf['global'] = cluster_config.get_original_global_conf()
for server in cluster_config.servers:
server_config = cluster_config.get_original_server_conf(server)
if server_config:
conf[server.name] = server_config
return conf
class ClusterConfig(object):
def __init__(self, servers, name, version, tag, release, package_hash, parser=None):
self._version = version
self.origin_version = version
self.tag = tag
self.origin_tag = tag
self._release = release
self.origin_release = release
self.name = name
self.origin_package_hash = package_hash
self._package_hash = package_hash
self._temp_conf = {}
self._all_default_conf = {}
self._default_conf = {}
self._global_conf = None
self._server_conf = {}
self._cache_server = {}
self._original_global_conf = {}
self._rsync_list = None
self._include_config = None
self._origin_rsync_list = {}
self._include_file = None
self._origin_include_file = None
self._origin_include_config = None
self._unprocessed_global_conf = None
self._unprocessed_server_conf = {}
self._environments = None
self._origin_environments = {}
self._inner_config = {}
self._base_dir = ''
servers = list(servers)
self.servers = servers
self._original_servers = servers # 保证顺序
for server in servers:
self._server_conf[server] = {}
self._cache_server[server] = None
self._deploy_config = None
self._depends = {}
self._be_depends = {}
self.parser = parser
self._has_package_pattern = None
self._object_hash = None
self.added_servers = []
if sys.version_info.major == 2:
def __hash__(self):
if self._object_hash is None:
m_sum = hashlib.md5()
m_sum.update(str(self.package_hash).encode('utf-8'))
m_sum.update(str(self.get_global_conf()).encode('utf-8'))
for server in self.servers:
m_sum.update(str(self.get_server_conf(server)).encode('utf-8'))
m_sum.update(str(self.depends).encode('utf-8'))
self._object_hash = int(''.join(['%03d' % ord(v) for v in m_sum.digest()]))
return self._object_hash
else:
def __hash__(self):
if self._object_hash is None:
m_sum = hashlib.md5()
m_sum.update(str(self.package_hash).encode('utf-8'))
m_sum.update(str(self.get_global_conf()).encode('utf-8'))
for server in self.servers:
m_sum.update(str(self.get_server_conf(server)).encode('utf-8'))
m_sum.update(str(self.depends).encode('utf-8'))
self._object_hash = (int(''.join(['%03d' % v for v in m_sum.digest()])))
return self._object_hash
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
# todo 检查 rsync include等
if self.servers != other.servers:
return False
if self.get_global_conf() != other.get_global_conf():
return False
for server in self.servers:
if self.get_server_conf(server) != other.get_server_conf(server):
return False
return True
def __deepcopy__(self, memo):
cluster_config = self.__class__(deepcopy(self.servers), self.name, self.version, self.tag, self.release, self.package_hash, self.parser)
copy_attrs = ['origin_tag', 'origin_version', 'origin_package_hash', 'parser', 'added_servers']
deepcopy_attrs = ['_temp_conf', '_all_default_conf', '_default_conf', '_global_conf', '_server_conf', '_cache_server', '_original_global_conf', '_depends', '_original_servers', '_inner_config']
for attr in copy_attrs:
setattr(cluster_config, attr, getattr(self, attr))
for attr in deepcopy_attrs:
setattr(cluster_config, attr, deepcopy(getattr(self, attr)))
return cluster_config
def set_deploy_config(self, _deploy_config):
if self._deploy_config is None:
self._deploy_config = _deploy_config
self.set_base_dir(self._deploy_config.get_base_dir())
return True
return False
def set_base_dir(self, base_dir):
if self._base_dir != base_dir:
self._base_dir = base_dir
self._rsync_list = None
self._include_config = None
self._global_conf = None
@property
def deploy_name(self):
return self._deploy_config.name
@property
def original_servers(self):
return self._original_servers
@property
def depends(self):
return self._depends.keys()
@property
def be_depends(self):
return self._be_depends.keys()
def _clear_cache_server(self):
for server in self._cache_server:
self._cache_server[server] = None
if server in self._unprocessed_server_conf:
del self._unprocessed_server_conf[server]
def get_inner_config(self):
return self._inner_config
def update_component_attr(self, key, value, save=True):
self._inner_config.update_attr(key, value)
return self._deploy_config.dump() if save else True
def del_component_attr(self, key, save=True):
self._inner_config.del_attr(key)
return self._deploy_config.dump() if save else True
def get_component_attr(self, key):
return self._inner_config.get_attr(key)
def is_cp_install_mode(self):
return self._deploy_config.is_cp_install_mode()
def is_ln_install_mode(self):
return self._deploy_config.is_ln_install_mode()
def apply_inner_config(self, config):
if not isinstance(config, ComponentInnerConfig):
config = ComponentInnerConfig(self.name, {} if config is None else config)
self._inner_config = config
self._clear_cache_server()
def add_depend(self, name, cluster_conf):
if self.name == name:
raise Exception('Can not set %s as %s\'s dependency' % (name, name))
if self.name in cluster_conf.depends:
raise Exception('Circular Dependency: %s and %s' % (self.name, name))
self._depends[name] = cluster_conf
cluster_conf.add_be_depend(self.name, self)
def add_be_depend(self, name, cluster_conf):
if self.name == name:
raise Exception('Can not set %s as %s\'s dependency' % (name, name))
if self.name not in cluster_conf.depends:
raise Exception('%s is not %s\'s dependency' % (self.name, name))
if self.name in cluster_conf.be_depends:
raise Exception('Circular Dependency: %s and %s' % (self.name, name))
self._be_depends[name] = cluster_conf
def add_depend_component(self, depend_component_name):
return self._deploy_config.add_depend_for_component(self.name, depend_component_name, save=False)
def del_depend(self, name, component_name):
if component_name in self._depends:
del self._depends[component_name]
def get_depend_servers(self, name):
if name not in self._depends:
return []
cluster_config = self._depends[name]
return deepcopy(cluster_config.original_servers)
def get_be_depend_servers(self, name):
if name not in self._be_depends:
return []
cluster_config = self._be_depends[name]
return deepcopy(cluster_config.original_servers)
def get_depend_added_servers(self, name):
if name not in self._depends:
return None
cluster_config = self._depends[name]
return deepcopy(cluster_config.added_servers)
def get_deploy_added_components(self):
return self._deploy_config.added_components
def get_deploy_changed_components(self):
return self._deploy_config.changed_components
def get_deploy_removed_components(self):
return self._deploy_config.removed_components
def get_depend_config(self, name, server=None, with_default=True):
if name not in self._depends:
return None
cluster_config = self._depends[name]
if with_default:
config = cluster_config.get_server_conf_with_default(server) if server else cluster_config.get_global_conf_with_default()
else:
config = cluster_config.get_server_conf(server) if server else cluster_config.get_global_conf()
return deepcopy(config)
def get_be_depend_config(self, name, server=None, with_default=True):
if name not in self._be_depends:
return None
cluster_config = self._be_depends[name]
if with_default:
config = cluster_config.get_server_conf_with_default(server) if server else cluster_config.get_global_conf_with_default()
else:
config = cluster_config.get_server_conf(server) if server else cluster_config.get_global_conf()
return deepcopy(config)
def update_server_conf(self, server, key, value, save=True):
if self._deploy_config is None:
return False
if server not in self._server_conf:
return False
if self._temp_conf and key in self._temp_conf:
value = self._temp_conf[key].param_type(value).value
if not self._deploy_config.update_component_server_conf(self.name, server, key, value, save):
return False
self._server_conf[server][key] = value
if self._cache_server[server] is not None:
self._cache_server[server][key] = value
return True
def update_global_conf(self, key, value, save=True):
if self._deploy_config is None:
return False
if self._temp_conf and key in self._temp_conf:
value = self._temp_conf[key].param_type(value).value
if not self._deploy_config.update_component_global_conf(self.name, key, value, save):
return False
self._update_global_conf(key, value)
return True
def _update_global_conf(self, key, value):
self._original_global_conf[key] = value
self._global_conf = None
self._unprocessed_global_conf = None
self._clear_cache_server()
def update_rsync_list(self, rsync_list, save=True):
if self._deploy_config is None:
return False
if not self._deploy_config.update_component_rsync_list(self.name, rsync_list, save):
return False
self._rsync_list = rsync_list
return True
def update_environments(self, environments, save=True):
if self._deploy_config is None:
return False
if not self._deploy_config.update_component_environments(self.name, environments, save):
return False
self._origin_environments = environments
self._environments = None
return True
def get_unconfigured_require_item(self, server, skip_keys=[]):
items = []
config = self._get_unprocessed_server_conf(server)
if config is not None:
for key in self._temp_conf:
if key in skip_keys:
continue
if not self._temp_conf[key].require:
continue
if key in config:
continue
items.append(key)
return items
def get_server_conf_with_default(self, server):
if server not in self._server_conf:
return None
config = deepcopy(self._all_default_conf)
server_config = self.get_server_conf(server)
if server_config:
config.update(server_config)
return config
def get_need_redeploy_items(self, server):
if server not in self._server_conf:
return None
items = {}
config = self.get_server_conf(server)
for key in config:
if key in self._temp_conf and self._temp_conf[key].need_redeploy:
items[key] = config[key]
return items
def get_need_restart_items(self, server):
if server not in self._server_conf:
return None
items = {}
config = self.get_server_conf(server)
for key in config:
if key in self._temp_conf and self._temp_conf[key].need_restart:
items[key] = config[key]
return items
def update_temp_conf(self, temp_conf):
self._default_conf = {}
self._all_default_conf = {}
self._temp_conf = temp_conf
for key in self._temp_conf:
if self._temp_conf[key].require and self._temp_conf[key].default is not None:
self._default_conf[key] = self._temp_conf[key].default
if self._temp_conf[key].default is not None:
self._all_default_conf[key] = self._temp_conf[key].default
self._global_conf = None
self._unprocessed_global_conf = None
self._clear_cache_server()
def _apply_temp_conf(self, conf):
if self._temp_conf:
for key in conf:
if key in self._temp_conf:
conf[key] = self._temp_conf[key].param_type(conf[key]).value
return conf
def get_temp_conf_item(self, key):
if self._temp_conf:
return self._temp_conf.get(key)
else:
return None
def check_param(self):
errors = []
if self._temp_conf:
_, g_errs = self.global_check_param()
errors += g_errs
for server in self._server_conf:
s_errs, _ = self._check_param(self._server_conf[server])
errors += s_errs
return not errors, set(errors)
def global_check_param(self):
errors = []
if self._temp_conf:
errors, _ = self._check_param(self._get_unprocessed_global_conf())
return not errors, errors
def servers_check_param(self):
check_res = {}
if self._temp_conf:
global_config = self._get_unprocessed_global_conf()
for server in self._server_conf:
config = deepcopy(self._server_conf[server])
config.update(global_config)
errors, items = self._check_param(config)
check_res[server] = {'errors': errors, 'items': items}
return check_res
def _check_param(self, config):
errors = []
items = []
for key in config:
item = self._temp_conf.get(key)
if item:
try:
item.check_value(config[key])
except Exception as e:
errors.append(str(e))
items.append(item)
return errors, items
def set_global_conf(self, conf):
if not isinstance(conf, dict):
raise Exception('%s global config is not a dictionary. Please check the syntax of your configuration file.\n See https://github.com/oceanbase/obdeploy/blob/master/docs/zh-CN/4.configuration-file-description.md' % self.name)
self._original_global_conf = deepcopy(conf)
self._global_conf = None
self._clear_cache_server()
def set_rsync_list(self, configs):
self._origin_rsync_list = configs
def set_include_file(self, path):
if path != self._origin_include_file:
self._origin_include_file = path
self._include_file = None
self._include_config = None
def set_environments(self, config):
self._origin_environments = config
self._environments = None
def add_server_conf(self, server, conf):
if server not in self.servers:
self.servers.append(server)
if server not in self._original_servers:
self._original_servers.append(server)
self._server_conf[server] = conf
self._cache_server[server] = None
def _get_unprocessed_global_conf(self):
if self._unprocessed_global_conf is None:
self._unprocessed_global_conf = deepcopy(self._default_conf)
self._unprocessed_global_conf.update(self._get_include_config('config', {}))
if self._original_global_conf:
self._unprocessed_global_conf.update(self._original_global_conf)
return self._unprocessed_global_conf
def get_global_conf(self):
if self._global_conf is None:
self._global_conf = self._apply_temp_conf(self._get_unprocessed_global_conf())
return self._global_conf
def get_global_conf_with_default(self):
config = deepcopy(self._all_default_conf)
config.update(self.get_global_conf())
return config
def _add_base_dir(self, path):
if not os.path.isabs(path):
if self._base_dir:
path = os.path.join(self._base_dir, path)
else:
raise Exception("`{}` need to use absolute paths. If you want to use relative paths, please enable developer mode "
"and set environment variables {}".format(RsyncConfig.RSYNC, ENV_BASE_DIR))
return path
@property
def has_package_pattern(self):
if self._has_package_pattern is None:
patterns = (self.origin_package_hash, self.origin_version, self.origin_release, self.origin_tag)
self._has_package_pattern = any([x is not None for x in patterns])
return self._has_package_pattern
@property
def version(self):
if self._version is None:
self._version = self.config_version
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def config_version(self):
if not self.has_package_pattern:
return self._get_include_config('version', None)
else:
return self.origin_version
@property
def release(self):
if self._release is None:
self._release = self.config_release
return self._release
@release.setter
def release(self, value):
self._release = value
@property
def config_release(self):
if not self.has_package_pattern:
return self._get_include_config('release', None)
else:
return self.origin_release
@property
def package_hash(self):
if self._package_hash is None:
self._package_hash = self.config_package_hash
return self._package_hash
@package_hash.setter
def package_hash(self, value):
self._package_hash = value
@property
def config_package_hash(self):
if not self.has_package_pattern:
return self._get_include_config('package_hash', None)
else:
return self.origin_package_hash
def _get_include_config(self, key=None, default=None, not_found_act="ignore"):
if self._include_config is None:
if self._origin_include_file:
if os.path.isabs(self._origin_include_file):
include_file = self._origin_include_file
else:
include_file = os.path.join(self._base_dir, self._origin_include_file)
if include_file != self._include_file:
self._include_file = include_file
self._origin_include_config = self._deploy_config.load_include_file(self._include_file)
if self._origin_include_config is None:
self._origin_include_config = {}
self._include_config = self._origin_include_config
value = self._include_config.get(key, default) if key else self._include_config
return deepcopy(value)
def get_rsync_list(self):
if self._rsync_list is None:
self._rsync_list = self._get_include_config(RsyncConfig.RSYNC, [])
self._rsync_list += self._origin_rsync_list
for item in self._rsync_list:
item[RsyncConfig.SOURCE_PATH] = self._add_base_dir(item[RsyncConfig.SOURCE_PATH])
return self._rsync_list
def get_environments(self):
if self._environments is None:
self._environments = self._get_include_config(ENV, OrderedDict())
self._environments.update(self._origin_environments)
return self._environments
def _get_unprocessed_server_conf(self, server):
if server not in self._unprocessed_server_conf:
conf = deepcopy(self._inner_config.get(server.name, {}))
conf.update(self._get_unprocessed_global_conf())
conf.update(self._server_conf[server])
self._unprocessed_server_conf[server] = conf
return self._unprocessed_server_conf[server]
def get_server_conf(self, server):
if server not in self._server_conf:
return None
if self._cache_server[server] is None:
self._cache_server[server] = self._apply_temp_conf(self._get_unprocessed_server_conf(server))
return self._cache_server[server]
def get_original_global_conf(self, format_conf=False):
conf = deepcopy(self._original_global_conf)
format_conf and self._apply_temp_conf(conf)
return conf
def get_original_server_conf(self, server, format_conf=False):
conf = deepcopy(self._server_conf.get(server))
format_conf and self._apply_temp_conf(conf)
return conf