-
Notifications
You must be signed in to change notification settings - Fork 133
/
core.py
5599 lines (5008 loc) · 285 KB
/
core.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
import re
import os
import time
import signal
from optparse import Values
from copy import deepcopy, copy
from collections import defaultdict
import tempfile
from subprocess import call as subprocess_call
from ssh import SshClient, SshConfig
from tool import FileUtil, DirectoryUtil, YamlLoader, timeout, COMMAND_ENV, OrderedDict
from _stdio import MsgLevel, FormatText
from _rpm import Version
from _mirror import MirrorRepositoryManager, PackageInfo, RemotePackageInfo
from _plugin import PluginManager, PluginType, InstallPlugin, PluginContextNamespace
from _deploy import DeployManager, DeployStatus, DeployConfig, DeployConfigStatus, Deploy, ClusterStatus
from _tool import Tool, ToolManager
from _repository import RepositoryManager, LocalPackage, Repository, RepositoryVO
import _errno as err
from _lock import LockManager, LockMode
from _optimize import OptimizeManager
from _environ import ENV_REPO_INSTALL_MODE, ENV_BASE_DIR
from _types import Capacity
from const import COMP_OCEANBASE_DIAGNOSTIC_TOOL, COMP_OBCLIENT, PKG_RPM_FILE, TEST_TOOLS, COMPS_OB, PKG_REPO_FILE, TOOL_TPCC, TOOL_TPCH, TOOL_SYSBENCH
from ssh import LocalClient
class ObdHome(object):
HOME_LOCK_RELATIVE_PATH = 'obd.conf'
def __init__(self, home_path, dev_mode=False, lock_mode=None, stdio=None):
self.home_path = home_path
self.dev_mode = dev_mode
self._lock = None
self._home_conf = None
self._mirror_manager = None
self._repository_manager = None
self._deploy_manager = None
self._plugin_manager = None
self._lock_manager = None
self._optimize_manager = None
self._tool_manager = None
self.stdio = None
self._stdio_func = None
self.ssh_clients = {}
self.deploy = None
self.cmds = []
self.options = Values()
self.repositories = None
self.namespaces = {}
self.set_stdio(stdio)
if lock_mode is None:
lock_mode = LockMode.DEPLOY_SHARED_LOCK if dev_mode else LockMode.DEFAULT
self.lock_manager.set_lock_mode(lock_mode)
self.lock_manager.global_sh_lock()
@property
def mirror_manager(self):
if not self._mirror_manager:
self._mirror_manager = MirrorRepositoryManager(self.home_path, self.lock_manager, self.stdio)
return self._mirror_manager
@property
def repository_manager(self):
if not self._repository_manager:
self._repository_manager = RepositoryManager(self.home_path, self.lock_manager, self.stdio)
return self._repository_manager
@property
def plugin_manager(self):
if not self._plugin_manager:
self._plugin_manager = PluginManager(self.home_path, self.dev_mode, self.stdio)
return self._plugin_manager
@property
def deploy_manager(self):
if not self._deploy_manager:
self._deploy_manager = DeployManager(self.home_path, self.lock_manager, self.stdio)
return self._deploy_manager
@property
def lock_manager(self):
if not self._lock_manager:
self._lock_manager = LockManager(self.home_path, self.stdio)
return self._lock_manager
@property
def optimize_manager(self):
if not self._optimize_manager:
self._optimize_manager = OptimizeManager(self.home_path, stdio=self.stdio)
return self._optimize_manager
@property
def tool_manager(self):
if not self._tool_manager:
self._tool_manager = ToolManager(self.home_path, self.repository_manager, self.lock_manager, self.stdio)
return self._tool_manager
def _global_ex_lock(self):
self.lock_manager.global_ex_lock()
def fork(self, deploy=None, repositories=None, cmds=None, options=None, stdio=None):
new_obd = copy(self)
if deploy:
new_obd.set_deploy(deploy)
if repositories:
new_obd.set_repositories(repositories)
if cmds:
new_obd.set_cmds(cmds)
if options:
new_obd.set_options(options)
if stdio:
new_obd.set_stdio(stdio)
return new_obd
def set_deploy(self, deploy):
self.deploy = deploy
def set_repositories(self, repositories):
self.repositories = repositories
def set_cmds(self, cmds):
self.cmds = cmds
def set_options(self, options):
self.options = options
def set_stdio(self, stdio):
def _print(msg, *arg, **kwarg):
sep = kwarg['sep'] if 'sep' in kwarg else None
end = kwarg['end'] if 'end' in kwarg else None
return print(msg, sep='' if sep is None else sep, end='\n' if end is None else end)
self.stdio = stdio
self._stdio_func = {}
if not self.stdio:
return
for func in ['start_loading', 'stop_loading', 'print', 'confirm', 'verbose', 'warn', 'exception', 'error', 'critical', 'print_list', 'read']:
self._stdio_func[func] = getattr(self.stdio, func, _print)
def get_namespace(self, spacename):
if spacename in self.namespaces:
namespace = self.namespaces[spacename]
else:
namespace = PluginContextNamespace(spacename=spacename)
self.namespaces[spacename] = namespace
return namespace
def call_plugin(self, plugin, repository, spacename=None, target_servers=None, **kwargs):
args = {
'namespace': self.get_namespace(repository.name if spacename == None else spacename),
'namespaces': self.namespaces,
'deploy_name': None,
'deploy_status': None,
'cluster_config': None,
'repositories': self.repositories,
'repository': repository,
'components': None,
'cmd': self.cmds,
'options': self.options,
'stdio': self.stdio,
'target_servers': target_servers
}
if self.deploy:
args['deploy_name'] = self.deploy.name
args['deploy_status'] = self.deploy.deploy_info.status
args['components'] = self.deploy.deploy_config.components.keys()
args['cluster_config'] = self.deploy.deploy_config.components[repository.name]
if "clients" not in kwargs:
args['clients'] = self.get_clients(self.deploy.deploy_config, self.repositories)
args.update(kwargs)
self._call_stdio('verbose', 'Call %s for %s' % (plugin, repository))
return plugin(**args)
def _call_stdio(self, func, msg, *arg, **kwarg):
if func not in self._stdio_func:
return None
return self._stdio_func[func](msg, *arg, **kwarg)
def add_mirror(self, src):
if re.match('^https?://', src):
return self.mirror_manager.add_remote_mirror(src)
else:
return self.mirror_manager.add_local_mirror(src, getattr(self.options, 'force', False))
def deploy_param_check(self, repositories, deploy_config, gen_config_plugins={}):
# parameter check
errors = []
for repository in repositories:
cluster_config = deploy_config.components[repository.name]
errors += cluster_config.check_param()[1]
skip_keys = []
if repository in gen_config_plugins:
ret = self.call_plugin(gen_config_plugins[repository], repository, return_generate_keys=True, clients={})
if ret:
skip_keys = ret.get_return('generate_keys', [])
for server in cluster_config.servers:
self._call_stdio('verbose', '%s %s param check' % (server, repository))
need_items = cluster_config.get_unconfigured_require_item(server, skip_keys=skip_keys)
if need_items:
errors.append(str(err.EC_NEED_CONFIG.format(server=server, component=repository.name, miss_keys=','.join(need_items))))
return errors
def deploy_param_check_return_check_status(self, repositories, deploy_config, gen_config_plugins={}):
# parameter check
param_check_status = {}
check_pass = True
for repository in repositories:
cluster_config = deploy_config.components[repository.name]
check_status = param_check_status[repository.name] = {}
skip_keys = []
if repository in gen_config_plugins:
ret = self.call_plugin(gen_config_plugins[repository], repository, return_generate_keys=True, clients={})
if ret:
skip_keys = ret.get_return('generate_keys', [])
check_res = cluster_config.servers_check_param()
for server in check_res:
status = err.CheckStatus()
errors = check_res[server].get('errors', [])
self._call_stdio('verbose', '%s %s param check' % (server, repository))
need_items = cluster_config.get_unconfigured_require_item(server, skip_keys=skip_keys)
if need_items:
errors.append(err.EC_NEED_CONFIG.format(server=server, component=repository.name, miss_keys=','.join(need_items)))
if errors:
status.status = err.CheckStatus.FAIL
check_pass = False
status.error = err.EC_PARAM_CHECK.format(errors=errors)
status.suggests.append(err.SUG_PARAM_CHECK.format())
else:
status.status = err.CheckStatus.PASS
check_status[server] = status
return param_check_status, check_pass
def get_clients(self, deploy_config, repositories):
ssh_clients, _ = self.get_clients_with_connect_status(deploy_config, repositories, True)
return ssh_clients
def get_clients_with_connect_status(self, deploy_config, repositories, fail_exit=False):
servers = set()
user_config = deploy_config.user
if user_config not in self.ssh_clients:
self.ssh_clients[user_config] = {}
ssh_clients = self.ssh_clients[user_config]
connect_status = {}
for repository in repositories:
cluster_config = deploy_config.components[repository.name]
for server in cluster_config.servers:
if server not in ssh_clients:
servers.add(server)
else:
connect_status[server] = err.CheckStatus(err.CheckStatus.PASS)
if servers:
connect_status.update(self.ssh_clients_connect(servers, ssh_clients, user_config, fail_exit))
return ssh_clients, connect_status
def get_clients_with_connect_servers(self, deploy_config, repositories, fail_exit=False):
ssh_clients, connect_status = self.get_clients_with_connect_status(deploy_config, repositories, fail_exit)
for repository in repositories:
cluster_config = deploy_config.components[repository.name]
cluster_config.servers = [server for server in cluster_config.servers if server in ssh_clients]
failed_servers = []
for k, v in connect_status.items():
if v.status == v.FAIL:
failed_servers.append(k.ip)
for server in failed_servers:
self._call_stdio('warn', '%s connect failed' % server)
return ssh_clients
def ssh_clients_connect(self, servers, ssh_clients, user_config, fail_exit=False):
self._call_stdio('start_loading', 'Open ssh connection')
connect_io = self.stdio if fail_exit else self.stdio.sub_io(msg_lv=MsgLevel.CRITICAL)
connect_status = {}
success = True
for server in servers:
if server not in ssh_clients:
client = SshClient(
SshConfig(
server.ip,
user_config.username,
user_config.password,
user_config.key_file,
user_config.port,
user_config.timeout
),
self.stdio
)
error = client.connect(stdio=connect_io, exit=fail_exit)
connect_status[server] = status = err.CheckStatus()
if error is not True:
success = False
status.status = err.CheckStatus.FAIL
status.error = error
status.suggests.append(err.SUG_SSH_FAILED.format())
else:
status.status = err.CheckStatus.PASS
ssh_clients[server] = client
self._call_stdio('stop_loading', 'succeed' if success else 'fail')
return connect_status
def search_plugin(self, repository, plugin_type, no_found_exit=True):
self._call_stdio('verbose', 'Search %s plugin for %s' % (plugin_type.name.lower(), repository.name))
plugin = self.plugin_manager.get_best_plugin(plugin_type, repository.name, repository.version)
if plugin:
self._call_stdio('verbose', 'Found for %s for %s-%s' % (plugin, repository.name, repository.version))
else:
if no_found_exit:
self._call_stdio('critical', 'No such %s plugin for %s-%s' % (plugin_type.name.lower(), repository.name, repository.version))
else:
self._call_stdio('warn', 'No such %s plugin for %s-%s' % (plugin_type.name.lower(), repository.name, repository.version))
return plugin
def search_plugins(self, repositories, plugin_type, no_found_exit=True):
plugins = {}
self._call_stdio('verbose', 'Searching %s plugin for components ...', plugin_type.name.lower())
for repository in repositories:
plugin = self.search_plugin(repository, plugin_type, no_found_exit)
if plugin:
plugins[repository] = plugin
elif no_found_exit:
return None
return plugins
def search_py_script_plugin(self, repositories, script_name, no_found_act='exit'):
if no_found_act == 'exit':
no_found_exit = True
else:
no_found_exit = False
msg_lv = 'warn' if no_found_act == 'warn' else 'verbose'
plugins = {}
self._call_stdio('verbose', 'Searching %s plugin for components ...', script_name)
for repository in repositories:
self._call_stdio('verbose', 'Searching %s plugin for %s' % (script_name, repository))
plugin = self.plugin_manager.get_best_py_script_plugin(script_name, repository.name, repository.version)
if plugin:
plugins[repository] = plugin
self._call_stdio('verbose', 'Found for %s for %s-%s' % (plugin, repository.name, repository.version))
else:
if no_found_exit:
self._call_stdio('critical', 'No such %s plugin for %s-%s' % (script_name, repository.name, repository.version))
break
else:
self._call_stdio(msg_lv, 'No such %s plugin for %s-%s' % (script_name, repository.name, repository.version))
return plugins
def search_images(self, component_name, version=None, min_version=None, max_version=None, release=None, disable=[],
usable=[], release_first=False, print_match=True):
matchs = {}
usable_matchs = []
for pkg in self.mirror_manager.get_pkgs_info(component_name, version=version, min_version=min_version,
max_version=max_version, release=release):
if pkg.md5 in disable:
self._call_stdio('verbose', 'Disable %s' % pkg.md5)
else:
matchs[pkg.md5] = pkg
for repo in self.repository_manager.get_repositories(component_name, version):
if release and release != repo.release:
continue
if repo.md5 in disable:
self._call_stdio('verbose', 'Disable %s' % repo.md5)
else:
matchs[repo.md5] = repo
if matchs:
print_match and self._call_stdio(
'print_list',
matchs,
['name', 'version', 'release', 'arch', 'md5'],
lambda x: [matchs[x].name, matchs[x].version, matchs[x].release, matchs[x].arch, matchs[x].md5],
title='Search %s %s Result' % (component_name, version)
)
for md5 in usable:
if md5 in matchs:
self._call_stdio('verbose', 'Usable %s' % md5)
usable_matchs.append(matchs[md5])
if not usable_matchs:
usable_matchs = [info[1] for info in sorted(matchs.items())]
if release_first:
usable_matchs = usable_matchs[:1]
return usable_matchs
def search_components_from_mirrors(self, deploy_config, fuzzy_match=False, only_info=True, update_if_need=None, components=None):
pkgs = []
errors = []
repositories = []
self._call_stdio('verbose', 'Search package for components...')
if components is None:
components = deploy_config.components.keys()
for component in components:
if component not in deploy_config.components:
errors.append('No such component name: {}'.format(component))
continue
config = deploy_config.components[component]
# First, check if the component exists in the repository. If exists, check if the version is available. If so, use the repository directly.
self._call_stdio('verbose', 'Get %s repository' % component)
repository = self.repository_manager.get_repository(name=component, version=config.version, tag=config.tag, release=config.release, package_hash=config.package_hash)
if repository and not repository.hash:
repository = None
if not config.tag:
self._call_stdio('verbose', 'Search %s package from mirror' % component)
pkg = self.mirror_manager.get_best_pkg(
name=component, version=config.version, md5=config.package_hash, release=config.release, fuzzy=fuzzy_match, only_info=only_info)
else:
pkg = None
if repository or pkg:
if pkg:
self._call_stdio('verbose', 'Found Package %s-%s-%s-%s' % (pkg.name, pkg.version, pkg.release, pkg.md5))
if repository:
if repository >= pkg or (
(
update_if_need is None and
not self._call_stdio('confirm', 'Found a higher version\n%s\nDo you want to use it?' % pkg)
) or update_if_need is False
):
if pkg and repository.release == pkg.release:
pkgs.append(pkg)
self._call_stdio('verbose', '%s as same as %s, Use package %s' % (pkg, repository, pkg))
else:
repositories.append(repository)
self._call_stdio('verbose', 'Use repository %s' % repository)
self._call_stdio('print', '%s-%s already installed.' % (repository.name, repository.version))
continue
if config.version and pkg.version != config.version:
self._call_stdio('warn', 'No such package %s-%s-%s. Use similar package %s-%s-%s.' % (component, config.version, config.release, pkg.name, pkg.version, pkg.release))
else:
self._call_stdio('print', 'Package %s-%s-%s is available.' % (pkg.name, pkg.version, pkg.release))
repository = self.repository_manager.get_repository(pkg.name, pkg.md5)
if repository:
repositories.append(repository)
else:
pkgs.append(pkg)
else:
pkg_name = [component]
if config.version:
pkg_name.append("version: %s" % config.version)
if config.release:
pkg_name.append("release: %s" % config.release)
if config.package_hash:
pkg_name.append("package hash: %s" % config.package_hash)
if config.tag:
pkg_name.append("tag: %s" % config.tag)
errors.append('No such package name: %s.' % (', '.join(pkg_name)))
return pkgs, repositories, errors
def load_local_repositories(self, deploy_info, allow_shadow=True):
repositories = []
if allow_shadow:
get_repository = self.repository_manager.get_repository_allow_shadow
else:
get_repository = self.repository_manager.get_repository
components = deploy_info.components
for component_name in components:
data = components[component_name]
version = data.get('version')
pkg_hash = data.get('hash')
self._call_stdio('verbose', 'Get local repository %s-%s-%s' % (component_name, version, pkg_hash))
repository = get_repository(component_name, version, pkg_hash)
if repository:
repositories.append(repository)
else:
self._call_stdio('critical', 'Local repository %s-%s-%s is empty.' % (component_name, version, pkg_hash))
return repositories
def get_local_repositories(self, components, allow_shadow=True):
repositories = []
if allow_shadow:
get_repository = self.repository_manager.get_repository_allow_shadow
else:
get_repository = self.repository_manager.get_repository
for component_name in components:
cluster_config = components[component_name]
self._call_stdio('verbose', 'Get local repository %s-%s-%s' % (component_name, cluster_config.version, cluster_config.tag))
repository = get_repository(component_name, cluster_config.version, cluster_config.package_hash if cluster_config.package_hash else cluster_config.tag)
if repository:
repositories.append(repository)
else:
self._call_stdio('critical', 'Local repository %s-%s-%s is empty.' % (component_name, cluster_config.version, cluster_config.tag))
return repositories
def search_param_plugin_and_apply(self, repositories, deploy_config):
self._call_stdio('verbose', 'Searching param plugin for components ...')
for repository in repositories:
plugin = self.search_plugin(repository, PluginType.PARAM, False)
if plugin:
self._call_stdio('verbose', 'Applying %s for %s' % (plugin, repository))
cluster_config = deploy_config.components[repository.name]
cluster_config.update_temp_conf(plugin.params)
def edit_deploy_config(self, name):
def confirm(msg):
if self.stdio:
self._call_stdio('print', msg)
if self._call_stdio('confirm', 'edit?'):
return True
return False
def is_server_list_change(deploy_config):
for component_name in deploy_config.components:
if deploy_config.components[component_name].servers != deploy.deploy_config.components[component_name].servers:
return True
return False
if not self.stdio:
raise IOError("IO Not Found")
self._call_stdio('verbose', 'Get Deploy by name')
deploy = self.deploy_manager.get_deploy_config(name)
if deploy and deploy.deploy_info.status == DeployStatus.STATUS_UPRADEING:
self._call_stdio('error', 'Deploy "%s" is %s. You could not edit an upgrading cluster' % (name, deploy.deploy_info.status.value))
return False
self.set_deploy(deploy)
param_plugins = {}
repositories, pkgs = [], []
is_deployed = deploy and deploy.deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]
is_started = deploy and deploy.deploy_info.status in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_STOPPED]
user_input = self._call_stdio('read', '')
if not user_input and not self.stdio.isatty():
time.sleep(0.1)
user_input = self._call_stdio('read', '')
if not user_input:
self._call_stdio('error', 'Input is empty')
return False
initial_config = ''
if deploy:
try:
deploy.deploy_config.allow_include_error()
if deploy.deploy_info.config_status == DeployConfigStatus.UNCHNAGE:
path = deploy.deploy_config.yaml_path
else:
path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
if user_input:
initial_config = user_input
else:
self._call_stdio('verbose', 'Load %s' % path)
with open(path, 'r') as f:
initial_config = f.read()
except:
self._call_stdio('exception', '')
msg = 'Save deploy "%s" configuration' % name
else:
if user_input:
initial_config = user_input
else:
if not self.stdio:
return False
if not initial_config and not self._call_stdio('confirm', 'No such deploy: %s. Create?' % name):
return False
msg = 'Create deploy "%s" configuration' % name
if is_deployed:
repositories = self.load_local_repositories(deploy.deploy_info)
self._call_stdio('start_loading', 'Search param plugin and load')
for repository in repositories:
self._call_stdio('verbose', 'Search param plugin for %s' % repository)
plugin = self.plugin_manager.get_best_plugin(PluginType.PARAM, repository.name, repository.version)
if plugin:
self._call_stdio('verbose', 'Applying %s for %s' % (plugin, repository))
cluster_config = deploy.deploy_config.components[repository.name]
cluster_config.update_temp_conf(plugin.params)
param_plugins[repository.name] = plugin
self._call_stdio('stop_loading', 'succeed')
EDITOR = os.environ.get('EDITOR','vi')
self._call_stdio('verbose', 'Get environment variable EDITOR=%s' % EDITOR)
self._call_stdio('verbose', 'Create tmp yaml file')
tf = tempfile.NamedTemporaryFile(suffix=".yaml")
tf.write(initial_config.encode())
tf.flush()
self.lock_manager.set_try_times(-1)
config_status = DeployConfigStatus.UNCHNAGE
diff_need_redeploy_keys = []
while True:
if not user_input:
tf.seek(0)
self._call_stdio('verbose', '%s %s' % (EDITOR, tf.name))
subprocess_call([EDITOR, tf.name])
self._call_stdio('verbose', 'Load %s' % tf.name)
try:
deploy_config = DeployConfig(
tf.name, yaml_loader=YamlLoader(self.stdio),
config_parser_manager=self.deploy_manager.config_parser_manager,
inner_config=deploy.deploy_config.inner_config if deploy else None,
stdio=self.stdio
)
deploy_config.allow_include_error()
if not deploy_config.get_base_dir():
deploy_config.set_base_dir('/', save=False)
except Exception as e:
if not user_input and confirm(e):
continue
break
self._call_stdio('verbose', 'Configure component change check')
if not deploy_config.components:
if self._call_stdio('confirm', 'Empty configuration. Continue editing?'):
continue
return False
self._call_stdio('verbose', 'Information check for the configuration component.')
if not deploy:
config_status = DeployConfigStatus.UNCHNAGE
elif is_deployed:
if deploy_config.components.keys() != deploy.deploy_config.components.keys() or is_server_list_change(deploy_config):
if not self._call_stdio('confirm', FormatText.warning('Modifications to the deployment architecture take effect after you redeploy the architecture. Are you sure that you want to start a redeployment? ')):
if user_input:
return False
continue
config_status = DeployConfigStatus.NEED_REDEPLOY
if config_status != DeployConfigStatus.NEED_REDEPLOY:
comp_attr_changed = False
for component_name in deploy_config.components:
old_cluster_config = deploy.deploy_config.components[component_name]
new_cluster_config = deploy_config.components[component_name]
comp_attr_map = {'version': 'config_version', 'package_hash': 'config_package_hash', 'release': 'config_release', 'tag': 'tag'}
for key, value in comp_attr_map.items():
if getattr(new_cluster_config, key) != getattr(old_cluster_config, value):
comp_attr_changed = True
diff_need_redeploy_keys.append(key)
config_status = DeployConfigStatus.NEED_REDEPLOY
if comp_attr_changed:
if not self._call_stdio('confirm', FormatText.warning('Modifications to the version, release or hash of the component take effect after you redeploy the cluster. Are you sure that you want to start a redeployment? ')):
if user_input:
return False
continue
config_status = DeployConfigStatus.NEED_REDEPLOY
if config_status != DeployConfigStatus.NEED_REDEPLOY:
rsync_conf_changed = False
for component_name in deploy_config.components:
old_cluster_config = deploy.deploy_config.components[component_name]
new_cluster_config = deploy_config.components[component_name]
if new_cluster_config.get_rsync_list() != old_cluster_config.get_rsync_list():
rsync_conf_changed = True
break
if rsync_conf_changed:
if not self._call_stdio('confirm', FormatText.warning('Modifications to the rsync config of a deployed cluster take effect after you redeploy the cluster. Are you sure that you want to start a redeployment? ')):
if user_input:
return False
continue
config_status = DeployConfigStatus.NEED_REDEPLOY
# Loading the parameter plugins that are available to the application
self._call_stdio('start_loading', 'Search param plugin and load')
if not is_deployed or config_status == DeployConfigStatus.NEED_REDEPLOY:
param_plugins = {}
pkgs, repositories, errors = self.search_components_from_mirrors(deploy_config, update_if_need=False)
for repository in repositories:
self._call_stdio('verbose', 'Search param plugin for %s' % repository)
plugin = self.plugin_manager.get_best_plugin(PluginType.PARAM, repository.name, repository.version)
if plugin:
param_plugins[repository.name] = plugin
for pkg in pkgs:
self._call_stdio('verbose', 'Search param plugin for %s' % pkg)
plugin = self.plugin_manager.get_best_plugin(PluginType.PARAM, pkg.name, pkg.version)
if plugin:
param_plugins[pkg.name] = plugin
for component_name in param_plugins:
deploy_config.components[component_name].update_temp_conf(param_plugins[component_name].params)
self._call_stdio('stop_loading', 'succeed')
# Parameter check
self._call_stdio('start_loading', 'Parameter check')
errors = self.deploy_param_check(repositories, deploy_config) + self.deploy_param_check(pkgs, deploy_config)
self._call_stdio('stop_loading', 'fail' if errors else 'succeed')
if errors:
if confirm('\n'.join(errors)):
continue
return False
self._call_stdio('verbose', 'configure change check')
if initial_config and initial_config == tf.read().decode(errors='replace'):
config_status = deploy.deploy_info.config_status if deploy else DeployConfigStatus.UNCHNAGE
self._call_stdio('print', 'Deploy "%s" config %s%s' % (name, config_status.value, deploy.effect_tip() if deploy else ''))
return True
if is_deployed and config_status != DeployConfigStatus.NEED_REDEPLOY:
if is_started:
if deploy.deploy_config.user.username != deploy_config.user.username:
config_status = DeployConfigStatus.NEED_RESTART
errors = []
for component_name in param_plugins:
old_cluster_config = deploy.deploy_config.components[component_name]
new_cluster_config = deploy_config.components[component_name]
modify_limit_params = param_plugins[component_name].modify_limit_params
for server in old_cluster_config.servers:
old_config = old_cluster_config.get_server_conf(server)
new_config = new_cluster_config.get_server_conf(server)
for item in modify_limit_params:
key = item.name
try:
item.modify_limit(old_config.get(key), new_config.get(key))
except Exception as e:
self._call_stdio('exceptione', '')
errors.append('[%s] %s: %s' % (component_name, server, str(e)))
if errors:
self._call_stdio('print', '\n'.join(errors))
if user_input:
return False
if self._call_stdio('confirm', FormatText.warning('Modifications take effect after a redeployment. Are you sure that you want to start a redeployment?')):
config_status = DeployConfigStatus.NEED_REDEPLOY
elif self._call_stdio('confirm', 'Continue to edit?'):
continue
else:
return False
for component_name in deploy_config.components:
if config_status == DeployConfigStatus.NEED_REDEPLOY:
break
old_cluster_config = deploy.deploy_config.components[component_name]
new_cluster_config = deploy_config.components[component_name]
if old_cluster_config == new_cluster_config:
continue
if config_status == DeployConfigStatus.UNCHNAGE:
config_status = DeployConfigStatus.NEED_RELOAD
for server in old_cluster_config.servers:
new_redeploy_items = new_cluster_config.get_need_redeploy_items(server)
old_redeploy_items = old_cluster_config.get_need_redeploy_items(server)
if new_redeploy_items != old_redeploy_items:
diff_need_redeploy_keys = [key for key in list(set(old_redeploy_items) | set(new_redeploy_items)) if new_redeploy_items.get(key, '') != old_redeploy_items.get(key, '')]
config_status = DeployConfigStatus.NEED_REDEPLOY
break
if old_cluster_config.get_need_restart_items(server) != new_cluster_config.get_need_restart_items(server):
config_status = DeployConfigStatus.NEED_RESTART
if deploy.deploy_info.status == DeployStatus.STATUS_DEPLOYED and config_status != DeployConfigStatus.NEED_REDEPLOY:
config_status = DeployConfigStatus.UNCHNAGE
break
if config_status == DeployConfigStatus.NEED_REDEPLOY:
for comp in set(COMPS_OB) & set(list(deploy.deploy_config.components.keys())):
cluster_config = deploy.deploy_config.components[comp]
default_config = cluster_config.get_global_conf_with_default()
if default_config.get('production_mode', True):
diff_need_redeploy_keys = [f'`{key}`' for key in diff_need_redeploy_keys]
diff_need_redeploy_keys = list(set(diff_need_redeploy_keys))
self._call_stdio('error', err.EC_RUNNING_CLUSTER_NO_REDEPLOYED.format(key=', '.join(diff_need_redeploy_keys)))
return False
self._call_stdio('verbose', 'Set deploy configuration status to %s' % config_status)
self._call_stdio('verbose', 'Save new configuration yaml file')
if config_status == DeployConfigStatus.UNCHNAGE:
ret = self.deploy_manager.create_deploy_config(name, tf.name).update_deploy_config_status(config_status)
else:
target_src_path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
old_config_status = deploy.deploy_info.config_status
try:
if deploy.update_deploy_config_status(config_status):
FileUtil.copy(tf.name, target_src_path, self.stdio)
ret = True
if deploy:
if is_started or (config_status == DeployConfigStatus.NEED_REDEPLOY and is_deployed):
msg += deploy.effect_tip()
except Exception as e:
deploy.update_deploy_config_status(old_config_status)
self._call_stdio('exception', 'Copy %s to %s failed, error: \n%s' % (tf.name, target_src_path, e))
msg += ' failed'
ret = False
self._call_stdio('print', msg)
tf.close()
return ret
def list_deploy(self):
self._call_stdio('verbose', 'Get deploy list')
deploys = self.deploy_manager.get_deploy_configs()
if deploys:
self._call_stdio('print_list', deploys,
['Name', 'Configuration Path', 'Status (Cached)'],
lambda x: [x.name, x.config_dir, x.deploy_info.status.value],
title='Cluster List',
)
else:
self._call_stdio('print', 'Local deploy is empty')
return True
def get_install_plugin_and_install(self, repositories, pkgs):
# Check if the component contains the installation plugins
install_plugins = self.search_plugins(repositories, PluginType.INSTALL)
if install_plugins is None:
return None
temp = self.search_plugins(pkgs, PluginType.INSTALL)
if temp is None:
return None
for pkg in temp:
repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
install_plugins[repository] = temp[pkg]
# Install for local
# self._call_stdio('print', 'install package for local ...')
for pkg in pkgs:
self._call_stdio('verbose', 'create instance repository for %s-%s' % (pkg.name, pkg.version))
repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
if repository.need_load(pkg, install_plugins[repository]):
self._call_stdio('start_loading', 'install %s-%s for local' % (pkg.name, pkg.version))
if not repository.load_pkg(pkg, install_plugins[repository]):
self._call_stdio('stop_loading', 'fail')
self._call_stdio('error', 'Failed to extract file from %s' % pkg.path)
return None
self._call_stdio('stop_loading', 'succeed')
self._call_stdio('verbose', 'get head repository')
head_repository = self.repository_manager.get_repository(pkg.name, pkg.version, pkg.name)
self._call_stdio('verbose', 'head repository: %s' % head_repository)
if repository > head_repository:
self.repository_manager.create_tag_for_repository(repository, pkg.name, True)
else:
self._call_stdio('verbose', '%s-%s is already install' % (pkg.name, pkg.version))
repositories.append(repository)
return install_plugins
def install_lib_for_repositories(self, need_libs):
all_data = []
temp_libs = need_libs
while temp_libs:
data = {}
temp_map = {}
libs = temp_libs
temp_libs = []
for lib in libs:
repository = lib['repository']
for requirement in lib['requirement']:
lib_name = requirement.name
if lib_name in data:
# To avoid remove one when require different version of same lib
temp_libs.append(lib)
continue
data[lib_name] = {
'version': requirement.version,
'min_version': requirement.min_version,
'max_version': requirement.max_version,
}
temp_map[lib_name] = repository
all_data.append((data, temp_map))
try:
repositories_lib_map = {}
for data, temp_map in all_data:
with tempfile.NamedTemporaryFile(suffix=".yaml", mode='w') as tf:
yaml_loader = YamlLoader(self.stdio)
yaml_loader.dump(data, tf)
deploy_config = DeployConfig(tf.name, yaml_loader=yaml_loader, config_parser_manager=self.deploy_manager.config_parser_manager, stdio=self.stdio)
# Look for the best suitable mirrors for the components
self._call_stdio('verbose', 'Search best suitable repository libs')
pkgs, lib_repositories, errors = self.search_components_from_mirrors(deploy_config, only_info=False)
if errors:
self._call_stdio('error', '\n'.join(errors))
return False
# Get the installation plugin and install locally
install_plugins = self.get_install_plugin_and_install(lib_repositories, pkgs)
if not install_plugins:
return False
for lib_repository in lib_repositories:
repository = temp_map[lib_repository.name]
install_plugin = install_plugins[lib_repository]
repositories_lib_map[repository] = {
'repositories': lib_repository,
'install_plugin': install_plugin
}
return repositories_lib_map
except:
self._call_stdio('exception', 'Failed to create lib-repo config file')
pass
return False
def servers_repository_install(self, ssh_clients, servers, repository, install_plugin):
self._call_stdio('start_loading', 'Remote %s repository install' % repository)
self._call_stdio('verbose', 'Remote %s repository integrity check' % repository)
for server in servers:
self._call_stdio('verbose', '%s %s repository integrity check' % (server, repository))
client = ssh_clients[server]
remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
remote_repository_data_path = repository.data_file_path.replace(self.home_path, remote_home_path)
remote_repository_data = client.execute_command('cat %s' % remote_repository_data_path).stdout
self._call_stdio('verbose', '%s %s install check' % (server, repository))
try:
yaml_loader = YamlLoader(self.stdio)
data = yaml_loader.load(remote_repository_data)
if not data:
self._call_stdio('verbose', '%s %s need to be installed ' % (server, repository))
elif data == repository:
# Version sync. Check for damages (TODO)
self._call_stdio('verbose', '%s %s has installed ' % (server, repository))
continue
else:
self._call_stdio('verbose', '%s %s need to be updated' % (server, repository))
except:
self._call_stdio('verbose', '%s %s need to be installed ' % (server, repository))
for file_path in repository.file_list(install_plugin):
remote_file_path = file_path.replace(self.home_path, remote_home_path)
self._call_stdio('verbose', '%s %s installing' % (server, repository))
if not client.put_file(file_path, remote_file_path):
self._call_stdio('stop_loading', 'fail')
return False
client.put_file(repository.data_file_path, remote_repository_data_path)
self._call_stdio('verbose', '%s %s installed' % (server, repository.name))
self._call_stdio('stop_loading', 'succeed')
return True
def servers_repository_lib_check(self, ssh_clients, servers, repository, install_plugin, msg_lv='error'):
ret = True
self._call_stdio('start_loading', 'Remote %s repository lib check' % repository)
for server in servers:
self._call_stdio('verbose', '%s %s repository lib check' % (server, repository))
client = ssh_clients[server]
need_libs = set()
remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
remote_repository_path = repository.repository_dir.replace(self.home_path, remote_home_path)
remote_repository_data_path = repository.data_file_path.replace(self.home_path, remote_home_path)
client.add_env('LD_LIBRARY_PATH', '%s/lib:' % remote_repository_path, True)
for file_path in repository.bin_list(install_plugin):
remote_file_path = file_path.replace(self.home_path, remote_home_path)
libs = client.execute_command('ldd %s' % remote_file_path).stdout
need_libs.update(re.findall('(/?[\w+\-/]+\.\w+[\.\w]+)[\s\\n]*\=\>[\s\\n]*not found', libs))
if need_libs:
for lib in need_libs:
self._call_stdio(msg_lv, '%s %s require: %s' % (server, repository, lib))
ret = False
client.add_env('LD_LIBRARY_PATH', '', True)
self._call_stdio('stop_loading', 'succeed' if ret else msg_lv)
return ret
def servers_apply_lib_repository_and_check(self, ssh_clients, deploy_config, repositories, repositories_lib_map):
ret = True
servers_obd_home = {}
for repository in repositories:
cluster_config = deploy_config.components[repository.name]
lib_repository = repositories_lib_map[repository]['repositories']
install_plugin = repositories_lib_map[repository]['install_plugin']
self._call_stdio('print', 'Use %s for %s' % (lib_repository, repository))
for server in cluster_config.servers:
client = ssh_clients[server]
if server not in servers_obd_home:
servers_obd_home[server] = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
remote_home_path = servers_obd_home[server]
remote_lib_repository_data_path = lib_repository.repository_dir.replace(self.home_path, remote_home_path)
# lib installation
self._call_stdio('verbose', 'Remote %s repository integrity check' % repository)
if not self.servers_repository_install(ssh_clients, cluster_config.servers, lib_repository, install_plugin):
ret = False
break
for server in cluster_config.servers:
client = ssh_clients[server]
remote_home_path = servers_obd_home[server]
remote_repository_data_path = repository.repository_dir.replace(self.home_path, remote_home_path)
remote_lib_repository_data_path = lib_repository.repository_dir.replace(self.home_path, remote_home_path)
client.execute_command('ln -sf %s %s/lib' % (remote_lib_repository_data_path, remote_repository_data_path))
if self.servers_repository_lib_check(ssh_clients, cluster_config.servers, repository, install_plugin):
ret = False
for server in cluster_config.servers:
client = ssh_clients[server]
return ret
# check cluster server status, running/stopped
def cluster_server_status_check(self, status=ClusterStatus.STATUS_RUNNING):
if status not in [ClusterStatus.STATUS_RUNNING, ClusterStatus.STATUS_STOPPED]:
self.stdio.error(err.EC_INVALID_PARAMETER.format('status', status))
return False
component_status = {}
cluster_status = self.cluster_status_check(self.repositories, component_status)
if cluster_status is False or cluster_status != status.value:
self.stdio.error(err.EC_SOME_SERVER_STOPED.format())
for repository in component_status:
cluster_status = component_status[repository]
for server in cluster_status:
if cluster_status[server] != status.value:
self. stdio.error('server status error: %s %s is not %s' % (server, repository.name, status.name))
return False