core.py 205.2 KB
Newer Older
O
oceanbase-admin 已提交
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
# 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
from optparse import Values
R
Rongfeng Fu 已提交
27
from copy import deepcopy, copy
R
Rongfeng Fu 已提交
28
import requests
O
oceanbase-admin 已提交
29 30 31 32 33

import tempfile
from subprocess import call as subprocess_call

from ssh import SshClient, SshConfig
R
Rongfeng Fu 已提交
34
from tool import FileUtil, DirectoryUtil, YamlLoader, timeout, COMMAND_ENV, OrderedDict
O
oceanbase-admin 已提交
35
from _stdio import MsgLevel
R
Rongfeng Fu 已提交
36
from _rpm import Version
R
Rongfeng Fu 已提交
37
from _mirror import MirrorRepositoryManager, PackageInfo
R
Rongfeng Fu 已提交
38
from _plugin import PluginManager, PluginType, InstallPlugin, PluginContextNamespace
F
v1.6.0  
frf12 已提交
39
from _deploy import DeployManager, DeployStatus, DeployConfig, DeployConfigStatus, Deploy
R
Rongfeng Fu 已提交
40
from _repository import RepositoryManager, LocalPackage, Repository
R
Rongfeng Fu 已提交
41 42
import _errno as err
from _lock import LockManager, LockMode
F
v1.6.0  
frf12 已提交
43 44
from _optimize import OptimizeManager
from _environ import ENV_REPO_INSTALL_MODE, ENV_BASE_DIR
R
Rongfeng Fu 已提交
45
from const import OB_OFFICIAL_WEBSITE
O
oceanbase-admin 已提交
46 47 48 49 50 51


class ObdHome(object):

    HOME_LOCK_RELATIVE_PATH = 'obd.conf'

R
Rongfeng Fu 已提交
52
    def __init__(self, home_path, dev_mode=False, lock_mode=None, stdio=None):
O
oceanbase-admin 已提交
53
        self.home_path = home_path
R
Rongfeng Fu 已提交
54
        self.dev_mode = dev_mode
O
oceanbase-admin 已提交
55 56 57 58 59 60
        self._lock = None
        self._home_conf = None
        self._mirror_manager = None
        self._repository_manager = None
        self._deploy_manager = None
        self._plugin_manager = None
R
Rongfeng Fu 已提交
61
        self._lock_manager = None
F
v1.6.0  
frf12 已提交
62
        self._optimize_manager = None
O
oceanbase-admin 已提交
63 64
        self.stdio = None
        self._stdio_func = None
F
v1.6.0  
frf12 已提交
65
        self.ssh_clients = {}
R
Rongfeng Fu 已提交
66 67 68 69 70
        self.deploy = None
        self.cmds = []
        self.options = Values()
        self.repositories = None
        self.namespaces = {}
O
oceanbase-admin 已提交
71
        self.set_stdio(stdio)
R
Rongfeng Fu 已提交
72 73 74
        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)
R
Rongfeng Fu 已提交
75
        self.lock_manager.global_sh_lock()
O
oceanbase-admin 已提交
76 77 78 79

    @property
    def mirror_manager(self):
        if not self._mirror_manager:
R
Rongfeng Fu 已提交
80
            self._mirror_manager = MirrorRepositoryManager(self.home_path, self.lock_manager, self.stdio)
O
oceanbase-admin 已提交
81 82 83 84 85
        return self._mirror_manager

    @property
    def repository_manager(self):
        if not self._repository_manager:
R
Rongfeng Fu 已提交
86
            self._repository_manager = RepositoryManager(self.home_path, self.lock_manager, self.stdio)
O
oceanbase-admin 已提交
87 88 89 90 91
        return self._repository_manager

    @property
    def plugin_manager(self):
        if not self._plugin_manager:
R
Rongfeng Fu 已提交
92
            self._plugin_manager = PluginManager(self.home_path, self.dev_mode, self.stdio)
O
oceanbase-admin 已提交
93 94 95 96 97
        return self._plugin_manager

    @property
    def deploy_manager(self):
        if not self._deploy_manager:
R
Rongfeng Fu 已提交
98
            self._deploy_manager = DeployManager(self.home_path, self.lock_manager, self.stdio)
O
oceanbase-admin 已提交
99 100
        return self._deploy_manager

R
Rongfeng Fu 已提交
101 102 103 104 105 106
    @property
    def lock_manager(self):
        if not self._lock_manager:
            self._lock_manager = LockManager(self.home_path, self.stdio)
        return self._lock_manager

F
v1.6.0  
frf12 已提交
107 108 109 110 111 112
    @property
    def optimize_manager(self):
        if not self._optimize_manager:
            self._optimize_manager = OptimizeManager(self.home_path, stdio=self.stdio)
        return self._optimize_manager

R
Rongfeng Fu 已提交
113
    def _global_ex_lock(self):
R
Rongfeng Fu 已提交
114 115
        self.lock_manager.global_ex_lock()

R
Rongfeng Fu 已提交
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
    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

O
oceanbase-admin 已提交
142 143 144 145 146 147 148 149 150
    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
F
v1.6.0  
frf12 已提交
151
        for func in ['start_loading', 'stop_loading', 'print', 'confirm', 'verbose', 'warn', 'exception', 'error', 'critical', 'print_list', 'read']:
O
oceanbase-admin 已提交
152 153
            self._stdio_func[func] = getattr(self.stdio, func, _print)

R
Rongfeng Fu 已提交
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
    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, **kwargs):
        args = {
            'namespace': self.get_namespace(repository.name if spacename == None else spacename),
            'namespaces': self.namespaces,
            'deploy_name': None,
            'cluster_config': None,
            'repositories': self.repositories,
            'repository': repository,
            'components': None,
            'cmd': self.cmds,
            'options': self.options,
            'stdio': self.stdio
        }
        if self.deploy:
            args['deploy_name'] = self.deploy.name
            args['components'] = self.deploy.deploy_info.components
            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)

O
oceanbase-admin 已提交
186 187 188 189 190
    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)

R
Rongfeng Fu 已提交
191
    def add_mirror(self, src):
O
oceanbase-admin 已提交
192 193 194
        if re.match('^https?://', src):
            return self.mirror_manager.add_remote_mirror(src)
        else:
R
Rongfeng Fu 已提交
195
            return self.mirror_manager.add_local_mirror(src, getattr(self.options, 'force', False))
O
oceanbase-admin 已提交
196

R
Rongfeng Fu 已提交
197
    def deploy_param_check(self, repositories, deploy_config, gen_config_plugins={}):
O
oceanbase-admin 已提交
198 199 200 201
        # parameter check
        errors = []
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
202
            errors += cluster_config.check_param()[1]
R
Rongfeng Fu 已提交
203 204 205 206 207
            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', [])
O
oceanbase-admin 已提交
208 209
            for server in cluster_config.servers:
                self._call_stdio('verbose', '%s %s param check' % (server, repository))
R
Rongfeng Fu 已提交
210
                need_items = cluster_config.get_unconfigured_require_item(server, skip_keys=skip_keys)
O
oceanbase-admin 已提交
211
                if need_items:
R
Rongfeng Fu 已提交
212
                    errors.append(str(err.EC_NEED_CONFIG.format(server=server, component=repository.name, miss_keys=','.join(need_items))))
O
oceanbase-admin 已提交
213 214
        return errors

R
Rongfeng Fu 已提交
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
    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
    
O
oceanbase-admin 已提交
245
    def get_clients(self, deploy_config, repositories):
R
Rongfeng Fu 已提交
246 247 248 249
        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):
F
v1.6.0  
frf12 已提交
250 251 252 253 254
        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]
R
Rongfeng Fu 已提交
255 256
        connect_status = {}
    
O
oceanbase-admin 已提交
257 258
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
F
v1.6.0  
frf12 已提交
259 260 261
            for server in cluster_config.servers:
                if server not in ssh_clients:
                    servers.add(server)
R
Rongfeng Fu 已提交
262 263
                else:
                    connect_status[server] = err.CheckStatus(err.CheckStatus.PASS)
F
v1.6.0  
frf12 已提交
264
        if servers:
R
Rongfeng Fu 已提交
265 266
            connect_status.update(self.ssh_clients_connect(servers, ssh_clients, user_config, fail_exit))
        return ssh_clients, connect_status
O
oceanbase-admin 已提交
267

R
Rongfeng Fu 已提交
268
    def ssh_clients_connect(self, servers, ssh_clients, user_config, fail_exit=False):
F
v1.6.0  
frf12 已提交
269
        self._call_stdio('start_loading', 'Open ssh connection')
R
Rongfeng Fu 已提交
270 271 272
        connect_io = self.stdio if fail_exit else self.stdio.sub_io()
        connect_status = {}
        success = True
O
oceanbase-admin 已提交
273
        for server in servers:
F
v1.5.0  
frf12 已提交
274
            if server not in ssh_clients:
R
Rongfeng Fu 已提交
275
                client = SshClient(
O
oceanbase-admin 已提交
276 277 278 279 280 281 282 283 284 285
                    SshConfig(
                        server.ip,
                        user_config.username, 
                        user_config.password, 
                        user_config.key_file, 
                        user_config.port, 
                        user_config.timeout
                    ),
                    self.stdio
                )
R
Rongfeng Fu 已提交
286 287 288 289 290 291 292 293 294 295 296 297
                error = client.connect(stdio=connect_io)
                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
O
oceanbase-admin 已提交
298 299

    def search_plugin(self, repository, plugin_type, no_found_exit=True):
R
Rongfeng Fu 已提交
300
        self._call_stdio('verbose', 'Search %s plugin for %s' % (plugin_type.name.lower(), repository.name))
O
oceanbase-admin 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        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

R
Rongfeng Fu 已提交
322 323 324 325 326 327
    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'
O
oceanbase-admin 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340
        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:
R
Rongfeng Fu 已提交
341
                    self._call_stdio(msg_lv, 'No such %s plugin for %s-%s' % (script_name, repository.name, repository.version))
O
oceanbase-admin 已提交
342
        return plugins
R
Rongfeng Fu 已提交
343

R
Rongfeng Fu 已提交
344
    def search_images(self, component_name, version, release=None, disable=[], usable=[], release_first=False, print_match=True):
R
Rongfeng Fu 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
        matchs = {}
        usable_matchs = []
        for pkg in self.mirror_manager.get_pkgs_info(component_name, version=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:
R
Rongfeng Fu 已提交
360
            print_match and self._call_stdio(
R
Rongfeng Fu 已提交
361 362
                'print_list',
                matchs,
F
v1.5.0  
frf12 已提交
363
                ['name', 'version', 'release', 'arch', 'md5'],
R
Rongfeng Fu 已提交
364
                lambda x: [matchs[x].name, matchs[x].version, matchs[x].release, matchs[x].arch, matchs[x].md5],
F
v1.5.0  
frf12 已提交
365
                title='Search %s %s Result' % (component_name, version)
R
Rongfeng Fu 已提交
366 367 368 369 370 371 372 373 374
            )
            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]
F
v1.5.0  
frf12 已提交
375

R
Rongfeng Fu 已提交
376
        return usable_matchs
F
v1.5.0  
frf12 已提交
377

R
Rongfeng Fu 已提交
378
    def search_components_from_mirrors(self, deploy_config, fuzzy_match=False, only_info=True, update_if_need=None):
O
oceanbase-admin 已提交
379 380 381 382 383 384 385 386 387
        pkgs = []
        errors = []
        repositories = []
        self._call_stdio('verbose', 'Search package for components...')
        for component in deploy_config.components:
            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)
F
v1.5.0  
frf12 已提交
388
            repository = self.repository_manager.get_repository(name=component, version=config.version, tag=config.tag, release=config.release, package_hash=config.package_hash)
R
Rongfeng Fu 已提交
389 390
            if repository and not repository.hash:
                repository = None
F
v1.5.0  
frf12 已提交
391 392 393 394 395 396
            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_match=fuzzy_match, only_info=only_info)
            else:
                pkg = None
R
Rongfeng Fu 已提交
397 398
            if repository or pkg:
                if pkg:
F
v1.5.0  
frf12 已提交
399
                    self._call_stdio('verbose', 'Found Package %s-%s-%s-%s' % (pkg.name, pkg.version, pkg.release, pkg.md5))
R
Rongfeng Fu 已提交
400 401 402 403 404 405 406
                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
                    ):
F
v1.6.0  
frf12 已提交
407 408 409 410 411 412 413
                        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))
R
Rongfeng Fu 已提交
414
                        continue
O
oceanbase-admin 已提交
415
                if config.version and pkg.version != config.version:
F
v1.5.0  
frf12 已提交
416
                    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))
O
oceanbase-admin 已提交
417
                else:
F
v1.5.0  
frf12 已提交
418
                    self._call_stdio('print', 'Package %s-%s-%s is available.' % (pkg.name, pkg.version, pkg.release))
O
oceanbase-admin 已提交
419 420 421 422 423 424 425 426
                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:
F
v1.5.0  
frf12 已提交
427 428 429
                    pkg_name.append("version: %s" % config.version)
                if config.release:
                    pkg_name.append("release: %s" % config.release)
O
oceanbase-admin 已提交
430
                if config.package_hash:
F
v1.5.0  
frf12 已提交
431 432 433 434
                    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)))
O
oceanbase-admin 已提交
435 436
        return pkgs, repositories, errors

R
Rongfeng Fu 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    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
O
oceanbase-admin 已提交
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

    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
F
v1.6.0  
frf12 已提交
495 496 497
        if not self.stdio:
            raise IOError("IO Not Found")

O
oceanbase-admin 已提交
498 499
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
500
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
501 502 503 504
        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]
F
v1.6.0  
frf12 已提交
505
        user_input = self._call_stdio('read', '')
R
Rongfeng Fu 已提交
506
        if not user_input and not self.stdio.isatty():
F
v1.6.0  
frf12 已提交
507 508 509 510 511
            time.sleep(0.1)
            user_input = self._call_stdio('read', '')
            if not user_input:
                self._call_stdio('error', 'Input is empty')
                return False
O
oceanbase-admin 已提交
512 513 514
        initial_config = ''
        if deploy:
            try:
F
v1.5.0  
frf12 已提交
515
                deploy.deploy_config.allow_include_error()
O
oceanbase-admin 已提交
516 517 518
                if deploy.deploy_info.config_status == DeployConfigStatus.UNCHNAGE:
                    path = deploy.deploy_config.yaml_path
                else:
R
Rongfeng Fu 已提交
519
                    path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
F
v1.6.0  
frf12 已提交
520 521 522 523 524 525
                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()
O
oceanbase-admin 已提交
526 527 528 529
            except:
                self._call_stdio('exception', '')
            msg = 'Save deploy "%s" configuration' % name
        else:
F
v1.6.0  
frf12 已提交
530 531 532 533 534 535 536
            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
O
oceanbase-admin 已提交
537
            msg = 'Create deploy "%s" configuration' % name
R
Rongfeng Fu 已提交
538 539
        if is_deployed:
            repositories = self.load_local_repositories(deploy.deploy_info)
R
Rongfeng Fu 已提交
540
            self._call_stdio('start_loading', 'Search param plugin and load')
R
Rongfeng Fu 已提交
541 542 543 544 545 546 547 548
            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
R
Rongfeng Fu 已提交
549 550
            self._call_stdio('stop_loading', 'succeed')

O
oceanbase-admin 已提交
551 552 553 554 555 556
        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()
R
Rongfeng Fu 已提交
557
        self.lock_manager.set_try_times(-1)
R
Rongfeng Fu 已提交
558
        config_status = DeployConfigStatus.UNCHNAGE
O
oceanbase-admin 已提交
559
        while True:
F
v1.6.0  
frf12 已提交
560 561 562 563 564
            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)
R
Rongfeng Fu 已提交
565
            try:
F
v1.5.0  
frf12 已提交
566 567 568 569 570 571
                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
                    )
                deploy_config.allow_include_error()
F
v1.6.0  
frf12 已提交
572 573
                if not deploy_config.get_base_dir():
                    deploy_config.set_base_dir('/', save=False)
R
Rongfeng Fu 已提交
574
            except Exception as e:
F
v1.6.0  
frf12 已提交
575
                if not user_input and confirm(e):
R
Rongfeng Fu 已提交
576 577 578
                    continue
                break

O
oceanbase-admin 已提交
579 580
            self._call_stdio('verbose', 'Configure component change check')
            if not deploy_config.components:
R
Rongfeng Fu 已提交
581
                if self._call_stdio('confirm', 'Empty configuration. Continue editing?'):
O
oceanbase-admin 已提交
582 583 584 585
                    continue
                return False
            self._call_stdio('verbose', 'Information check for the configuration component.')
            if not deploy:
R
Rongfeng Fu 已提交
586
                config_status = DeployConfigStatus.UNCHNAGE
R
Rongfeng Fu 已提交
587
            elif is_deployed:
R
Rongfeng Fu 已提交
588 589
                if deploy_config.components.keys() != deploy.deploy_config.components.keys() or is_server_list_change(deploy_config):
                    if not self._call_stdio('confirm', 'Modifications to the deployment architecture take effect after you redeploy the architecture. Are you sure that you want to start a redeployment? '):
F
v1.6.0  
frf12 已提交
590 591
                        if user_input:
                            return False
O
oceanbase-admin 已提交
592
                        continue
R
Rongfeng Fu 已提交
593
                    config_status = DeployConfigStatus.NEED_REDEPLOY
F
v1.5.0  
frf12 已提交
594 595 596

                if config_status != DeployConfigStatus.NEED_REDEPLOY:
                    comp_attr_changed = False
R
Rongfeng Fu 已提交
597 598 599
                    for component_name in deploy_config.components:
                        old_cluster_config = deploy.deploy_config.components[component_name]
                        new_cluster_config = deploy_config.components[component_name]
F
v1.5.0  
frf12 已提交
600 601 602 603 604
                        if new_cluster_config.version != old_cluster_config.config_version \
                            or new_cluster_config.package_hash != old_cluster_config.config_package_hash \
                            or new_cluster_config.release != old_cluster_config.config_release \
                            or new_cluster_config.tag != old_cluster_config.tag:
                            comp_attr_changed = True
R
Rongfeng Fu 已提交
605 606
                            config_status = DeployConfigStatus.NEED_REDEPLOY
                            break
F
v1.5.0  
frf12 已提交
607 608
                    if comp_attr_changed:
                        if not self._call_stdio('confirm', '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? '):
F
v1.6.0  
frf12 已提交
609 610
                            if user_input:
                                return False
F
v1.5.0  
frf12 已提交
611 612 613 614 615 616 617 618 619 620 621 622 623
                            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', '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? '):
F
v1.6.0  
frf12 已提交
624 625
                            if user_input:
                                return False
F
v1.5.0  
frf12 已提交
626 627 628
                            continue
                        config_status = DeployConfigStatus.NEED_REDEPLOY

O
oceanbase-admin 已提交
629 630
            # Loading the parameter plugins that are available to the application
            self._call_stdio('start_loading', 'Search param plugin and load')
R
Rongfeng Fu 已提交
631
            if not is_deployed or config_status == DeployConfigStatus.NEED_REDEPLOY:
R
Rongfeng Fu 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
                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)

O
oceanbase-admin 已提交
648
            self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
649

O
oceanbase-admin 已提交
650 651 652 653 654 655 656 657
            # 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
R
Rongfeng Fu 已提交
658

O
oceanbase-admin 已提交
659 660 661
            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
R
Rongfeng Fu 已提交
662
                self._call_stdio('print', 'Deploy "%s" config %s%s' % (name, config_status.value, deploy.effect_tip() if deploy else ''))
O
oceanbase-admin 已提交
663
                return True
R
Rongfeng Fu 已提交
664

R
Rongfeng Fu 已提交
665
            if is_deployed and config_status != DeployConfigStatus.NEED_REDEPLOY:
R
Rongfeng Fu 已提交
666
                if is_started:
R
Rongfeng Fu 已提交
667 668
                    if deploy.deploy_config.user.username != deploy_config.user.username:
                        config_status = DeployConfigStatus.NEED_RESTART
R
Rongfeng Fu 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
                    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:
R
Rongfeng Fu 已提交
685
                        self._call_stdio('print', '\n'.join(errors))
F
v1.6.0  
frf12 已提交
686 687
                        if user_input:
                            return False
R
Rongfeng Fu 已提交
688 689 690
                        if self._call_stdio('confirm', '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?'):
R
Rongfeng Fu 已提交
691
                            continue
R
Rongfeng Fu 已提交
692 693
                        else:
                            return False
F
v1.5.0  
frf12 已提交
694

O
oceanbase-admin 已提交
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
                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:
                        if old_cluster_config.get_need_redeploy_items(server) != new_cluster_config.get_need_redeploy_items(server):
                            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
R
Rongfeng Fu 已提交
713

O
oceanbase-admin 已提交
714 715 716 717 718
        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:
R
Rongfeng Fu 已提交
719
            target_src_path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
O
oceanbase-admin 已提交
720 721 722 723 724 725
            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:
R
Rongfeng Fu 已提交
726
                    if is_started or (config_status == DeployConfigStatus.NEED_REDEPLOY and is_deployed):
R
Rongfeng Fu 已提交
727
                        msg += deploy.effect_tip()
O
oceanbase-admin 已提交
728 729 730 731 732
            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
R
Rongfeng Fu 已提交
733

O
oceanbase-admin 已提交
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
        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:
R
Rongfeng Fu 已提交
766
            self._call_stdio('verbose', 'create instance repository for %s-%s' % (pkg.name, pkg.version))
O
oceanbase-admin 已提交
767
            repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
R
Rongfeng Fu 已提交
768 769 770 771 772 773 774 775 776 777 778 779 780 781
            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))
O
oceanbase-admin 已提交
782 783 784 785
            repositories.append(repository)
        return install_plugins

    def install_lib_for_repositories(self, repositories):
R
Rongfeng Fu 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
        all_data = []
        temp_repositories = repositories
        while temp_repositories:
            data = {}
            temp_map = {}
            repositories = temp_repositories
            temp_repositories = []
            for repository in repositories:
                lib_name = '%s-libs' % repository.name
                if lib_name in data:
                    temp_repositories.append(repository)
                    continue
                data[lib_name] = {'global': {
                    'version': repository.version
                }}
                temp_map[lib_name] = repository
            all_data.append((data, temp_map))
O
oceanbase-admin 已提交
803
        try:
R
Rongfeng Fu 已提交
804 805 806 807 808 809 810 811 812 813 814 815
            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)
                    # 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
O
oceanbase-admin 已提交
816

R
Rongfeng Fu 已提交
817 818 819 820 821 822 823 824 825 826 827 828
                    # 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
O
oceanbase-admin 已提交
829 830 831 832 833 834 835 836 837 838 839
        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]
R
Rongfeng Fu 已提交
840
            remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
            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))
R
Rongfeng Fu 已提交
860 861
                if not client.put_file(file_path, remote_file_path):
                    self._call_stdio('stop_loading', 'fail')
R
Rongfeng Fu 已提交
862
                    return False
O
oceanbase-admin 已提交
863 864 865
            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')
R
Rongfeng Fu 已提交
866
        return True
O
oceanbase-admin 已提交
867 868 869 870 871 872 873 874

    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()
R
Rongfeng Fu 已提交
875
            remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
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
            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:
R
Rongfeng Fu 已提交
905
                    servers_obd_home[server] = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
906 907 908 909
                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)
R
Rongfeng Fu 已提交
910 911 912
            if not self.servers_repository_install(ssh_clients, cluster_config.servers, lib_repository, install_plugin):
                ret = False
                break
O
oceanbase-admin 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925 926
            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

    # If the cluster states are consistent, the status value is returned. Else False is returned.
R
Rongfeng Fu 已提交
927
    def cluster_status_check(self, repositories, ret_status={}):
R
Rongfeng Fu 已提交
928
        self._call_stdio('start_loading', 'Cluster status check')
O
oceanbase-admin 已提交
929 930 931
        status_plugins = self.search_py_script_plugin(repositories, 'status')
        component_status = {}
        for repository in repositories:
R
Rongfeng Fu 已提交
932
            plugin_ret = self.call_plugin(status_plugins[repository], repository)
O
oceanbase-admin 已提交
933 934 935 936 937 938 939 940
            cluster_status = plugin_ret.get_return('cluster_status')
            ret_status[repository] = cluster_status
            for server in cluster_status:
                if repository not in component_status:
                    component_status[repository] = cluster_status[server]
                    continue
                if component_status[repository] != cluster_status[server]:
                    self._call_stdio('verbose', '%s cluster status is inconsistent' % repository)
R
Rongfeng Fu 已提交
941
                    component_status[repository] = False
O
oceanbase-admin 已提交
942 943 944
                    break
            else:
                continue
R
Rongfeng Fu 已提交
945

O
oceanbase-admin 已提交
946 947 948 949 950 951 952
        status = None
        for repository in component_status:
            if status is None:
                status = component_status[repository]
                continue
            if status != component_status[repository]:
                self._call_stdio('verbose', 'Deploy status inconsistent')
R
Rongfeng Fu 已提交
953
                self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
954
                return False
R
Rongfeng Fu 已提交
955
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
956 957
        return status

R
Rongfeng Fu 已提交
958 959 960 961 962 963 964 965 966 967 968 969
    def search_components_from_mirrors_and_install(self, deploy_config):
        # Check the best suitable mirror for the components
        self._call_stdio('verbose', 'Search best suitable repository')
        pkgs, repositories, errors = self.search_components_from_mirrors(deploy_config, only_info=False)
        if errors:
            self._call_stdio('error', '\n'.join(errors))
            return repositories, None

        # Get the installation plugins. Install locally
        install_plugins = self.get_install_plugin_and_install(repositories, pkgs)
        return repositories, install_plugins

R
Rongfeng Fu 已提交
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    def sort_repositories_by_depends(self, deploy_config, repositories):
        sort_repositories = []
        wait_repositories = repositories
        imported_depends = []
        available_depends = [repository.name for repository in repositories]
        while wait_repositories:
            repositories = wait_repositories
            wait_repositories = []
            for repository in repositories:
                cluster_config = deploy_config.components[repository.name]
                for component_name in cluster_config.depends:
                    if component_name not in available_depends:
                        continue
                    if component_name not in imported_depends:
                        wait_repositories.append(repository)
                        break
                else:
                    sort_repositories.append(repository)
                    imported_depends.append(repository.name)
        return sort_repositories

R
Rongfeng Fu 已提交
991
    def genconfig(self, name):
R
Rongfeng Fu 已提交
992 993
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
994
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
995 996 997
        if deploy:
            deploy_info = deploy.deploy_info
            if deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]:
R
Rongfeng Fu 已提交
998
                self._call_stdio('error', 'Deploy "%s" is %s. You could not deploy an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
R
Rongfeng Fu 已提交
999 1000 1001 1002
                return False
            # self._call_stdio('error', 'Deploy name `%s` have been occupied.' % name)
            # return False

R
Rongfeng Fu 已提交
1003
        config_path = getattr(self.options, 'config', '')
R
Rongfeng Fu 已提交
1004 1005 1006 1007 1008 1009
        if not config_path:
            self._call_stdio('error', "Configuration file is need.\nPlease use -c to set configuration file")
            return False

        self._call_stdio('verbose', 'Create deploy by configuration path')
        deploy = self.deploy_manager.create_deploy_config(name, config_path)
R
Rongfeng Fu 已提交
1010
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
1011 1012
        if not deploy:
            return False
R
Rongfeng Fu 已提交
1013 1014 1015 1016

        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        if not deploy_config:
R
Rongfeng Fu 已提交
1017
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.\nSee https://github.com/oceanbase/obdeploy/blob/master/docs/zh-CN/4.configuration-file-description.md')
R
Rongfeng Fu 已提交
1018 1019
            return False

F
v1.5.0  
frf12 已提交
1020
        # Check the best suitable mirror for the components and installation plugins. Install locally
R
Rongfeng Fu 已提交
1021 1022 1023
        repositories, install_plugins = self.search_components_from_mirrors_and_install(deploy_config)
        if not install_plugins or not repositories:
            return False
R
Rongfeng Fu 已提交
1024
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

        for repository in repositories:
            real_servers = set()
            cluster_config = deploy_config.components[repository.name]
            for server in cluster_config.servers:
                if server.ip in real_servers:
                    self._call_stdio('error', 'Deploying multiple %s instances on the same server is not supported.' % repository.name)
                    return False
                real_servers.add(server.ip)
        
        self._call_stdio('start_loading', 'Cluster param config check')
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
1038
        gen_config_plugins = self.search_py_script_plugin(repositories, 'generate_config')
R
Rongfeng Fu 已提交
1039

R
Rongfeng Fu 已提交
1040
        if not  getattr(self.options, 'skip_param_check', False):
F
v1.6.0  
frf12 已提交
1041
            # Parameter check
R
Rongfeng Fu 已提交
1042
            errors = self.deploy_param_check(repositories, deploy_config, gen_config_plugins=gen_config_plugins)
F
v1.6.0  
frf12 已提交
1043 1044 1045 1046 1047
            if errors:
                self._call_stdio('stop_loading', 'fail')
                self._call_stdio('error', '\n'.join(errors))
                return False

R
Rongfeng Fu 已提交
1048 1049 1050 1051 1052
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

R
Rongfeng Fu 已提交
1053
        generate_consistent_config = getattr(self.options, 'generate_consistent_config', False)
R
Rongfeng Fu 已提交
1054 1055
        component_num = len(repositories)
        for repository in repositories:
R
Rongfeng Fu 已提交
1056
            ret = self.call_plugin(gen_config_plugins[repository], repository, generate_consistent_config=generate_consistent_config)
R
Rongfeng Fu 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065
            if ret:
                component_num -= 1
                
        if component_num == 0 and deploy_config.dump():
            return True
        
        self.deploy_manager.remove_deploy_config(name)
        return False

R
Rongfeng Fu 已提交
1066
    def check_for_ocp(self, name):
R
Rongfeng Fu 已提交
1067 1068
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1069
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
1070 1071 1072
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
F
v1.5.0  
frf12 已提交
1073

R
Rongfeng Fu 已提交
1074 1075 1076 1077 1078
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('error', 'Deploy "%s" not RUNNING' % (name))
            return False
F
v1.5.0  
frf12 已提交
1079

R
Rongfeng Fu 已提交
1080
        version = getattr(self.options, 'version', '')
R
Rongfeng Fu 已提交
1081 1082 1083 1084 1085
        if not version:
            self._call_stdio('error', 'Use the --version option to specify the required OCP version.')
            return False

        deploy_config = deploy.deploy_config
R
Rongfeng Fu 已提交
1086
        components = getattr(self.options, 'components', '')
R
Rongfeng Fu 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
        if components:
            components = components.split(',')
            for component in components:
                if component not in deploy_config.components:
                    self._call_stdio('error', 'No such component: %s' % component)
                    return False
        else:
            components = deploy_config.components.keys()

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1099
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

        ocp_check = self.search_py_script_plugin(repositories, 'ocp_check', no_found_act='ignore')
        connect_plugins = self.search_py_script_plugin([repository for repository in ocp_check], 'connect')

        self._call_stdio('stop_loading', 'succeed')

        self._call_stdio('start_loading', 'Load cluster param plugin')
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        if deploy_info.config_status != DeployConfigStatus.UNCHNAGE:
            new_deploy_config = deploy.temp_deploy_config
            change_user = deploy_config.user.username != new_deploy_config.user.username
            self.search_param_plugin_and_apply(repositories, new_deploy_config)
        else:
            new_deploy_config = None

        self._call_stdio('stop_loading', 'succeed')
F
v1.5.0  
frf12 已提交
1117

R
Rongfeng Fu 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)
        if new_deploy_config and deploy_config.user.username != new_deploy_config.user.username:
            new_ssh_clients = self.get_clients(new_deploy_config, repositories)
        else:
            new_ssh_clients = None

        component_num = len(repositories)
        for repository in repositories:
            if repository.name not in components:
                continue
            if repository not in ocp_check:
                component_num -= 1
                self._call_stdio('print', '%s No check plugin available.' % repository.name)
                continue
F
v1.5.0  
frf12 已提交
1133

R
Rongfeng Fu 已提交
1134 1135 1136
            cluster_config = deploy_config.components[repository.name]
            new_cluster_config = new_deploy_config.components[repository.name] if new_deploy_config else None
            cluster_servers = cluster_config.servers
F
v1.5.0  
frf12 已提交
1137

R
Rongfeng Fu 已提交
1138
            ret = self.call_plugin(connect_plugins[repository], repository)
R
Rongfeng Fu 已提交
1139 1140 1141 1142 1143
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            else:
                break
F
v1.5.0  
frf12 已提交
1144

R
Rongfeng Fu 已提交
1145
            if self.call_plugin(ocp_check[repository], repository, cursor=cursor, ocp_version=version, new_cluster_config=new_cluster_config, new_clients=new_ssh_clients):
R
Rongfeng Fu 已提交
1146 1147
                component_num -= 1
                self._call_stdio('print', '%s Check passed.' % repository.name)
F
v1.5.0  
frf12 已提交
1148

R
Rongfeng Fu 已提交
1149 1150
        return component_num == 0

F
v1.6.0  
frf12 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    def sort_repository_by_depend(self, repositories, deploy_config):
        sorted_repositories = []
        sorted_componets = {}
        while repositories:
            temp_repositories = []
            for repository in repositories:
                cluster_config = deploy_config.components.get(repository.name)
                for componet_name in cluster_config.depends:
                    if componet_name not in sorted_componets:
                        temp_repositories.append(repository)
                        break
                else:
                    sorted_componets[repository.name] = 1
                    sorted_repositories.append(repository)
            if len(temp_repositories) == len(repositories):
                sorted_repositories += temp_repositories
                break
            repositories = temp_repositories
        return sorted_repositories

R
Rongfeng Fu 已提交
1171
    def change_deploy_config_style(self, name):
R
Rongfeng Fu 已提交
1172 1173
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1174
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
1175 1176 1177
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
F
v1.5.0  
frf12 已提交
1178

R
Rongfeng Fu 已提交
1179 1180 1181 1182 1183 1184 1185
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy config status judge')
        if deploy_info.config_status != DeployConfigStatus.UNCHNAGE:
            self._call_stdio('error', 'Deploy %s %s' % (name, deploy_info.config_status.value))
            return False
        deploy_config = deploy.deploy_config
        if not deploy_config:
R
Rongfeng Fu 已提交
1186
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.\nSee https://github.com/oceanbase/obdeploy/blob/master/docs/zh-CN/4.configuration-file-description.md')
R
Rongfeng Fu 已提交
1187 1188
            return False

R
Rongfeng Fu 已提交
1189
        style = getattr(self.options, 'style', '')
R
Rongfeng Fu 已提交
1190 1191 1192 1193
        if not style:
            self._call_stdio('error', 'Use the --style option to specify the preferred style.')
            return False

R
Rongfeng Fu 已提交
1194
        components = getattr(self.options, 'components', '')
R
Rongfeng Fu 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203
        if components:
            components = components.split(',')
            for component in components:
                if component not in deploy_config.components:
                    self._call_stdio('error', 'No such component: %s' % component)
                    return False
        else:
            components = deploy_config.components.keys()

F
v1.6.0  
frf12 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212
        self._call_stdio('start_loading', 'Load param plugin')

        # Get the repository
        if deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]:
            repositories = self.load_local_repositories(deploy_info)
        else:
            repositories = []
            for component_name in components:
                repositories.append(self.repository_manager.get_repository_allow_shadow(component_name, '100000.0'))
R
Rongfeng Fu 已提交
1213
        self.set_repositories(repositories)
F
v1.6.0  
frf12 已提交
1214 1215 1216 1217 1218

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

R
Rongfeng Fu 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
        self._call_stdio('start_loading', 'Change style')
        try:
            parsers = {}
            for component_name in components:
                parsers[component_name] = self.deploy_manager.config_parser_manager.get_parser(component_name, style)
                self._call_stdio('verbose', 'get %s for %s' % (parsers[component_name], component_name))

            for component_name in deploy_config.components:
                if component_name in parsers:
                    deploy_config.change_component_config_style(component_name, style)
            if deploy_config.dump():
                self._call_stdio('stop_loading', 'succeed')
                return True
        except Exception as e:
            self._call_stdio('exception', e)
F
v1.5.0  
frf12 已提交
1234

R
Rongfeng Fu 已提交
1235 1236 1237
        self._call_stdio('stop_loading', 'fail')
        return False

R
Rongfeng Fu 已提交
1238
    def demo(self):
F
v1.6.0  
frf12 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        name = 'demo'
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        if deploy:
            self._call_stdio('verbose', 'Get deploy info')
            deploy_info = deploy.deploy_info
            self._call_stdio('verbose', 'judge deploy status')
            if deploy_info.status == DeployStatus.STATUS_DEPLOYED:
                if not self.destroy_cluster(name):
                    return False
            elif deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]:
                self._call_stdio('error', 'Deploy "%s" is %s. You could not deploy an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
                return False

        components = set()
R
Rongfeng Fu 已提交
1254
        for component_name in getattr(self.options, 'components', '').split(','):
F
v1.6.0  
frf12 已提交
1255 1256
            if component_name:
                components.add(component_name)
R
Rongfeng Fu 已提交
1257
                self.get_namespace(component_name).set_variable('generate_config_mini', True)
R
Rongfeng Fu 已提交
1258
                self.get_namespace(component_name).set_variable('generate_password', False)
R
Rongfeng Fu 已提交
1259
                self.get_namespace(component_name).set_variable('auto_depend', True)
R
Rongfeng Fu 已提交
1260

F
v1.6.0  
frf12 已提交
1261 1262 1263 1264 1265 1266 1267
        if not components:
            self._call_stdio('error', 'Use `-c/--components` to set in the components to be deployed')
            return
        global_key = 'global'
        home_path_key = 'home_path'
        global_config = {home_path_key: os.getenv('HOME')}
        opt_config = {}
R
Rongfeng Fu 已提交
1268
        for key in self.options.__dict__:
F
v1.6.0  
frf12 已提交
1269 1270 1271
            tmp = key.split('.', 1)
            if len(tmp) == 1:
                if key == home_path_key:
R
Rongfeng Fu 已提交
1272
                    global_config[key] = self.options.__dict__[key]
F
v1.6.0  
frf12 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
            else:
                component_name = tmp[0]
                if component_name not in components:
                    component_name = component_name.replace('_', '-')
                if component_name not in opt_config:
                    opt_config[component_name] = {global_key: {}}
                if tmp[1] in ['version', 'tag', 'package_hash', 'release']:
                    _config = opt_config[component_name]
                else:
                    _config = opt_config[component_name][global_key]
R
Rongfeng Fu 已提交
1283
                _config[tmp[1]] = self.options.__dict__[key]
F
v1.6.0  
frf12 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

        configs = OrderedDict()
        for component_name in components:
            configs[component_name] = {
                'servers': ['127.0.0.1'],
                global_key: deepcopy(global_config)
            }
            configs[component_name][global_key][home_path_key] = os.path.join(configs[component_name][global_key][home_path_key], component_name)
            if component_name in opt_config:
                configs[component_name][global_key].update(opt_config[component_name][global_key])
                del opt_config[component_name][global_key]
                configs[component_name].update(opt_config[component_name])

        with tempfile.NamedTemporaryFile(suffix=".yaml", mode='w') as tf:
            yaml_loader = YamlLoader(self.stdio)
            yaml_loader.dump(configs, tf)
R
Rongfeng Fu 已提交
1300 1301 1302
            setattr(self.options, 'config', tf.name)
            setattr(self.options, 'skip_param_check', True)
            if not self.genconfig(name):
F
v1.6.0  
frf12 已提交
1303
                return False
R
Rongfeng Fu 已提交
1304 1305
            setattr(self.options, 'config', '')
            return self.deploy_cluster(name) and self.start_cluster(name)
F
v1.6.0  
frf12 已提交
1306

R
Rongfeng Fu 已提交
1307
    def deploy_cluster(self, name):
O
oceanbase-admin 已提交
1308 1309 1310 1311 1312 1313 1314
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        if deploy:
            self._call_stdio('verbose', 'Get deploy info')
            deploy_info = deploy.deploy_info
            self._call_stdio('verbose', 'judge deploy status')
            if deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]:
R
Rongfeng Fu 已提交
1315
                self._call_stdio('error', 'Deploy "%s" is %s. You could not deploy an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
O
oceanbase-admin 已提交
1316 1317 1318 1319 1320 1321
                return False
            if deploy_info.config_status != DeployConfigStatus.UNCHNAGE:
                self._call_stdio('verbose', 'Apply temp deploy configuration')
                if not deploy.apply_temp_deploy_config():
                    self._call_stdio('error', 'Failed to apply new deploy configuration')
                    return False
F
v1.5.0  
frf12 已提交
1322

R
Rongfeng Fu 已提交
1323 1324 1325
        config_path = getattr(self.options, 'config', '')
        unuse_lib_repo = getattr(self.options, 'unuselibrepo', False)
        auto_create_tenant = getattr(self.options, 'auto_create_tenant', False)
O
oceanbase-admin 已提交
1326 1327 1328 1329 1330 1331 1332
        self._call_stdio('verbose', 'config path is None or not')
        if config_path:
            self._call_stdio('verbose', 'Create deploy by configuration path')
            deploy = self.deploy_manager.create_deploy_config(name, config_path)
            if not deploy:
                self._call_stdio('error', 'Failed to create deploy: %s. please check you configuration file' % name)
                return False
F
v1.5.0  
frf12 已提交
1333

O
oceanbase-admin 已提交
1334 1335 1336
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s. you can input configuration path to create a new deploy' % name)
            return False
R
Rongfeng Fu 已提交
1337 1338
        self.set_deploy(deploy)

O
oceanbase-admin 已提交
1339 1340 1341
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        if not deploy_config:
R
Rongfeng Fu 已提交
1342
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.\nSee https://github.com/oceanbase/obdeploy/blob/master/docs/zh-CN/4.configuration-file-description.md')
O
oceanbase-admin 已提交
1343 1344 1345
            return False

        if not deploy_config.components:
R
Rongfeng Fu 已提交
1346
            self._call_stdio('error', 'Components not detected.\nPlease check the syntax of your configuration file.\nSee https://github.com/oceanbase/obdeploy/blob/master/docs/zh-CN/4.configuration-file-description.md')
O
oceanbase-admin 已提交
1347 1348 1349 1350 1351 1352 1353
            return False

        for component_name in deploy_config.components:
            if not deploy_config.components[component_name].servers:
                self._call_stdio('error', '%s\'s servers list is empty.' % component_name)
                return False

F
v1.6.0  
frf12 已提交
1354 1355 1356 1357 1358
        install_mode = COMMAND_ENV.get(ENV_REPO_INSTALL_MODE)
        if not install_mode:
            install_mode = 'cp' if self.dev_mode else 'ln'

        if install_mode == 'cp':
F
v1.5.0  
frf12 已提交
1359
            deploy_config.enable_cp_install_mode(save=False)
F
v1.6.0  
frf12 已提交
1360
        elif install_mode == 'ln':
F
v1.5.0  
frf12 已提交
1361
            deploy_config.enable_ln_install_mode(save=False)
F
v1.6.0  
frf12 已提交
1362 1363 1364 1365 1366 1367 1368
        else:
            self._call_stdio('error', 'Invalid repository install mode: {}'.format(install_mode))
            return False

        if self.dev_mode:
            base_dir = COMMAND_ENV.get(ENV_BASE_DIR, '')
            deploy_config.set_base_dir(base_dir, save=False)
F
v1.5.0  
frf12 已提交
1369 1370

        # Check the best suitable mirror for the components and installation plugins. Install locally
R
Rongfeng Fu 已提交
1371
        repositories, install_plugins = self.search_components_from_mirrors_and_install(deploy_config)
F
v1.5.0  
frf12 已提交
1372 1373
        if not repositories or not install_plugins:
            return False
R
Rongfeng Fu 已提交
1374
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
1375 1376 1377 1378 1379

        if unuse_lib_repo and not deploy_config.unuse_lib_repository:
            deploy_config.set_unuse_lib_repository(True)
        if auto_create_tenant and not deploy_config.auto_create_tenant:
            deploy_config.set_auto_create_tenant(True)
R
Rongfeng Fu 已提交
1380
        return self._deploy_cluster(deploy, repositories)
F
v1.5.0  
frf12 已提交
1381

R
Rongfeng Fu 已提交
1382
    def _deploy_cluster(self, deploy, repositories):
F
v1.5.0  
frf12 已提交
1383 1384
        deploy_config = deploy.deploy_config
        install_plugins = self.search_plugins(repositories, PluginType.INSTALL)
O
oceanbase-admin 已提交
1385 1386 1387
        if not install_plugins:
            return False

R
Rongfeng Fu 已提交
1388 1389 1390 1391 1392 1393 1394
        self._call_stdio(
            'print_list', 
            repositories, 
            ['Repository', 'Version', 'Release', 'Md5'], 
            lambda repository: [repository.name, repository.version, repository.release, repository.hash], 
            title='Packages'
        )
O
oceanbase-admin 已提交
1395 1396

        errors = []
R
Rongfeng Fu 已提交
1397
        self._call_stdio('start_loading', 'Repository integrity check')
O
oceanbase-admin 已提交
1398 1399
        for repository in repositories:
            if not repository.file_check(install_plugins[repository]):
F
v1.5.0  
frf12 已提交
1400
                errors.append('%s install failed' % repository.name)
O
oceanbase-admin 已提交
1401
        if errors:
R
Rongfeng Fu 已提交
1402
            self._call_stdio('stop_loading', 'fail')
O
oceanbase-admin 已提交
1403 1404
            self._call_stdio('error', '\n'.join(errors))
            return False
R
Rongfeng Fu 已提交
1405
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1406

R
Rongfeng Fu 已提交
1407
        self._call_stdio('start_loading', 'Parameter check')
O
oceanbase-admin 已提交
1408 1409 1410
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)

R
Rongfeng Fu 已提交
1411 1412 1413 1414 1415 1416
        # Generate password when password is None
        gen_config_plugins = self.search_py_script_plugin(repositories, 'generate_config')
        for repository in repositories:
            if repository in gen_config_plugins:
                self.call_plugin(gen_config_plugins[repository], repository, only_generate_password=True)

O
oceanbase-admin 已提交
1417 1418 1419 1420
        # Parameter check
        self._call_stdio('verbose', 'Cluster param configuration check')
        errors = self.deploy_param_check(repositories, deploy_config)
        if errors:
R
Rongfeng Fu 已提交
1421
            self._call_stdio('stop_loading', 'fail')
O
oceanbase-admin 已提交
1422 1423
            self._call_stdio('error', '\n'.join(errors))
            return False
R
Rongfeng Fu 已提交
1424
        self._call_stdio('stop_loading', 'succeed')
F
v1.5.0  
frf12 已提交
1425

O
oceanbase-admin 已提交
1426 1427 1428
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

F
v1.5.0  
frf12 已提交
1429
        # Check the status for the deployed cluster
R
Rongfeng Fu 已提交
1430
        if not getattr(self.options, 'skip_cluster_status_check', False):
F
v1.5.0  
frf12 已提交
1431
            component_status = {}
R
Rongfeng Fu 已提交
1432
            cluster_status = self.cluster_status_check(repositories, component_status)
F
v1.5.0  
frf12 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449
            if cluster_status is False or cluster_status == 1:
                if self.stdio:
                    self._call_stdio('error', 'Some of the servers in the cluster have been started')
                    for repository in component_status:
                        cluster_status = component_status[repository]
                        for server in cluster_status:
                            if cluster_status[server] == 1:
                                self._call_stdio('print', '%s %s is started' % (server, repository.name))
                return False

        self._call_stdio('verbose', 'Search init plugin')
        init_plugins = self.search_py_script_plugin(repositories, 'init')
        component_num = len(repositories)
        for repository in repositories:
            init_plugin = init_plugins[repository]
            self._call_stdio('verbose', 'Exec %s init plugin' % repository)
            self._call_stdio('verbose', 'Apply %s for %s-%s' % (init_plugin, repository.name, repository.version))
R
Rongfeng Fu 已提交
1450
            if self.call_plugin(init_plugin, repository):
F
v1.5.0  
frf12 已提交
1451 1452 1453 1454 1455
                component_num -= 1
        if component_num != 0:
            return False

        # Install repository to servers
R
Rongfeng Fu 已提交
1456
        if not self.install_repositories_to_servers(deploy_config, repositories, install_plugins, ssh_clients, self.options):
F
v1.5.0  
frf12 已提交
1457 1458 1459
            return False

        # Sync runtime dependencies
R
Rongfeng Fu 已提交
1460
        if not self.sync_runtime_dependencies(deploy_config, repositories, ssh_clients, self.options):
F
v1.5.0  
frf12 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
            return False

        for repository in repositories:
            deploy.use_model(repository.name, repository, False)

        if deploy.update_deploy_status(DeployStatus.STATUS_DEPLOYED) and deploy_config.dump():
            self._call_stdio('print', '%s deployed' % deploy.name)
            return True
        return False

R
Rongfeng Fu 已提交
1471
    def install_repository_to_servers(self, components, cluster_config, repository, ssh_clients, unuse_lib_repository=False):
F
v1.5.0  
frf12 已提交
1472 1473 1474 1475 1476 1477
        install_repo_plugin = self.plugin_manager.get_best_py_script_plugin('install_repo', 'general', '0.1')
        install_plugins = self.search_plugins([repository], PluginType.INSTALL)
        if not install_plugins:
            return False
        install_plugin = install_plugins[repository]
        check_file_map = install_plugin.file_map(repository)
R
Rongfeng Fu 已提交
1478 1479 1480 1481
        ret = self.call_plugin(install_repo_plugin, repository, obd_home=self.home_path, install_repository=repository,
                               install_plugin=install_plugin, check_repository=repository,
                               check_file_map=check_file_map,
                               msg_lv='error' if unuse_lib_repository else 'warn')
F
v1.5.0  
frf12 已提交
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        if not ret:
            return False
        elif ret.get_return('checked'):
            return True
        elif unuse_lib_repository:
            return False
        self._call_stdio('print', 'Try to get lib-repository')
        repositories_lib_map = self.install_lib_for_repositories([repository])
        if repositories_lib_map is False:
            self._call_stdio('error', 'Failed to install lib package for local')
            return False
        lib_repository = repositories_lib_map[repository]['repositories']
        install_plugin = repositories_lib_map[repository]['install_plugin']
R
Rongfeng Fu 已提交
1495 1496 1497
        ret = self.call_plugin(install_repo_plugin, repository, obd_home=self.home_path, install_repository=lib_repository,
                               install_plugin=install_plugin, check_repository=repository,
                               check_file_map=check_file_map, msg_lv='error')
F
v1.5.0  
frf12 已提交
1498 1499 1500 1501 1502 1503 1504
        if not ret or not ret.get_return('checked'):
            self._call_stdio('error', 'Failed to install lib package for cluster servers')
            return False

    def install_repositories_to_servers(self, deploy_config, repositories, install_plugins, ssh_clients, options):
        install_repo_plugin = self.plugin_manager.get_best_py_script_plugin('install_repo', 'general', '0.1')
        check_file_maps = {}
O
oceanbase-admin 已提交
1505 1506 1507
        need_lib_repositories = []
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
F
v1.5.0  
frf12 已提交
1508 1509
            install_plugin = install_plugins[repository]
            check_file_map = check_file_maps[repository] = install_plugin.file_map(repository)
R
Rongfeng Fu 已提交
1510 1511 1512
            ret = self.call_plugin(install_repo_plugin, repository, obd_home=self.home_path, install_repository=repository,
                                   install_plugin=install_plugin, check_repository=repository, check_file_map=check_file_map,
                                   msg_lv='error' if deploy_config.unuse_lib_repository else 'warn')
F
v1.5.0  
frf12 已提交
1513 1514 1515
            if not ret:
                return False
            if not ret.get_return('checked'):
O
oceanbase-admin 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
                need_lib_repositories.append(repository)

        if need_lib_repositories:
            if deploy_config.unuse_lib_repository:
                # self._call_stdio('print', 'You could try using -U to work around the problem')
                return False
            self._call_stdio('print', 'Try to get lib-repository')
            repositories_lib_map = self.install_lib_for_repositories(need_lib_repositories)
            if repositories_lib_map is False:
                self._call_stdio('error', 'Failed to install lib package for local')
                return False
F
v1.5.0  
frf12 已提交
1527 1528 1529 1530 1531
            for need_lib_repository in need_lib_repositories:
                cluster_config = deploy_config.components[need_lib_repository.name]
                check_file_map = check_file_maps[need_lib_repository]
                lib_repository = repositories_lib_map[need_lib_repository]['repositories']
                install_plugin = repositories_lib_map[need_lib_repository]['install_plugin']
R
Rongfeng Fu 已提交
1532 1533 1534
                ret = self.call_plugin(install_repo_plugin, need_lib_repository, obd_home=self.home_path, install_repository=lib_repository,
                                       install_plugin=install_plugin, check_repository=need_lib_repository,
                                       check_file_map=check_file_map, msg_lv='error')
F
v1.5.0  
frf12 已提交
1535 1536 1537 1538
                if not ret or not ret.get_return('checked'):
                    self._call_stdio('error', 'Failed to install lib package for cluster servers')
                    return False
        return True
O
oceanbase-admin 已提交
1539

F
v1.5.0  
frf12 已提交
1540 1541 1542
    def sync_runtime_dependencies(self, deploy_config, repositories, ssh_clients, option):
        rsync_plugin = self.plugin_manager.get_best_py_script_plugin('rsync', 'general', '0.1')
        ret = True
O
oceanbase-admin 已提交
1543
        for repository in repositories:
R
Rongfeng Fu 已提交
1544
            ret = self.call_plugin(rsync_plugin, repository) and ret
F
v1.5.0  
frf12 已提交
1545
        return ret
O
oceanbase-admin 已提交
1546

R
Rongfeng Fu 已提交
1547
    def start_cluster(self, name):
O
oceanbase-admin 已提交
1548 1549
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1550
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status not in [DeployStatus.STATUS_DEPLOYED, DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_RUNNING]:
            self._call_stdio('error', 'Deploy "%s" is %s. You could not start an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
            return False

        if deploy_info.config_status == DeployConfigStatus.NEED_REDEPLOY:
            self._call_stdio('error', 'Deploy needs redeploy')
            return False
R
Rongfeng Fu 已提交
1564
        if deploy_info.config_status != DeployConfigStatus.UNCHNAGE and not getattr(self.options, 'without_parameter', False):
R
Rongfeng Fu 已提交
1565 1566
            self._call_stdio('error', 'Deploy %s.%s\nIf you still need to start the cluster, use the `obd cluster start %s --wop` option to start the cluster without loading parameters. ' % (deploy_info.config_status.value, deploy.effect_tip(), name))
            return False
O
oceanbase-admin 已提交
1567

F
v1.5.0  
frf12 已提交
1568 1569 1570 1571
        self._call_stdio('start_loading', 'Get local repositories')

        # Get the repository
        repositories = self.load_local_repositories(deploy_info, False)
R
Rongfeng Fu 已提交
1572
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
1573
        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
1574
        return self._start_cluster(deploy, repositories)
F
v1.5.0  
frf12 已提交
1575

R
Rongfeng Fu 已提交
1576
    def _start_cluster(self, deploy, repositories):
O
oceanbase-admin 已提交
1577 1578
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config
F
v1.5.0  
frf12 已提交
1579 1580
        deploy_info = deploy.deploy_info
        name = deploy.name
O
oceanbase-admin 已提交
1581

R
Rongfeng Fu 已提交
1582
        update_deploy_status = True
R
Rongfeng Fu 已提交
1583
        components = getattr(self.options, 'components', '')
R
Rongfeng Fu 已提交
1584
        if components:
R
Rongfeng Fu 已提交
1585 1586 1587 1588 1589 1590
            components = components.split(',')
            for component in components:
                if component not in deploy_info.components:
                    self._call_stdio('error', 'No such component: %s' % component)
                    return False
            if len(components) != len(deploy_info.components):
R
Rongfeng Fu 已提交
1591
                update_deploy_status = False
R
Rongfeng Fu 已提交
1592 1593
        else:
            components = deploy_info.components.keys()
R
Rongfeng Fu 已提交
1594

R
Rongfeng Fu 已提交
1595
        servers = getattr(self.options, 'servers', '')
R
Rongfeng Fu 已提交
1596 1597
        server_list = servers.split(',') if servers else []

F
v1.5.0  
frf12 已提交
1598
        self._call_stdio('start_loading', 'Search plugins')
R
Rongfeng Fu 已提交
1599
        start_check_plugins = self.search_py_script_plugin(repositories, 'start_check', no_found_act='warn')
R
Rongfeng Fu 已提交
1600
        create_tenant_plugins = self.search_py_script_plugin(repositories, 'create_tenant', no_found_act='ignore')
R
Rongfeng Fu 已提交
1601 1602 1603 1604 1605 1606
        start_plugins = self.search_py_script_plugin(repositories, 'start')
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
        bootstrap_plugins = self.search_py_script_plugin(repositories, 'bootstrap')
        display_plugins = self.search_py_script_plugin(repositories, 'display')
        self._call_stdio('stop_loading', 'succeed')

O
oceanbase-admin 已提交
1607 1608 1609
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

R
Rongfeng Fu 已提交
1610
        self._call_stdio('start_loading', 'Load cluster param plugin')
R
Rongfeng Fu 已提交
1611 1612
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
1613
        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
1614

O
oceanbase-admin 已提交
1615 1616 1617
        # Check the status for the deployed cluster
        component_status = {}
        if DeployStatus.STATUS_RUNNING == deploy_info.status:
R
Rongfeng Fu 已提交
1618
            cluster_status = self.cluster_status_check(repositories, component_status)
O
oceanbase-admin 已提交
1619 1620 1621 1622
            if cluster_status == 1:
                self._call_stdio('print', 'Deploy "%s" is running' % name)
                return True

F
v1.6.0  
frf12 已提交
1623 1624
        repositories = self.sort_repository_by_depend(repositories, deploy_config)

R
Rongfeng Fu 已提交
1625
        strict_check = getattr(self.options, 'strict_check', False)
O
oceanbase-admin 已提交
1626
        success = True
F
v1.6.0  
frf12 已提交
1627
        repository_dir_map = {}
R
Rongfeng Fu 已提交
1628 1629
        repositories_start_all = {}
        start_repositories = []
O
oceanbase-admin 已提交
1630
        for repository in repositories:
F
v1.6.0  
frf12 已提交
1631
            repository_dir_map[repository.name] = repository.repository_dir
R
Rongfeng Fu 已提交
1632 1633
            if repository.name not in components:
                continue
O
oceanbase-admin 已提交
1634 1635 1636
            if repository not in start_check_plugins:
                continue
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
1637 1638 1639 1640 1641 1642 1643 1644
            cluster_servers = cluster_config.servers
            if servers:
                cluster_config.servers = [srv for srv in cluster_servers if srv.ip in server_list or srv.name in server_list]
            repositories_start_all[repository] = start_all = cluster_servers == cluster_config.servers
            update_deploy_status = update_deploy_status and start_all
            if not cluster_config.servers:
                continue
            ret = self.call_plugin(start_check_plugins[repository], repository, strict_check=strict_check)
O
oceanbase-admin 已提交
1645
            if not ret:
R
Rongfeng Fu 已提交
1646
                self._call_stdio('verbose', '%s starting check failed.' % repository.name)
O
oceanbase-admin 已提交
1647
                success = False
R
Rongfeng Fu 已提交
1648
            start_repositories.append(repository)
O
oceanbase-admin 已提交
1649
        
R
Rongfeng Fu 已提交
1650
        if success is False:
O
oceanbase-admin 已提交
1651 1652 1653
            # self._call_stdio('verbose', 'Starting check failed. Use --skip-check to skip the starting check. However, this may lead to a starting failure.')
            return False

R
Rongfeng Fu 已提交
1654
        component_num = len(start_repositories)
F
v1.6.0  
frf12 已提交
1655 1656
        display_repositories = []
        connect_ret = {}
R
Rongfeng Fu 已提交
1657 1658 1659
        for repository in start_repositories:
            start_all = repositories_start_all[repository]
            ret = self.call_plugin(start_plugins[repository], repository, local_home_path=self.home_path, repository_dir_map=repository_dir_map)
O
oceanbase-admin 已提交
1660 1661 1662 1663 1664 1665
            if ret:
                need_bootstrap = ret.get_return('need_bootstrap')
            else:
                self._call_stdio('error', '%s start failed' % repository.name)
                break

R
Rongfeng Fu 已提交
1666
            ret = self.call_plugin(connect_plugins[repository], repository)
O
oceanbase-admin 已提交
1667 1668 1669
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
F
v1.6.0  
frf12 已提交
1670
                connect_ret[repository] = ret.kwargs
O
oceanbase-admin 已提交
1671 1672 1673
            else:
                break

R
Rongfeng Fu 已提交
1674
            if need_bootstrap and start_all:
R
Rongfeng Fu 已提交
1675 1676
                self._call_stdio('start_loading', 'Initialize %s' % repository.name)
                if not self.call_plugin(bootstrap_plugins[repository], repository, cursor=cursor):
F
v1.6.0  
frf12 已提交
1677
                    self._call_stdio('stop_loading', 'fail')
R
Rongfeng Fu 已提交
1678
                    self._call_stdio('error', 'Cluster init failed')
O
oceanbase-admin 已提交
1679
                    break
F
v1.6.0  
frf12 已提交
1680
                self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
1681
                if repository in create_tenant_plugins:
R
Rongfeng Fu 已提交
1682 1683 1684 1685 1686 1687
                    if self.get_namespace(repository.name).get_variable("create_tenant_options"):
                        self.call_plugin(create_tenant_plugins[repository], repository, cursor=cursor)

                    if deploy_config.auto_create_tenant:
                        create_tenant_options = Values({"variables": "ob_tcp_invited_nodes='%'", "create_if_not_exists": True})
                        self.call_plugin(create_tenant_plugins[repository], repository, create_tenant_options=create_tenant_options, cursor=cursor)
R
Rongfeng Fu 已提交
1688 1689 1690 1691

            if not start_all:
                component_num -= 1
                continue
F
v1.6.0  
frf12 已提交
1692 1693 1694
            display_repositories.append(repository)
        
        for repository in display_repositories:
R
Rongfeng Fu 已提交
1695
            if self.call_plugin(display_plugins[repository], repository, **connect_ret[repository]):
O
oceanbase-admin 已提交
1696 1697 1698
                component_num -= 1
        
        if component_num == 0:
R
Rongfeng Fu 已提交
1699 1700 1701 1702 1703 1704 1705
            if update_deploy_status:
                self._call_stdio('verbose', 'Set %s deploy status to running' % name)
                if deploy.update_deploy_status(DeployStatus.STATUS_RUNNING):
                    self._call_stdio('print', '%s running' % name)
                    return True
            else:
                self._call_stdio('print', "succeed")
O
oceanbase-admin 已提交
1706 1707 1708
                return True
        return False

R
Rongfeng Fu 已提交
1709
    def create_tenant(self, name):
R
Rongfeng Fu 已提交
1710 1711
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1712
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1727
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1728
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
1729 1730 1731 1732 1733

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
            
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
R
Rongfeng Fu 已提交
1734
        create_tenant_plugins = self.search_py_script_plugin(repositories, 'create_tenant', no_found_act='ignore')
R
Rongfeng Fu 已提交
1735 1736 1737 1738 1739 1740 1741 1742
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)
            
        for repository in create_tenant_plugins:
            db = None
            cursor = None
R
Rongfeng Fu 已提交
1743
            ret = self.call_plugin(connect_plugins[repository], repository)
R
Rongfeng Fu 已提交
1744 1745 1746 1747 1748 1749
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                return False

R
Rongfeng Fu 已提交
1750
            if not self.call_plugin(create_tenant_plugins[repository], repository, cursor=cursor):
R
Rongfeng Fu 已提交
1751 1752 1753
                return False
        return True

R
Rongfeng Fu 已提交
1754
    def drop_tenant(self, name):
R
Rongfeng Fu 已提交
1755 1756
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1757
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1772
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1773
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
1774 1775 1776 1777 1778

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
            
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
R
Rongfeng Fu 已提交
1779
        drop_tenant_plugins = self.search_py_script_plugin(repositories, 'drop_tenant', no_found_act='ignore')
R
Rongfeng Fu 已提交
1780 1781 1782 1783 1784 1785 1786 1787 1788
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)
            
        for repository in drop_tenant_plugins:
            cluster_config = deploy_config.components[repository.name]
            db = None
            cursor = None
R
Rongfeng Fu 已提交
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834
            ret = self.call_plugin(connect_plugins[repository], repository)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                return False

            if not self.call_plugin(drop_tenant_plugins[repository], repository, cursor=cursor):
                return False
        return True

    def list_tenant(self, name):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        self.set_deploy(deploy)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False

        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
        self.set_repositories(repositories)

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
        list_tenant_plugins = self.search_py_script_plugin(repositories, 'list_tenant', no_found_act='ignore')
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        for repository in list_tenant_plugins:
            cluster_config = deploy_config.components[repository.name]
            db = None
            cursor = None
            ret = self.call_plugin(connect_plugins[repository], repository)
R
Rongfeng Fu 已提交
1835 1836 1837 1838 1839 1840
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                return False

R
Rongfeng Fu 已提交
1841
            if not self.call_plugin(list_tenant_plugins[repository], repository, cursor=cursor):
R
Rongfeng Fu 已提交
1842 1843 1844
                return False
        return True

O
oceanbase-admin 已提交
1845 1846 1847
    def reload_cluster(self, name):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1848
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
1849 1850 1851 1852 1853 1854
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s. Input the configuration path to create a new deploy' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
R
Rongfeng Fu 已提交
1855
        if deploy_info.status not in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_STOPPED]:
R
Rongfeng Fu 已提交
1856
            self._call_stdio('error', 'Deploy "%s" is %s. You could not reload an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
O
oceanbase-admin 已提交
1857 1858
            return False

R
Rongfeng Fu 已提交
1859 1860 1861
        if deploy_info.config_status == DeployConfigStatus.UNCHNAGE:
            self._call_stdio('print', 'Deploy config is UNCHNAGE')
            return True
O
oceanbase-admin 已提交
1862

R
Rongfeng Fu 已提交
1863 1864 1865 1866 1867 1868 1869 1870
        if deploy_info.config_status != DeployConfigStatus.NEED_RELOAD:
            self._call_stdio('error', 'Deploy `%s` %s%s' % (name, deploy_info.config_status.value, deploy.effect_tip()))
            return False

        return self._reload_cluster(deploy)

    def _reload_cluster(self, deploy):
        deploy_info = deploy.deploy_info
O
oceanbase-admin 已提交
1871 1872
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config
R
Rongfeng Fu 已提交
1873
        self._call_stdio('verbose', 'Get new deploy config')
R
Rongfeng Fu 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
        new_deploy_config = deploy.temp_deploy_config

        if deploy_config.components.keys() != new_deploy_config.components.keys():
            self._call_stdio('error', 'The deployment architecture is changed and cannot be reloaded.')
            return False

        for component_name in deploy_config.components:
            if deploy_config.components[component_name].servers != new_deploy_config.components[component_name].servers:
                self._call_stdio('error', 'The deployment architecture is changed and cannot be reloaded.')
                return False
O
oceanbase-admin 已提交
1884 1885 1886

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1887
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1888
        self.set_repositories(repositories)
O
oceanbase-admin 已提交
1889 1890 1891 1892 1893 1894

        reload_plugins = self.search_py_script_plugin(repositories, 'reload')
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')

        self._call_stdio('stop_loading', 'succeed')

R
Rongfeng Fu 已提交
1895 1896 1897 1898 1899 1900
        self._call_stdio('start_loading', 'Load cluster param plugin')
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self.search_param_plugin_and_apply(repositories, new_deploy_config)
        self._call_stdio('stop_loading', 'succeed')

O
oceanbase-admin 已提交
1901 1902 1903 1904 1905
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
1906
        cluster_status = self.cluster_status_check(repositories, component_status)
O
oceanbase-admin 已提交
1907
        if cluster_status is False or cluster_status == 0:
R
Rongfeng Fu 已提交
1908 1909 1910 1911 1912 1913 1914 1915
            sub_io = None
            if getattr(self.stdio, 'sub_io'):
                sub_io = self.stdio.sub_io(msg_lv=MsgLevel.ERROR)
            obd = self.fork(options=Values({'without_parameter': True}), stdio=sub_io)
            if not obd._start_cluster(deploy, repositories):
                if self.stdio:
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
                return False
O
oceanbase-admin 已提交
1916
            
R
Rongfeng Fu 已提交
1917
        repositories = self.sort_repositories_by_depends(deploy_config, repositories)
O
oceanbase-admin 已提交
1918 1919 1920 1921 1922
        component_num = len(repositories)
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
            new_cluster_config = new_deploy_config.components[repository.name]

R
Rongfeng Fu 已提交
1923 1924 1925
            ret = self.call_plugin(connect_plugins[repository], repository)
            if not ret:
                ret = self.call_plugin(connect_plugins[repository], repository, components=new_deploy_config.components.keys(), cluster_config=new_cluster_config)
O
oceanbase-admin 已提交
1926 1927 1928 1929 1930 1931
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            else:
                continue

R
Rongfeng Fu 已提交
1932
            if not self.call_plugin(reload_plugins[repository], repository, cursor=cursor, new_cluster_config=new_cluster_config):
O
oceanbase-admin 已提交
1933 1934 1935 1936
                continue
            component_num -= 1
        if component_num == 0:
            if deploy.apply_temp_deploy_config():
R
Rongfeng Fu 已提交
1937
                self._call_stdio('print', '%s reload' % deploy.name)
O
oceanbase-admin 已提交
1938 1939 1940 1941 1942 1943 1944 1945 1946
                return True
        else:
            deploy_config.dump()
            self._call_stdio('warn', 'Some configuration items reload failed')
        return False

    def display_cluster(self, name):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
1947
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1962
        repositories = self.load_local_repositories(deploy_info)
F
v1.6.0  
frf12 已提交
1963
        repositories = self.sort_repository_by_depend(repositories, deploy_config)
R
Rongfeng Fu 已提交
1964
        self.set_repositories(repositories)
O
oceanbase-admin 已提交
1965 1966 1967 1968 1969 1970

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
            
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
        display_plugins = self.search_py_script_plugin(repositories, 'display')
R
Rongfeng Fu 已提交
1971
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1972 1973 1974 1975 1976 1977

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
1978
        self.cluster_status_check(repositories, component_status)
O
oceanbase-admin 已提交
1979 1980
            
        for repository in repositories:
R
Rongfeng Fu 已提交
1981 1982 1983 1984 1985 1986 1987 1988 1989
            cluster_status = component_status[repository]
            servers = []
            for server in cluster_status:
                if cluster_status[server] == 0:
                    self._call_stdio('warn', '%s %s is stopped' % (server, repository.name))
                else:
                    servers.append(server)
            if not servers:
                continue
O
oceanbase-admin 已提交
1990 1991 1992

            db = None
            cursor = None
R
Rongfeng Fu 已提交
1993
            ret = self.call_plugin(connect_plugins[repository], repository)
O
oceanbase-admin 已提交
1994 1995 1996 1997
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
R
Rongfeng Fu 已提交
1998
                continue
O
oceanbase-admin 已提交
1999

R
Rongfeng Fu 已提交
2000
            self.call_plugin(display_plugins[repository], repository, cursor=cursor)
O
oceanbase-admin 已提交
2001 2002
        return True

R
Rongfeng Fu 已提交
2003
    def stop_cluster(self, name):
O
oceanbase-admin 已提交
2004 2005
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2006
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
2007 2008 2009 2010 2011 2012
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check the deploy status')
R
Rongfeng Fu 已提交
2013
        status = [DeployStatus.STATUS_DEPLOYED, DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_RUNNING]
R
Rongfeng Fu 已提交
2014
        if getattr(self.options, 'force', False):
R
Rongfeng Fu 已提交
2015 2016
            status.append(DeployStatus.STATUS_UPRADEING)
        if deploy_info.status not in status:
O
oceanbase-admin 已提交
2017 2018
            self._call_stdio('error', 'Deploy "%s" is %s. You could not stop an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
            return False
F
v1.5.0  
frf12 已提交
2019 2020 2021 2022

        self._call_stdio('start_loading', 'Get local repositories')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2023
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
2024
        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
2025
        return self._stop_cluster(deploy, repositories)
F
v1.5.0  
frf12 已提交
2026

R
Rongfeng Fu 已提交
2027
    def _stop_cluster(self, deploy, repositories):
O
oceanbase-admin 已提交
2028 2029
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config
F
v1.5.0  
frf12 已提交
2030 2031
        deploy_info = deploy.deploy_info
        name = deploy.name
O
oceanbase-admin 已提交
2032

R
Rongfeng Fu 已提交
2033
        update_deploy_status = True
R
Rongfeng Fu 已提交
2034
        components = getattr(self.options, 'components', '')
R
Rongfeng Fu 已提交
2035
        if components:
R
Rongfeng Fu 已提交
2036 2037 2038 2039 2040 2041
            components = components.split(',')
            for component in components:
                if component not in deploy_info.components:
                    self._call_stdio('error', 'No such component: %s' % component)
                    return False
            if len(components) != len(deploy_info.components):
R
Rongfeng Fu 已提交
2042
                update_deploy_status = False
R
Rongfeng Fu 已提交
2043 2044
        else:
            components = deploy_info.components.keys()
R
Rongfeng Fu 已提交
2045

R
Rongfeng Fu 已提交
2046
        servers = getattr(self.options, 'servers', '')
R
Rongfeng Fu 已提交
2047 2048
        server_list = servers.split(',') if servers else []

F
v1.5.0  
frf12 已提交
2049
        self._call_stdio('start_loading', 'Search plugins')
O
oceanbase-admin 已提交
2050 2051 2052 2053 2054
        # Check whether the components have the parameter plugins and apply the plugins

        self.search_param_plugin_and_apply(repositories, deploy_config)

        stop_plugins = self.search_py_script_plugin(repositories, 'stop')
R
Rongfeng Fu 已提交
2055
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
2056 2057 2058 2059

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

R
Rongfeng Fu 已提交
2060
        component_num = len(components)
O
oceanbase-admin 已提交
2061
        for repository in repositories:
R
Rongfeng Fu 已提交
2062 2063
            if repository.name not in components:
                continue
O
oceanbase-admin 已提交
2064
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
2065 2066 2067
            cluster_servers = cluster_config.servers
            if servers:
                cluster_config.servers = [srv for srv in cluster_servers if srv.ip in server_list or srv.name in server_list]
R
Rongfeng Fu 已提交
2068 2069 2070 2071
            if not cluster_config.servers:
                component_num -= 1
                continue

R
Rongfeng Fu 已提交
2072 2073 2074
            start_all = cluster_servers == cluster_config.servers
            update_deploy_status = update_deploy_status and start_all

R
Rongfeng Fu 已提交
2075
            if self.call_plugin(stop_plugins[repository], repository):
O
oceanbase-admin 已提交
2076 2077
                component_num -= 1
        
R
Rongfeng Fu 已提交
2078
        if component_num == 0:
R
Rongfeng Fu 已提交
2079
            if len(components) != len(repositories) or servers:
R
Rongfeng Fu 已提交
2080 2081 2082 2083 2084 2085 2086
                self._call_stdio('print', "succeed")
                return True
            else:
                self._call_stdio('verbose', 'Set %s deploy status to stopped' % name)
                if deploy.update_deploy_status(DeployStatus.STATUS_STOPPED):
                    self._call_stdio('print', '%s stopped' % name)
                    return True
O
oceanbase-admin 已提交
2087 2088
        return False

R
Rongfeng Fu 已提交
2089
    def restart_cluster(self, name):
O
oceanbase-admin 已提交
2090 2091
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2092
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
2093 2094 2095 2096 2097
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
R
Rongfeng Fu 已提交
2098 2099 2100 2101 2102
        status = [DeployStatus.STATUS_DEPLOYED, DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_RUNNING]
        if deploy_info.status not in status:
            self._call_stdio('error', 'Deploy "%s" is %s. You could not restart an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
            return False
        
R
Rongfeng Fu 已提交
2103 2104 2105 2106
        if deploy_info.config_status == DeployConfigStatus.NEED_REDEPLOY:
            self._call_stdio('error', 'Deploy needs redeploy')
            return False

R
Rongfeng Fu 已提交
2107 2108 2109 2110 2111
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status not in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_STOPPED]:
            self._call_stdio('error', 'Deploy "%s" is %s. You could not restart an %s cluster.' % (name, deploy_info.status.value, deploy_info.status.value))
            return False

R
Rongfeng Fu 已提交
2112 2113 2114 2115
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        deploy_config = deploy.deploy_config
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2116
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
2117 2118 2119

        restart_plugins = self.search_py_script_plugin(repositories, 'restart')
        reload_plugins = self.search_py_script_plugin(repositories, 'reload')
R
Rongfeng Fu 已提交
2120
        start_check_plugins = self.search_py_script_plugin(repositories, 'start_check')
R
Rongfeng Fu 已提交
2121 2122 2123 2124
        start_plugins = self.search_py_script_plugin(repositories, 'start')
        stop_plugins = self.search_py_script_plugin(repositories, 'stop')
        connect_plugins = self.search_py_script_plugin(repositories, 'connect')
        display_plugins = self.search_py_script_plugin(repositories, 'display')
R
Rongfeng Fu 已提交
2125
        bootstrap_plugins = self.search_py_script_plugin(repositories, 'bootstrap')
R
Rongfeng Fu 已提交
2126 2127 2128 2129 2130 2131

        self._call_stdio('stop_loading', 'succeed')

        self._call_stdio('start_loading', 'Load cluster param plugin')
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
2132
        if getattr(self.options, 'without_parameter', False) is False and deploy_info.config_status != DeployConfigStatus.UNCHNAGE:
R
Rongfeng Fu 已提交
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
            apply_change = True
            new_deploy_config = deploy.temp_deploy_config
            change_user = deploy_config.user.username != new_deploy_config.user.username
            self.search_param_plugin_and_apply(repositories, new_deploy_config)
        else:
            new_deploy_config = None
            apply_change = change_user = False

        self._call_stdio('stop_loading', 'succeed')

F
v1.5.0  
frf12 已提交
2143
        update_deploy_status = True
R
Rongfeng Fu 已提交
2144
        components = getattr(self.options, 'components', '')
R
Rongfeng Fu 已提交
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
        if components:
            components = components.split(',')
            for component in components:
                if component not in deploy_info.components:
                    self._call_stdio('error', 'No such component: %s' % component)
                    return False
            if len(components) != len(deploy_info.components):
                if apply_change:
                    self._call_stdio('error', 'Configurations are changed and must be applied to all components and servers.')
                    return False
                update_deploy_status = False
        else:
            components = deploy_info.components.keys()

R
Rongfeng Fu 已提交
2159
        servers = getattr(self.options, 'servers', '')
R
Rongfeng Fu 已提交
2160
        if servers:
F
v1.5.0  
frf12 已提交
2161
            server_list = servers.split(',')
R
Rongfeng Fu 已提交
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
            if apply_change:
                for repository in repositories:
                    cluster_config = deploy_config.components[repository.name]
                    for server in cluster_config.servers:
                        if server.name not in server_list:
                            self._call_stdio('error', 'Configurations are changed and must be applied to all components and servers.')
                            return False
        else:
            server_list = []

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)
        if new_deploy_config and deploy_config.user.username != new_deploy_config.user.username:
            new_ssh_clients = self.get_clients(new_deploy_config, repositories)
            self._call_stdio('start_loading', 'Check sudo')
            for server in new_ssh_clients:
                client = new_ssh_clients[server]
                ret = client.execute_command('sudo whoami')
                if not ret:
                    self._call_stdio('error', ret.stderr)
                    self._call_stdio('stop_loading', 'fail')
                    return False
            self._call_stdio('stop_loading', 'succeed')
        else:
            new_ssh_clients = None

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
2190
        cluster_status = self.cluster_status_check(repositories, component_status)
R
Rongfeng Fu 已提交
2191
        if cluster_status is False or cluster_status == 0:
R
Rongfeng Fu 已提交
2192 2193 2194 2195 2196 2197 2198 2199
            sub_io = None
            if getattr(self.stdio, 'sub_io'):
                sub_io = self.stdio.sub_io(msg_lv=MsgLevel.ERROR)
            obd = self.fork(options=Values({'without_parameter': True}), stdio=sub_io)
            if not obd._start_cluster(deploy, repositories):
                if self.stdio:
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
                return False
R
Rongfeng Fu 已提交
2200 2201 2202 2203 2204

        done_repositories = []
        cluster_configs = {}
        component_num = len(components)
        repositories = self.sort_repositories_by_depends(deploy_config, repositories)
R
Rongfeng Fu 已提交
2205
        self.set_repositories(repositories)
F
v1.6.0  
frf12 已提交
2206 2207 2208
        repository_dir_map = {}
        for repository in repositories:
            repository_dir_map[repository.name] = repository.repository_dir
R
Rongfeng Fu 已提交
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
        for repository in repositories:
            if repository.name not in components:
                continue
            cluster_config = deploy_config.components[repository.name]
            new_cluster_config = new_deploy_config.components[repository.name] if new_deploy_config else None
            if apply_change is False:
                cluster_servers = cluster_config.servers
                if servers:
                    cluster_config.servers = [srv for srv in cluster_servers if srv.ip in server_list or srv.name in server_list]
                if not cluster_config.servers:
                    component_num -= 1
                    continue

                start_all = cluster_servers == cluster_config.servers
                update_deploy_status = update_deploy_status and start_all

R
Rongfeng Fu 已提交
2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
            if self.call_plugin(
                    restart_plugins[repository],
                    repository,
                    local_home_path=self.home_path,
                    start_check_plugin=start_check_plugins[repository],
                    start_plugin=start_plugins[repository],
                    reload_plugin=reload_plugins[repository],
                    stop_plugin=stop_plugins[repository],
                    connect_plugin=connect_plugins[repository],
                    bootstrap_plugin=bootstrap_plugins[repository],
                    display_plugin=display_plugins[repository],
                    new_cluster_config=new_cluster_config,
                    new_clients=new_ssh_clients,
                    repository_dir_map=repository_dir_map,
R
Rongfeng Fu 已提交
2239 2240 2241 2242 2243 2244 2245 2246
            ):
                component_num -= 1
                done_repositories.append(repository)
                if new_cluster_config:
                    cluster_configs[repository.name] = cluster_config
                    deploy_config.update_component(new_cluster_config)
            else:
                break
F
v1.5.0  
frf12 已提交
2247

R
Rongfeng Fu 已提交
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
        if component_num == 0:
            if len(components) != len(repositories) or servers:
                self._call_stdio('print', "succeed")
                return True
            else:
                if apply_change and not deploy.apply_temp_deploy_config():
                    self._call_stdio('error', 'Failed to apply new deploy configuration')
                    return False
                self._call_stdio('verbose', 'Set %s deploy status to running' % name)
                if deploy.update_deploy_status(DeployStatus.STATUS_RUNNING):
                    self._call_stdio('print', '%s restart' % name)
                    return True
        elif new_ssh_clients:
            self._call_stdio('start_loading', 'Rollback')
            component_num = len(done_repositories)
            for repository in done_repositories:
                new_cluster_config = new_deploy_config.components[repository.name]
                cluster_config = cluster_configs[repository.name]

R
Rongfeng Fu 已提交
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
                if self.call_plugin(
                        restart_plugins[repository],
                        repository,
                        local_home_path=self.home_path,
                        start_plugin=start_plugins[repository],
                        reload_plugin=reload_plugins[repository],
                        stop_plugin=stop_plugins[repository],
                        connect_plugin=connect_plugins[repository],
                        display_plugin=display_plugins[repository],
                        new_cluster_config=new_cluster_config,
                        new_clients=new_ssh_clients,
                        rollback=True,
                        bootstrap_plugin=bootstrap_plugins[repository],
                        repository_dir_map=repository_dir_map,
R
Rongfeng Fu 已提交
2281 2282 2283 2284 2285
                ):
                    deploy_config.update_component(cluster_config)

            self._call_stdio('stop_loading', 'succeed')
        return False
O
oceanbase-admin 已提交
2286

R
Rongfeng Fu 已提交
2287
    def redeploy_cluster(self, name, search_repo=True):
O
oceanbase-admin 已提交
2288 2289
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2290
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
2291 2292 2293 2294
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        deploy_info = deploy.deploy_info
F
v1.5.0  
frf12 已提交
2295 2296 2297 2298 2299 2300

        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        self._call_stdio('start_loading', 'Get local repositories')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2301
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
2302 2303
        self._call_stdio('stop_loading', 'succeed')

O
oceanbase-admin 已提交
2304
        self._call_stdio('verbose', 'Check deploy status')
R
Rongfeng Fu 已提交
2305
        if deploy_info.status in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_UPRADEING]:
R
Rongfeng Fu 已提交
2306 2307
            obd = self.fork(options=Values({'force': True}))
            if not obd._stop_cluster(deploy, repositories):
O
oceanbase-admin 已提交
2308 2309
                return False
        elif deploy_info.status not in [DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_DEPLOYED]:
F
v1.5.0  
frf12 已提交
2310 2311 2312 2313 2314 2315
            self._call_stdio('error', 'Deploy "%s" is %s. You could not destroy an undeployed cluster' % (
                name, deploy_info.status.value))
            return False

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
2316
        if not self._destroy_cluster(deploy, repositories):
F
v1.5.0  
frf12 已提交
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
            return False
        if search_repo:
            if deploy_info.config_status != DeployConfigStatus.UNCHNAGE and not deploy.apply_temp_deploy_config():
                self._call_stdio('error', 'Failed to apply new deploy configuration')
                return False
            self._call_stdio('verbose', 'Get deploy configuration')
            deploy_config = deploy.deploy_config
            repositories, install_plugins = self.search_components_from_mirrors_and_install(deploy_config)
            if not repositories or not install_plugins:
                return False
R
Rongfeng Fu 已提交
2327 2328
            self.set_repositories(repositories)
        return self._deploy_cluster(deploy, repositories) and self._start_cluster(deploy, repositories)
F
v1.5.0  
frf12 已提交
2329

R
Rongfeng Fu 已提交
2330
    def destroy_cluster(self, name):
F
v1.5.0  
frf12 已提交
2331 2332
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2333
        self.set_deploy(deploy)
F
v1.5.0  
frf12 已提交
2334 2335
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
O
oceanbase-admin 已提交
2336
            return False
F
v1.5.0  
frf12 已提交
2337 2338 2339

        deploy_info = deploy.deploy_info

O
oceanbase-admin 已提交
2340 2341
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
F
v1.5.0  
frf12 已提交
2342 2343
        # allow included file not exist
        deploy_config.allow_include_error()
O
oceanbase-admin 已提交
2344

F
v1.5.0  
frf12 已提交
2345
        self._call_stdio('start_loading', 'Get local repositories')
O
oceanbase-admin 已提交
2346
        # Get the repository
R
Rongfeng Fu 已提交
2347
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2348
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
2349 2350 2351 2352
        self._call_stdio('stop_loading', 'succeed')

        self._call_stdio('verbose', 'Check deploy status')
        if deploy_info.status in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_UPRADEING]:
R
Rongfeng Fu 已提交
2353 2354
            obd = self.fork(options=Values({'force': True}))
            if not obd._stop_cluster(deploy, repositories):
F
v1.5.0  
frf12 已提交
2355 2356 2357 2358
                return False
        elif deploy_info.status not in [DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_DEPLOYED]:
            self._call_stdio('error', 'Deploy "%s" is %s. You could not destroy an undeployed cluster' % (name, deploy_info.status.value))
            return False
O
oceanbase-admin 已提交
2359 2360 2361

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
2362
        return self._destroy_cluster(deploy, repositories)
O
oceanbase-admin 已提交
2363

R
Rongfeng Fu 已提交
2364
    def _destroy_cluster(self, deploy, repositories):
F
v1.5.0  
frf12 已提交
2365 2366 2367
        deploy_config = deploy.deploy_config
        self._call_stdio('start_loading', 'Search plugins')
        # Get the repository
R
Rongfeng Fu 已提交
2368
        destroy_plugins = self.search_py_script_plugin(repositories, 'destroy')
R
Rongfeng Fu 已提交
2369
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
2370 2371 2372 2373 2374
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
2375
        cluster_status = self.cluster_status_check(repositories, component_status)
O
oceanbase-admin 已提交
2376
        if cluster_status is False or cluster_status == 1:
R
Rongfeng Fu 已提交
2377
            if getattr(self.options, 'force_kill', False):
O
oceanbase-admin 已提交
2378 2379 2380
                self._call_stdio('verbose', 'Try to stop cluster')
                status = deploy.deploy_info.status
                deploy.update_deploy_status(DeployStatus.STATUS_RUNNING)
F
v1.5.0  
frf12 已提交
2381
                if not self._stop_cluster(deploy, repositories):
O
oceanbase-admin 已提交
2382 2383 2384 2385
                    deploy.update_deploy_status(status)
                    self._call_stdio('error', 'Fail to stop cluster')
                    return False
            else:
R
Rongfeng Fu 已提交
2386 2387 2388 2389 2390 2391 2392
                self._call_stdio('error', 'Some of the servers in the cluster are running')
                for repository in component_status:
                    cluster_status = component_status[repository]
                    for server in cluster_status:
                        if cluster_status[server] == 1:
                            self._call_stdio('print', '%s %s is running' % (server, repository.name))
                self._call_stdio('print', 'You could try using -f to force kill process')
O
oceanbase-admin 已提交
2393 2394 2395
                return False

        for repository in repositories:
R
Rongfeng Fu 已提交
2396
            self.call_plugin(destroy_plugins[repository], repository)
O
oceanbase-admin 已提交
2397

F
v1.5.0  
frf12 已提交
2398
        self._call_stdio('verbose', 'Set %s deploy status to destroyed' % deploy.name)
O
oceanbase-admin 已提交
2399
        if deploy.update_deploy_status(DeployStatus.STATUS_DESTROYED):
F
v1.5.0  
frf12 已提交
2400
            self._call_stdio('print', '%s destroyed' % deploy.name)
O
oceanbase-admin 已提交
2401 2402 2403
            return True
        return False

R
Rongfeng Fu 已提交
2404
    def reinstall(self, name):
R
Rongfeng Fu 已提交
2405 2406
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2407
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
        if deploy_info.status in [DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_UPRADEING]:
            self._call_stdio('error', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False

R
Rongfeng Fu 已提交
2418 2419
        component = getattr(self.options, 'component')
        usable = getattr(self.options, 'hash')
R
Rongfeng Fu 已提交
2420
        if not component:
F
v1.5.0  
frf12 已提交
2421
            self._call_stdio('error', 'Specify the components you want to reinstall.')
R
Rongfeng Fu 已提交
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434
            return False
        if component not in deploy_info.components:
            self._call_stdio('error', 'Not found %s in Deploy "%s" ' % (component, name))
            return False

        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
        for current_repository in repositories:
            if current_repository.name == component:
                break
R
Rongfeng Fu 已提交
2435
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
2436 2437 2438 2439

        stop_plugins = self.search_py_script_plugin([current_repository], 'stop')
        start_plugins = self.search_py_script_plugin([current_repository], 'start')

F
v1.5.0  
frf12 已提交
2440
        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
2441 2442 2443
        # Get the client
        ssh_clients = self.get_clients(deploy_config, [current_repository])

F
v1.5.0  
frf12 已提交
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
        current_cluster_config = deploy_config.components[current_repository.name]
        need_sync = bool(current_cluster_config.get_rsync_list())
        need_change_repo = bool(usable)
        sync_repositories = [current_repository]
        repository = current_repository
        cluster_config = current_cluster_config

        # search repo and install
        if usable:
            self._call_stdio('verbose', 'search target repository')
            dest_repository = self.repository_manager.get_repository(current_repository.name, version=current_repository.version, tag=usable)
            if not dest_repository:
                pkg = self.mirror_manager.get_exact_pkg(name=current_repository.name, version=current_repository.version, md5=usable)
                if not pkg:
                    self._call_stdio('error', 'No such package %s-%s-%s' % (component, current_repository.version, usable))
                    return False
R
Rongfeng Fu 已提交
2460 2461
                repositories_temp = []
                install_plugins = self.get_install_plugin_and_install(repositories_temp, [pkg])
F
v1.5.0  
frf12 已提交
2462 2463
                if not install_plugins:
                    return False
R
Rongfeng Fu 已提交
2464
                dest_repository = repositories_temp[0]
F
v1.5.0  
frf12 已提交
2465 2466
            else:
                install_plugins = self.search_plugins([dest_repository], PluginType.INSTALL)
R
Rongfeng Fu 已提交
2467

F
v1.5.0  
frf12 已提交
2468 2469
            if dest_repository is None:
                self._call_stdio('error', 'Target version not found')
R
Rongfeng Fu 已提交
2470 2471
                return False

F
v1.5.0  
frf12 已提交
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
            if dest_repository == current_repository:
                self._call_stdio('print', 'The current version is already %s.\nNoting to do.' % current_repository)
                need_change_repo = False
            else:
                self._call_stdio('start_loading', 'Load cluster param plugin')
                # Check whether the components have the parameter plugins and apply the plugins
                self.search_param_plugin_and_apply(repositories, deploy_config)
                self._call_stdio('stop_loading', 'succeed')
                cluster_config = deploy_config.components[dest_repository.name]
        need_restart = need_sync or need_change_repo
        # stop cluster if needed
        if need_restart:
            # Check the status for the deployed cluster
            component_status = {}
R
Rongfeng Fu 已提交
2486
            cluster_status = self.cluster_status_check([current_repository], component_status)
F
v1.5.0  
frf12 已提交
2487
            if cluster_status is False or cluster_status == 1:
R
Rongfeng Fu 已提交
2488
                if not self.call_plugin(stop_plugins[current_repository], current_repository):
F
v1.5.0  
frf12 已提交
2489
                    return False
R
Rongfeng Fu 已提交
2490

F
v1.5.0  
frf12 已提交
2491 2492
        # install repo to remote servers
        if need_change_repo:
R
Rongfeng Fu 已提交
2493
            if not self.install_repositories_to_servers(deploy_config, [dest_repository, ], install_plugins, ssh_clients, self.options):
R
Rongfeng Fu 已提交
2494
                return False
F
v1.5.0  
frf12 已提交
2495 2496
            sync_repositories = [dest_repository]
            repository = dest_repository
R
Rongfeng Fu 已提交
2497

F
v1.5.0  
frf12 已提交
2498
        # sync runtime dependencies
R
Rongfeng Fu 已提交
2499
        if not self.sync_runtime_dependencies(deploy_config, sync_repositories, ssh_clients, self.options):
R
Rongfeng Fu 已提交
2500 2501
            return False

F
v1.5.0  
frf12 已提交
2502 2503
        # start cluster if needed
        if need_restart and deploy_info.status == DeployStatus.STATUS_RUNNING:
R
Rongfeng Fu 已提交
2504 2505 2506 2507
            setattr(self.options, 'without_parameter', True)
            obd = self.fork(options=self.options)
            if not obd.call_plugin(start_plugins[current_repository], current_repository, home_path=self.home_path) and getattr(self.options, 'force', False) is False:
                self.install_repositories_to_servers(deploy_config, [current_repository, ], install_plugins, ssh_clients, self.options)
R
Rongfeng Fu 已提交
2508
                return False
F
v1.5.0  
frf12 已提交
2509 2510 2511 2512

        # update deploy info
        if need_change_repo:
            deploy.use_model(dest_repository.name, dest_repository)
R
Rongfeng Fu 已提交
2513 2514
        return True

R
Rongfeng Fu 已提交
2515
    def upgrade_cluster(self, name):
R
Rongfeng Fu 已提交
2516 2517
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2518
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
2519 2520 2521
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
F
v1.5.0  
frf12 已提交
2522

R
Rongfeng Fu 已提交
2523 2524
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Deploy status judge')
R
Rongfeng Fu 已提交
2525 2526
        if deploy_info.status not in [DeployStatus.STATUS_UPRADEING, DeployStatus.STATUS_RUNNING]:
            self._call_stdio('error', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
R
Rongfeng Fu 已提交
2527
            return False
F
v1.5.0  
frf12 已提交
2528

R
Rongfeng Fu 已提交
2529
        deploy_config = deploy.deploy_config
R
Rongfeng Fu 已提交
2530

R
Rongfeng Fu 已提交
2531 2532 2533
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2534
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
2535 2536 2537 2538 2539 2540 2541 2542

        # Check whether the components have the parameter plugins and apply the plugins

        self.search_param_plugin_and_apply(repositories, deploy_config)

        self._call_stdio('stop_loading', 'succeed')

        if deploy_info.status == DeployStatus.STATUS_RUNNING:
R
Rongfeng Fu 已提交
2543 2544 2545 2546
            component = getattr(self.options, 'component')
            version = getattr(self.options, 'version')
            usable = getattr(self.options, 'usable', '')
            disable = getattr(self.options, 'disable', '')
R
Rongfeng Fu 已提交
2547 2548 2549 2550 2551 2552

            if component:
                if component not in deploy_info.components:
                    self._call_stdio('error', 'Not found %s in Deploy "%s" ' % (component, name))
                    return False
            else:
R
Rongfeng Fu 已提交
2553 2554 2555
                for component in deploy_info.components:
                    break
                if not component:
R
Rongfeng Fu 已提交
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
                    self._call_stdio('error', 'Specify the components you want to upgrade.')
                    return False

            for current_repository in repositories:
                if current_repository.name == component:
                    break

            if not version:
                self._call_stdio('error', 'Specify the target version.')
                return False
            if Version(version) < current_repository.version:
                self._call_stdio('error', 'The target version %s is lower than the current version %s.' % (version, current_repository.version))
R
Rongfeng Fu 已提交
2568 2569
                return False

R
Rongfeng Fu 已提交
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
            usable = usable.split(',')
            disable = disable.split(',')

            self._call_stdio('verbose', 'search target version')
            images = self.search_images(component, version=version, disable=disable, usable=usable)
            if not images:
                self._call_stdio('error', 'No such package %s-%s' % (component, version))
                return False
            if len(images) > 1:
                self._call_stdio(
                    'print_list',
                    images,
F
v1.5.0  
frf12 已提交
2582
                    ['name', 'version', 'release', 'arch', 'md5'],
R
Rongfeng Fu 已提交
2583
                    lambda x: [x.name, x.version, x.release, x.arch, x.md5],
F
v1.5.0  
frf12 已提交
2584
                    title='%s %s Candidates' % (component, version)
R
Rongfeng Fu 已提交
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
                )
                self._call_stdio('error', 'Too many match')
                return False

            if isinstance(images[0], Repository):
                pkg = self.mirror_manager.get_exact_pkg(name=images[0].name, md5=images[0].md5)
                if pkg:
                    repositories = []
                    pkgs = [pkg]
                else:
                    repositories = [images[0]]
                    pkgs = []
R
Rongfeng Fu 已提交
2597
            else:
R
Rongfeng Fu 已提交
2598 2599 2600
                repositories = []
                pkg = self.mirror_manager.get_exact_pkg(name=images[0].name, md5=images[0].md5)
                pkgs = [pkg]
F
v1.5.0  
frf12 已提交
2601

R
Rongfeng Fu 已提交
2602 2603 2604
            install_plugins = self.get_install_plugin_and_install(repositories, pkgs)
            if not install_plugins:
                return False
F
v1.5.0  
frf12 已提交
2605

R
Rongfeng Fu 已提交
2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
            dest_repository = repositories[0]
            if dest_repository is None:
                self._call_stdio('error', 'Target version not found')
                return False

            if dest_repository == current_repository:
                self._call_stdio('print', 'The current version is already %s.\nNoting to do.' % current_repository)
                return False
            # Get the client
            ssh_clients = self.get_clients(deploy_config, [current_repository])
            cluster_config = deploy_config.components[current_repository.name]

R
Rongfeng Fu 已提交
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
            # Check the status for the deployed cluster
            component_status = {}
            cluster_status = self.cluster_status_check(repositories, component_status)
            if cluster_status is False or cluster_status == 0:
                if self.stdio:
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED)
                    for repository in component_status:
                        cluster_status = component_status[repository]
                        for server in cluster_status:
                            if cluster_status[server] == 0:
                                self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
                return False

R
Rongfeng Fu 已提交
2631 2632
            route = []
            use_images = []
R
Rongfeng Fu 已提交
2633
            upgrade_route_plugins = self.search_py_script_plugin([current_repository], 'upgrade_route', no_found_act='warn')
R
Rongfeng Fu 已提交
2634
            if current_repository in upgrade_route_plugins:
R
Rongfeng Fu 已提交
2635
                ret = self.call_plugin(upgrade_route_plugins[current_repository], current_repository , current_repository=current_repository, dest_repository=dest_repository)
R
Rongfeng Fu 已提交
2636 2637 2638 2639
                route = ret.get_return('route')
                if not route:
                    return False
                for node in route[1: -1]:
F
v1.5.0  
frf12 已提交
2640 2641 2642
                    _version = node.get('version')
                    _release = node.get('release')
                    images = self.search_images(component, version=_version, release=_release, disable=disable, usable=usable, release_first=True)
R
Rongfeng Fu 已提交
2643
                    if not images:
F
v1.5.0  
frf12 已提交
2644 2645 2646 2647 2648 2649
                        pkg_name = component
                        if _version:
                            pkg_name = pkg_name + '-' + str(_version)
                        if _release:
                            pkg_name = pkg_name + '-' + str(_release)
                        self._call_stdio('error', 'No such package %s' % pkg_name)
R
Rongfeng Fu 已提交
2650 2651 2652 2653 2654
                        return False
                    if len(images) > 1:
                        self._call_stdio(
                            'print_list',
                            images,
F
v1.5.0  
frf12 已提交
2655
                            ['name', 'version', 'release', 'arch', 'md5'],
R
Rongfeng Fu 已提交
2656
                            lambda x: [x.name, x.version, x.release, x.arch, x.md5],
F
v1.5.0  
frf12 已提交
2657
                            title='%s %s Candidates' % (component, version)
R
Rongfeng Fu 已提交
2658 2659 2660 2661 2662 2663 2664 2665
                        )
                        self._call_stdio('error', 'Too many match')
                        return False
                    use_images.append(images[0])
            else:
                use_images = []

            pkgs = []
R
Rongfeng Fu 已提交
2666
            upgrade_repositories = [current_repository]
R
Rongfeng Fu 已提交
2667 2668
            for image in use_images:
                if isinstance(image, Repository):
R
Rongfeng Fu 已提交
2669
                    upgrade_repositories.append(image)
R
Rongfeng Fu 已提交
2670
                else:
F
v1.5.0  
frf12 已提交
2671
                    repository = self.repository_manager.get_repository(name=image.name, version=image.version, package_hash=image.md5)
R
Rongfeng Fu 已提交
2672 2673 2674 2675 2676 2677 2678 2679 2680
                    if repository:
                        upgrade_repositories.append(repository)
                    else:
                        pkg = self.mirror_manager.get_exact_pkg(name=image.name, version=image.version, md5=image.md5)
                        if not pkg:
                            return False
                        install_plugins = self.get_install_plugin_and_install(upgrade_repositories, [pkg])
                        if not install_plugins:
                            return False
R
Rongfeng Fu 已提交
2681 2682
            upgrade_repositories.append(dest_repository)

R
Rongfeng Fu 已提交
2683
            self.set_repositories(upgrade_repositories)
R
Rongfeng Fu 已提交
2684
            upgrade_check_plugins = self.search_py_script_plugin(upgrade_repositories, 'upgrade_check', no_found_act='warn')
R
Rongfeng Fu 已提交
2685 2686 2687 2688
            if current_repository in upgrade_check_plugins:
                connect_plugin = self.search_py_script_plugin(upgrade_repositories, 'connect')[current_repository]
                db = None
                cursor = None
R
Rongfeng Fu 已提交
2689
                ret = self.call_plugin(connect_plugin, current_repository)
R
Rongfeng Fu 已提交
2690 2691 2692 2693 2694
                if ret:
                    db = ret.get_return('connect')
                    cursor = ret.get_return('cursor')
                if not db:
                    return False
R
Rongfeng Fu 已提交
2695 2696
                if not self.call_plugin(
                    upgrade_check_plugins[current_repository], current_repository,
R
Rongfeng Fu 已提交
2697 2698 2699
                    current_repository=current_repository,
                    route=route,
                    cursor=cursor
R
Rongfeng Fu 已提交
2700
                ):
R
Rongfeng Fu 已提交
2701 2702
                    return False
                cursor.close()
R
Rongfeng Fu 已提交
2703

R
Rongfeng Fu 已提交
2704 2705 2706
            self._call_stdio(
                'print_list',
                upgrade_repositories,
F
v1.5.0  
frf12 已提交
2707
                ['name', 'version', 'release', 'arch', 'md5', 'mark'],
R
Rongfeng Fu 已提交
2708
                lambda x: [x.name, x.version, x.release, x.arch, x.md5, 'start' if x == current_repository else 'dest' if x == dest_repository else ''],
F
v1.5.0  
frf12 已提交
2709
                title='Packages Will Be Used'
R
Rongfeng Fu 已提交
2710
            )
F
v1.5.0  
frf12 已提交
2711

R
Rongfeng Fu 已提交
2712 2713 2714 2715 2716
            if not self._call_stdio('confirm', 'If you use a non-official release, we cannot guarantee a successful upgrade or technical support when you fail. Make sure that you want to use the above package to upgrade.'):
                return False

            index = 1
            upgrade_ctx = {
F
v1.5.0  
frf12 已提交
2717
                'route': route,
R
Rongfeng Fu 已提交
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
                'upgrade_repositories': [
                    {
                    'version': repository.version,
                    'hash': repository.md5
                    } for repository in upgrade_repositories
                ],
                'index': 1
            }
            deploy.start_upgrade(component, **upgrade_ctx)
        else:
            component = deploy.upgrading_component
            upgrade_ctx = deploy.upgrade_ctx
            upgrade_repositories = []
            for data in upgrade_ctx['upgrade_repositories']:
                repository = self.repository_manager.get_repository(component, data['version'], data['hash'])
                upgrade_repositories.append(repository)
            route = upgrade_ctx['route']
            current_repository = upgrade_repositories[0]
            dest_repository = upgrade_repositories[-1]
            # Get the client
            ssh_clients = self.get_clients(deploy_config, [current_repository])
            cluster_config = deploy_config.components[current_repository.name]
F
v1.5.0  
frf12 已提交
2740

R
Rongfeng Fu 已提交
2741 2742 2743
        install_plugins = self.get_install_plugin_and_install(upgrade_repositories, [])
        if not install_plugins:
            return False
R
Rongfeng Fu 已提交
2744

R
Rongfeng Fu 已提交
2745
        if not self.install_repositories_to_servers(deploy_config, upgrade_repositories[1:], install_plugins, ssh_clients, self.options):
F
v1.5.0  
frf12 已提交
2746
            return False
R
Rongfeng Fu 已提交
2747

R
Rongfeng Fu 已提交
2748
        script_query_timeout = getattr(self.options, 'script_query_timeout', '')
R
Rongfeng Fu 已提交
2749 2750
        n = len(upgrade_repositories)
        while upgrade_ctx['index'] < n:
R
Rongfeng Fu 已提交
2751
            repository = upgrade_repositories[upgrade_ctx['index']]
R
Rongfeng Fu 已提交
2752 2753
            repositories = [repository]
            upgrade_plugin = self.search_py_script_plugin(repositories, 'upgrade')[repository]
R
Rongfeng Fu 已提交
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
            self.set_repositories(repositories)
            ret = self.call_plugin(
                upgrade_plugin, repository,
                search_py_script_plugin=self.search_py_script_plugin,
                local_home_path=self.home_path,
                current_repository=current_repository,
                upgrade_repositories=upgrade_repositories,
                apply_param_plugin=lambda repository: self.search_param_plugin_and_apply([repository], deploy_config),
                upgrade_ctx=upgrade_ctx,
                install_repository_to_servers=self.install_repository_to_servers,
R
Rongfeng Fu 已提交
2764 2765
                unuse_lib_repository=deploy_config.unuse_lib_repository,
                script_query_timeout=script_query_timeout
R
Rongfeng Fu 已提交
2766
            )
R
Rongfeng Fu 已提交
2767 2768 2769
            deploy.update_upgrade_ctx(**upgrade_ctx)
            if not ret:
                return False
R
Rongfeng Fu 已提交
2770

R
Rongfeng Fu 已提交
2771
        deploy.stop_upgrade(dest_repository)
R
Rongfeng Fu 已提交
2772

R
Rongfeng Fu 已提交
2773
        return True
R
Rongfeng Fu 已提交
2774

R
Rongfeng Fu 已提交
2775 2776
    def create_repository(self):
        force = getattr(self.options, 'force', False)
O
oceanbase-admin 已提交
2777
        necessary = ['name', 'version', 'path']
R
Rongfeng Fu 已提交
2778
        attrs = self.options.__dict__
O
oceanbase-admin 已提交
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795
        success = True
        for key in necessary:
            if key not in attrs or not attrs[key]:
                success = False
                self._call_stdio('error', 'option: %s is necessary' % key)
        if success is False:
            return False
        plugin = self.plugin_manager.get_best_plugin(PluginType.INSTALL, attrs['name'], attrs['version'])
        if plugin:
            self._call_stdio('verbose', 'Found %s for %s-%s' % (plugin, attrs['name'], attrs['version']))
        else:
            self._call_stdio('error', 'No such %s plugin for %s-%s' % (PluginType.INSTALL.name.lower(), attrs['name'], attrs['version']))
            return False

        files = {}
        success = True
        repo_path = attrs['path']
R
Rongfeng Fu 已提交
2796 2797
        info = PackageInfo(name=attrs['name'], version=attrs['version'], release=None, arch=None, md5=None)
        for item in plugin.file_list(info):
O
oceanbase-admin 已提交
2798 2799
            path = os.path.join(repo_path, item.src_path)
            path = os.path.normcase(path)
F
v1.5.0  
frf12 已提交
2800
            if not os.path.exists(path) or os.path.isdir(path) != (item.type == InstallPlugin.FileItemType.DIR):
O
oceanbase-admin 已提交
2801 2802 2803
                path = os.path.join(repo_path, item.target_path)
                path = os.path.normcase(path)
                if not os.path.exists(path):
R
Rongfeng Fu 已提交
2804
                    self._call_stdio('error', 'need %s: %s ' % ('dir' if item.type == InstallPlugin.FileItemType.DIR else 'file', path))
O
oceanbase-admin 已提交
2805 2806
                    success = False
                    continue
F
v1.5.0  
frf12 已提交
2807 2808 2809 2810
                if os.path.isdir(path) != (item.type == InstallPlugin.FileItemType.DIR):
                    self._call_stdio('error', 'need %s, but %s is %s' % (item.type, path, 'file' if item.type == InstallPlugin.FileItemType.DIR else 'dir'))
                    success = False
                    continue
O
oceanbase-admin 已提交
2811 2812 2813 2814 2815 2816
            files[item.src_path] = path
        if success is False:
            return False

        self._call_stdio('start_loading', 'Package')
        try:
R
Rongfeng Fu 已提交
2817
            pkg = LocalPackage(repo_path, attrs['name'], attrs['version'], files, getattr(self.options, 'release', None), getattr(self.options, 'arch', None))
O
oceanbase-admin 已提交
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
            self._call_stdio('stop_loading', 'succeed')
        except:
            self._call_stdio('exception', 'Package failed')
            self._call_stdio('stop_loading', 'fail')
            return False
        self._call_stdio('print', pkg)
        repository = self.repository_manager.get_repository_allow_shadow(attrs['name'], attrs['version'], pkg.md5)
        if os.path.exists(repository.repository_dir):
            if not force or not DirectoryUtil.rm(repository.repository_dir):
                self._call_stdio('error', 'Repository(%s) exists' % repository.repository_dir)
                return False
        repository = self.repository_manager.create_instance_repository(attrs['name'], attrs['version'], pkg.md5)
        if not repository.load_pkg(pkg, plugin):
            self._call_stdio('error', 'Failed to extract file from %s' % pkg.path)
            return False
        if 'tag' in attrs and attrs['tag']:
            for tag in attrs['tag'].split(','):
                tag_repository = self.repository_manager.get_repository_allow_shadow(tag, attrs['version'])
                self._call_stdio('verbose', 'Create tag(%s) for %s' % (tag, attrs['name']))
                if not self.repository_manager.create_tag_for_repository(repository, tag, force):
                    self._call_stdio('error', 'Repository(%s) existed' % tag_repository.repository_dir)
        return True

R
Rongfeng Fu 已提交
2841 2842 2843
    def _test_optimize_init(self, test_name, repository):
        opts = self.options
        deploy_config = self.deploy.deploy_config
F
v1.6.0  
frf12 已提交
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
        optimize_config_path = getattr(opts, 'optimize_config', None)
        if optimize_config_path:
            self._call_stdio('verbose', 'load optimize config {}'.format(optimize_config_path))
            self.optimize_manager.load_config(optimize_config_path, stdio=self.stdio)
        else:
            for component, cluster_config in deploy_config.components.items():
                self.optimize_manager.register_component(component, cluster_config.version)
            self._call_stdio('verbose', 'load default optimize config for {}'.format(test_name))
            self.optimize_manager.load_default_config(test_name=test_name, stdio=self.stdio)
        self._call_stdio('verbose', 'Get optimize config')
        optimize_config = self.optimize_manager.optimize_config
        check_options_plugin = self.plugin_manager.get_best_py_script_plugin('check_options', 'optimize', '0.1')
R
Rongfeng Fu 已提交
2856
        return self.call_plugin(check_options_plugin, repository, optimize_config=optimize_config)
F
v1.6.0  
frf12 已提交
2857 2858

    @staticmethod
R
Rongfeng Fu 已提交
2859
    def _get_first_db_and_cursor_from_connect(namespace):
R
Rongfeng Fu 已提交
2860 2861
        if not namespace:
            return None, None
R
Rongfeng Fu 已提交
2862
        connect_ret = namespace.get_return('connect')
F
v1.6.0  
frf12 已提交
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
        dbs = connect_ret.get_return('connect')
        cursors = connect_ret.get_return('cursor')
        if not dbs or not cursors:
            return None, None
        if isinstance(dbs, dict) and isinstance(cursors, dict):
            tmp_server = list(dbs.keys())[0]
            db = dbs[tmp_server]
            cursor = cursors[tmp_server]
            return db, cursor
        else:
            return dbs, cursors

R
Rongfeng Fu 已提交
2875
    def _test_optimize_operation(self, repository, ob_repository, optimize_envs, connect_namespaces, connect_plugin, stage=None, operation='optimize'):
F
v1.6.0  
frf12 已提交
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
        """
        :param stage: optimize stage
        :param optimize_envs: envs for optimize plugin
        :param operation: "optimize" or "recover"
        :return:
        """
        if operation == 'optimize':
            self._call_stdio('verbose', 'Optimize for stage {}'.format(stage))
        elif operation == 'recover':
            self._call_stdio('verbose', 'Recover the optimizes')
        else:
            raise Exception("Invalid optimize operation!")
        ob_cursor = None
        odp_cursor = None
R
Rongfeng Fu 已提交
2890 2891 2892 2893 2894 2895 2896 2897 2898
        for namespace in connect_namespaces:
            db, cursor = self._get_first_db_and_cursor_from_connect(namespace)
            if not db or not cursor:
                if not self.call_plugin(connect_plugin, repository, spacename=namespace.spacename):
                    raise Exception('call connect plugin for {} failed'.format(namespace.spacename))
            if namespace.spacename in ['oceanbase', 'oceanbase-ce']:
                ob_db, ob_cursor = db, cursor
            elif namespace.spacename in ['obproxy', 'obproxy-ce']:
                odp_db, odp_cursor = db, cursor
F
v1.6.0  
frf12 已提交
2899 2900
        operation_plugin = self.plugin_manager.get_best_py_script_plugin(operation, 'optimize', '0.1')
        optimize_config = self.optimize_manager.optimize_config
R
Rongfeng Fu 已提交
2901 2902 2903
        ret = self.call_plugin(operation_plugin, repository,
                               optimize_config=optimize_config, stage=stage,
                               ob_cursor=ob_cursor, odp_cursor=odp_cursor, optimize_envs=optimize_envs)
F
v1.6.0  
frf12 已提交
2904 2905 2906 2907 2908 2909
        if ret:
            restart_components = ret.get_return('restart_components')
        else:
            return False
        if restart_components:
            self._call_stdio('verbose', 'Components {} need restart.'.format(','.join(restart_components)))
R
Rongfeng Fu 已提交
2910 2911 2912 2913 2914
            for namespace in connect_namespaces:
                db, cursor = self._get_first_db_and_cursor_from_connect(namespace)
                if cursor:
                    cursor.close()
            ret = self._restart_cluster_for_optimize(self.deploy.name, restart_components)
F
v1.6.0  
frf12 已提交
2915 2916 2917
            if not ret:
                return False
            if operation == 'optimize':
R
Rongfeng Fu 已提交
2918 2919 2920 2921 2922 2923 2924 2925 2926
                for namespace in connect_namespaces:
                    if not self.call_plugin(connect_plugin, repository, spacename=namespace.spacename):
                        raise Exception('call connect plugin for {} failed'.format(namespace.spacename))
                    if namespace.spacename == ob_repository.name and ob_repository.name in restart_components:
                        self._call_stdio('verbose', '{}: major freeze for component ready'.format(ob_repository.name))
                        self._call_stdio('start_loading', 'Waiting for {} ready'.format(ob_repository.name))
                        db, cursor = self._get_first_db_and_cursor_from_connect(namespace)
                        if not self._major_freeze(repository=ob_repository, cursor=cursor, tenant=optimize_envs.get('tenant')):
                            self._call_stdio('stop_loading', 'fail')
F
v1.6.0  
frf12 已提交
2927 2928 2929 2930
                            return False
                    self._call_stdio('stop_loading', 'succeed')
        return True

R
Rongfeng Fu 已提交
2931 2932
    def _major_freeze(self, repository, **kwargs):
        major_freeze_plugin = self.plugin_manager.get_best_py_script_plugin('major_freeze', repository.name, repository.version)
F
v1.6.0  
frf12 已提交
2933
        if not major_freeze_plugin:
R
Rongfeng Fu 已提交
2934
            self._call_stdio('verbose', 'no major freeze plugin for component {}, skip.'.format(repository.name))
F
v1.6.0  
frf12 已提交
2935
            return True
R
Rongfeng Fu 已提交
2936
        return self.call_plugin(major_freeze_plugin, repository, **kwargs)
F
v1.6.0  
frf12 已提交
2937 2938 2939 2940 2941 2942 2943 2944 2945

    def _restart_cluster_for_optimize(self, deploy_name, components):
        self._call_stdio('start_loading', 'Restart cluster')
        if getattr(self.stdio, 'sub_io'):
            stdio = self.stdio.sub_io(msg_lv=MsgLevel.ERROR)
        else:
            stdio = None
        obd = ObdHome(self.home_path, self.dev_mode, stdio=stdio)
        obd.lock_manager.set_try_times(-1)
R
Rongfeng Fu 已提交
2946 2947 2948
        obd.set_options(Values({'components': ','.join(components), 'without_parameter': True}))
        if obd.stop_cluster(name=deploy_name) and \
                obd.start_cluster(name=deploy_name) and obd.display_cluster(name=deploy_name):
F
v1.6.0  
frf12 已提交
2949 2950 2951 2952 2953 2954
            self._call_stdio('stop_loading', 'succeed')
            return True
        else:
            self._call_stdio('stop_loading', 'fail')
            return False

R
Rongfeng Fu 已提交
2955
    def create_mysqltest_snap(self, repositories, create_snap_plugin, start_plugins, stop_plugins, snap_configs, env={}):
F
v1.6.0  
frf12 已提交
2956 2957
        for repository in repositories:
            if repository in snap_configs:
R
Rongfeng Fu 已提交
2958
                if not self.call_plugin(stop_plugins[repository], repository):
F
v1.6.0  
frf12 已提交
2959
                    return False
R
Rongfeng Fu 已提交
2960
                if not self.call_plugin(create_snap_plugin, repository, env=env, snap_config=snap_configs[repository]):
F
v1.6.0  
frf12 已提交
2961
                    return False
R
Rongfeng Fu 已提交
2962
                if not self.call_plugin(start_plugins[repository], repository, home_path=self.home_path):
F
v1.6.0  
frf12 已提交
2963 2964 2965
                    return False
        return True

O
oceanbase-admin 已提交
2966 2967 2968
    def mysqltest(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
2969
        self.set_deploy(deploy)
O
oceanbase-admin 已提交
2970 2971 2972 2973
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
F
v1.6.0  
frf12 已提交
2974
        fast_reboot = getattr(opts, 'fast_reboot', False)
O
oceanbase-admin 已提交
2975 2976
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check deploy status')
F
v1.6.0  
frf12 已提交
2977 2978 2979 2980 2981 2982
        if fast_reboot:
            setattr(opts, 'without_parameter', True)
            status = [DeployStatus.STATUS_DEPLOYED, DeployStatus.STATUS_RUNNING]
        else:
            status = [DeployStatus.STATUS_RUNNING]
        if deploy_info.status not in status:
O
oceanbase-admin 已提交
2983 2984 2985 2986 2987 2988
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

        if opts.component is None:
R
Rongfeng Fu 已提交
2989
            for component_name in ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']:
O
oceanbase-admin 已提交
2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        if opts.component not in deploy_config.components:
            self._call_stdio('error', 'Can not find the component for mysqltest, use `--component` to select component')
            return False
        
        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.test_server is None:
            opts.test_server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.test_server:
                    opts.test_server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.test_server, opts.component))
                return False

        if opts.auto_retry:
            for component_name in ['oceanbase', 'oceanbase-ce']:
                if component_name in deploy_config.components:
                    break
            else:
                opts.auto_retry = False
                self._call_stdio('warn', 'Set auto-retry to false because of %s does not contain the configuration of oceanbase database' % name)

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
F
v1.5.0  
frf12 已提交
3022 3023
        # repositories = self.get_local_repositories({opts.component: deploy_config.components[opts.component]})
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3024
        self.set_repositories(repositories)
F
v1.6.0  
frf12 已提交
3025 3026
        target_repository = None
        ob_repository = None
F
v1.5.0  
frf12 已提交
3027 3028
        for repository in repositories:
            if repository.name == opts.component:
F
v1.6.0  
frf12 已提交
3029 3030 3031 3032 3033
                target_repository = repository
            if repository.name in ['oceanbase', 'oceanbase-ce']:
                ob_repository = repository

        if not target_repository:
F
v1.5.0  
frf12 已提交
3034 3035
            self._call_stdio('error', 'Can not find the component for mysqltest, use `--component` to select component')
            return False
F
v1.6.0  
frf12 已提交
3036 3037 3038
        if not ob_repository:
            self._call_stdio('error', 'Deploy {} must contain the component oceanbase or oceanbase-ce.'.format(deploy.name))
            return False
O
oceanbase-admin 已提交
3039 3040
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
3041
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
3042

F
v1.6.0  
frf12 已提交
3043 3044 3045
        if deploy_info.status == DeployStatus.STATUS_DEPLOYED and not self._start_cluster(deploy, repositories):
            return False

O
oceanbase-admin 已提交
3046 3047 3048 3049 3050
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
3051
        cluster_status = self.cluster_status_check(repositories, component_status)
O
oceanbase-admin 已提交
3052 3053
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
3054
                self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
O
oceanbase-admin 已提交
3055 3056 3057 3058 3059 3060
                for repository in component_status:
                    cluster_status = component_status[repository]
                    for server in cluster_status:
                        if cluster_status[server] == 0:
                            self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
            return False
R
Rongfeng Fu 已提交
3061 3062 3063
        namespace = self.get_namespace(target_repository.name)
        namespace.set_variable('target_server', opts.test_server)
        namespace.set_variable('connect_proxysys', False)
O
oceanbase-admin 已提交
3064

F
v1.6.0  
frf12 已提交
3065
        connect_plugin = self.search_py_script_plugin(repositories, 'connect')[target_repository]
R
Rongfeng Fu 已提交
3066
        ret = self.call_plugin(connect_plugin, target_repository)
O
oceanbase-admin 已提交
3067 3068 3069 3070 3071 3072 3073 3074
        if not ret or not ret.get_return('connect'):
            return False
        db = ret.get_return('connect')
        cursor = ret.get_return('cursor')
        env = opts.__dict__
        env['cursor'] = cursor
        env['host'] = opts.test_server.ip
        env['port'] = db.port
F
v1.6.0  
frf12 已提交
3075

R
Rongfeng Fu 已提交
3076
        namespace.set_variable('env', env)
F
v1.6.0  
frf12 已提交
3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092
        mysqltest_init_plugin = self.plugin_manager.get_best_py_script_plugin('init', 'mysqltest', ob_repository.version)
        mysqltest_check_opt_plugin = self.plugin_manager.get_best_py_script_plugin('check_opt', 'mysqltest', ob_repository.version)
        mysqltest_check_test_plugin = self.plugin_manager.get_best_py_script_plugin('check_test', 'mysqltest', ob_repository.version)
        mysqltest_run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'mysqltest', ob_repository.version)
        mysqltest_collect_log_plugin = self.plugin_manager.get_best_py_script_plugin('collect_log', 'mysqltest', ob_repository.version)

        start_plugins = self.search_py_script_plugin(repositories, 'start')
        stop_plugins = self.search_py_script_plugin(repositories, 'stop')
        # display_plugin = self.search_py_script_plugin(repositories, 'display')[repository]

        if fast_reboot:
            create_snap_plugin = self.plugin_manager.get_best_py_script_plugin('create_snap', 'general', '0.1')
            load_snap_plugin = self.plugin_manager.get_best_py_script_plugin('load_snap', 'general', '0.1')
            snap_check_plugin = self.plugin_manager.get_best_py_script_plugin('snap_check', 'general', '0.1')
            snap_configs = self.search_plugins(repositories, PluginType.SNAP_CONFIG, no_found_exit=False)

R
Rongfeng Fu 已提交
3093
        ret = self.call_plugin(mysqltest_check_opt_plugin, target_repository)
O
oceanbase-admin 已提交
3094 3095
        if not ret:
            return False
F
v1.5.0  
frf12 已提交
3096
        if not env['init_only']:
R
Rongfeng Fu 已提交
3097
            ret = self.call_plugin(mysqltest_check_test_plugin, target_repository)
F
v1.5.0  
frf12 已提交
3098 3099 3100 3101 3102 3103
            if not ret:
                self._call_stdio('error', 'Failed to get test set')
                return False
            if env['test_set'] is None:
                self._call_stdio('error', 'Test set is empty')
                return False
O
oceanbase-admin 已提交
3104

F
v1.6.0  
frf12 已提交
3105
        use_snap = False
F
v1.5.0  
frf12 已提交
3106
        if env['need_init'] or env['init_only']:
R
Rongfeng Fu 已提交
3107
            if not self.call_plugin(mysqltest_init_plugin, target_repository, env=env):
O
oceanbase-admin 已提交
3108 3109
                self._call_stdio('error', 'Failed to init for mysqltest')
                return False
F
v1.6.0  
frf12 已提交
3110
            if fast_reboot:
R
Rongfeng Fu 已提交
3111
                if not self.create_mysqltest_snap(repositories, create_snap_plugin, start_plugins, stop_plugins, snap_configs, env):
F
v1.6.0  
frf12 已提交
3112
                    return False
R
Rongfeng Fu 已提交
3113
                ret = self.call_plugin(connect_plugin, target_repository)
F
v1.6.0  
frf12 已提交
3114 3115 3116 3117 3118 3119 3120 3121 3122
                if not ret or not ret.get_return('connect'):
                    return False
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
                env['cursor'] = cursor
                env['host'] = opts.test_server.ip
                env['port'] = db.port
                self._call_stdio('start_loading', 'Check init')
                env['load_snap'] = True
R
Rongfeng Fu 已提交
3123
                self.call_plugin(mysqltest_init_plugin, target_repository)
F
v1.6.0  
frf12 已提交
3124 3125 3126 3127
                env['load_snap'] = False
                self._call_stdio('stop_loading', 'succeed')
                use_snap = True

F
v1.5.0  
frf12 已提交
3128 3129 3130
            if env['init_only']:
                return True

F
v1.6.0  
frf12 已提交
3131 3132 3133
        if fast_reboot and use_snap is False:
            self._call_stdio('start_loading', 'Check init')
            env['load_snap'] = True
R
Rongfeng Fu 已提交
3134
            self.call_plugin(mysqltest_init_plugin, target_repository)
F
v1.6.0  
frf12 已提交
3135 3136 3137 3138 3139
            env['load_snap'] = False
            self._call_stdio('stop_loading', 'succeed')
            snap_num = 0
            for repository in repositories:
                if repository in snap_configs:
R
Rongfeng Fu 已提交
3140
                    if not self.call_plugin(snap_check_plugin, repository, env=env, snap_config=snap_configs[repository]):
F
v1.6.0  
frf12 已提交
3141 3142 3143 3144 3145
                        break
                    snap_num += 1
            use_snap = len(snap_configs) == snap_num
        env['load_snap'] = use_snap

F
v1.5.0  
frf12 已提交
3146 3147 3148 3149
        self._call_stdio('verbose', 'test set: {}'.format(env['test_set']))
        self._call_stdio('verbose', 'total: {}'.format(len(env['test_set'])))
        reboot_success = True
        while True:
R
Rongfeng Fu 已提交
3150
            ret = self.call_plugin(mysqltest_run_test_plugin, target_repository)
O
oceanbase-admin 已提交
3151 3152
            if not ret:
                break
R
Rongfeng Fu 已提交
3153
            self.call_plugin(mysqltest_collect_log_plugin, target_repository)
F
v1.5.0  
frf12 已提交
3154 3155 3156
            if ret.get_return('finished'):
                break
            if ret.get_return('reboot') and not env['disable_reboot']:
O
oceanbase-admin 已提交
3157 3158 3159 3160 3161
                cursor.close()
                if getattr(self.stdio, 'sub_io'):
                    stdio = self.stdio.sub_io(msg_lv=MsgLevel.ERROR)
                else:
                    stdio = None
F
v1.5.0  
frf12 已提交
3162 3163 3164 3165 3166 3167
                reboot_timeout = getattr(opts, 'reboot_timeout', 0)
                reboot_retries = getattr(opts, 'reboot_retries', 5)
                reboot_success = False
                while reboot_retries and not reboot_success:
                    reboot_retries -= 1
                    with timeout(reboot_timeout):
F
v1.6.0  
frf12 已提交
3168 3169 3170 3171 3172
                        if use_snap:
                            self._call_stdio('start_loading', 'Snap Reboot')
                            for repository in repositories:
                                if repository in snap_configs:
                                    cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
3173
                                    if not self.call_plugin(stop_plugins[repository]):
F
v1.6.0  
frf12 已提交
3174 3175
                                        self._call_stdio('stop_loading', 'fail')
                                        continue
R
Rongfeng Fu 已提交
3176
                                    if not self.call_plugin(load_snap_plugin, repository,  env=env, snap_config=snap_configs[repository]):
F
v1.6.0  
frf12 已提交
3177 3178
                                        self._call_stdio('stop_loading', 'fail')
                                        continue
R
Rongfeng Fu 已提交
3179
                                    if not self.call_plugin(start_plugins[repository], repository, home_path=self.home_path):
F
v1.6.0  
frf12 已提交
3180 3181
                                        self._call_stdio('stop_loading', 'fail')
                                        continue
F
v1.5.0  
frf12 已提交
3182
                        else:
F
v1.6.0  
frf12 已提交
3183 3184 3185
                            self._call_stdio('start_loading', 'Reboot')
                            obd = ObdHome(self.home_path, self.dev_mode, stdio=stdio)
                            obd.lock_manager.set_try_times(-1)
R
Rongfeng Fu 已提交
3186 3187
                            obd.set_options(Values({'force_kill': True, 'force': True, 'force_delete': True}))
                            if not obd.redeploy_cluster(name, search_repo=False):
F
v1.6.0  
frf12 已提交
3188 3189 3190 3191 3192 3193
                                self._call_stdio('stop_loading', 'fail')
                                continue
                            obd.lock_manager.set_try_times(6000)
                            obd = None

                        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
3194
                        ret = self.call_plugin(connect_plugin, target_repository)
F
v1.5.0  
frf12 已提交
3195 3196 3197 3198 3199 3200
                        if not ret or not ret.get_return('connect'):
                            self._call_stdio('error', 'Failed to connect server')
                            continue
                        db = ret.get_return('connect')
                        cursor = ret.get_return('cursor')
                        env['cursor'] = cursor
F
v1.6.0  
frf12 已提交
3201

R
Rongfeng Fu 已提交
3202
                        if self.call_plugin(mysqltest_init_plugin, target_repository):
F
v1.6.0  
frf12 已提交
3203
                            if fast_reboot and use_snap is False:
R
Rongfeng Fu 已提交
3204
                                if not self.create_mysqltest_snap(repositories, create_snap_plugin, start_plugins, stop_plugins, snap_configs, env):
F
v1.6.0  
frf12 已提交
3205 3206
                                    return False
                                use_snap = True
R
Rongfeng Fu 已提交
3207
                                ret = self.call_plugin(connect_plugin, target_repository)
F
v1.6.0  
frf12 已提交
3208 3209 3210 3211 3212 3213
                                if not ret or not ret.get_return('connect'):
                                    self._call_stdio('error', 'Failed to connect server')
                                    continue
                                db = ret.get_return('connect')
                                cursor = ret.get_return('cursor')
                                env['cursor'] = cursor
R
Rongfeng Fu 已提交
3214
                                self.call_plugin(mysqltest_init_plugin, target_repository)
F
v1.5.0  
frf12 已提交
3215 3216 3217 3218 3219
                            reboot_success = True
                        else:
                            self._call_stdio('error', 'Failed to prepare for mysqltest')
                if not reboot_success:
                    env['collect_log'] = True
R
Rongfeng Fu 已提交
3220
                    self.call_plugin(mysqltest_collect_log_plugin, target_repository, test_name='reboot_failed')
O
oceanbase-admin 已提交
3221
                    break
F
v1.5.0  
frf12 已提交
3222
        result = env.get('case_results', [])
O
oceanbase-admin 已提交
3223
        passcnt = len(list(filter(lambda x: x["ret"] == 0, result)))
F
v1.5.0  
frf12 已提交
3224
        totalcnt = len(env.get('run_test_cases', []))
O
oceanbase-admin 已提交
3225 3226 3227 3228 3229 3230 3231 3232
        failcnt = totalcnt - passcnt
        if result:
            self._call_stdio(
                'print_list', result, ['Case', 'Cost (s)', 'Status'], 
                lambda x: [x['name'], '%.2f' % x['cost'], '\033[31mFAILED\033[0m' if x['ret'] else '\033[32mPASSED\033[0m'], 
                title='Result (Total %d, Passed %d, Failed %s)' % (totalcnt, passcnt, failcnt), 
                align={'Cost (s)': 'r'}
            )
F
v1.5.0  
frf12 已提交
3233 3234 3235
        if failcnt or not reboot_success:
            if not reboot_success:
                self._call_stdio('error', 'reboot cluster failed')
O
oceanbase-admin 已提交
3236 3237 3238 3239 3240
            self._call_stdio('print', 'Mysqltest failed')
        else:
            self._call_stdio('print', 'Mysqltest passed')
            return True
        return False
R
Rongfeng Fu 已提交
3241

R
Rongfeng Fu 已提交
3242 3243 3244
    def sysbench(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
3245
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check deploy status')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

R
Rongfeng Fu 已提交
3258
        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
R
Rongfeng Fu 已提交
3259
        if opts.component is None:
R
Rongfeng Fu 已提交
3260
            for component_name in allow_components:
R
Rongfeng Fu 已提交
3261
                if component_name in deploy_config.components:
F
v1.4.0  
frf12 已提交
3262 3263 3264 3265 3266 3267 3268 3269
                    if opts.test_server is not None:
                        cluster_config = deploy_config.components[component_name]
                        for server in cluster_config.servers:
                            if server.name == opts.test_server:
                                break
                        else:
                            continue
                    self._call_stdio('verbose', 'Select component %s' % component_name)
R
Rongfeng Fu 已提交
3270 3271
                    opts.component = component_name
                    break
R
Rongfeng Fu 已提交
3272 3273 3274
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
R
Rongfeng Fu 已提交
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295
        if opts.component not in deploy_config.components:
            self._call_stdio('error', 'Can not find the component for sysbench, use `--component` to select component')
            return False
        
        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.test_server is None:
            opts.test_server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.test_server:
                    opts.test_server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.test_server, opts.component))
                return False

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
3296
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3297 3298
        self.set_repositories(repositories)
        self.get_clients(deploy_config, repositories)
R
Rongfeng Fu 已提交
3299 3300 3301 3302 3303 3304

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        # Check the status for the deployed cluster
F
v1.6.0  
frf12 已提交
3305 3306
        if not getattr(opts, 'skip_cluster_status_check', False):
            component_status = {}
R
Rongfeng Fu 已提交
3307
            cluster_status = self.cluster_status_check(repositories, component_status)
F
v1.6.0  
frf12 已提交
3308 3309
            if cluster_status is False or cluster_status == 0:
                if self.stdio:
R
Rongfeng Fu 已提交
3310
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
F
v1.6.0  
frf12 已提交
3311 3312 3313 3314 3315 3316
                    for repository in component_status:
                        cluster_status = component_status[repository]
                        for server in cluster_status:
                            if cluster_status[server] == 0:
                                self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
                return False
R
Rongfeng Fu 已提交
3317

F
v1.5.0  
frf12 已提交
3318 3319
        ob_repository = None
        repository = None
R
Rongfeng Fu 已提交
3320
        connect_namespaces = []
F
v1.5.0  
frf12 已提交
3321 3322 3323 3324 3325
        for tmp_repository in repositories:
            if tmp_repository.name in ["oceanbase", "oceanbase-ce"]:
                ob_repository = tmp_repository
            if tmp_repository.name == opts.component:
                repository = tmp_repository
F
v1.6.0  
frf12 已提交
3326 3327 3328
        if not ob_repository:
            self._call_stdio('error', 'Deploy {} must contain the component oceanbase or oceanbase-ce.'.format(deploy.name))
            return False
R
Rongfeng Fu 已提交
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346
        sys_namespace = self.get_namespace(ob_repository.name)
        connect_plugin = self.plugin_manager.get_best_py_script_plugin('connect', repository.name, repository.version)
        if repository.name in ['obproxy', 'obproxy-ce']:
            for component_name in deploy_config.components:
                if component_name in ['oceanbase', 'oceanbase-ce']:
                    ob_cluster_config = deploy_config.components[component_name]
                    sys_namespace.set_variable("connect_proxysys", False)
                    sys_namespace.set_variable("user", "root")
                    sys_namespace.set_variable("password", ob_cluster_config.get_global_conf().get('root_password', ''))
                    sys_namespace.set_variable("target_server",  opts.test_server)
                    break
            proxysys_namespace = self.get_namespace(repository.name)
            proxysys_namespace.set_variable("component_name", repository)
            proxysys_namespace.set_variable("target_server", opts.test_server)
            ret = self.call_plugin(connect_plugin, repository, spacename=proxysys_namespace.spacename)
            if not ret or not ret.get_return('connect'):
                return False
            connect_namespaces.append(proxysys_namespace)
F
v1.5.0  
frf12 已提交
3347
        plugin_version = ob_repository.version if ob_repository else repository.version
R
Rongfeng Fu 已提交
3348
        ret = self.call_plugin(connect_plugin, repository, spacename=sys_namespace.spacename)
R
Rongfeng Fu 已提交
3349 3350
        if not ret or not ret.get_return('connect'):
            return False
R
Rongfeng Fu 已提交
3351 3352
        connect_namespaces.append(sys_namespace)
        db, cursor = self._get_first_db_and_cursor_from_connect(namespace=sys_namespace)
F
v1.6.0  
frf12 已提交
3353
        pre_test_plugin = self.plugin_manager.get_best_py_script_plugin('pre_test', 'sysbench', plugin_version)
F
v1.5.0  
frf12 已提交
3354
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'sysbench', plugin_version)
R
Rongfeng Fu 已提交
3355 3356 3357 3358

        setattr(opts, 'host', opts.test_server.ip)
        setattr(opts, 'port', db.port)

F
v1.6.0  
frf12 已提交
3359 3360
        optimization = getattr(opts, 'optimization', 0)

R
Rongfeng Fu 已提交
3361
        ret = self.call_plugin(pre_test_plugin, repository, cursor=cursor)
F
v1.6.0  
frf12 已提交
3362 3363 3364 3365 3366 3367
        if not ret:
            return False
        kwargs = ret.kwargs
        optimization_init = False
        try:
            if optimization:
R
Rongfeng Fu 已提交
3368
                if not self._test_optimize_init(test_name='sysbench', repository=repository):
F
v1.6.0  
frf12 已提交
3369 3370
                    return False
                optimization_init = True
R
Rongfeng Fu 已提交
3371
                if not self._test_optimize_operation(repository=repository, ob_repository=ob_repository, stage='test', connect_namespaces=connect_namespaces, connect_plugin=connect_plugin, optimize_envs=kwargs):
F
v1.6.0  
frf12 已提交
3372
                    return False
R
Rongfeng Fu 已提交
3373
            if self.call_plugin(run_test_plugin, repository):
F
v1.6.0  
frf12 已提交
3374 3375 3376 3377
                return True
            return False
        finally:
            if optimization and optimization_init:
R
Rongfeng Fu 已提交
3378
                self._test_optimize_operation(repository=repository,  ob_repository=ob_repository, connect_namespaces=connect_namespaces, connect_plugin=connect_plugin, optimize_envs=kwargs, operation='recover')
R
Rongfeng Fu 已提交
3379

R
Rongfeng Fu 已提交
3380 3381 3382
    def tpch(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
3383
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check deploy status')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

        allow_components = ['oceanbase', 'oceanbase-ce']
        if opts.component is None:
            for component_name in allow_components:
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
        if opts.component not in deploy_config.components:
            self._call_stdio('error', 'Can not find the component for tpch, use `--component` to select component')
            return False
        
        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.test_server is None:
            opts.test_server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.test_server:
                    opts.test_server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.test_server, opts.component))
                return False

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.get_local_repositories({opts.component: deploy_config.components[opts.component]})
R
Rongfeng Fu 已提交
3427
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
3428 3429 3430 3431 3432 3433 3434 3435

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

F
v1.6.0  
frf12 已提交
3436 3437 3438
        if not getattr(opts, 'skip_cluster_status_check', False):
            # Check the status for the deployed cluster
            component_status = {}
R
Rongfeng Fu 已提交
3439
            cluster_status = self.cluster_status_check(repositories, component_status)
F
v1.6.0  
frf12 已提交
3440 3441
            if cluster_status is False or cluster_status == 0:
                if self.stdio:
R
Rongfeng Fu 已提交
3442
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
F
v1.6.0  
frf12 已提交
3443 3444 3445 3446 3447 3448
                    for repository in component_status:
                        cluster_status = component_status[repository]
                        for server in cluster_status:
                            if cluster_status[server] == 0:
                                self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
                return False
R
Rongfeng Fu 已提交
3449 3450 3451 3452 3453
        repository = repositories[0]
        namespace = self.get_namespace(repository.name)
        namespace.set_variable('target_server', opts.test_server)
        connect_plugin = self.plugin_manager.get_best_py_script_plugin('connect', repository.name, repository.version)
        ret = self.call_plugin(connect_plugin, repository)
R
Rongfeng Fu 已提交
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
        if not ret or not ret.get_return('connect'):
            return False
        db = ret.get_return('connect')
        cursor = ret.get_return('cursor')

        pre_test_plugin = self.plugin_manager.get_best_py_script_plugin('pre_test', 'tpch', repository.version)
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'tpch', repository.version)

        setattr(opts, 'host', opts.test_server.ip)
        setattr(opts, 'port', db.port)

F
v1.6.0  
frf12 已提交
3465
        optimization = getattr(opts, 'optimization', 0)
R
Rongfeng Fu 已提交
3466

R
Rongfeng Fu 已提交
3467
        ret = self.call_plugin(pre_test_plugin,repository, cursor=cursor)
F
v1.6.0  
frf12 已提交
3468 3469 3470 3471 3472 3473
        if not ret:
            return False
        kwargs = ret.kwargs
        optimization_init = False
        try:
            if optimization:
R
Rongfeng Fu 已提交
3474
                if not self._test_optimize_init(test_name='tpch', repository=repository):
F
v1.6.0  
frf12 已提交
3475 3476
                    return False
                optimization_init = True
R
Rongfeng Fu 已提交
3477 3478 3479
                if not self._test_optimize_operation(
                        repository=repository, ob_repository=repository, stage='test',
                        connect_namespaces=[namespace], connect_plugin=connect_plugin, optimize_envs=kwargs):
F
v1.6.0  
frf12 已提交
3480
                    return False
R
Rongfeng Fu 已提交
3481
            if self.call_plugin(run_test_plugin, repository, db=db, cursor=cursor, **kwargs):
R
Rongfeng Fu 已提交
3482
                return True
F
v1.6.0  
frf12 已提交
3483 3484 3485 3486 3487 3488
            return False
        except Exception as e:
            self._call_stdio('error', e)
            return False
        finally:
            if optimization and optimization_init:
R
Rongfeng Fu 已提交
3489 3490 3491
                self._test_optimize_operation(
                    repository=repository, ob_repository=repository, connect_namespaces=[namespace],
                    connect_plugin=connect_plugin, optimize_envs=kwargs, operation='recover')
R
Rongfeng Fu 已提交
3492

R
Rongfeng Fu 已提交
3493
    def update_obd(self, version, install_prefix='/'):
R
Rongfeng Fu 已提交
3494
        self._global_ex_lock()
R
Rongfeng Fu 已提交
3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507
        component_name = 'ob-deploy'
        plugin = self.plugin_manager.get_best_plugin(PluginType.INSTALL, component_name, '1.0.0')
        if not plugin:
            self._call_stdio('critical', 'OBD upgrade plugin not found')
            return False
        pkg = self.mirror_manager.get_best_pkg(name=component_name)
        if not (pkg and pkg > PackageInfo(component_name, version, pkg.release, pkg.arch, '')):
            self._call_stdio('print', 'No updates detected. OBD is already up to date.')
            return False
        
        self._call_stdio('print', 'Found a higher version package for OBD\n%s' % pkg)
        repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
        repository.load_pkg(pkg, plugin)
R
Rongfeng Fu 已提交
3508
        if DirectoryUtil.copy(repository.repository_dir, install_prefix, self.stdio):
R
Rongfeng Fu 已提交
3509 3510 3511
            self._call_stdio('print', 'Upgrade successful.\nCurrent version : %s' % pkg.version)
            return True
        return False
R
Rongfeng Fu 已提交
3512

F
v1.5.0  
frf12 已提交
3513 3514 3515
    def tpcds(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
3516
        self.set_deploy(deploy)
F
v1.5.0  
frf12 已提交
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False

        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check deploy status')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

        db_component = None
        db_components = ['oceanbase', 'oceanbase-ce']
        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
        if opts.component is None:
            for component_name in allow_components:
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
        if opts.component not in deploy_config.components:
            self._call_stdio('error', 'Can not find the component for tpcds, use `--component` to select component')
            return False
F
v1.6.0  
frf12 已提交
3543

F
v1.5.0  
frf12 已提交
3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554
        for component_name in db_components:
            if component_name in deploy_config.components:
                db_component = component_name
        if db_component is None:
            self._call_stdio('error', 'Missing database component (%s) in deploy' % ','.join(db_components))
            return False

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        # repositories = self.get_local_repositories({opts.component: deploy_config.components[opts.component]})
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3555
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
3556 3557 3558 3559 3560 3561 3562 3563 3564 3565

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
R
Rongfeng Fu 已提交
3566
        cluster_status = self.cluster_status_check(repositories, component_status)
F
v1.5.0  
frf12 已提交
3567 3568
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
3569
                self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
F
v1.5.0  
frf12 已提交
3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
                for repository in component_status:
                    cluster_status = component_status[repository]
                    for server in cluster_status:
                        if cluster_status[server] == 0:
                            self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
            return False

        db_cluster_config =  deploy_config.components[db_component]
        cluster_config =  deploy_config.components[opts.component]

        if opts.test_server is None:
            opts.test_server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.test_server:
                    opts.test_server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.test_server, opts.component))
                return False

        check_opt_plugin = self.plugin_manager.get_best_py_script_plugin('check_opt', 'tpcds', db_cluster_config.version)
        load_data_plugin = self.plugin_manager.get_best_py_script_plugin('load_data', 'tpcds', cluster_config.version)
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'tpcds', cluster_config.version)
R
Rongfeng Fu 已提交
3594 3595 3596 3597
        repository = None
        for tmp_repository in repositories:
            if tmp_repository.name == opts.component:
                repository = tmp_repository
F
v1.5.0  
frf12 已提交
3598

R
Rongfeng Fu 已提交
3599
        if not self.call_plugin(check_opt_plugin, repository, db_cluster_config=db_cluster_config):
F
v1.5.0  
frf12 已提交
3600
            return False
R
Rongfeng Fu 已提交
3601
        if not self.call_plugin(load_data_plugin, repository):
F
v1.5.0  
frf12 已提交
3602
            return False
R
Rongfeng Fu 已提交
3603
        return self.call_plugin(run_test_plugin)
F
v1.5.0  
frf12 已提交
3604

R
Rongfeng Fu 已提交
3605 3606 3607
    def tpcc(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
3608
        self.set_deploy(deploy)
R
Rongfeng Fu 已提交
3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False

        deploy_info = deploy.deploy_info
        self._call_stdio('verbose', 'Check deploy status')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

R
Rongfeng Fu 已提交
3621
        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
R
Rongfeng Fu 已提交
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
        if opts.component is None:
            for component_name in allow_components:
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
        if opts.component not in deploy_config.components:
            self._call_stdio('error', 'Can not find the component for tpcc, use `--component` to select component')
            return False

        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.test_server is None:
            opts.test_server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.test_server:
                    opts.test_server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.test_server, opts.component))
                return False

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
F
v1.5.0  
frf12 已提交
3651
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3652
        self.set_repositories(repositories)
R
Rongfeng Fu 已提交
3653 3654 3655 3656 3657 3658 3659 3660 3661

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
F
v1.6.0  
frf12 已提交
3662 3663
        if not getattr(opts, 'skip_cluster_status_check', False):
            component_status = {}
R
Rongfeng Fu 已提交
3664
            cluster_status = self.cluster_status_check(repositories, component_status)
F
v1.6.0  
frf12 已提交
3665 3666
            if cluster_status is False or cluster_status == 0:
                if self.stdio:
R
Rongfeng Fu 已提交
3667
                    self._call_stdio('error', err.EC_SOME_SERVER_STOPED.format())
F
v1.6.0  
frf12 已提交
3668 3669 3670 3671 3672 3673
                    for repository in component_status:
                        cluster_status = component_status[repository]
                        for server in cluster_status:
                            if cluster_status[server] == 0:
                                self._call_stdio('print', '%s %s is stopped' % (server, repository.name))
                return False
R
Rongfeng Fu 已提交
3674

F
v1.5.0  
frf12 已提交
3675 3676
        ob_repository = None
        repository = None
F
v1.6.0  
frf12 已提交
3677
        odp_cursor = None
R
Rongfeng Fu 已提交
3678 3679
        proxysys_namespace = None
        connect_namespaces = []
F
v1.5.0  
frf12 已提交
3680 3681 3682 3683 3684
        for tmp_repository in repositories:
            if tmp_repository.name in ["oceanbase", "oceanbase-ce"]:
                ob_repository = tmp_repository
            if tmp_repository.name == opts.component:
                repository = tmp_repository
F
v1.6.0  
frf12 已提交
3685 3686 3687
        if not ob_repository:
            self._call_stdio('error', 'Deploy {} must contain the component oceanbase or oceanbase-ce.'.format(deploy.name))
            return False
R
Rongfeng Fu 已提交
3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706
        sys_namespace = self.get_namespace(ob_repository.name)
        connect_plugin = self.plugin_manager.get_best_py_script_plugin('connect', repository.name, repository.version)
        if repository.name in ['obproxy', 'obproxy-ce']:
            for component_name in deploy_config.components:
                if component_name in ['oceanbase', 'oceanbase-ce']:
                    ob_cluster_config = deploy_config.components[component_name]
                    sys_namespace.set_variable("connect_proxysys", False)
                    sys_namespace.set_variable("user", "root")
                    sys_namespace.set_variable("password", ob_cluster_config.get_global_conf().get('root_password', ''))
                    sys_namespace.set_variable("target_server", opts.test_server)
                    break
            proxysys_namespace = self.get_namespace(repository.name)
            proxysys_namespace.set_variable("component_name", repository)
            proxysys_namespace.set_variable("target_server", opts.test_server)
            ret = self.call_plugin(connect_plugin, repository, spacename=proxysys_namespace.spacename)
            if not ret or not ret.get_return('connect'):
                return False
            odp_db, odp_cursor = self._get_first_db_and_cursor_from_connect(proxysys_namespace)
            connect_namespaces.append(proxysys_namespace)
F
v1.5.0  
frf12 已提交
3707
        plugin_version = ob_repository.version if ob_repository else repository.version
R
Rongfeng Fu 已提交
3708
        ret = self.call_plugin(connect_plugin, repository, spacename=sys_namespace.spacename)
R
Rongfeng Fu 已提交
3709 3710
        if not ret or not ret.get_return('connect'):
            return False
R
Rongfeng Fu 已提交
3711 3712
        connect_namespaces.append(sys_namespace)
        db, cursor = self._get_first_db_and_cursor_from_connect(namespace=sys_namespace)
F
v1.5.0  
frf12 已提交
3713 3714 3715
        pre_test_plugin = self.plugin_manager.get_best_py_script_plugin('pre_test', 'tpcc', plugin_version)
        build_plugin = self.plugin_manager.get_best_py_script_plugin('build', 'tpcc', plugin_version)
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'tpcc', plugin_version)
R
Rongfeng Fu 已提交
3716 3717 3718 3719 3720 3721 3722 3723

        setattr(opts, 'host', opts.test_server.ip)
        setattr(opts, 'port', db.port)

        kwargs = {}

        optimization = getattr(opts, 'optimization', 0)
        test_only = getattr(opts, 'test_only', False)
F
v1.6.0  
frf12 已提交
3724
        optimization_inited = False
R
Rongfeng Fu 已提交
3725
        try:
R
Rongfeng Fu 已提交
3726
            ret = self.call_plugin(pre_test_plugin, repository, cursor=cursor, odp_cursor=odp_cursor, **kwargs)
R
Rongfeng Fu 已提交
3727 3728 3729 3730 3731
            if not ret:
                return False
            else:
                kwargs.update(ret.kwargs)
            if optimization:
R
Rongfeng Fu 已提交
3732
                if not self._test_optimize_init(test_name='tpcc', repository=repository):
F
v1.6.0  
frf12 已提交
3733 3734
                    return False
                optimization_inited = True
R
Rongfeng Fu 已提交
3735 3736 3737
                if not self._test_optimize_operation(repository=repository, ob_repository=ob_repository, stage='build',
                                                     connect_namespaces=connect_namespaces,
                                                     connect_plugin=connect_plugin, optimize_envs=kwargs):
R
Rongfeng Fu 已提交
3738 3739
                    return False
            if not test_only:
R
Rongfeng Fu 已提交
3740 3741 3742
                db, cursor = self._get_first_db_and_cursor_from_connect(sys_namespace)
                odp_db, odp_cursor = self._get_first_db_and_cursor_from_connect(proxysys_namespace)
                ret = self.call_plugin(build_plugin, repository,  cursor=cursor, odp_cursor=odp_cursor, **kwargs)
R
Rongfeng Fu 已提交
3743 3744 3745 3746 3747
                if not ret:
                    return False
                else:
                    kwargs.update(ret.kwargs)
            if optimization:
R
Rongfeng Fu 已提交
3748 3749 3750
                if not self._test_optimize_operation(repository=repository, ob_repository=ob_repository, stage='test',
                                                     connect_namespaces=connect_namespaces,
                                                     connect_plugin=connect_plugin, optimize_envs=kwargs):
R
Rongfeng Fu 已提交
3751
                    return False
R
Rongfeng Fu 已提交
3752 3753
            db, cursor = self._get_first_db_and_cursor_from_connect(sys_namespace)
            ret = self.call_plugin(run_test_plugin, repository, cursor=cursor, **kwargs)
R
Rongfeng Fu 已提交
3754 3755 3756 3757 3758 3759
            if not ret:
                return False
            else:
                kwargs.update(ret.kwargs)
            return True
        except Exception as e:
R
Rongfeng Fu 已提交
3760
            self._call_stdio('exception', e)
R
Rongfeng Fu 已提交
3761 3762
            return False
        finally:
F
v1.6.0  
frf12 已提交
3763
            if optimization and optimization_inited:
R
Rongfeng Fu 已提交
3764 3765 3766
                self._test_optimize_operation(repository=repository, ob_repository=ob_repository,
                                              connect_namespaces=connect_namespaces,
                                              connect_plugin=connect_plugin, optimize_envs=kwargs, operation='recover')
R
Rongfeng Fu 已提交
3767

F
v1.5.0  
frf12 已提交
3768 3769 3770 3771 3772 3773
    def db_connect(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name, read_only=True)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
R
Rongfeng Fu 已提交
3774
        self.set_deploy(deploy)
F
v1.5.0  
frf12 已提交
3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        deploy_info = deploy.deploy_info

        if deploy_info.status in (DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED):
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False

        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
        if opts.component is None:
            for component_name in allow_components:
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
        if opts.component not in deploy_config.components:
F
v1.6.0  
frf12 已提交
3793
            self._call_stdio('error', 'Can not find the component for db connect, use `--component` to select component')
F
v1.5.0  
frf12 已提交
3794
            return False
R
Rongfeng Fu 已提交
3795

F
v1.5.0  
frf12 已提交
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.server is None:
            opts.server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.server:
                    opts.server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.server, opts.component))
                return False
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
3812 3813 3814 3815 3816 3817
        repositories = self.load_local_repositories(deploy_info)
        self.set_repositories(repositories)
        repository = None
        for tmp_repository in repositories:
            if tmp_repository.name == opts.component:
                repository = tmp_repository
F
v1.6.0  
frf12 已提交
3818

F
v1.5.0  
frf12 已提交
3819 3820 3821 3822 3823
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        sync_config_plugin = self.plugin_manager.get_best_py_script_plugin('sync_cluster_config', 'general', '0.1')
R
Rongfeng Fu 已提交
3824
        self.call_plugin(sync_config_plugin, repository)
F
v1.5.0  
frf12 已提交
3825
        db_connect_plugin = self.plugin_manager.get_best_py_script_plugin('db_connect', 'general', '0.1')
R
Rongfeng Fu 已提交
3826
        return self.call_plugin(db_connect_plugin, repository)
F
v1.5.0  
frf12 已提交
3827 3828 3829 3830 3831 3832 3833

    def commands(self, name, cmd_name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name, read_only=True)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
R
Rongfeng Fu 已提交
3834
        self.set_deploy(deploy)
F
v1.5.0  
frf12 已提交
3835 3836 3837 3838 3839 3840 3841
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        deploy_info = deploy.deploy_info

        if deploy_info.status in (DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED):
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False
R
Rongfeng Fu 已提交
3842

F
v1.5.0  
frf12 已提交
3843 3844 3845
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3846 3847
        repositories = self.sort_repositories_by_depends(deploy_config, repositories)
        self.set_repositories(repositories)
F
v1.5.0  
frf12 已提交
3848 3849 3850 3851 3852 3853 3854 3855 3856
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        check_opt_plugin = self.plugin_manager.get_best_py_script_plugin('check_opt', 'commands', '0.1')
        prepare_variables_plugin = self.plugin_manager.get_best_py_script_plugin('prepare_variables', 'commands', '0.1')
        commands_plugin = self.plugin_manager.get_best_py_script_plugin('commands', 'commands', '0.1')
        sync_config_plugin = self.plugin_manager.get_best_py_script_plugin('sync_cluster_config', 'general', '0.1')

R
Rongfeng Fu 已提交
3857
        repository = repositories[0]
F
v1.5.0  
frf12 已提交
3858
        context = {}
R
Rongfeng Fu 已提交
3859 3860
        self.call_plugin(sync_config_plugin, repository)
        ret = self.call_plugin(check_opt_plugin, repository, name=cmd_name, context=context)
F
v1.5.0  
frf12 已提交
3861 3862 3863
        if not ret:
            return
        for component in context['components']:
R
Rongfeng Fu 已提交
3864 3865 3866
            for repository in repositories:
                if repository.name == component:
                    break
F
v1.5.0  
frf12 已提交
3867
            for server in context['servers']:
R
Rongfeng Fu 已提交
3868
                ret = self.call_plugin(prepare_variables_plugin, repository, name=cmd_name, component=component, server=server, context=context)
F
v1.5.0  
frf12 已提交
3869 3870 3871
                if not ret:
                    return
                if not ret.get_return("skip"):
R
Rongfeng Fu 已提交
3872
                    ret = self.call_plugin(commands_plugin, repository, context=context)
F
v1.5.0  
frf12 已提交
3873 3874 3875 3876 3877
        if context.get('interactive'):
            return bool(ret)
        results = context.get('results', [])
        self._call_stdio("print_list", results, ["Component", "Server", cmd_name.title()], title=cmd_name.title())
        return not context.get('failed')
F
v1.6.0  
frf12 已提交
3878 3879 3880 3881 3882 3883 3884

    def dooba(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name, read_only=True)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
R
Rongfeng Fu 已提交
3885
        self.set_deploy(deploy)
F
v1.6.0  
frf12 已提交
3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        deploy_info = deploy.deploy_info

        if deploy_info.status in (DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED):
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False

        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
        if opts.component is None:
            for component_name in allow_components:
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
        elif opts.component not in allow_components:
            self._call_stdio('error', '%s not support. %s is allowed' % (opts.component, allow_components))
            return False
        if opts.component not in deploy_config.components:
            self._call_stdio('error',
                             'Can not find the component for dooba, use `--component` to select component')
            return False

        for component in deploy_config.components:
            if component in ['oceanbase', 'oceanbase-ce']:
                break
        else:
            self._call_stdio('error', 'Dooba must contain the component oceanbase or oceanbase-ce.')
            return False

        cluster_config = deploy_config.components[opts.component]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % opts.component)
            return False
        if opts.server is None:
            opts.server = cluster_config.servers[0]
        else:
            for server in cluster_config.servers:
                if server.name == opts.server:
                    opts.server = server
                    break
            else:
                self._call_stdio('error', '%s is not a server in %s' % (opts.server, opts.component))
                return False
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
3932
        self.set_repositories(repositories)
F
v1.6.0  
frf12 已提交
3933
        plugin_version = None
R
Rongfeng Fu 已提交
3934
        target_repository = None
F
v1.6.0  
frf12 已提交
3935 3936 3937
        for repository in repositories:
            if repository.name in ['oceanbase', 'oceanbase-ce']:
                plugin_version = repository.version
R
Rongfeng Fu 已提交
3938 3939
            if repository.name == opts.component:
                target_repository = repository
F
v1.6.0  
frf12 已提交
3940 3941 3942 3943 3944
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
        self._call_stdio('stop_loading', 'succeed')

        sync_config_plugin = self.plugin_manager.get_best_py_script_plugin('sync_cluster_config', 'general', '0.1')
R
Rongfeng Fu 已提交
3945
        self.call_plugin(sync_config_plugin, target_repository)
F
v1.6.0  
frf12 已提交
3946
        dooba_plugin = self.plugin_manager.get_best_py_script_plugin('run', 'dooba', plugin_version)
R
Rongfeng Fu 已提交
3947
        return self.call_plugin(dooba_plugin, target_repository)
R
Rongfeng Fu 已提交
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966

    def telemetry_post(self, name):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        self.set_deploy(deploy)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False

        deploy_info = deploy.deploy_info
        if deploy_info.status in (DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED):
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False

        repositories = self.load_local_repositories(deploy_info)
        if repositories == []:
            return
        self.set_repositories(repositories)

R
Rongfeng Fu 已提交
3967 3968 3969 3970 3971 3972 3973
        telemetry_info_collect_plugin = self.plugin_manager.get_best_py_script_plugin('telemetry_info_collect', 'general', '0.1')
        for repository in repositories:
            if not self.call_plugin(telemetry_info_collect_plugin, repository, spacename='telemetry'):
                return False
            
        telemetry_post_plugin = self.plugin_manager.get_best_py_script_plugin('telemetry_post', 'general', '0.1')
        return self.call_plugin(telemetry_post_plugin, repository, spacename='telemetry')
R
Rongfeng Fu 已提交
3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156


    def obdiag_gather(self, name, gather_type, opts):
        self._global_ex_lock()
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name, read_only=True)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        self.set_deploy(deploy)
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        deploy_info = deploy.deploy_info

        if deploy_info.status in (DeployStatus.STATUS_DESTROYED, DeployStatus.STATUS_CONFIGURED):
            self._call_stdio('print', 'Deploy "%s" is %s' % (name, deploy_info.status.value))
            return False

        allow_components = []
        if gather_type.startswith("gather_obproxy"):
            allow_components = ['obproxy-ce', 'obproxy']
        else:
            allow_components = ['oceanbase-ce', 'oceanbase']

        component_name = ""
        for component in deploy_config.components:
            if component in allow_components:
                component_name = component
                break
        if component_name == "":
            self._call_stdio('error', err.EC_OBDIAG_NOT_CONTAIN_DEPEND_COMPONENT.format(components=allow_components))
            return False

        cluster_config = deploy_config.components[component_name]
        if not cluster_config.servers:
            self._call_stdio('error', '%s server list is empty' % allow_components[0])
            return False
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)
        self.set_repositories(repositories)
        self._call_stdio('stop_loading', 'succeed')
        target_repository = None
        for repository in repositories:
            if repository.name == allow_components[0]:
                target_repository = repository
        if gather_type in ['gather_plan_monitor']:
            setattr(opts, 'connect_cluster', True)          
        obdiag_path = getattr(opts, 'obdiag_dir', None) 

        diagnostic_component_name = 'oceanbase-diagnostic-tool'
        obdiag_version = '1.0'
        pre_check_plugin = self.plugin_manager.get_best_py_script_plugin('pre_check', diagnostic_component_name, obdiag_version)    
        check_pass = self.call_plugin(pre_check_plugin,
            target_repository,
            gather_type = gather_type,
            obdiag_path = obdiag_path, 
            version_check = True,
            utils_work_dir_check = True)
        if not check_pass:
            # obdiag checker return False
            if not check_pass.get_return('obdiag_found'):
                if not self._call_stdio('confirm', 'Could not find the obdiag, please confirm whether to install it' ):
                    return False
                self.obdiag_deploy(auto_deploy=True, install_prefix=obdiag_path)
            # utils checker return False
            if not check_pass.get_return('utils_status'):
                repositories_utils_map = self.get_repositories_utils(repositories)
                if repositories_utils_map is False:
                    self._call_stdio('error', 'Failed to get utils package')
                else:
                    if not self._call_stdio('confirm', 'obdiag gather clog/slog need to install ob_admin\nDo you want to install ob_admin?'):
                        if not check_pass.get_return('skip'):
                            return False
                        else:
                            self._call_stdio('warn', 'Just skip gather clog/slog')
                    else:
                        if not self.install_utils_to_servers(repositories, repositories_utils_map):
                            self._call_stdio('error', 'Failed to install utils to servers')
        obdiag_version = check_pass.get_return('obdiag_version')
        generate_config_plugin = self.plugin_manager.get_best_py_script_plugin('generate_config', diagnostic_component_name, obdiag_version)
        self.call_plugin(generate_config_plugin, target_repository, deploy_config=deploy_config)
        self._call_stdio('generate_config', 'succeed')
        obdiag_plugin = self.plugin_manager.get_best_py_script_plugin(gather_type, diagnostic_component_name, obdiag_version)
        return self.call_plugin(obdiag_plugin, target_repository)


    def obdiag_deploy(self, auto_deploy=False, install_prefix=None):
        self._global_ex_lock()
        component_name = 'oceanbase-diagnostic-tool'
        if install_prefix is None:
            install_prefix = os.path.join(os.getenv('HOME'), component_name)
        pkg = self.mirror_manager.get_best_pkg(name=component_name)
        if not pkg:
            self._call_stdio('critical', '%s package not found' % component_name)
            return False
        plugin = self.plugin_manager.get_best_plugin(PluginType.INSTALL, component_name, pkg.version)
        self._call_stdio('print', 'obdiag plugin : %s' % plugin)

        repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
        check_plugin = self.plugin_manager.get_best_py_script_plugin('pre_check', component_name, pkg.version)
        if not auto_deploy:
            ret = self.call_plugin(check_plugin,
                repository,
                clients={},
                obdiag_path = install_prefix,
                obdiag_new_version = pkg.version, 
                version_check = True)
            if not ret and ret.get_return('obdiag_found'):
                self._call_stdio('print', 'No updates detected. obdiag is already up to date.')
                return False
            if not self._call_stdio('confirm', 'Found a higher version\n%s\nDo you want to use it?' % pkg):
                return False
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        repository.load_pkg(pkg, plugin)
        src_path = os.path.join(repository.repository_dir, component_name)
        if FileUtil.symlink(src_path, install_prefix, self.stdio):
            self._call_stdio('stop_loading', 'succeed')
            self._call_stdio('print', 'Deploy obdiag successful.\nCurrent version : %s. \nPath of obdiag : %s' % (pkg.version, install_prefix))
        return True


    def get_repositories_utils(self, repositories):
        all_data = []
        data = {}
        temp_map = {}
        need_install_repositories = ['oceanbase-ce']
        for repository in repositories:
            utils_name = '%s-utils' % repository.name
            if (utils_name in data) or (repository.name not in need_install_repositories):
                continue
            data[utils_name] = {'version': repository.version}
            temp_map[utils_name] = repository
        all_data.append((data, temp_map))
        try:
            repositories_utils_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)
                    self._call_stdio('verbose', 'Search best suitable repository utils')
                    pkgs, utils_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
                    install_plugins = self.get_install_plugin_and_install(utils_repositories, pkgs)
                    if not install_plugins:
                        return False
                    for utils_repository in utils_repositories:
                        repository = temp_map[utils_repository.name]
                        install_plugin = install_plugins[utils_repository]
                        repositories_utils_map[repository] = {
                            'repositories': utils_repository,
                            'install_plugin': install_plugin
                        }
            return repositories_utils_map
        except:
            self._call_stdio('exception', 'Failed to create utils-repo config file')
            pass
        return False


    def install_utils_to_servers(self, repositories, repositories_utils_map, unuse_utils_repository=True):
        install_repo_plugin = self.plugin_manager.get_best_py_script_plugin('install_repo', 'general', '0.1')
        check_file_maps = {}
        need_install_repositories = ['oceanbase-ce']
        for repository in repositories:
            if (repository.name not in need_install_repositories):
                continue
            temp_repository = deepcopy(repository)
            temp_repository.name = '%s-utils' % repository.name
            utils_repository = repositories_utils_map[temp_repository]['repositories']
            install_plugin = repositories_utils_map[temp_repository]['install_plugin']
            check_file_map = check_file_maps[repository] = install_plugin.file_map(repository)
            ret = self.call_plugin(install_repo_plugin, repository, obd_home=self.home_path, install_repository=utils_repository,
                        install_plugin=install_plugin, check_repository=repository, check_file_map=check_file_map,
                        msg_lv='error' if unuse_utils_repository else 'warn')
            if not ret:
                return False
        return True