core.py 139.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 27 28 29 30 31 32 33 34 35 36 37
# 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 sys
import time
import fcntl
from optparse import Values

import tempfile
from subprocess import call as subprocess_call
from prettytable import PrettyTable
from halo import Halo

from ssh import SshClient, SshConfig
from tool import ConfigUtil, FileUtil, DirectoryUtil, YamlLoader
from _stdio import MsgLevel
R
Rongfeng Fu 已提交
38
from _rpm import Version
R
Rongfeng Fu 已提交
39 40
from _mirror import MirrorRepositoryManager, PackageInfo
from _plugin import PluginManager, PluginType, InstallPlugin
R
Rongfeng Fu 已提交
41
from _repository import RepositoryManager, LocalPackage, Repository
R
Rongfeng Fu 已提交
42 43 44 45 46 47
from _deploy import (
    DeployManager, DeployStatus, 
    DeployConfig, DeployConfigStatus,
    ParserError, Deploy
)
from _errno import EC_SOME_SERVER_STOPED
R
Rongfeng Fu 已提交
48
from _lock import LockManager
O
oceanbase-admin 已提交
49 50 51 52 53 54


class ObdHome(object):

    HOME_LOCK_RELATIVE_PATH = 'obd.conf'

R
Rongfeng Fu 已提交
55
    def __init__(self, home_path, dev_mode=False, stdio=None):
O
oceanbase-admin 已提交
56
        self.home_path = home_path
R
Rongfeng Fu 已提交
57
        self.dev_mode = dev_mode
O
oceanbase-admin 已提交
58 59 60 61 62 63
        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 已提交
64
        self._lock_manager = None
O
oceanbase-admin 已提交
65 66 67
        self.stdio = None
        self._stdio_func = None
        self.set_stdio(stdio)
R
Rongfeng Fu 已提交
68
        self.lock_manager.global_sh_lock()
O
oceanbase-admin 已提交
69 70 71 72

    @property
    def mirror_manager(self):
        if not self._mirror_manager:
R
Rongfeng Fu 已提交
73
            self._mirror_manager = MirrorRepositoryManager(self.home_path, self.lock_manager, self.stdio)
O
oceanbase-admin 已提交
74 75 76 77 78
        return self._mirror_manager

    @property
    def repository_manager(self):
        if not self._repository_manager:
R
Rongfeng Fu 已提交
79
            self._repository_manager = RepositoryManager(self.home_path, self.lock_manager, self.stdio)
O
oceanbase-admin 已提交
80 81 82 83 84
        return self._repository_manager

    @property
    def plugin_manager(self):
        if not self._plugin_manager:
R
Rongfeng Fu 已提交
85
            self._plugin_manager = PluginManager(self.home_path, self.dev_mode, self.stdio)
O
oceanbase-admin 已提交
86 87 88 89 90
        return self._plugin_manager

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

R
Rongfeng Fu 已提交
94 95 96 97 98 99 100 101 102
    @property
    def lock_manager(self):
        if not self._lock_manager:
            self._lock_manager = LockManager(self.home_path, self.stdio)
        return self._lock_manager

    def _obd_update_lock(self):
        self.lock_manager.global_ex_lock()

O
oceanbase-admin 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    def set_stdio(self, stdio):
        def _print(msg, *arg, **kwarg):
            sep = kwarg['sep'] if 'sep' in kwarg else None
            end = kwarg['end'] if 'end' in kwarg else None
            return print(msg, sep='' if sep is None else sep, end='\n' if end is None else end)
        self.stdio = stdio
        self._stdio_func = {}
        if not self.stdio:
            return
        for func in ['start_loading', 'stop_loading', 'print', 'confirm', 'verbose', 'warn', 'exception', 'error', 'critical', 'print_list']:
            self._stdio_func[func] = getattr(self.stdio, func, _print)

    def _call_stdio(self, func, msg, *arg, **kwarg):
        if func not in self._stdio_func:
            return None
        return self._stdio_func[func](msg, *arg, **kwarg)

    def add_mirror(self, src, opts):
        if re.match('^https?://', src):
            return self.mirror_manager.add_remote_mirror(src)
        else:
            return self.mirror_manager.add_local_mirror(src, getattr(opts, 'force', False))

    def deploy_param_check(self, repositories, deploy_config):
        # parameter check
        errors = []
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
131
            errors += cluster_config.check_param()[1]
O
oceanbase-admin 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
            for server in cluster_config.servers:
                self._call_stdio('verbose', '%s %s param check' % (server, repository))
                need_items = cluster_config.get_unconfigured_require_item(server)
                if need_items:
                    errors.append('%s %s need config: %s' % (server, repository.name, ','.join(need_items)))
        return errors

    def get_clients(self, deploy_config, repositories):
        ssh_clients = {}
        self._call_stdio('start_loading', 'Open ssh connection')
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
            # ssh check
            self.ssh_clients_connect(ssh_clients, cluster_config.servers, deploy_config.user)
        self._call_stdio('stop_loading', 'succeed')
        return ssh_clients

    def ssh_clients_connect(self, ssh_clients, servers, user_config):
        for server in servers:
            if server.ip not in ssh_clients:
                ssh_clients[server] = SshClient(
                    SshConfig(
                        server.ip,
                        user_config.username, 
                        user_config.password, 
                        user_config.key_file, 
                        user_config.port, 
                        user_config.timeout
                    ),
                    self.stdio
                )
                ssh_clients[server].connect()

    def search_plugin(self, repository, plugin_type, no_found_exit=True):
R
Rongfeng Fu 已提交
166
        self._call_stdio('verbose', 'Search %s plugin for %s' % (plugin_type.name.lower(), repository.name))
O
oceanbase-admin 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
        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 已提交
188 189 190 191 192 193
    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 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206
        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 已提交
207
                    self._call_stdio(msg_lv, 'No such %s plugin for %s-%s' % (script_name, repository.name, repository.version))
O
oceanbase-admin 已提交
208
        return plugins
R
Rongfeng Fu 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

    def search_images(self, component_name, version, release=None, disable=[], usable=[], release_first=False):
        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:
            self._call_stdio(
                'print_list',
                matchs,
                ['name', 'version', 'release', 'arch', 'md5'], 
                lambda x: [matchs[x].name, matchs[x].version, matchs[x].release, matchs[x].arch, matchs[x].md5],
                title='Search %s %s Result' % (component_name, version) 
            )
            for md5 in usable:
                if md5 in matchs:
                    self._call_stdio('verbose', 'Usable %s' % md5)
                    usable_matchs.append(matchs[md5])
            if not usable_matchs:
                usable_matchs = [info[1] for info in sorted(matchs.items())]
                if release_first:
                    usable_matchs = usable_matchs[:1]
            
        return usable_matchs
O
oceanbase-admin 已提交
243
    
R
Rongfeng Fu 已提交
244
    def search_components_from_mirrors(self, deploy_config, fuzzy_match=False, only_info=True, update_if_need=None):
O
oceanbase-admin 已提交
245 246 247 248 249 250 251 252 253 254
        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)
            repository = self.repository_manager.get_repository(component, config.version, config.package_hash if config.package_hash else config.tag)
R
Rongfeng Fu 已提交
255 256
            if repository and not repository.hash:
                repository = None
O
oceanbase-admin 已提交
257 258
            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, fuzzy_match=fuzzy_match, only_info=only_info)
R
Rongfeng Fu 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271 272
            if repository or pkg:
                if pkg:
                    self._call_stdio('verbose', 'Found Package %s-%s-%s' % (pkg.name, pkg.version, pkg.md5))
                if repository:
                    if repository >= pkg or (
                        (
                            update_if_need is None and 
                            not self._call_stdio('confirm', 'Found a higher version\n%s\nDo you want to use it?' % pkg)
                        ) or update_if_need is False
                    ):
                        repositories.append(repository)
                        self._call_stdio('verbose', 'Use repository %s' % repository)
                        self._call_stdio('print', '%s-%s already installed.' % (repository.name, repository.version))
                        continue
O
oceanbase-admin 已提交
273
                if config.version and pkg.version != config.version:
R
Rongfeng Fu 已提交
274
                    self._call_stdio('warn', 'No such package %s-%s. Use similar package %s-%s.' % (component, config.version, pkg.name, pkg.version))
O
oceanbase-admin 已提交
275
                else:
R
Rongfeng Fu 已提交
276
                    self._call_stdio('print', 'Package %s-%s is available.' % (pkg.name, pkg.version))
O
oceanbase-admin 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                repository = self.repository_manager.get_repository(pkg.name, pkg.md5)
                if repository:
                    repositories.append(repository)
                else:
                    pkgs.append(pkg)
            else:
                pkg_name = [component]
                if config.version:
                    pkg_name.append(config.version)
                if config.package_hash:
                    pkg_name.append(config.package_hash)
                elif config.tag:
                    pkg_name.append(config.tag)
                errors.append('No such package %s.' % ('-'.join(pkg_name)))
        return pkgs, repositories, errors

R
Rongfeng Fu 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    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 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352

    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
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
R
Rongfeng Fu 已提交
353 354 355 356
        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]
O
oceanbase-admin 已提交
357 358 359 360 361 362
        initial_config = ''
        if deploy:
            try:
                if deploy.deploy_info.config_status == DeployConfigStatus.UNCHNAGE:
                    path = deploy.deploy_config.yaml_path
                else:
R
Rongfeng Fu 已提交
363
                    path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
O
oceanbase-admin 已提交
364 365 366 367 368 369 370 371 372 373 374 375
                self._call_stdio('verbose', 'Load %s' % path)
                with open(path, 'r') as f:
                    initial_config = f.read()
            except:
                self._call_stdio('exception', '')
            msg = 'Save deploy "%s" configuration' % name
        else:
            if not self.stdio:
                return False
            if not self._call_stdio('confirm', 'No such deploy: %s. Create?' % name):
                return False
            msg = 'Create deploy "%s" configuration' % name
R
Rongfeng Fu 已提交
376 377
        if is_deployed:
            repositories = self.load_local_repositories(deploy.deploy_info)
R
Rongfeng Fu 已提交
378
            self._call_stdio('start_loading', 'Search param plugin and load')
R
Rongfeng Fu 已提交
379 380 381 382 383 384 385 386
            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 已提交
387 388
            self._call_stdio('stop_loading', 'succeed')

O
oceanbase-admin 已提交
389 390 391 392 393 394
        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 已提交
395
        self.lock_manager.set_try_times(-1)
R
Rongfeng Fu 已提交
396
        config_status = DeployConfigStatus.UNCHNAGE
O
oceanbase-admin 已提交
397 398 399 400 401
        while True:
            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 已提交
402 403 404 405 406 407 408
            try:
                deploy_config = DeployConfig(tf.name, yaml_loader=YamlLoader(self.stdio), config_parser_manager=self.deploy_manager.config_parser_manager)
            except Exception as e:
                if confirm(e):
                    continue
                break

O
oceanbase-admin 已提交
409 410
            self._call_stdio('verbose', 'Configure component change check')
            if not deploy_config.components:
R
Rongfeng Fu 已提交
411
                if self._call_stdio('confirm', 'Empty configuration. Continue editing?'):
O
oceanbase-admin 已提交
412 413 414 415
                    continue
                return False
            self._call_stdio('verbose', 'Information check for the configuration component.')
            if not deploy:
R
Rongfeng Fu 已提交
416
                config_status = DeployConfigStatus.UNCHNAGE
R
Rongfeng Fu 已提交
417
            elif is_deployed:
R
Rongfeng Fu 已提交
418 419
                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? '):
O
oceanbase-admin 已提交
420
                        continue
R
Rongfeng Fu 已提交
421 422 423 424 425 426 427 428 429 430
                    config_status = DeployConfigStatus.NEED_REDEPLOY
                else:
                    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.version != old_cluster_config.origin_version \
                            or new_cluster_config.package_hash != old_cluster_config.origin_package_hash \
                            or new_cluster_config.tag != old_cluster_config.origin_tag:
                            config_status = DeployConfigStatus.NEED_REDEPLOY
                            break
R
Rongfeng Fu 已提交
431
                    
O
oceanbase-admin 已提交
432 433
            # Loading the parameter plugins that are available to the application
            self._call_stdio('start_loading', 'Search param plugin and load')
R
Rongfeng Fu 已提交
434
            if not is_deployed or config_status == DeployConfigStatus.NEED_REDEPLOY:
R
Rongfeng Fu 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
                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 已提交
451
            self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
452

O
oceanbase-admin 已提交
453 454 455 456 457 458 459 460
            # 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 已提交
461

O
oceanbase-admin 已提交
462 463 464
            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 已提交
465
                self._call_stdio('print', 'Deploy "%s" config %s%s' % (name, config_status.value, deploy.effect_tip() if deploy else ''))
O
oceanbase-admin 已提交
466
                return True
R
Rongfeng Fu 已提交
467

R
Rongfeng Fu 已提交
468
            if is_deployed and config_status != DeployConfigStatus.NEED_REDEPLOY:
R
Rongfeng Fu 已提交
469
                if is_started:
R
Rongfeng Fu 已提交
470 471
                    if deploy.deploy_config.user.username != deploy_config.user.username:
                        config_status = DeployConfigStatus.NEED_RESTART
R
Rongfeng Fu 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                    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 已提交
488 489 490 491
                        self._call_stdio('print', '\n'.join(errors))
                        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 已提交
492
                            continue
R
Rongfeng Fu 已提交
493 494
                        else:
                            return False
R
Rongfeng Fu 已提交
495
                    
O
oceanbase-admin 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                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 已提交
514

O
oceanbase-admin 已提交
515 516 517 518 519
        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 已提交
520
            target_src_path = Deploy.get_temp_deploy_yaml_path(deploy.config_dir)
O
oceanbase-admin 已提交
521 522 523 524 525 526 527
            old_config_status = deploy.deploy_info.config_status
            try:
                if deploy.update_deploy_config_status(config_status):
                    FileUtil.copy(tf.name, target_src_path, self.stdio)
                ret = True
                if deploy:
                    if deploy.deploy_info.status == DeployStatus.STATUS_RUNNING or (
R
Rongfeng Fu 已提交
528
                        config_status == DeployConfigStatus.NEED_REDEPLOY and is_deployed
O
oceanbase-admin 已提交
529
                    ):
R
Rongfeng Fu 已提交
530
                        msg += deploy.effect_tip()
O
oceanbase-admin 已提交
531 532 533 534 535
            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 已提交
536

O
oceanbase-admin 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
        self._call_stdio('print', msg)
        tf.close()
        return ret

    def list_deploy(self):
        self._call_stdio('verbose', 'Get deploy list')
        deploys = self.deploy_manager.get_deploy_configs()
        if deploys:
            self._call_stdio('print_list', deploys, 
                ['Name', 'Configuration Path', 'Status (Cached)'], 
                lambda x: [x.name, x.config_dir, x.deploy_info.status.value], 
                title='Cluster List',
            )
        else:
            self._call_stdio('print', 'Local deploy is empty')
        return True

    def get_install_plugin_and_install(self, repositories, pkgs):
        # Check if the component contains the installation plugins
        install_plugins = self.search_plugins(repositories, PluginType.INSTALL)
        if install_plugins is None:
            return None
        temp = self.search_plugins(pkgs, PluginType.INSTALL)
        if temp is None:
            return None
        for pkg in temp:
            repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
            install_plugins[repository] = temp[pkg]

        # Install for local
        # self._call_stdio('print', 'install package for local ...')
        for pkg in pkgs:
            self._call_stdio('start_loading', 'install %s-%s for local' % (pkg.name, pkg.version))
            # self._call_stdio('verbose', 'install %s-%s for local' % (pkg.name, pkg.version))
            repository = self.repository_manager.create_instance_repository(pkg.name, pkg.version, pkg.md5)
            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')
R
Rongfeng Fu 已提交
577
            self._call_stdio('verbose', 'get head repository')
R
Rongfeng Fu 已提交
578
            head_repository = self.repository_manager.get_repository(pkg.name, pkg.version, pkg.name)
R
Rongfeng Fu 已提交
579
            self._call_stdio('verbose', 'head repository: %s' % head_repository)
R
Rongfeng Fu 已提交
580 581
            if repository > head_repository:
                self.repository_manager.create_tag_for_repository(repository, pkg.name, True)
O
oceanbase-admin 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
            repositories.append(repository)
        return install_plugins

    def install_lib_for_repositories(self, repositories):
        data = {}
        temp_map = {}
        for repository in repositories:
            lib_name = '%s-libs' % repository.name
            data[lib_name] = {'global': {
                'version': repository.version
            }}
            temp_map[lib_name] = repository
        try:
            with tempfile.NamedTemporaryFile(suffix=".yaml", mode='w') as tf:
                yaml_loader = YamlLoader(self.stdio)
                yaml_loader.dump(data, tf)
R
Rongfeng Fu 已提交
598
                deploy_config = DeployConfig(tf.name, yaml_loader=yaml_loader, config_parser_manager=self.deploy_manager.config_parser_manager)
O
oceanbase-admin 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
                # Look for the best suitable mirrors for the components
                self._call_stdio('verbose', 'Search best suitable repository libs')
                pkgs, lib_repositories, errors = self.search_components_from_mirrors(deploy_config, only_info=False)
                if errors:
                    self._call_stdio('error', '\n'.join(errors))
                    return False

                # Get the installation plugin and install locally
                install_plugins = self.get_install_plugin_and_install(lib_repositories, pkgs)
                if not install_plugins:
                    return False
                repositories_lib_map = {}
                for lib_repository in lib_repositories:
                    repository = temp_map[lib_repository.name]
                    install_plugin = install_plugins[lib_repository]
                    repositories_lib_map[repository] = {
                        'repositories': lib_repository,
                        'install_plugin': install_plugin
                    }
                return repositories_lib_map
        except:
            self._call_stdio('exception', 'Failed to create lib-repo config file')
            pass
        return False

    def servers_repository_install(self, ssh_clients, servers, repository, install_plugin):
        self._call_stdio('start_loading', 'Remote %s repository install' % repository)
        self._call_stdio('verbose', 'Remote %s repository integrity check' % repository)
        for server in servers:
            self._call_stdio('verbose', '%s %s repository integrity check' % (server, repository))
            client = ssh_clients[server]
R
Rongfeng Fu 已提交
630
            remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
            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 已提交
650 651 652
                if not client.put_file(file_path, remote_file_path):
                    self._call_stdio('stop_loading', 'fail')
                    return 
O
oceanbase-admin 已提交
653 654 655 656 657 658 659 660 661 662 663
            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')

    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 已提交
664
            remote_home_path = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
            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 已提交
694
                    servers_obd_home[server] = client.execute_command('echo ${OBD_HOME:-"$HOME"}/.obd').stdout.strip()
O
oceanbase-admin 已提交
695 696 697 698
                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 已提交
699 700 701
            if not self.servers_repository_install(ssh_clients, cluster_config.servers, lib_repository, install_plugin):
                ret = False
                break
O
oceanbase-admin 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
            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.
    def cluster_status_check(self, ssh_clients, deploy_config, repositories, ret_status={}):
R
Rongfeng Fu 已提交
717
        self._call_stdio('start_loading', 'Cluster status check')
O
oceanbase-admin 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
        status_plugins = self.search_py_script_plugin(repositories, 'status')
        component_status = {}
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
            self._call_stdio('verbose', 'Call %s for %s' % (status_plugins[repository], repository))
            plugin_ret = status_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
            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)
                    break
            else:
                continue
R
Rongfeng Fu 已提交
735
            self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
736 737 738 739 740 741 742 743
            return False
        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 已提交
744
                self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
745
                return False
R
Rongfeng Fu 已提交
746
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
747 748
        return status

R
Rongfeng Fu 已提交
749 750 751 752 753 754 755 756 757 758 759 760
    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 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    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 已提交
782 783 784 785 786 787
    def genconfig(self, name, opt=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        if deploy:
            deploy_info = deploy.deploy_info
            if deploy_info.status not in [DeployStatus.STATUS_CONFIGURED, DeployStatus.STATUS_DESTROYED]:
R
Rongfeng Fu 已提交
788
                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 已提交
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
                return False
            # self._call_stdio('error', 'Deploy name `%s` have been occupied.' % name)
            # return False

        config_path = getattr(opt, 'config', '')
        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)

        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        if not deploy_config:
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.')
            return False

        # Check the best suitable mirror for the components and installation plguins. Install locally
        repositories, install_plugins = self.search_components_from_mirrors_and_install(deploy_config)
        if not install_plugins or not repositories:
            return False

        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)

        # Parameter check
        errors = self.deploy_param_check(repositories, deploy_config)
        if errors:
            self._call_stdio('stop_loading', 'fail')
            self._call_stdio('error', '\n'.join(errors))
            return False
        self._call_stdio('stop_loading', 'succeed')

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

        gen_config_plugins = self.search_py_script_plugin(repositories, 'generate_config')
        
        component_num = len(repositories)
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]

            self._call_stdio('verbose', 'Call %s for %s' % (gen_config_plugins[repository], repository))
            ret = gen_config_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], opt, self.stdio, deploy_config)
            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 已提交
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    def check_for_ocp(self, name, options=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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('error', 'Deploy "%s" not RUNNING' % (name))
            return False
            
        version = getattr(options, 'version', '')
        if not version:
            self._call_stdio('error', 'Use the --version option to specify the required OCP version.')
            return False

        deploy_config = deploy.deploy_config
        components = getattr(options, 'components', '')
        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)

        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')
        
        # 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
                
            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
            
            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, '', options, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            else:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                break
            
            self._call_stdio('verbose', 'Call %s for %s' % (ocp_check[repository], repository))
            if ocp_check[repository](deploy_config.components.keys(), ssh_clients, cluster_config, '', options, self.stdio, cursor=cursor, ocp_version=version, new_cluster_config=new_cluster_config, new_clients=new_ssh_clients):
                component_num -= 1
                self._call_stdio('print', '%s Check passed.' % repository.name)
        
        return component_num == 0

    def change_deploy_config_style(self, name, options=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
            
        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:
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.')
            return False

        style = getattr(options, 'style', '')
        if not style:
            self._call_stdio('error', 'Use the --style option to specify the preferred style.')
            return False

        components = getattr(options, 'components', '')
        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', '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)
        
        self._call_stdio('stop_loading', 'fail')
        return False


O
oceanbase-admin 已提交
991 992 993 994 995 996 997 998
    def deploy_cluster(self, name, opt=Values()):
        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 已提交
999
                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 已提交
1000 1001 1002 1003 1004 1005 1006 1007 1008
                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
        
        config_path = getattr(opt, 'config', '')
        unuse_lib_repo = getattr(opt, 'unuselibrepo', False)
R
Rongfeng Fu 已提交
1009
        auto_create_tenant = getattr(opt, 'auto_create_tenant', False)
O
oceanbase-admin 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        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
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s. you can input configuration path to create a new deploy' % name)
            return False

        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config
        if not deploy_config:
            self._call_stdio('error', 'Deploy configuration is empty.\nIt may be caused by a failure to resolve the configuration.\nPlease check your configuration file.')
            return False

        if not deploy_config.components:
            self._call_stdio('error', 'Components not detected.\nPlease check the syntax of your configuration file.')
            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

R
Rongfeng Fu 已提交
1036 1037
        # Check the best suitable mirror for the components and installation plguins. Install locally
        repositories, install_plugins = self.search_components_from_mirrors_and_install(deploy_config)
O
oceanbase-admin 已提交
1038 1039 1040
        if not install_plugins:
            return False

R
Rongfeng Fu 已提交
1041 1042 1043 1044 1045 1046 1047
        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 已提交
1048 1049

        errors = []
R
Rongfeng Fu 已提交
1050
        self._call_stdio('start_loading', 'Repository integrity check')
O
oceanbase-admin 已提交
1051 1052 1053 1054
        for repository in repositories:
            if not repository.file_check(install_plugins[repository]):
                errors.append('%s intstall failed' % repository.name)
        if errors:
R
Rongfeng Fu 已提交
1055
            self._call_stdio('stop_loading', 'fail')
O
oceanbase-admin 已提交
1056 1057
            self._call_stdio('error', '\n'.join(errors))
            return False
R
Rongfeng Fu 已提交
1058
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1059

R
Rongfeng Fu 已提交
1060
        self._call_stdio('start_loading', 'Parameter check')
O
oceanbase-admin 已提交
1061 1062 1063 1064 1065 1066 1067
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)

        # Parameter check
        self._call_stdio('verbose', 'Cluster param configuration check')
        errors = self.deploy_param_check(repositories, deploy_config)
        if errors:
R
Rongfeng Fu 已提交
1068
            self._call_stdio('stop_loading', 'fail')
O
oceanbase-admin 已提交
1069 1070
            self._call_stdio('error', '\n'.join(errors))
            return False
R
Rongfeng Fu 已提交
1071
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1072 1073 1074
        
        if unuse_lib_repo and not deploy_config.unuse_lib_repository:
            deploy_config.set_unuse_lib_repository(True)
R
Rongfeng Fu 已提交
1075 1076
        if auto_create_tenant and not deploy_config.auto_create_tenant:
            deploy_config.set_auto_create_tenant(True)
O
oceanbase-admin 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085
        
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        need_lib_repositories = []
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
            # cluster files check
            self.servers_repository_install(ssh_clients, cluster_config.servers, repository, install_plugins[repository])
R
Rongfeng Fu 已提交
1086
            # lib check 
O
oceanbase-admin 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
            msg_lv = 'error' if deploy_config.unuse_lib_repository else 'warn'
            if not self.servers_repository_lib_check(ssh_clients, cluster_config.servers, repository, install_plugins[repository], msg_lv):
                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
            if self.servers_apply_lib_repository_and_check(ssh_clients, deploy_config, need_lib_repositories, repositories_lib_map):
                self._call_stdio('error', 'Failed to install lib package for cluster servers')
                return False

        # Check the status for the deployed cluster
        component_status = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        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')
R
Rongfeng Fu 已提交
1118
        init_plugins = self.search_py_script_plugin(repositories, 'init')
O
oceanbase-admin 已提交
1119 1120 1121
        component_num = len(repositories)
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
1122 1123 1124 1125 1126 1127
            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))
            if init_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opt, self.stdio, self.home_path, repository.repository_dir):
                deploy.use_model(repository.name, repository, False)
                component_num -= 1
O
oceanbase-admin 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
        
        if component_num == 0 and deploy.update_deploy_status(DeployStatus.STATUS_DEPLOYED):
            self._call_stdio('print', '%s deployed' % name)
            return True
        return False

    def start_cluster(self, name, cmd=[], options=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
1150
        if deploy_info.config_status != DeployConfigStatus.UNCHNAGE and not getattr(options, 'without_parameter', False):
R
Rongfeng Fu 已提交
1151 1152
            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 已提交
1153 1154 1155 1156

        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

R
Rongfeng Fu 已提交
1157 1158 1159
        update_deploy_status = True
        components = getattr(options, 'components', '')
        if components:
R
Rongfeng Fu 已提交
1160 1161 1162 1163 1164 1165
            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 已提交
1166
                update_deploy_status = False
R
Rongfeng Fu 已提交
1167 1168
        else:
            components = deploy_info.components.keys()
R
Rongfeng Fu 已提交
1169 1170 1171 1172

        servers = getattr(options, 'servers', '')
        server_list = servers.split(',') if servers else []

O
oceanbase-admin 已提交
1173 1174 1175
        self._call_stdio('start_loading', 'Get local repositories and plugins')

        # Get the repository
R
Rongfeng Fu 已提交
1176
        repositories = self.load_local_repositories(deploy_info, False)
O
oceanbase-admin 已提交
1177

R
Rongfeng Fu 已提交
1178 1179
        start_check_plugins = self.search_py_script_plugin(repositories, 'start_check', no_found_act='warn')
        create_tenant_plugins = self.search_py_script_plugin(repositories, 'create_tenant', no_found_act='ignore') if deploy_config.auto_create_tenant else {}
R
Rongfeng Fu 已提交
1180 1181 1182 1183 1184 1185
        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 已提交
1186 1187 1188
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

R
Rongfeng Fu 已提交
1189
        self._call_stdio('start_loading', 'Load cluster param plugin')
R
Rongfeng Fu 已提交
1190 1191
        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
1192
        self._call_stdio('stop_loading', 'succeed')
R
Rongfeng Fu 已提交
1193

O
oceanbase-admin 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        # Check the status for the deployed cluster
        component_status = {}
        if DeployStatus.STATUS_RUNNING == deploy_info.status:
            cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
            if cluster_status == 1:
                self._call_stdio('print', 'Deploy "%s" is running' % name)
                return True

        strict_check = getattr(options, 'strict_check', False)
        success = True
        for repository in repositories:
R
Rongfeng Fu 已提交
1205 1206
            if repository.name not in components:
                continue
O
oceanbase-admin 已提交
1207 1208 1209 1210
            if repository not in start_check_plugins:
                continue
            cluster_config = deploy_config.components[repository.name]
            self._call_stdio('verbose', 'Call %s for %s' % (start_check_plugins[repository], repository))
R
Rongfeng Fu 已提交
1211
            ret = start_check_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, cmd, options, self.stdio, strict_check=strict_check)
O
oceanbase-admin 已提交
1212 1213 1214
            if not ret:
                success = False
        
R
Rongfeng Fu 已提交
1215
        if success is False:
O
oceanbase-admin 已提交
1216 1217 1218
            # 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 已提交
1219
        component_num = len(components)
O
oceanbase-admin 已提交
1220
        for repository in repositories:
R
Rongfeng Fu 已提交
1221 1222
            if repository.name not in components:
                continue
O
oceanbase-admin 已提交
1223
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
1224 1225 1226
            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 已提交
1227 1228 1229
            if not cluster_config.servers:
                component_num -= 1
                continue
R
Rongfeng Fu 已提交
1230 1231
            start_all = cluster_servers == cluster_config.servers
            update_deploy_status = update_deploy_status and start_all
O
oceanbase-admin 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249

            self._call_stdio('verbose', 'Call %s for %s' % (start_plugins[repository], repository))
            ret = start_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, cmd, options, self.stdio, self.home_path, repository.repository_dir)
            if ret:
                need_bootstrap = ret.get_return('need_bootstrap')
            else:
                self._call_stdio('error', '%s start failed' % repository.name)
                break

            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, cmd, options, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            else:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                break

R
Rongfeng Fu 已提交
1250
            if need_bootstrap and start_all:
O
oceanbase-admin 已提交
1251 1252 1253
                self._call_stdio('print', 'Initialize cluster')
                self._call_stdio('verbose', 'Call %s for %s' % (bootstrap_plugins[repository], repository))
                if not bootstrap_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, cmd, options, self.stdio, cursor):
R
Rongfeng Fu 已提交
1254
                    self._call_stdio('error', 'Cluster init failed')
O
oceanbase-admin 已提交
1255
                    break
R
Rongfeng Fu 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264
                if repository in create_tenant_plugins:
                    create_tenant_options = Values({"variables": "ob_tcp_invited_nodes='%'"})
                    self._call_stdio('verbose', 'Call %s for %s' % (bootstrap_plugins[repository], repository))
                    create_tenant_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], create_tenant_options, self.stdio, cursor)

            if not start_all:
                component_num -= 1
                continue

O
oceanbase-admin 已提交
1265 1266 1267 1268 1269
            self._call_stdio('verbose', 'Call %s for %s' % (display_plugins[repository], repository))
            if display_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, cmd, options, self.stdio, cursor):
                component_num -= 1
        
        if component_num == 0:
R
Rongfeng Fu 已提交
1270 1271 1272 1273 1274 1275 1276
            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 已提交
1277 1278 1279
                return True
        return False

R
Rongfeng Fu 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    def create_tenant(self, name, options=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
1297
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1298 1299 1300 1301 1302

        # 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 已提交
1303
        create_tenant_plugins = self.search_py_script_plugin(repositories, 'create_tenant', no_found_act='ignore')
R
Rongfeng Fu 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
        self._call_stdio('stop_loading', 'succeed')

        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)
            
        for repository in create_tenant_plugins:
            cluster_config = deploy_config.components[repository.name]
            db = None
            cursor = None
            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                return False

            self._call_stdio('verbose', 'Call %s for %s' % (create_tenant_plugins[repository], repository))
            if not create_tenant_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], options, self.stdio, cursor):
                return False
        return True

    def drop_tenant(self, name, options=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
1344
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
1345 1346 1347 1348 1349

        # 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 已提交
1350
        drop_tenant_plugins = self.search_py_script_plugin(repositories, 'drop_tenant', no_found_act='ignore')
R
Rongfeng Fu 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        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
            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                return False

            self._call_stdio('verbose', 'Call %s for %s' % (drop_tenant_plugins[repository], repository))
            if not drop_tenant_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], options, self.stdio, cursor):
                return False
        return True

O
oceanbase-admin 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    def reload_cluster(self, name):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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')
        if deploy_info.status != DeployStatus.STATUS_RUNNING:
R
Rongfeng Fu 已提交
1384
            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 已提交
1385 1386
            return False

R
Rongfeng Fu 已提交
1387 1388 1389
        if deploy_info.config_status == DeployConfigStatus.UNCHNAGE:
            self._call_stdio('print', 'Deploy config is UNCHNAGE')
            return True
O
oceanbase-admin 已提交
1390

R
Rongfeng Fu 已提交
1391 1392 1393 1394 1395 1396 1397 1398
        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 已提交
1399 1400
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config
R
Rongfeng Fu 已提交
1401
        self._call_stdio('verbose', 'Get new deploy config')
R
Rongfeng Fu 已提交
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
        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 已提交
1412 1413 1414

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1415
        repositories = self.load_local_repositories(deploy_info)
O
oceanbase-admin 已提交
1416 1417 1418 1419 1420 1421

        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 已提交
1422 1423 1424 1425 1426 1427
        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 已提交
1428 1429 1430 1431 1432 1433 1434 1435
        # Get the client
        ssh_clients = self.get_clients(deploy_config, repositories)

        # Check the status for the deployed cluster
        component_status = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
1436
                self._call_stdio('error', EC_SOME_SERVER_STOPED)
O
oceanbase-admin 已提交
1437 1438 1439 1440 1441 1442 1443
                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 已提交
1444
        repositories = self.sort_repositories_by_depends(deploy_config, repositories)
O
oceanbase-admin 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        component_num = len(repositories)
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]
            new_cluster_config = new_deploy_config.components[repository.name]

            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            else:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                continue

            self._call_stdio('verbose', 'Call %s for %s' % (reload_plugins[repository], repository))
R
Rongfeng Fu 已提交
1460 1461 1462
            if not reload_plugins[repository](
                deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, 
                cursor=cursor, new_cluster_config=new_cluster_config, repository_dir=repository.repository_dir):
O
oceanbase-admin 已提交
1463 1464 1465 1466
                continue
            component_num -= 1
        if component_num == 0:
            if deploy.apply_temp_deploy_config():
R
Rongfeng Fu 已提交
1467
                self._call_stdio('print', '%s reload' % deploy.name)
O
oceanbase-admin 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
                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)
        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 已提交
1491
        repositories = self.load_local_repositories(deploy_info)
O
oceanbase-admin 已提交
1492 1493 1494 1495 1496 1497

        # 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 已提交
1498
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1499 1500 1501 1502 1503 1504 1505 1506 1507

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

        # Check the status for the deployed cluster
        component_status = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
1508
                self._call_stdio('error', EC_SOME_SERVER_STOPED)
O
oceanbase-admin 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
                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
            
        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]

            db = None
            cursor = None
            self._call_stdio('verbose', 'Call %s for %s' % (connect_plugins[repository], repository))
            ret = connect_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
            if ret:
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
            if not db:
                self._call_stdio('error', 'Failed to connect %s' % repository.name)
                return False

            self._call_stdio('verbose', 'Call %s for %s' % (display_plugins[repository], repository))
            display_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, cursor)
        return True

R
Rongfeng Fu 已提交
1534
    def stop_cluster(self, name, options=Values()):
O
oceanbase-admin 已提交
1535 1536 1537 1538 1539 1540 1541 1542
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
1543 1544 1545 1546
        status = [DeployStatus.STATUS_DEPLOYED, DeployStatus.STATUS_STOPPED, DeployStatus.STATUS_RUNNING]
        if getattr(options, 'force', False):
            status.append(DeployStatus.STATUS_UPRADEING)
        if deploy_info.status not in status:
O
oceanbase-admin 已提交
1547 1548 1549 1550 1551
            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
        self._call_stdio('verbose', 'Get deploy config')
        deploy_config = deploy.deploy_config

R
Rongfeng Fu 已提交
1552 1553 1554
        update_deploy_status = True
        components = getattr(options, 'components', '')
        if components:
R
Rongfeng Fu 已提交
1555 1556 1557 1558 1559 1560
            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 已提交
1561
                update_deploy_status = False
R
Rongfeng Fu 已提交
1562 1563
        else:
            components = deploy_info.components.keys()
R
Rongfeng Fu 已提交
1564 1565 1566 1567

        servers = getattr(options, 'servers', '')
        server_list = servers.split(',') if servers else []

O
oceanbase-admin 已提交
1568 1569
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1570
        repositories = self.load_local_repositories(deploy_info)
O
oceanbase-admin 已提交
1571 1572 1573 1574 1575 1576

        # 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 已提交
1577
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1578 1579 1580 1581

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

R
Rongfeng Fu 已提交
1582
        component_num = len(components)
O
oceanbase-admin 已提交
1583
        for repository in repositories:
R
Rongfeng Fu 已提交
1584 1585
            if repository.name not in components:
                continue
O
oceanbase-admin 已提交
1586
            cluster_config = deploy_config.components[repository.name]
R
Rongfeng Fu 已提交
1587 1588 1589
            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 已提交
1590 1591 1592 1593
            if not cluster_config.servers:
                component_num -= 1
                continue

R
Rongfeng Fu 已提交
1594 1595 1596
            start_all = cluster_servers == cluster_config.servers
            update_deploy_status = update_deploy_status and start_all

O
oceanbase-admin 已提交
1597 1598 1599 1600
            self._call_stdio('verbose', 'Call %s for %s' % (stop_plugins[repository], repository))
            if stop_plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio):
                component_num -= 1
        
R
Rongfeng Fu 已提交
1601
        if component_num == 0:
R
Rongfeng Fu 已提交
1602
            if len(components) != len(repositories) or servers:
R
Rongfeng Fu 已提交
1603 1604 1605 1606 1607 1608 1609
                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 已提交
1610 1611
        return False

R
Rongfeng Fu 已提交
1612
    def restart_cluster(self, name, options=Values()):
O
oceanbase-admin 已提交
1613 1614 1615 1616 1617 1618 1619
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        if not deploy:
            self._call_stdio('error', 'No such deploy: %s.' % name)
            return False
        
        deploy_info = deploy.deploy_info
R
Rongfeng Fu 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
        if deploy_info.config_status == DeployConfigStatus.NEED_REDEPLOY:
            self._call_stdio('error', 'Deploy needs redeploy')
            return False

        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)

        restart_plugins = self.search_py_script_plugin(repositories, 'restart')
        reload_plugins = self.search_py_script_plugin(repositories, 'reload')
        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 已提交
1635
        bootstrap_plugins = self.search_py_script_plugin(repositories, 'bootstrap')
R
Rongfeng Fu 已提交
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

        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 getattr(options, 'without_parameter', False) is False and deploy_info.config_status != DeployConfigStatus.UNCHNAGE:
            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')

        update_deploy_status = True 
        components = getattr(options, 'components', '')
        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()

        servers = getattr(options, 'servers', '')
        if servers:
            server_list = servers.split(',') 
            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 = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
                self._call_stdio('error', 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

        done_repositories = []
        cluster_configs = {}
        component_num = len(components)
        repositories = self.sort_repositories_by_depends(deploy_config, repositories)
        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

            self._call_stdio('verbose', 'Call %s for %s' % (restart_plugins[repository], repository))
            if restart_plugins[repository](
                deploy_config.components.keys(), ssh_clients, cluster_config, [], options, self.stdio,
                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],
                repository=repository, 
                new_cluster_config=new_cluster_config, 
                new_clients=new_ssh_clients
            ):
                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
        
        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]

                self._call_stdio('verbose', 'Call %s for %s' % (restart_plugins[repository], repository))
                if restart_plugins[repository](
                    deploy_config.components.keys(), ssh_clients, cluster_config, [], options, self.stdio,
                    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],
                    repository=repository, 
                    new_cluster_config=new_cluster_config, 
                    new_clients=new_ssh_clients,
R
Rongfeng Fu 已提交
1783 1784
                    rollback=True,
                    bootstrap_plugin=bootstrap_plugins[repository],
R
Rongfeng Fu 已提交
1785 1786 1787 1788 1789
                ):
                    deploy_config.update_component(cluster_config)

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

R
Rongfeng Fu 已提交
1791 1792
    def redeploy_cluster(self, name, opt=Values()):
        return self.destroy_cluster(name, opt) and self.deploy_cluster(name) and self.start_cluster(name)
O
oceanbase-admin 已提交
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

    def destroy_cluster(self, name, opt=Values()):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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')
R
Rongfeng Fu 已提交
1803 1804
        if deploy_info.status in [DeployStatus.STATUS_RUNNING, DeployStatus.STATUS_UPRADEING]:
            if not self.stop_cluster(name, Values({'force': True})):
O
oceanbase-admin 已提交
1805 1806 1807 1808 1809 1810 1811 1812 1813
                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
        self._call_stdio('verbose', 'Get deploy configuration')
        deploy_config = deploy.deploy_config

        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
R
Rongfeng Fu 已提交
1814
        repositories = self.load_local_repositories(deploy_info)
O
oceanbase-admin 已提交
1815 1816 1817 1818 1819

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

        plugins = self.search_py_script_plugin(repositories, 'destroy')
R
Rongfeng Fu 已提交
1820
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
1821 1822 1823 1824 1825 1826 1827 1828

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

        # Check the status for the deployed cluster
        component_status = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 1:
R
Rongfeng Fu 已提交
1829
            if getattr(opt, 'force_kill', False):
O
oceanbase-admin 已提交
1830 1831 1832 1833 1834 1835 1836 1837
                self._call_stdio('verbose', 'Try to stop cluster')
                status = deploy.deploy_info.status
                deploy.update_deploy_status(DeployStatus.STATUS_RUNNING)
                if not self.stop_cluster(name):
                    deploy.update_deploy_status(status)
                    self._call_stdio('error', 'Fail to stop cluster')
                    return False
            else:
R
Rongfeng Fu 已提交
1838 1839 1840 1841 1842 1843 1844
                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 已提交
1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
                return False

        for repository in repositories:
            cluster_config = deploy_config.components[repository.name]

            self._call_stdio('verbose', 'Call %s for %s' % (plugins[repository], repository))
            plugins[repository](deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
        
        self._call_stdio('verbose', 'Set %s deploy status to destroyed' % name)
        if deploy.update_deploy_status(DeployStatus.STATUS_DESTROYED):
            self._call_stdio('print', '%s destroyed' % name)
            return True
        return False

R
Rongfeng Fu 已提交
1859
    def upgrade_cluster(self, name, options=Values()):
R
Rongfeng Fu 已提交
1860 1861 1862 1863 1864 1865 1866 1867
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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')
R
Rongfeng Fu 已提交
1868 1869
        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 已提交
1870
            return False
R
Rongfeng Fu 已提交
1871 1872
        
        deploy_config = deploy.deploy_config
R
Rongfeng Fu 已提交
1873

R
Rongfeng Fu 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
        self._call_stdio('start_loading', 'Get local repositories and plugins')
        # Get the repository
        repositories = self.load_local_repositories(deploy_info)

        # 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:
            component = getattr(options, 'component')
            version = getattr(options, 'version')
            usable = getattr(options, 'usable', '')
            disable = getattr(options, 'disable', '')

            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 已提交
1895 1896 1897
                for component in deploy_info.components:
                    break
                if not component:
R
Rongfeng Fu 已提交
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
                    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 已提交
1910 1911
                return False

R
Rongfeng Fu 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
            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,
                    ['name', 'version', 'release', 'arch', 'md5'], 
                    lambda x: [x.name, x.version, x.release, x.arch, x.md5],
                    title='%s %s Candidates' % (component, version) 
                )
                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 已提交
1939
            else:
R
Rongfeng Fu 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
                repositories = []
                pkg = self.mirror_manager.get_exact_pkg(name=images[0].name, md5=images[0].md5)
                pkgs = [pkg]
                
            install_plugins = self.get_install_plugin_and_install(repositories, pkgs)
            if not install_plugins:
                return False
            
            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]

            route = []
            use_images = []
R
Rongfeng Fu 已提交
1962
            upgrade_route_plugins = self.search_py_script_plugin([current_repository], 'upgrade_route', no_found_act='warn')
R
Rongfeng Fu 已提交
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
            if current_repository in upgrade_route_plugins:
                ret = upgrade_route_plugins[current_repository](deploy_config.components.keys(), ssh_clients, cluster_config, {}, options, self.stdio, current_repository, dest_repository)
                route = ret.get_return('route')
                if not route:
                    return False
                for node in route[1: -1]:
                    images = self.search_images(component, version=node.get('version'), release=node.get('release'), disable=disable, usable=usable, release_first=True)
                    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,
                            ['name', 'version', 'release', 'arch', 'md5'], 
                            lambda x: [x.name, x.version, x.release, x.arch, x.md5],
                            title='%s %s Candidates' % (component, version) 
                        )
                        self._call_stdio('error', 'Too many match')
                        return False
                    use_images.append(images[0])
            else:
                use_images = []

            pkgs = []
            repositories = []
            for image in use_images:
                if isinstance(image, Repository):
                    pkg = self.mirror_manager.get_exact_pkg(name=image.name, md5=image.md5)
                    if pkg:
                        pkgs.append(pkg)
                    else:
                        repositories.append(image)
                else:
                    pkgs.append(image)

            if pkgs:
                install_plugins = self.get_install_plugin_and_install(repositories, pkgs)
                if not install_plugins:
                    return False
R
Rongfeng Fu 已提交
2003

R
Rongfeng Fu 已提交
2004 2005 2006 2007 2008 2009 2010
            upgrade_repositories = [current_repository]
            for image in use_images:
                upgrade_repositories.append(self.repository_manager.get_repository(image.name, version=image.version, tag=image.md5))
            upgrade_repositories.append(dest_repository)

            install_plugins = self.get_install_plugin_and_install(upgrade_repositories, [])
            if not install_plugins:
R
Rongfeng Fu 已提交
2011 2012
                return False

R
Rongfeng Fu 已提交
2013
            upgrade_check_plugins = self.search_py_script_plugin(upgrade_repositories, 'upgrade_check', no_found_act='warn')
R
Rongfeng Fu 已提交
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036
            if current_repository in upgrade_check_plugins:
                connect_plugin = self.search_py_script_plugin(upgrade_repositories, 'connect')[current_repository]
                db = None
                cursor = None
                self._call_stdio('verbose', 'Call %s for %s' % (connect_plugin, current_repository))
                ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio)
                if ret:
                    db = ret.get_return('connect')
                    cursor = ret.get_return('cursor')
                if not db:
                    self._call_stdio('error', 'Failed to connect %s' % current_repository.name)
                    return False
                self._call_stdio('verbose', 'Call %s for %s' % (upgrade_check_plugins[current_repository], current_repository))
                if not upgrade_check_plugins[current_repository](
                    deploy_config.components.keys(), ssh_clients, cluster_config, {}, options, self.stdio, 
                    current_repository=current_repository,
                    repositories=upgrade_repositories,
                    route=route,
                    cursor=cursor
                    ):
                    return False
                cursor.close()
                db.close()
R
Rongfeng Fu 已提交
2037

R
Rongfeng Fu 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
            self._call_stdio(
                'print_list',
                upgrade_repositories,
                ['name', 'version', 'release', 'arch', 'md5', 'mark'], 
                lambda x: [x.name, x.version, x.release, x.arch, x.md5, 'start' if x == current_repository else 'dest' if x == dest_repository else ''],
                title='Packages Will Be Used' 
            )
                    
            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 = {
                'route': route, 
                '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]
R
Rongfeng Fu 已提交
2074
        
R
Rongfeng Fu 已提交
2075 2076 2077
            install_plugins = self.get_install_plugin_and_install(upgrade_repositories, [])
            if not install_plugins:
                return False
R
Rongfeng Fu 已提交
2078 2079

        need_lib_repositories = []
R
Rongfeng Fu 已提交
2080
        for repository in upgrade_repositories[1:]:
R
Rongfeng Fu 已提交
2081 2082 2083 2084
            cluster_config = deploy_config.components[repository.name]
            # cluster files check
            self.servers_repository_install(ssh_clients, cluster_config.servers, repository, install_plugins[repository])
            # lib check
R
Rongfeng Fu 已提交
2085
            if not self.servers_repository_lib_check(ssh_clients, cluster_config.servers, repository, install_plugins[repository], 'warn'):
R
Rongfeng Fu 已提交
2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
                need_lib_repositories.append(repository)

        if need_lib_repositories:
            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
            if self.servers_apply_lib_repository_and_check(ssh_clients, deploy_config, need_lib_repositories, repositories_lib_map):
                self._call_stdio('error', 'Failed to install lib package for cluster servers')
                return False

R
Rongfeng Fu 已提交
2098 2099 2100 2101 2102
        n = len(upgrade_repositories)
        while upgrade_ctx['index'] < n:
            repository = upgrade_repositories[upgrade_ctx['index'] - 1]
            repositories = [repository]
            upgrade_plugin = self.search_py_script_plugin(repositories, 'upgrade')[repository]
R
Rongfeng Fu 已提交
2103

R
Rongfeng Fu 已提交
2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
            ret = upgrade_plugin(
                    deploy_config.components.keys(), ssh_clients, cluster_config, [], options, self.stdio,
                    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
                )
            deploy.update_upgrade_ctx(**upgrade_ctx)
            if not ret:
                return False
R
Rongfeng Fu 已提交
2116

R
Rongfeng Fu 已提交
2117
        deploy.stop_upgrade(dest_repository)
R
Rongfeng Fu 已提交
2118

R
Rongfeng Fu 已提交
2119
        return True
R
Rongfeng Fu 已提交
2120

O
oceanbase-admin 已提交
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
    def create_repository(self, options):
        force = getattr(options, 'force', False)
        necessary = ['name', 'version', 'path']
        attrs = options.__dict__
        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 已提交
2142 2143
        info = PackageInfo(name=attrs['name'], version=attrs['version'], release=None, arch=None, md5=None)
        for item in plugin.file_list(info):
O
oceanbase-admin 已提交
2144 2145 2146 2147 2148 2149
            path = os.path.join(repo_path, item.src_path)
            path = os.path.normcase(path)
            if not os.path.exists(path):
                path = os.path.join(repo_path, item.target_path)
                path = os.path.normcase(path)
                if not os.path.exists(path):
R
Rongfeng Fu 已提交
2150
                    self._call_stdio('error', 'need %s: %s ' % ('dir' if item.type == InstallPlugin.FileItemType.DIR else 'file', path))
O
oceanbase-admin 已提交
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 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 2190 2191 2192 2193 2194 2195 2196 2197 2198
                    success = False
                    continue
            files[item.src_path] = path
        if success is False:
            return False

        self._call_stdio('start_loading', 'Package')
        try:
            pkg = LocalPackage(repo_path, attrs['name'], attrs['version'], files, getattr(options, 'release', None), getattr(options, 'arch', None))
            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

    def mysqltest(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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

        if opts.component is None:
R
Rongfeng Fu 已提交
2199
            for component_name in ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']:
O
oceanbase-admin 已提交
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
                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
        repositories = self.get_local_repositories({opts.component: deploy_config.components[opts.component]})
        repository = repositories[0]

        # Check whether the components have the parameter plugins and apply the plugins
        self.search_param_plugin_and_apply(repositories, deploy_config)
R
Rongfeng Fu 已提交
2237
        self._call_stdio('stop_loading', 'succeed')
O
oceanbase-admin 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246

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

        # Check the status for the deployed cluster
        component_status = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
2247
                self._call_stdio('error', EC_SOME_SERVER_STOPED)
O
oceanbase-admin 已提交
2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
                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

        connect_plugin = self.search_py_script_plugin(repositories, 'connect')[repository]
        ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, target_server=opts.test_server, sys_root=False)
        if not ret or not ret.get_return('connect'):
            self._call_stdio('error', 'Failed to connect to the server')
            return False
        db = ret.get_return('connect')
        cursor = ret.get_return('cursor')

        mysqltest_init_plugin = self.plugin_manager.get_best_py_script_plugin('init', 'mysqltest', repository.version)
        mysqltest_check_opt_plugin = self.plugin_manager.get_best_py_script_plugin('check_opt', 'mysqltest', repository.version)
        mysqltest_check_test_plugin = self.plugin_manager.get_best_py_script_plugin('check_test', 'mysqltest', repository.version)
        mysqltest_run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'mysqltest', repository.version)

        env = opts.__dict__
        env['cursor'] = cursor
        env['host'] = opts.test_server.ip
        env['port'] = db.port
        self._call_stdio('verbose', 'Call %s for %s' % (mysqltest_check_opt_plugin, repository))
        ret = mysqltest_check_opt_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, env)
        if not ret:
            return False
        self._call_stdio('verbose', 'Call %s for %s' % (mysqltest_check_test_plugin, repository))
        ret = mysqltest_check_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, env)
        if not ret:
            self._call_stdio('error', 'Failed to get test set')
            return False
        if not env['test_set']:
            self._call_stdio('error', 'Test set is empty')
            return False

        if env['need_init']:
            self._call_stdio('verbose', 'Call %s for %s' % (mysqltest_init_plugin, repository))
            if not mysqltest_init_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, env):
                self._call_stdio('error', 'Failed to init for mysqltest')
                return False
        
        result = []
        for test in env['test_set']:
R
Rongfeng Fu 已提交
2293
            self._call_stdio('verbose', 'Call %s for %s' % (mysqltest_run_test_plugin, repository))
O
oceanbase-admin 已提交
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
            ret = mysqltest_run_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, test, env)
            if not ret:
                break
            case_result = ret.get_return('result')
            if case_result['ret'] != 0 and opts.auto_retry:
                cursor.close()
                db.close()
                if getattr(self.stdio, 'sub_io'):
                    stdio = self.stdio.sub_io(msg_lv=MsgLevel.ERROR)
                else:
                    stdio = None
                self._call_stdio('start_loading', 'Reboot')
R
Rongfeng Fu 已提交
2306
                obd = ObdHome(self.home_path, self.dev_mode, stdio=stdio)
R
Rongfeng Fu 已提交
2307
                obd.lock_manager.set_try_times(-1)
O
oceanbase-admin 已提交
2308 2309 2310 2311 2312 2313
                if obd.redeploy_cluster(name):
                    self._call_stdio('stop_loading', 'succeed')
                else:
                    self._call_stdio('stop_loading', 'fail')
                    result.append(case_result)
                    break
R
Rongfeng Fu 已提交
2314 2315
                obd.lock_manager.set_try_times(6000)
                obd = None
O
oceanbase-admin 已提交
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
                connect_plugin = self.search_py_script_plugin(repositories, 'connect')[repository]
                ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, target_server=opts.test_server, sys_root=False)
                if not ret or not ret.get_return('connect'):
                    self._call_stdio('error', 'Failed to connect server')
                    break
                db = ret.get_return('connect')
                cursor = ret.get_return('cursor')
                env['cursor'] = cursor
                self._call_stdio('verbose', 'Call %s for %s' % (mysqltest_init_plugin, repository))
                if not mysqltest_init_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, env):
                    self._call_stdio('error', 'Failed to prepare for mysqltest')
                    break
                ret = mysqltest_run_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, test, env)
                if not ret:
                    break
                case_result = ret.get_return('result')

            result.append(case_result)

        passcnt = len(list(filter(lambda x: x["ret"] == 0, result)))
        totalcnt = len(env['test_set'])
        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'}
            )
        if failcnt:
            self._call_stdio('print', 'Mysqltest failed')
        else:
            self._call_stdio('print', 'Mysqltest passed')
            return True
        return False
R
Rongfeng Fu 已提交
2351

R
Rongfeng Fu 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
    def sysbench(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
2367
        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
R
Rongfeng Fu 已提交
2368
        if opts.component is None:
R
Rongfeng Fu 已提交
2369
            for component_name in allow_components:
R
Rongfeng Fu 已提交
2370 2371 2372
                if component_name in deploy_config.components:
                    opts.component = component_name
                    break
R
Rongfeng Fu 已提交
2373 2374 2375
        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 已提交
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396
        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 已提交
2397
        repositories = self.load_local_repositories(deploy_info)
R
Rongfeng Fu 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410

        # 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 = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
2411
                self._call_stdio('error', EC_SOME_SERVER_STOPED)
R
Rongfeng Fu 已提交
2412 2413 2414 2415 2416 2417 2418
                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 已提交
2419 2420 2421 2422 2423 2424 2425
        for repository in repositories:
            if repository.name == opts.component:
                break
        
        env = {'sys_root': False}
        db = None
        cursor = None
R
Rongfeng Fu 已提交
2426 2427
        odp_db = None
        odp_cursor = None
R
Rongfeng Fu 已提交
2428 2429 2430 2431 2432
        ob_optimization = True

        connect_plugin = self.search_py_script_plugin(repositories, 'connect')[repository]

        
R
Rongfeng Fu 已提交
2433
        if repository.name in ['obproxy', 'obproxy-ce']:
R
Rongfeng Fu 已提交
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
            ob_optimization = False
            allow_components = ['oceanbase', 'oceanbase-ce']
            for component_name in deploy_config.components:
                if component_name in allow_components:
                    config = deploy_config.components[component_name]
                    env['user'] = 'root'
                    env['password'] = config.get_global_conf().get('root_password', '')
                    ob_optimization = True
                    break
            ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, target_server=opts.test_server)
R
Rongfeng Fu 已提交
2444 2445 2446 2447 2448
            if not ret or not ret.get_return('connect'):
                self._call_stdio('error', 'Failed to connect to the server')
                return False
            odp_db = ret.get_return('connect')
            odp_cursor = ret.get_return('cursor')
R
Rongfeng Fu 已提交
2449 2450 2451 2452 2453 2454 2455

        ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, target_server=opts.test_server, **env)
        if not ret or not ret.get_return('connect'):
            self._call_stdio('error', 'Failed to connect to the server')
            return False
        db = ret.get_return('connect')
        cursor = ret.get_return('cursor')
R
Rongfeng Fu 已提交
2456 2457 2458 2459 2460
    
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'sysbench', repository.version)

        setattr(opts, 'host', opts.test_server.ip)
        setattr(opts, 'port', db.port)
R
Rongfeng Fu 已提交
2461
        setattr(opts, 'ob_optimization', ob_optimization)
R
Rongfeng Fu 已提交
2462 2463 2464 2465 2466 2467

        self._call_stdio('verbose', 'Call %s for %s' % (run_test_plugin, repository))
        if run_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, db, cursor, odp_db, odp_cursor):
            return True
        return False

R
Rongfeng Fu 已提交
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
    def tpch(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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]})
        repository = repositories[0]

        # 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 = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
R
Rongfeng Fu 已提交
2528
                self._call_stdio('error', EC_SOME_SERVER_STOPED)
R
Rongfeng Fu 已提交
2529 2530 2531 2532 2533 2534 2535 2536
                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

        connect_plugin = self.search_py_script_plugin(repositories, 'connect')[repository]
R
Rongfeng Fu 已提交
2537
        ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio, target_server=opts.test_server)
R
Rongfeng Fu 已提交
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557
        if not ret or not ret.get_return('connect'):
            self._call_stdio('error', 'Failed to connect to the server')
            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)


        self._call_stdio('verbose', 'Call %s for %s' % (pre_test_plugin, repository))
        if pre_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio):
            self._call_stdio('verbose', 'Call %s for %s' % (run_test_plugin, repository))
            if run_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, db, cursor):
                return True
        return False

R
Rongfeng Fu 已提交
2558 2559
    def update_obd(self, version, install_prefix='/'):
        self._obd_update_lock()
R
Rongfeng Fu 已提交
2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572
        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 已提交
2573
        if DirectoryUtil.copy(repository.repository_dir, install_prefix, self.stdio):
R
Rongfeng Fu 已提交
2574 2575 2576
            self._call_stdio('print', 'Upgrade successful.\nCurrent version : %s' % pkg.version)
            return True
        return False
R
Rongfeng Fu 已提交
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592

    def tpcc(self, name, opts):
        self._call_stdio('verbose', 'Get Deploy by name')
        deploy = self.deploy_manager.get_deploy_config(name)
        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 已提交
2593
        allow_components = ['obproxy', 'obproxy-ce', 'oceanbase', 'oceanbase-ce']
R
Rongfeng Fu 已提交
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
        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
        repositories = self.get_local_repositories({opts.component: deploy_config.components[opts.component]})
        repository = repositories[0]

        # 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 = {}
        cluster_status = self.cluster_status_check(ssh_clients, deploy_config, repositories, component_status)
        if cluster_status is False or cluster_status == 0:
            if self.stdio:
                self._call_stdio('error', 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

        for repository in repositories:
            if repository.name == opts.component:
                break

        env = {'sys_root': False}
        odp_db = None
        odp_cursor = None
        ob_optimization = True
        ob_component = None
R
Rongfeng Fu 已提交
2655
        odp_component = None
R
Rongfeng Fu 已提交
2656 2657 2658 2659
        # ob_cluster_config = None

        connect_plugin = self.search_py_script_plugin(repositories, 'connect')[repository]

R
Rongfeng Fu 已提交
2660
        if repository.name in ['obproxy', 'obproxy-ce']:
R
Rongfeng Fu 已提交
2661
            odp_component = repository.name
R
Rongfeng Fu 已提交
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
            ob_optimization = False
            allow_components = ['oceanbase', 'oceanbase-ce']
            for component in deploy_info.components:
                if component in allow_components:
                    ob_component = component
                    config = deploy_config.components[component]
                    env['user'] = 'root'
                    env['password'] = config.get_global_conf().get('root_password', '')
                    ob_optimization = True
                    break
            ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio,
                                 target_server=opts.test_server)
            if not ret or not ret.get_return('connect'):
                self._call_stdio('error', 'Failed to connect to the server')
                return False
            odp_db = ret.get_return('connect')
            odp_cursor = ret.get_return('cursor')
            # ob_cluster_config = deploy_config.components[ob_component]
        else:
            ob_component = opts.component
            # ob_cluster_config = cluster_config

        ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {}, self.stdio,
                             target_server=opts.test_server, **env)
        if not ret or not ret.get_return('connect'):
            self._call_stdio('error', 'Failed to connect to the server')
            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', 'tpcc', repository.version)
        optimize_plugin = self.plugin_manager.get_best_py_script_plugin('optimize', 'tpcc', repository.version)
        build_plugin = self.plugin_manager.get_best_py_script_plugin('build', 'tpcc', repository.version)
        run_test_plugin = self.plugin_manager.get_best_py_script_plugin('run_test', 'tpcc', repository.version)
        recover_plugin = self.plugin_manager.get_best_py_script_plugin('recover', 'tpcc', repository.version)

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

        kwargs = {}

        optimized = False
        optimization = getattr(opts, 'optimization', 0)
        test_only = getattr(opts, 'test_only', False)
        components = []
        if getattr(self.stdio, 'sub_io'):
            stdio = self.stdio.sub_io()
        else:
            stdio = None
        obd = None
        try:
            self._call_stdio('verbose', 'Call %s for %s' % (pre_test_plugin, repository))
            ret = pre_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio,
                                  cursor, odp_cursor, **kwargs)
            if not ret:
                return False
            else:
                kwargs.update(ret.kwargs)
            if optimization:
                optimized = True
                kwargs['optimization_step'] = 'build'
                self._call_stdio('verbose', 'Call %s for %s' % (optimize_plugin, repository))
                ret = optimize_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, cursor,
                             odp_cursor, **kwargs)
                if not ret:
                    return False
                else:
                    kwargs.update(ret.kwargs)
R
Rongfeng Fu 已提交
2731 2732
                if kwargs.get('odp_need_reboot') and odp_component:
                    components.append(odp_component)
R
Rongfeng Fu 已提交
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
                if kwargs.get('obs_need_reboot') and ob_component:
                    components.append(ob_component)
                if components:
                    db.close()
                    cursor.close()
                    if odp_db:
                        odp_db.close()
                    if odp_cursor:
                        odp_cursor.close()
                    self._call_stdio('start_loading', 'Restart cluster')
R
Rongfeng Fu 已提交
2743
                    obd = ObdHome(self.home_path, self.dev_mode, stdio=stdio)
R
Rongfeng Fu 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
                    obd.lock_manager.set_try_times(-1)
                    option = Values({'components': ','.join(components), 'without_parameter': True})
                    if obd.stop_cluster(name=name, options=option) and obd.start_cluster(name=name, options=option) and obd.display_cluster(name=name):
                        self._call_stdio('stop_loading', 'succeed')
                    else:
                        self._call_stdio('stop_loading', 'fail')
                        return False
                    if repository.name == 'obproxy':
                        ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {},
                                             self.stdio,
                                             target_server=opts.test_server)
                        if not ret or not ret.get_return('connect'):
                            self._call_stdio('error', 'Failed to connect to the server')
                            return False
                        odp_db = ret.get_return('connect')
                        odp_cursor = ret.get_return('cursor')
                    ret = connect_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], {},
                                         self.stdio,
                                         target_server=opts.test_server, **env)
                    if not ret or not ret.get_return('connect'):
                        self._call_stdio('error', 'Failed to connect to the server')
                        return False
                    db = ret.get_return('connect')
                    cursor = ret.get_return('cursor')
            if not test_only:
                self._call_stdio('verbose', 'Call %s for %s' % (build_plugin, repository))
                ret = build_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, cursor,
                             odp_cursor, **kwargs)
                if not ret:
                    return False
                else:
                    kwargs.update(ret.kwargs)
            if optimization:
                kwargs['optimization_step'] = 'test'
                self._call_stdio('verbose', 'Call %s for %s' % (optimize_plugin, repository))
                ret = optimize_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, cursor,
                             odp_cursor, **kwargs)
                if not ret:
                    return False
                else:
                    kwargs.update(ret.kwargs)
            self._call_stdio('verbose', 'Call %s for %s' % (run_test_plugin, repository))
            ret = run_test_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio, cursor,
                         odp_cursor, **kwargs)
            if not ret:
                return False
            else:
                kwargs.update(ret.kwargs)
            return True
        except Exception as e:
            self._call_stdio('error', e)
            return False
        finally:
            if optimization and optimized:
                self._call_stdio('verbose', 'Call %s for %s' % (recover_plugin, repository))
                if not recover_plugin(deploy_config.components.keys(), ssh_clients, cluster_config, [], opts, self.stdio,
                                      cursor, odp_cursor, **kwargs):
                    return False
                if components and obd:
                    self._call_stdio('start_loading', 'Restart cluster')
                    option = Values({'components': ','.join(components), 'without_parameter': True})
                    if obd.stop_cluster(name=name, options=option) and obd.start_cluster(name=name, options=option):
                        self._call_stdio('stop_loading', 'succeed')
                    else:
                        self._call_stdio('stop_loading', 'fail')
            if db:
                db.close()
            if odp_db:
                odp_db.close()