_deploy.py 51.6 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
# 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 os
import re
R
Rongfeng Fu 已提交
25
import pickle
O
oceanbase-admin 已提交
26 27 28 29
import getpass
from copy import deepcopy
from enum import Enum

R
Rongfeng Fu 已提交
30 31
from ruamel.yaml.comments import CommentedMap

F
v1.5.0  
frf12 已提交
32
from tool import ConfigUtil, FileUtil, YamlLoader, OrderedDict, COMMAND_ENV
O
oceanbase-admin 已提交
33 34
from _manager import Manager
from _repository import Repository
F
v1.5.0  
frf12 已提交
35
from _stdio import SafeStdio
O
oceanbase-admin 已提交
36 37 38


yaml = YamlLoader()
R
Rongfeng Fu 已提交
39
DEFAULT_CONFIG_PARSER_MANAGER = None
F
v1.5.0  
frf12 已提交
40 41
ENV = 'env'
BASE_DIR_KEY = "OBD_DEPLOY_BASE_DIR"
R
Rongfeng Fu 已提交
42 43 44 45


class ParserError(Exception):
    pass
O
oceanbase-admin 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101


class UserConfig(object):

    DEFAULT = {
        'username': getpass.getuser(),
        'password': None,
        'key_file': None,
        'port': 22,
        'timeout': 30
    }

    def __init__(self, username=None, password=None, key_file=None, port=None, timeout=None):
        self.username = username if username else self.DEFAULT['username']
        self.password = password
        self.key_file = key_file if key_file else self.DEFAULT['key_file']
        self.port = port if port else self.DEFAULT['port']
        self.timeout = timeout if timeout else self.DEFAULT['timeout']


class ServerConfig(object):

    def __init__(self, ip, name=None):
        self.ip = ip
        self._name = name

    @property
    def name(self):
        return self._name if self._name else self.ip

    def __str__(self):
        return '%s(%s)' % (self._name, self.ip) if self._name else self.ip

    def __hash__(self):
        return hash(self.__str__())

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.ip == other.ip and self.name == other.name
        if isinstance(other, dict):
            return self.ip == other['ip'] and self.name == other['name']


class ServerConfigFlyweightFactory(object):

    _CACHE = {}

    @staticmethod
    def get_instance(ip, name=None):
        server = ServerConfig(ip, name)
        _key = server.__str__()
        if _key not in ServerConfigFlyweightFactory._CACHE:
            ServerConfigFlyweightFactory._CACHE[_key] = server
        return ServerConfigFlyweightFactory._CACHE[_key]


F
v1.5.0  
frf12 已提交
102 103 104 105 106 107 108
class RsyncConfig(object):

    RSYNC = 'runtime_dependencies'
    SOURCE_PATH = 'src_path'
    TARGET_PATH = 'target_path'


R
Rongfeng Fu 已提交
109 110 111 112
class InnerConfigItem(str):
    pass


F
v1.5.0  
frf12 已提交
113 114 115 116 117 118
class InnerConfigKeywords(object):

    DEPLOY_INSTALL_MODE = 'deploy_install_mode'
    DEPLOY_BASE_DIR = 'deploy_base_dir'


R
Rongfeng Fu 已提交
119 120
class InnerConfig(object):

F
v1.5.0  
frf12 已提交
121 122
    keyword_symbol = "$_"

R
Rongfeng Fu 已提交
123 124 125 126 127 128
    def __init__(self, path, yaml_loader):
        self.path = path
        self.yaml_loader = yaml_loader
        self.config = {}
        self._load()

F
v1.5.0  
frf12 已提交
129 130 131 132 133 134 135 136 137
    def is_keyword(self, s):
        return s.startswith(self.keyword_symbol)

    def to_keyword(self, key):
        return "{}{}".format(self.keyword_symbol, key)

    def keyword_to_str(self, _keyword):
        return str(_keyword.replace(self.keyword_symbol, '', 1))

R
Rongfeng Fu 已提交
138 139 140 141 142 143
    def _load(self):
        self.config = {}
        try:
            with FileUtil.open(self.path, 'rb') as f:
                config = self.yaml_loader.load(f)
                for component_name in config:
F
v1.5.0  
frf12 已提交
144 145 146
                    if self.is_keyword(component_name):
                        self.config[InnerConfigItem(component_name)] = config[component_name]
                        continue
R
Rongfeng Fu 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
                    self.config[component_name] = {}
                    c_config = config[component_name]
                    for server in c_config:
                        i_config = {}
                        s_config = c_config[server]
                        for key in s_config:
                            i_config[InnerConfigItem(key)] = s_config[key]
                        self.config[component_name][server] = i_config
        except:
            pass

    def _dump(self):
        try:
            stdio = self.yaml_loader.stdio if self.yaml_loader else None
            with FileUtil.open(self.path, 'w', stdio=stdio) as f:
                self.yaml_loader.dump(self.config, f)
            return True
        except:
            pass
        return False

    def dump(self):
        return self._dump()

    def get_component_config(self, component_name):
        return self.config.get(component_name, {})

    def get_server_config(self, component_name, server):
F
v1.5.0  
frf12 已提交
175 176 177 178 179 180 181 182
        return self.get_component_config(component_name).get(server, {})

    def get_global_config(self, key, default=None):
        key = self.to_keyword(key)
        return self.config.get(key, default)

    def update_global_config(self, key, value):
        self.config[self.to_keyword(key)] = value
R
Rongfeng Fu 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

    def update_component_config(self, component_name, config):
        self.config[component_name] = {}
        for server in config:
            c_config = {}
            data = config[server]
            for key in data:
                if not isinstance(key, InnerConfigItem):
                    key = InnerConfigItem(key)
                c_config[key] = data[key]
            self.config[component_name][server] = c_config


class ConfigParser(object):

    STYLE = ''
    INNER_CONFIG_MAP = {}
    PREFIX = '$_'

    @classmethod
    def _is_inner_item(cls, key):
        return isinstance(key, InnerConfigItem) and key.startswith(cls.PREFIX)
F
v1.5.0  
frf12 已提交
205

R
Rongfeng Fu 已提交
206 207 208
    @classmethod
    def extract_inner_config(cls, cluster_config, config):
        return {}
F
v1.5.0  
frf12 已提交
209

R
Rongfeng Fu 已提交
210 211 212 213 214 215 216
    @classmethod
    def _to_cluster_config(cls, component_name, config):
        raise NotImplementedError

    @classmethod
    def to_cluster_config(cls, component_name, config):
        cluster_config = cls._to_cluster_config(component_name, config)
F
v1.5.0  
frf12 已提交
217
        cluster_config.set_include_file(config.get('include', ''))
R
Rongfeng Fu 已提交
218 219 220 221 222 223
        cluster_config.parser = cls
        return cluster_config

    @classmethod
    def _from_cluster_config(cls, conf, cluster_config):
        raise NotImplementedError
F
v1.5.0  
frf12 已提交
224

R
Rongfeng Fu 已提交
225 226 227 228
    @classmethod
    def from_cluster_config(cls, cluster_config):
        if not cls.STYLE:
            raise NotImplementedError('undefined Style ConfigParser')
F
v1.5.0  
frf12 已提交
229

R
Rongfeng Fu 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        conf = CommentedMap()
        conf['style'] = cls.STYLE
        if cluster_config.origin_package_hash:
            conf['package_hash'] = cluster_config.origin_package_hash
        if cluster_config.origin_version:
            conf['version'] = cluster_config.origin_version
        if cluster_config.origin_tag:
            conf['tag'] = cluster_config.origin_tag
        if cluster_config.depends:
            conf['depends'] = cluster_config.depends
        conf = cls._from_cluster_config(conf, cluster_config)
        inner_config = cls.extract_inner_config(cluster_config, conf)
        return {
            'inner_config': inner_config,
            'config': conf
        }
F
v1.5.0  
frf12 已提交
246

R
Rongfeng Fu 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    @classmethod
    def get_server_src_conf(cls, cluster_config, component_config, server):
        if server.name not in component_config:
            component_config[server.name] = {}
        return component_config[server.name]

    @classmethod
    def get_global_src_conf(cls, cluster_config, component_config):
        if 'global' not in component_config:
            component_config['global'] = {}
        return component_config['global']


class DefaultConfigParser(ConfigParser):

    STYLE = 'default'

    @classmethod
    def _to_cluster_config(cls, component_name, conf):
        if 'servers' in conf and isinstance(conf['servers'], list):
            servers = []
            for server in conf['servers']:
                if isinstance(server, dict):
                    ip = ConfigUtil.get_value_from_dict(server, 'ip', transform_func=str)
                    name = ConfigUtil.get_value_from_dict(server, 'name', transform_func=str)
                else:
                    ip = server
                    name = None
                if not re.match('^\d{1,3}(\\.\d{1,3}){3}$', ip):
                    continue
                server = ServerConfigFlyweightFactory.get_instance(ip, name)
                if server not in servers:
                    servers.append(server)
        else:
            servers = []
        cluster_config = ClusterConfig(
            servers,
            component_name,
            ConfigUtil.get_value_from_dict(conf, 'version', None, str),
            ConfigUtil.get_value_from_dict(conf, 'tag', None, str),
F
v1.5.0  
frf12 已提交
287
            ConfigUtil.get_value_from_dict(conf, 'release', None, str),
R
Rongfeng Fu 已提交
288 289 290 291
            ConfigUtil.get_value_from_dict(conf, 'package_hash', None, str)
        )
        if 'global' in conf:
            cluster_config.set_global_conf(conf['global'])
F
v1.5.0  
frf12 已提交
292 293 294 295 296 297 298

        if RsyncConfig.RSYNC in conf:
            cluster_config.set_rsync_list(conf[RsyncConfig.RSYNC])

        if ENV in conf:
            cluster_config.set_environments(conf[ENV])

R
Rongfeng Fu 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
        for server in servers:
            if server.name in conf:
                cluster_config.add_server_conf(server, conf[server.name])
        return cluster_config

    @classmethod
    def extract_inner_config(cls, cluster_config, config):
        inner_config = cluster_config.get_inner_config()
        for server in cluster_config.servers:
            if server.name not in inner_config:
                inner_config[server.name] = {}

        global_config = config.get('global', {})
        keys = list(global_config.keys())
        for key in keys:
            if cls._is_inner_item(key):
                for server in cluster_config.servers:
                    inner_config[server.name][key] = global_config[key]
                del global_config[key]
F
v1.5.0  
frf12 已提交
318

R
Rongfeng Fu 已提交
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
        for server in cluster_config.servers:
            if server.name not in config:
                continue
            server_config = config[server.name]
            keys = list(server_config.keys())
            for key in keys:
                if cls._is_inner_item(key):
                    inner_config[server.name][key] = server_config[key]
                    del server_config[key]
        return inner_config

    @classmethod
    def _from_cluster_config(cls, conf, cluster_config):
        conf['servers'] = []
        for server in cluster_config.servers:
            if server.name == server.ip:
                conf['servers'].append(server.name)
            else:
                conf['servers'].append({'name': server.name, 'ip': server.ip})

        if cluster_config.get_original_global_conf():
            conf['global'] = cluster_config.get_original_global_conf()
        for server in cluster_config.servers:
            server_config = cluster_config.get_original_server_conf(server)
            if server_config:
                conf[server.name] = server_config
        return conf


O
oceanbase-admin 已提交
348 349
class ClusterConfig(object):

F
v1.5.0  
frf12 已提交
350 351
    def __init__(self, servers, name, version, tag, release, package_hash, parser=None):
        self._version = version
R
Rongfeng Fu 已提交
352
        self.origin_version = version
O
oceanbase-admin 已提交
353
        self.tag = tag
R
Rongfeng Fu 已提交
354
        self.origin_tag = tag
F
v1.5.0  
frf12 已提交
355 356
        self._release = release
        self.origin_release = release
O
oceanbase-admin 已提交
357
        self.name = name
R
Rongfeng Fu 已提交
358
        self.origin_package_hash = package_hash
F
v1.5.0  
frf12 已提交
359
        self._package_hash = package_hash
O
oceanbase-admin 已提交
360 361
        self._temp_conf = {}
        self._default_conf = {}
F
v1.5.0  
frf12 已提交
362
        self._global_conf = None
O
oceanbase-admin 已提交
363 364
        self._server_conf = {}
        self._cache_server = {}
R
Rongfeng Fu 已提交
365
        self._original_global_conf = {}
F
v1.5.0  
frf12 已提交
366 367 368 369 370 371 372 373
        self._rsync_list = None
        self._include_config = None
        self._origin_rsync_list = {}
        self._include_file = None
        self._origin_include_file = None
        self._origin_include_config = None
        self._environments = None
        self._origin_environments = {}
R
Rongfeng Fu 已提交
374
        self._inner_config = {}
F
v1.5.0  
frf12 已提交
375
        self._base_dir = ''
R
Rongfeng Fu 已提交
376
        servers = list(servers)
O
oceanbase-admin 已提交
377
        self.servers = servers
R
Rongfeng Fu 已提交
378
        self._original_servers = servers # 保证顺序
O
oceanbase-admin 已提交
379 380 381 382
        for server in servers:
            self._server_conf[server] = {}
            self._cache_server[server] = None
        self._deploy_config = None
R
Rongfeng Fu 已提交
383
        self._depends = {}
R
Rongfeng Fu 已提交
384
        self.parser = parser
F
v1.5.0  
frf12 已提交
385
        self._has_package_pattern = None
O
oceanbase-admin 已提交
386 387 388 389

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False
F
v1.5.0  
frf12 已提交
390
        # todo 检查 rsync include等
O
oceanbase-admin 已提交
391 392
        return self._global_conf == other._global_conf and self._server_conf == other._server_conf

R
Rongfeng Fu 已提交
393 394 395 396 397 398 399 400 401 402
    def __deepcopy__(self, memo):
        cluster_config = self.__class__(deepcopy(self.servers), self.name, self.version, self.tag, self.package_hash, self.parser)
        copy_attrs = ['origin_tag', 'origin_version', 'origin_package_hash', 'parser']
        deepcopy_attrs = ['_temp_conf', '_default_conf', '_global_conf', '_server_conf', '_cache_server', '_original_global_conf', '_depends', '_original_servers', '_inner_config']
        for attr in copy_attrs:
            setattr(cluster_config, attr, getattr(self, attr))
        for attr in deepcopy_attrs:
            setattr(cluster_config, attr, deepcopy(getattr(self, attr)))
        return cluster_config

O
oceanbase-admin 已提交
403 404 405
    def set_deploy_config(self, _deploy_config):
        if self._deploy_config is None:
            self._deploy_config = _deploy_config
F
v1.5.0  
frf12 已提交
406
            self.set_base_dir(self._deploy_config.get_base_dir())
O
oceanbase-admin 已提交
407 408
            return True
        return False
F
v1.5.0  
frf12 已提交
409 410 411 412 413 414 415 416

    def set_base_dir(self, base_dir):
        if self._base_dir != base_dir:
            self._base_dir = base_dir
            self._rsync_list = None
            self._include_config = None
            self._global_conf = None

R
Rongfeng Fu 已提交
417 418 419 420 421 422 423 424
    @property
    def original_servers(self):
        return self._original_servers

    @property
    def depends(self):
        return self._depends.keys()

R
Rongfeng Fu 已提交
425 426 427 428 429 430 431
    def _clear_cache_server(self):
        for server in self._cache_server:
            self._cache_server[server] = None

    def get_inner_config(self):
        return self._inner_config

F
v1.5.0  
frf12 已提交
432 433 434 435 436 437
    def is_cp_install_mode(self):
        return self._deploy_config.is_cp_install_mode()

    def is_ln_install_mode(self):
        return self._deploy_config.is_ln_install_mode()

R
Rongfeng Fu 已提交
438 439 440 441
    def apply_inner_config(self, config):
        self._inner_config = config
        self._clear_cache_server()

R
Rongfeng Fu 已提交
442
    def add_depend(self, name, cluster_conf):
R
Rongfeng Fu 已提交
443 444 445 446
        if self.name == name:
            raise Exception('Can not set %s as %s\'s dependency' % (name, name))
        if self.name in cluster_conf.depends:
            raise Exception('Circular Dependency: %s and %s' % (self.name, name))
R
Rongfeng Fu 已提交
447 448 449 450 451 452
        self._depends[name] = cluster_conf

    def del_depend(self, name, component_name):
        if component_name in self._depends:
            del self._depends[component_name]

R
Rongfeng Fu 已提交
453
    def get_depend_servers(self, name):
R
Rongfeng Fu 已提交
454 455 456 457 458
        if name not in self._depends:
            return None
        cluster_config = self._depends[name]
        return deepcopy(cluster_config.original_servers)
        
R
Rongfeng Fu 已提交
459
    def get_depend_config(self, name, server=None):
R
Rongfeng Fu 已提交
460 461 462 463 464
        if name not in self._depends:
            return None
        cluster_config = self._depends[name]
        config = cluster_config.get_server_conf_with_default(server) if server else cluster_config.get_global_conf()
        return deepcopy(config)
R
Rongfeng Fu 已提交
465

O
oceanbase-admin 已提交
466 467 468
    def update_server_conf(self, server, key, value, save=True):
        if self._deploy_config is None:
            return False
R
Rongfeng Fu 已提交
469 470
        if server not in self._server_conf:
            return False
O
oceanbase-admin 已提交
471 472 473 474 475 476 477 478 479 480 481 482
        if not self._deploy_config.update_component_server_conf(self.name, server, key, value, save):
            return False
        self._server_conf[server][key] = value
        if self._cache_server[server] is not None:
            self._cache_server[server][key] = value
        return True

    def update_global_conf(self, key, value, save=True):
        if self._deploy_config is None:
            return False
        if not self._deploy_config.update_component_global_conf(self.name, key, value, save):
            return False
R
Rongfeng Fu 已提交
483
        self._update_global_conf(key, value)
O
oceanbase-admin 已提交
484 485 486 487 488
        for server in self._cache_server:
            if self._cache_server[server] is not None:
                self._cache_server[server][key] = value
        return True

R
Rongfeng Fu 已提交
489 490 491 492
    def _update_global_conf(self, key, value):
        self._original_global_conf[key] = value
        self._global_conf[key] = value

F
v1.5.0  
frf12 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    def update_rsync_list(self, rsync_list, save=True):
        if self._deploy_config is None:
            return False
        if not self._deploy_config.update_component_rsync_list(self.name, rsync_list, save):
            return False
        self._rsync_list = rsync_list
        return True

    def update_environments(self, environments, save=True):
        if self._deploy_config is None:
            return False
        if not self._deploy_config.update_component_environments(self.name, environments, save):
            return False
        self._origin_environments = environments
        self._environments = None
        return True

O
oceanbase-admin 已提交
510 511 512
    def get_unconfigured_require_item(self, server):
        items = []
        config = self.get_server_conf(server)
R
Rongfeng Fu 已提交
513 514 515 516 517 518 519
        if config is not None:
            for key in self._temp_conf:
                if not self._temp_conf[key].require:
                    continue
                if key in config:
                    continue
                items.append(key)
O
oceanbase-admin 已提交
520 521 522
        return items

    def get_server_conf_with_default(self, server):
R
Rongfeng Fu 已提交
523 524
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
525 526 527 528 529 530 531 532
        config = {}
        for key in self._temp_conf:
            if self._temp_conf[key].default is not None:
                config[key] = self._temp_conf[key].default
        config.update(self.get_server_conf(server))
        return config

    def get_need_redeploy_items(self, server):
R
Rongfeng Fu 已提交
533 534
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
535 536 537 538 539 540 541 542
        items = {}
        config = self.get_server_conf(server)
        for key in config:
            if key in self._temp_conf and self._temp_conf[key].need_redeploy:
                items[key] = config[key]
        return items

    def get_need_restart_items(self, server):
R
Rongfeng Fu 已提交
543 544
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
545 546 547 548 549 550 551 552 553 554 555
        items = {}
        config = self.get_server_conf(server)
        for key in config:
            if key in self._temp_conf and self._temp_conf[key].need_restart:
                items[key] = config[key]
        return items
        
    def update_temp_conf(self, temp_conf):
        self._default_conf = {}
        self._temp_conf = temp_conf
        for key in self._temp_conf:
R
Rongfeng Fu 已提交
556
            if self._temp_conf[key].require and self._temp_conf[key].default is not None:
O
oceanbase-admin 已提交
557
                self._default_conf[key] = self._temp_conf[key].default
F
v1.5.0  
frf12 已提交
558 559
        self._global_conf = None
        self._clear_cache_server()
O
oceanbase-admin 已提交
560

R
Rongfeng Fu 已提交
561 562 563 564 565
    def get_temp_conf_item(self, key):
        if self._temp_conf:
            return self._temp_conf.get(key)
        else:
            return None
F
v1.5.0  
frf12 已提交
566

R
Rongfeng Fu 已提交
567 568 569
    def check_param(self):
        error = []
        if self._temp_conf:
F
v1.5.0  
frf12 已提交
570
            error += self._check_param(self.get_global_conf())
R
Rongfeng Fu 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
            for server in self._server_conf:
                error += self._check_param(self._server_conf[server])
        return not error, set(error)

    def _check_param(self, config):
        error = []
        for key in config:
            item = self._temp_conf.get(key)
            if item:
                try:
                    item.check_value(config[key])
                except Exception as e:
                    error.append(str(e))
        return error

O
oceanbase-admin 已提交
586
    def set_global_conf(self, conf):
R
Rongfeng Fu 已提交
587
        self._original_global_conf = deepcopy(conf)
F
v1.5.0  
frf12 已提交
588
        self._global_conf = None
R
Rongfeng Fu 已提交
589
        self._clear_cache_server()
O
oceanbase-admin 已提交
590

F
v1.5.0  
frf12 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603
    def set_rsync_list(self, configs):
        self._origin_rsync_list = configs

    def set_include_file(self, path):
        if path != self._origin_include_file:
            self._origin_include_file = path
            self._include_file = None
            self._include_config = None

    def set_environments(self, config):
        self._origin_environments = config
        self._environments = None

O
oceanbase-admin 已提交
604 605 606
    def add_server_conf(self, server, conf):
        if server not in self.servers:
            self.servers.append(server)
R
Rongfeng Fu 已提交
607 608
        if server not in self._original_servers:
            self._original_servers.append(server)
O
oceanbase-admin 已提交
609 610 611 612
        self._server_conf[server] = conf
        self._cache_server[server] = None

    def get_global_conf(self):
F
v1.5.0  
frf12 已提交
613 614 615 616
        if self._global_conf is None:
            self._global_conf = deepcopy(self._default_conf)
            self._global_conf.update(self._get_include_config('config', {}))
            self._global_conf.update(self._original_global_conf)
O
oceanbase-admin 已提交
617 618
        return self._global_conf

F
v1.5.0  
frf12 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
    def _add_base_dir(self, path):
        if not os.path.isabs(path):
            if self._base_dir:
                path = os.path.join(self._base_dir, path)
            else:
                raise Exception("`{}` need to use absolute paths. If you want to use relative paths, please enable developer mode "
                "and set environment variables {}".format(RsyncConfig.RSYNC, BASE_DIR_KEY))
        return path

    @property
    def has_package_pattern(self):
        if self._has_package_pattern is None:
            patterns = (self.origin_package_hash, self.origin_version, self.origin_release, self.origin_tag)
            self._has_package_pattern = any([x is not None for x in patterns])
        return self._has_package_pattern

    @property
    def version(self):
        if self._version is None:
            self._version = self.config_version
        return self._version

    @version.setter
    def version(self, value):
        self._version = value

    @property
    def config_version(self):
        if not self.has_package_pattern:
            return self._get_include_config('version', None)
        else:
            return self.origin_version

    @property
    def release(self):
        if self._release is None:
            self._release = self.config_release
        return self._release

    @release.setter
    def release(self, value):
        self._release = value

    @property
    def config_release(self):
        if not self.has_package_pattern:
            return self._get_include_config('release', None)
        else:
            return self.origin_release

    @property
    def package_hash(self):
        if self._package_hash is None:
            self._package_hash = self.config_package_hash
        return self._package_hash

    @package_hash.setter
    def package_hash(self, value):
        self._package_hash = value

    @property
    def config_package_hash(self):
        if not self.has_package_pattern:
            return self._get_include_config('package_hash', None)
        else:
            return self.origin_package_hash
    
    def _get_include_config(self, key=None, default=None, not_found_act="ignore"):
        if self._include_config is None:
            if self._origin_include_file:
                if os.path.isabs(self._origin_include_file):
                    include_file = self._origin_include_file
                else:
                    include_file = os.path.join(self._base_dir, self._origin_include_file)
                if include_file != self._include_file:
                    self._include_file = include_file
                    self._origin_include_config = self._deploy_config.load_include_file(self._include_file)
            if self._origin_include_config is None:
                self._origin_include_config = {}
            self._include_config = self._origin_include_config
        value = self._include_config.get(key, default) if key else self._include_config
        return deepcopy(value)

    def get_rsync_list(self):
        if self._rsync_list is None:
            self._rsync_list = self._get_include_config(RsyncConfig.RSYNC, [])
            self._rsync_list += self._origin_rsync_list
            for item in self._rsync_list:
                item[RsyncConfig.SOURCE_PATH] = self._add_base_dir(item[RsyncConfig.SOURCE_PATH])
        return self._rsync_list

    def get_environments(self):
        if self._environments is None:
            self._environments = self._get_include_config(ENV, OrderedDict())
            self._environments.update(self._origin_environments)
        return self._environments

O
oceanbase-admin 已提交
716 717 718 719
    def get_server_conf(self, server):
        if server not in self._server_conf:
            return None
        if self._cache_server[server] is None:
R
Rongfeng Fu 已提交
720
            conf = deepcopy(self._inner_config.get(server.name, {}))
F
v1.5.0  
frf12 已提交
721
            conf.update(self.get_global_conf())
O
oceanbase-admin 已提交
722 723 724 725
            conf.update(self._server_conf[server])
            self._cache_server[server] = conf
        return self._cache_server[server]

R
Rongfeng Fu 已提交
726 727 728
    def get_original_global_conf(self):
        return self._original_global_conf

R
Rongfeng Fu 已提交
729 730 731
    def get_original_server_conf(self, server):
        return self._server_conf.get(server)

O
oceanbase-admin 已提交
732 733 734 735 736 737 738 739 740 741 742 743

class DeployStatus(Enum):

    STATUS_CONFIGUREING = 'configuring'
    STATUS_CONFIGURED = 'configured'
    STATUS_DEPLOYING = 'delopying'
    STATUS_DEPLOYED = 'deployed'
    STATUS_RUNNING = 'running'
    STATUS_STOPING = 'stoping'
    STATUS_STOPPED = 'stopped'
    STATUS_DESTROYING = 'destroying'
    STATUS_DESTROYED = 'destroyed'
R
Rongfeng Fu 已提交
744
    STATUS_UPRADEING = 'upgrading'
O
oceanbase-admin 已提交
745 746 747 748 749 750 751 752 753 754


class DeployConfigStatus(Enum):

    UNCHNAGE = 'unchange'
    NEED_RELOAD = 'need reload'
    NEED_RESTART = 'need restart'
    NEED_REDEPLOY = 'need redeploy'


F
v1.5.0  
frf12 已提交
755 756 757 758 759 760
class  DeployInstallMode(object):

    LN = 'ln'
    CP = 'cp'


O
oceanbase-admin 已提交
761 762
class DeployInfo(object):

R
Rongfeng Fu 已提交
763
    def __init__(self, name, status, components=OrderedDict(), config_status=DeployConfigStatus.UNCHNAGE):
O
oceanbase-admin 已提交
764 765 766 767 768 769 770 771 772 773 774 775
        self.status = status
        self.name = name
        self.components = components
        self.config_status = config_status

    def __str__(self):
        info = ['%s (%s)' % (self.name, self.status.value)]
        for name in self.components:
            info.append('%s-%s' % (name, self.components[name]))
        return '\n'.join(info)


F
v1.5.0  
frf12 已提交
776
class DeployConfig(SafeStdio):
O
oceanbase-admin 已提交
777

F
v1.5.0  
frf12 已提交
778
    def __init__(self, yaml_path, yaml_loader=yaml, inner_config=None, config_parser_manager=None, stdio=None):
O
oceanbase-admin 已提交
779 780
        self._user = None
        self.unuse_lib_repository = False
R
Rongfeng Fu 已提交
781
        self.auto_create_tenant = False
R
Rongfeng Fu 已提交
782
        self._inner_config = inner_config
R
Rongfeng Fu 已提交
783
        self.components = OrderedDict()
O
oceanbase-admin 已提交
784 785 786
        self._src_data = None
        self.yaml_path = yaml_path
        self.yaml_loader = yaml_loader
R
Rongfeng Fu 已提交
787
        self.config_parser_manager = config_parser_manager if config_parser_manager else DEFAULT_CONFIG_PARSER_MANAGER
F
v1.5.0  
frf12 已提交
788 789
        self.stdio = stdio
        self._ignore_include_error = False
R
Rongfeng Fu 已提交
790 791
        if self.config_parser_manager is None:
            raise ParserError('ConfigParaserManager Not Set')
O
oceanbase-admin 已提交
792 793 794 795 796 797
        self._load()

    @property
    def user(self):
        return self._user

R
Rongfeng Fu 已提交
798 799 800 801 802 803 804 805 806 807 808 809
    @property
    def inner_config(self):
        return self._inner_config

    @inner_config.setter
    def inner_config(self, inner_config):
        if inner_config:
            def get_inner_config(component_name):
                return inner_config.get_component_config(component_name)
        else:
            def get_inner_config(component_name):
                return {}
F
v1.5.0  
frf12 已提交
810

R
Rongfeng Fu 已提交
811
        self._inner_config = inner_config
F
v1.5.0  
frf12 已提交
812 813 814 815 816
        base_dir = self.get_base_dir()
        for component_name in self.components:
            cluster_config = self.components[component_name]
            cluster_config.apply_inner_config(get_inner_config(component_name))
            cluster_config.set_base_dir(base_dir)
R
Rongfeng Fu 已提交
817

O
oceanbase-admin 已提交
818 819 820 821 822 823 824
    def set_unuse_lib_repository(self, status):
        if self.unuse_lib_repository != status:
            self.unuse_lib_repository = status
            self._src_data['unuse_lib_repository'] = status
            return self._dump()
        return True

R
Rongfeng Fu 已提交
825 826 827 828 829 830 831
    def set_auto_create_tenant(self, status):
        if self.auto_create_tenant != status:
            self.auto_create_tenant = status
            self._src_data['auto_create_tenant'] = status
            return self._dump()
        return True

R
Rongfeng Fu 已提交
832 833 834 835 836 837 838 839 840 841 842 843
    def update_component_package_hash(self, component, package_hash, version=None):
        if component not in self.components:
            return False
        ori_data = self._src_data[component]
        src_data = deepcopy(ori_data)
        src_data['package_hash'] = package_hash
        if version:
            src_data['version'] = version
        elif 'version' in src_data:
            del src_data['version']
        if 'tag' in src_data:
            del src_data['tag']
F
v1.5.0  
frf12 已提交
844

R
Rongfeng Fu 已提交
845 846 847 848 849 850 851 852 853 854
        self._src_data[component] = src_data
        if self._dump():
            cluster_config = self.components[component]
            cluster_config.package_hash = src_data.get('package_hash')
            cluster_config.version = src_data.get('version')
            cluster_config.tag = None
            return True
        self._src_data[component] = ori_data
        return False

O
oceanbase-admin 已提交
855
    def _load(self):
R
Rongfeng Fu 已提交
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
        with open(self.yaml_path, 'rb') as f:
            depends = {}
            self._src_data = self.yaml_loader.load(f)
            for key in self._src_data:
                if key == 'user':
                    self.set_user_conf(UserConfig(
                        ConfigUtil.get_value_from_dict(self._src_data[key], 'username'),
                        ConfigUtil.get_value_from_dict(self._src_data[key], 'password'),
                        ConfigUtil.get_value_from_dict(self._src_data[key], 'key_file'),
                        ConfigUtil.get_value_from_dict(self._src_data[key], 'port', 0, int),
                        ConfigUtil.get_value_from_dict(self._src_data[key], 'timeout', 0, int),
                    ))
                elif key == 'unuse_lib_repository':
                    self.unuse_lib_repository = self._src_data['unuse_lib_repository']
                elif key == 'auto_create_tenant':
                    self.auto_create_tenant = self._src_data['auto_create_tenant']
                elif issubclass(type(self._src_data[key]), dict):
                    self._add_component(key, self._src_data[key])
                    depends[key] = self._src_data[key].get('depends', [])
            for comp in depends:
                conf = self.components[comp]
                for name in depends[comp]:
                    if name == comp:
                        continue
                    if name in self.components:
                        conf.add_depend(name, self.components[name])
O
oceanbase-admin 已提交
882 883 884
        if not self.user:
            self.set_user_conf(UserConfig())

F
v1.5.0  
frf12 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    def allow_include_error(self):
        self.stdio.verbose("allow include file not exists")
        self._ignore_include_error = True

    def load_include_file(self, path):
        if not os.path.isabs(path):
            raise Exception("`{}` need to use absolute path. If you want to use relative paths, please enable developer mode "
            "and set environment variables {}".format('include', BASE_DIR_KEY))
        if os.path.isfile(path):
            with open(path, 'rb') as f:
                return self.yaml_loader.load(f)
        else:
            if self._ignore_include_error:
                self.stdio.warn("include file: {} not found, some configurations may be lost".format(path))
                return {}
            else:
                raise Exception('Not such file: %s' % path)

R
Rongfeng Fu 已提交
903 904 905 906 907 908 909 910 911
    def _separate_config(self):
        if self.inner_config:
            for component_name in self.components:
                cluster_config = self.components[component_name]
                src_data = self._src_data[component_name]
                parser = cluster_config.parser
                if parser:
                    inner_config = parser.extract_inner_config(cluster_config, src_data)
                    self.inner_config.update_component_config(component_name, inner_config)
F
v1.5.0  
frf12 已提交
912
        
R
Rongfeng Fu 已提交
913 914 915 916 917
    def _dump_inner_config(self):
        if self.inner_config:
            self._separate_config()
            self.inner_config.dump()

O
oceanbase-admin 已提交
918 919 920
    def _dump(self):
        try:
            with open(self.yaml_path, 'w') as f:
R
Rongfeng Fu 已提交
921
                self._dump_inner_config()
O
oceanbase-admin 已提交
922 923 924
                self.yaml_loader.dump(self._src_data, f)
            return True
        except:
R
Rongfeng Fu 已提交
925 926
            import logging
            logging.exception('')
O
oceanbase-admin 已提交
927 928 929 930 931 932
            pass
        return False

    def dump(self):
        return self._dump()

F
v1.5.0  
frf12 已提交
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
    def _update_global_inner_config(self, key, value, save=True):
        if self.inner_config:
            self.inner_config.update_global_config(key, value)
        return self._dump_inner_config() if save else True

    def _get_global_inner_config(self, key, default=None):
        if self.inner_config:
            return self.inner_config.get_global_config(key, default)
        return default

    def set_base_dir(self, path, save=True):
        if path and not os.path.isabs(path):
            raise Exception('%s is not an absolute path' % path)
        if self._update_global_inner_config(InnerConfigKeywords.DEPLOY_BASE_DIR, path, save=save):
            for component_name in self.components:
                cluster_config = self.components[component_name]
                cluster_config.set_base_dir(path)
            return True
        return False

    def get_base_dir(self):
        return self._get_global_inner_config(InnerConfigKeywords.DEPLOY_BASE_DIR, '')

    def set_deploy_install_mode(self, mode, save=True):
        return self._update_global_inner_config(InnerConfigKeywords.DEPLOY_INSTALL_MODE, mode, save=save)

    def get_deploy_install_mode(self):
        return self._get_global_inner_config(InnerConfigKeywords.DEPLOY_INSTALL_MODE, DeployInstallMode.CP)

    def enable_ln_install_mode(self, save=True):
        return self.set_deploy_install_mode(DeployInstallMode.LN, save=save)

    def enable_cp_install_mode(self, save=True):
        return self.set_deploy_install_mode(DeployInstallMode.CP, save=save)

    def is_ln_install_mode(self):
        return self.get_deploy_install_mode() == DeployInstallMode.LN

    def is_cp_install_mode(self):
        return self.get_deploy_install_mode() == DeployInstallMode.CP

O
oceanbase-admin 已提交
974 975 976
    def set_user_conf(self, conf):
        self._user = conf

R
Rongfeng Fu 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
    def add_depend_for_component(self, component_name, depend_component_name, save=True):
        if component_name not in self.components:
            return False
        if depend_component_name not in self.components:
            return False
        cluster_config = self.components[component_name]
        if depend_component_name in cluster_config.depends:
            return True
        cluster_config.add_depend(depend_component_name, self.components[depend_component_name])
        component_config = self._src_data[component_name]
        if 'depends' not in component_config:
            component_config['depends'] = []
        component_config['depends'].append(depend_component_name)
        return self.dump() if save else True

    def del_depend_for_component(self, component_name, depend_component_name, save=True):
        if component_name not in self.components:
            return False
        if depend_component_name not in self.components:
            return False
        cluster_config = self.components[component_name]
        if depend_component_name not in cluster_config.depends:
            return True
        cluster_config.del_depend(depend_component_name, depend_component_name)
        component_config = self._src_data[component_name]
        component_config['depends'] = cluster_config.depends
        return self.dump() if save else True

O
oceanbase-admin 已提交
1005 1006 1007 1008 1009 1010
    def update_component_server_conf(self, component_name, server, key, value, save=True):
        if component_name not in self.components:
            return False
        cluster_config = self.components[component_name]
        if server not in cluster_config.servers:
            return False
R
Rongfeng Fu 已提交
1011 1012
        component_config = cluster_config.parser.get_server_src_conf(cluster_config, self._src_data[component_name], server)
        component_config[key] = value
O
oceanbase-admin 已提交
1013 1014 1015 1016 1017
        return self.dump() if save else True

    def update_component_global_conf(self, component_name, key, value, save=True):
        if component_name not in self.components:
            return False
R
Rongfeng Fu 已提交
1018 1019 1020
        cluster_config = self.components[component_name]
        component_config = cluster_config.parser.get_global_src_conf(cluster_config, self._src_data[component_name])
        component_config[key] = value
O
oceanbase-admin 已提交
1021 1022
        return self.dump() if save else True

R
Rongfeng Fu 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    def _set_component(self, cluster_config):
        cluster_config.set_deploy_config(self)
        if self.inner_config:
            inner_config = self.inner_config.get_component_config(cluster_config.name)
            if inner_config:
                cluster_config.apply_inner_config(inner_config)
        self.components[cluster_config.name] = cluster_config

    def update_component(self, cluster_config):
        component_name = cluster_config.name
        if cluster_config.parser:
            parser = cluster_config.parser
O
oceanbase-admin 已提交
1035
        else:
R
Rongfeng Fu 已提交
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
            conf = self._src_data.get('component_name', {})
            style = conf.get('style', 'default')
            parser = self.config_parser_manager.get_parser(component_name, style)

        conf = parser.from_cluster_config(cluster_config)
        if component_name in self.components:
            self.components[component_name].set_deploy_config(None)
        cluster_config = deepcopy(cluster_config)
        cluster_config.apply_inner_config(conf['inner_config'])
        if self.inner_config:
            self.inner_config.update_component_config(component_name, conf['inner_config'])
        self._src_data[component_name] = conf['config']
        self._set_component(cluster_config)
        return True

    def _add_component(self, component_name, conf):
        parser = self.config_parser_manager.get_parser(component_name, conf.get('style'))
        cluster_config = parser.to_cluster_config(component_name, conf)
        self._set_component(cluster_config)

    def change_component_config_style(self, component_name, style):
        if component_name not in self.components:
            return False

        parser = self.config_parser_manager.get_parser(component_name, style)
        cluster_config = self.components[component_name]
        if cluster_config.parser != parser:
            new_config = parser.from_cluster_config(cluster_config)
            self._add_component(component_name, new_config)
            self.components[component_name].apply_inner_config(new_config['inner_config'])
            if self.inner_config:
                self.inner_config.update_component_config(component_name, new_config['inner_config'])
            self._src_data[component_name] = new_config['config']
        return True
O
oceanbase-admin 已提交
1070 1071 1072 1073 1074 1075


class Deploy(object):

    DEPLOY_STATUS_FILE = '.data'
    DEPLOY_YAML_NAME = 'config.yaml'
R
Rongfeng Fu 已提交
1076
    INNER_CONFIG_NAME = 'inner_config.yaml'
R
Rongfeng Fu 已提交
1077
    UPRADE_META_NAME = '.upgrade'
O
oceanbase-admin 已提交
1078

R
Rongfeng Fu 已提交
1079
    def __init__(self, config_dir, config_parser_manager=None, stdio=None):
O
oceanbase-admin 已提交
1080 1081 1082 1083 1084
        self.config_dir = config_dir
        self.name = os.path.split(config_dir)[1]
        self._info = None
        self._config = None
        self.stdio = stdio
R
Rongfeng Fu 已提交
1085
        self.config_parser_manager = config_parser_manager
R
Rongfeng Fu 已提交
1086
        self._uprade_meta = None
O
oceanbase-admin 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

    def use_model(self, name, repository, dump=True):
        self.deploy_info.components[name] = {
            'hash': repository.hash,
            'version': repository.version,
        }
        return self._dump_deploy_info() if dump else True

    @staticmethod
    def get_deploy_file_path(path):
        return os.path.join(path, Deploy.DEPLOY_STATUS_FILE)

    @staticmethod
    def get_deploy_yaml_path(path):
        return os.path.join(path, Deploy.DEPLOY_YAML_NAME)

R
Rongfeng Fu 已提交
1103 1104 1105 1106
    @staticmethod
    def get_upgrade_meta_path(path):
        return os.path.join(path, Deploy.UPRADE_META_NAME)

R
Rongfeng Fu 已提交
1107 1108 1109 1110
    @staticmethod
    def get_inner_config_path(path):
        return os.path.join(path, Deploy.INNER_CONFIG_NAME)

O
oceanbase-admin 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    @staticmethod
    def get_temp_deploy_yaml_path(path):
        return os.path.join(path, 'tmp_%s' % Deploy.DEPLOY_YAML_NAME)

    @property
    def deploy_info(self):
        if self._info is None:
            try:
                path = self.get_deploy_file_path(self.config_dir)
                with open(path, 'rb') as f:
                    data = yaml.load(f)
                    self._info = DeployInfo(
                        data['name'],
                        getattr(DeployStatus, data['status'], DeployStatus.STATUS_CONFIGURED),
R
Rongfeng Fu 已提交
1125
                        ConfigUtil.get_value_from_dict(data, 'components', OrderedDict()),
O
oceanbase-admin 已提交
1126 1127 1128 1129 1130 1131
                        getattr(DeployConfigStatus, ConfigUtil.get_value_from_dict(data, 'config_status', '_'), DeployConfigStatus.UNCHNAGE),
                    )
            except:
                self._info = DeployInfo(self.name, DeployStatus.STATUS_CONFIGURED)
        return self._info

R
Rongfeng Fu 已提交
1132 1133
    def _load_deploy_config(self, path):
        yaml_loader = YamlLoader(stdio=self.stdio)
F
v1.5.0  
frf12 已提交
1134
        deploy_config = DeployConfig(path, yaml_loader=yaml_loader, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
R
Rongfeng Fu 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
        deploy_info = self.deploy_info
        for component_name in deploy_info.components:
            if component_name not in deploy_config.components:
                continue
            config = deploy_info.components[component_name]
            cluster_config = deploy_config.components[component_name]
            if 'version' in config and config['version']:
                cluster_config.version = config['version']
            if 'hash' in config and config['hash']:
                cluster_config.package_hash = config['hash']
        deploy_config.inner_config = InnerConfig(self.get_inner_config_path(self.config_dir), yaml_loader=yaml_loader)
        return deploy_config
F
v1.5.0  
frf12 已提交
1147

R
Rongfeng Fu 已提交
1148 1149 1150 1151 1152
    @property
    def temp_deploy_config(self):
        path = self.get_temp_deploy_yaml_path(self.config_dir)
        return self._load_deploy_config(path)

O
oceanbase-admin 已提交
1153 1154 1155
    @property
    def deploy_config(self):
        if self._config is None:
R
Rongfeng Fu 已提交
1156 1157
            path = self.get_deploy_yaml_path(self.config_dir)
            self._config = self._load_deploy_config(path)
O
oceanbase-admin 已提交
1158 1159
        return self._config

R
Rongfeng Fu 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    def _get_uprade_meta(self):
        if self._uprade_meta is None and self.deploy_info.status == DeployStatus.STATUS_UPRADEING:
            try:
                path = self.get_upgrade_meta_path(self.config_dir)
                with open(path) as f:
                    self._uprade_meta = yaml.load(f)
            except:
                self.stdio and getattr(self.stdio, 'exception', print)('fail to load uprade meta data')
        return self._uprade_meta

    @property
    def upgrade_ctx(self):
        uprade_meta = self._get_uprade_meta()
        return uprade_meta.get('uprade_ctx') if uprade_meta else None

    @property
    def upgrading_component(self):
        uprade_meta = self._get_uprade_meta()
        return uprade_meta.get('component') if uprade_meta else None

O
oceanbase-admin 已提交
1180
    def apply_temp_deploy_config(self):
R
Rongfeng Fu 已提交
1181
        self.stdio and getattr(self.stdio, 'verbose', print)('%s apply temp config' % self.name)
O
oceanbase-admin 已提交
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
        src_yaml_path = self.get_temp_deploy_yaml_path(self.config_dir)
        target_src_path = self.get_deploy_yaml_path(self.config_dir)
        try:
            FileUtil.move(src_yaml_path, target_src_path)
            self._config = None
            self.update_deploy_config_status(DeployConfigStatus.UNCHNAGE)
            return True
        except Exception as e:
            self.stdio and getattr(self.stdio, 'exception', print)('mv %s to %s failed, error: \n%s' % (src_yaml_path, target_src_path, e))
        return False

    def _dump_deploy_info(self):
        path = self.get_deploy_file_path(self.config_dir)
        self.stdio and getattr(self.stdio, 'verbose', print)('dump deploy info to %s' % path)
        try:
            with open(path, 'w') as f:
                data = {
                    'name': self.deploy_info.name,
                    'components': self.deploy_info.components,
                    'status': self.deploy_info.status.name,
                    'config_status': self.deploy_info.config_status.name,
                }
                yaml.dump(data, f)
            return True
        except:
            self.stdio and getattr(self.stdio, 'exception', print)('dump deploy info to %s failed' % path)
        return False

R
Rongfeng Fu 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    def _update_deploy_status(self, status):
        old = self.deploy_info.status
        self.deploy_info.status = status
        if self._dump_deploy_info():
            return True
        self.deploy_info.status = old
        return False

    def _update_deploy_config_status(self, status):
        old = self.deploy_info.config_status
        self.deploy_info.config_status = status
        if self._dump_deploy_info():
            return True
        self.deploy_info.config_status = old
        return False

    def _dump_upgrade_meta_data(self):
        path = self.get_upgrade_meta_path(self.config_dir)
        self.stdio and getattr(self.stdio, 'verbose', print)('dump upgrade meta data to %s' % path)
        try:
            if self._uprade_meta:
                with open(path, 'wb') as f:
                    yaml.dump(self._uprade_meta, f)
            else:
                FileUtil.rm(path, self.stdio)
            return True
        except:
            self.stdio and getattr(self.stdio, 'exception', print)('dump upgrade meta data to %s failed' % path)
        return False

    def start_upgrade(self, component, **uprade_ctx):
        if self.deploy_info.status != DeployStatus.STATUS_RUNNING:
            return False
        self._uprade_meta = {
            'component': component,
            'uprade_ctx': uprade_ctx
        }
        if self._dump_upgrade_meta_data() and self._update_deploy_status(DeployStatus.STATUS_UPRADEING):
            return True
        self._uprade_meta = None
        return False

    def update_upgrade_ctx(self, **uprade_ctx):
        if self.deploy_info.status != DeployStatus.STATUS_UPRADEING:
            return False
        uprade_meta = deepcopy(self._get_uprade_meta())
        self._uprade_meta['uprade_ctx'].update(uprade_ctx)
        if self._dump_upgrade_meta_data():
            return True
        self._uprade_meta = uprade_meta
        return False

R
Rongfeng Fu 已提交
1262 1263
    def update_component_repository(self, repository):
        if not self.deploy_config.update_component_package_hash(repository.name, repository.hash, repository.version):
R
Rongfeng Fu 已提交
1264
            return False
R
Rongfeng Fu 已提交
1265
        self.use_model(repository.name, repository)
R
Rongfeng Fu 已提交
1266 1267 1268 1269 1270 1271 1272
        return True

    def stop_upgrade(self, dest_repository=None):
        if self._update_deploy_status(DeployStatus.STATUS_RUNNING):
            self._uprade_meta = None
            self._dump_upgrade_meta_data()
            if dest_repository:
R
Rongfeng Fu 已提交
1273
                self.update_component_repository(dest_repository)
R
Rongfeng Fu 已提交
1274 1275 1276
            return True
        return False

O
oceanbase-admin 已提交
1277 1278
    def update_deploy_status(self, status):
        if isinstance(status, DeployStatus):
R
Rongfeng Fu 已提交
1279 1280 1281 1282 1283
            if self._update_deploy_status(status):
                if DeployStatus.STATUS_DESTROYED == status:
                    self.deploy_info.components = {}
                    self._dump_deploy_info()
                return True
O
oceanbase-admin 已提交
1284 1285 1286 1287
        return False

    def update_deploy_config_status(self, status):
        if isinstance(status, DeployConfigStatus):
R
Rongfeng Fu 已提交
1288
            return self._update_deploy_config_status(status)
O
oceanbase-admin 已提交
1289 1290
        return False

R
Rongfeng Fu 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    def effect_tip(self):
        cmd_map = {
            DeployConfigStatus.NEED_RELOAD: 'obd cluster reload %s' % self.name,
            DeployConfigStatus.NEED_RESTART: 'obd cluster restart %s --wp' % self.name,
            DeployConfigStatus.NEED_REDEPLOY: 'obd cluster redeploy %s' % self.name,
        }
        if self.deploy_info.config_status in cmd_map:
            return '\nUse `%s` to make changes take effect.' % cmd_map[self.deploy_info.config_status]
        return ''


class ConfigParserManager(Manager):

    RELATIVE_PATH = 'config_parser/'
F
v1.5.0  
frf12 已提交
1305

R
Rongfeng Fu 已提交
1306 1307 1308 1309 1310 1311 1312
    def __init__(self, home_path, stdio=None):
        super(ConfigParserManager, self).__init__(home_path, stdio)
        self.global_parsers = {
            'default': DefaultConfigParser,
        }
        self.component_parsers = {}

R
Rongfeng Fu 已提交
1313
    def _format_paraser_name(self, style):
R
Rongfeng Fu 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
        style = style.title()
        return '%sConfigParser' % style.replace('-', '').replace(' ', '').replace('_', '')

    def _load_paraser(self, lib_path, style):
        from tool import DynamicLoading
        module_name = '%s_config_parser' % style
        file_name = '%s.py' % module_name
        path = os.path.join(lib_path, file_name)
        if os.path.isfile(path):
            DynamicLoading.add_lib_path(lib_path)
            self.stdio and getattr(self.stdio, 'verbose', 'print')('load config parser: %s' % path)
            module = DynamicLoading.import_module(module_name, self.stdio)
R
Rongfeng Fu 已提交
1326
            clz_name = self._format_paraser_name(style)
R
Rongfeng Fu 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
            try:
                return getattr(module, clz_name)
            except:
                self.stdio and getattr(self.stdio, 'exception', 'print')('')
                return None
            finally:
                DynamicLoading.remove_lib_path(lib_path)
        else:
            self.stdio and getattr(self.stdio, 'verbose', 'print')('No config parser: %s' % path)
            return None

    def _get_component_parser(self, component, style):
        if component not in self.component_parsers:
            self.component_parsers[component] = {}
        component_parsers = self.component_parsers[component]
        if style not in component_parsers:
            lib_path = os.path.join(self.path, component)
            component_parsers[style] = self._load_paraser(lib_path, style)
        return component_parsers[style]

    def _get_global_parser(self, style):
        if style not in self.global_parsers:
            self.global_parsers[style] = self._load_paraser(self.path, style)
        return self.global_parsers[style]

    def get_parser(self, component='', style=''):
        if not style or style == 'default':
            return self.global_parsers['default']
        if component:
            parser = self._get_component_parser(component, style)
            if parser:
                return parser
        parser = self._get_global_parser(style)
        if not parser:
F
v1.4.0  
frf12 已提交
1361
            raise ParserError('Unsupported configuration style: %s %s' % (component, style))
R
Rongfeng Fu 已提交
1362 1363
        return parser

O
oceanbase-admin 已提交
1364 1365 1366 1367 1368

class DeployManager(Manager):

    RELATIVE_PATH = 'cluster/'
    
R
Rongfeng Fu 已提交
1369
    def __init__(self, home_path, lock_manager=None, stdio=None):
O
oceanbase-admin 已提交
1370
        super(DeployManager, self).__init__(home_path, stdio)
R
Rongfeng Fu 已提交
1371
        self.lock_manager = lock_manager
R
Rongfeng Fu 已提交
1372
        self.config_parser_manager = ConfigParserManager(home_path, stdio)
R
Rongfeng Fu 已提交
1373 1374 1375 1376 1377 1378 1379 1380

    def _lock(self, name, read_only=False):
        if self.lock_manager:
            if read_only:
                return self.lock_manager.deploy_sh_lock(name)
            else:
                return self.lock_manager.deploy_ex_lock(name)
        return True
O
oceanbase-admin 已提交
1381

R
Rongfeng Fu 已提交
1382
    def get_deploy_configs(self, read_only=True):
O
oceanbase-admin 已提交
1383
        configs = []
R
Rongfeng Fu 已提交
1384 1385
        for name in os.listdir(self.path):
            path = os.path.join(self.path, name)
O
oceanbase-admin 已提交
1386
            if os.path.isdir(path):
R
Rongfeng Fu 已提交
1387
                self._lock(name, read_only)
R
Rongfeng Fu 已提交
1388
                configs.append(Deploy(path, config_parser_manager=self.config_parser_manager, stdio=self.stdio))
O
oceanbase-admin 已提交
1389 1390
        return configs

R
Rongfeng Fu 已提交
1391 1392
    def get_deploy_config(self, name, read_only=False):
        self._lock(name, read_only)
O
oceanbase-admin 已提交
1393 1394
        path = os.path.join(self.path, name)
        if os.path.isdir(path):
R
Rongfeng Fu 已提交
1395
            return Deploy(path, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
O
oceanbase-admin 已提交
1396 1397 1398
        return None

    def create_deploy_config(self, name, src_yaml_path):
R
Rongfeng Fu 已提交
1399
        self._lock(name)
O
oceanbase-admin 已提交
1400 1401 1402 1403
        config_dir = os.path.join(self.path, name)
        target_src_path = Deploy.get_deploy_yaml_path(config_dir)
        self._mkdir(config_dir)
        if FileUtil.copy(src_yaml_path, target_src_path, self.stdio):
R
Rongfeng Fu 已提交
1404
            return Deploy(config_dir, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
O
oceanbase-admin 已提交
1405 1406 1407 1408 1409
        else:
            self._rm(config_dir)
            return None
        
    def remove_deploy_config(self, name):
R
Rongfeng Fu 已提交
1410
        self._lock(name)
O
oceanbase-admin 已提交
1411 1412
        config_dir = os.path.join(self.path, name)
        self._rm(config_dir)