_deploy.py 53.8 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
F
v1.6.0  
frf12 已提交
25
import sys
R
Rongfeng Fu 已提交
26
import pickle
O
oceanbase-admin 已提交
27
import getpass
F
v1.6.0  
frf12 已提交
28
import hashlib
O
oceanbase-admin 已提交
29 30 31
from copy import deepcopy
from enum import Enum

R
Rongfeng Fu 已提交
32 33
from ruamel.yaml.comments import CommentedMap

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


yaml = YamlLoader()
R
Rongfeng Fu 已提交
42
DEFAULT_CONFIG_PARSER_MANAGER = None
F
v1.5.0  
frf12 已提交
43
ENV = 'env'
R
Rongfeng Fu 已提交
44 45 46 47


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


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 已提交
104 105 106 107 108 109 110
class RsyncConfig(object):

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


R
Rongfeng Fu 已提交
111 112 113 114
class InnerConfigItem(str):
    pass


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

    DEPLOY_INSTALL_MODE = 'deploy_install_mode'
    DEPLOY_BASE_DIR = 'deploy_base_dir'


R
Rongfeng Fu 已提交
121 122
class InnerConfig(object):

F
v1.5.0  
frf12 已提交
123 124
    keyword_symbol = "$_"

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

F
v1.5.0  
frf12 已提交
131 132 133 134 135 136 137 138 139
    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 已提交
140 141 142 143 144 145
    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 已提交
146 147 148
                    if self.is_keyword(component_name):
                        self.config[InnerConfigItem(component_name)] = config[component_name]
                        continue
R
Rongfeng Fu 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
                    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 已提交
177 178 179 180 181 182 183 184
        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 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    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 已提交
207

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

R
Rongfeng Fu 已提交
212 213 214 215 216 217 218
    @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 已提交
219
        cluster_config.set_include_file(config.get('include', ''))
R
Rongfeng Fu 已提交
220 221 222 223 224 225
        cluster_config.parser = cls
        return cluster_config

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

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

R
Rongfeng Fu 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        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 已提交
248

R
Rongfeng Fu 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    @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 已提交
289
            ConfigUtil.get_value_from_dict(conf, 'release', None, str),
R
Rongfeng Fu 已提交
290 291 292 293
            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 已提交
294 295 296 297 298 299 300

        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 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        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 已提交
320

R
Rongfeng Fu 已提交
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
        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 已提交
350 351
class ClusterConfig(object):

F
v1.5.0  
frf12 已提交
352 353
    def __init__(self, servers, name, version, tag, release, package_hash, parser=None):
        self._version = version
R
Rongfeng Fu 已提交
354
        self.origin_version = version
O
oceanbase-admin 已提交
355
        self.tag = tag
R
Rongfeng Fu 已提交
356
        self.origin_tag = tag
F
v1.5.0  
frf12 已提交
357 358
        self._release = release
        self.origin_release = release
O
oceanbase-admin 已提交
359
        self.name = name
R
Rongfeng Fu 已提交
360
        self.origin_package_hash = package_hash
F
v1.5.0  
frf12 已提交
361
        self._package_hash = package_hash
O
oceanbase-admin 已提交
362 363
        self._temp_conf = {}
        self._default_conf = {}
F
v1.5.0  
frf12 已提交
364
        self._global_conf = None
O
oceanbase-admin 已提交
365 366
        self._server_conf = {}
        self._cache_server = {}
R
Rongfeng Fu 已提交
367
        self._original_global_conf = {}
F
v1.5.0  
frf12 已提交
368 369 370 371 372 373 374 375
        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 已提交
376
        self._inner_config = {}
F
v1.5.0  
frf12 已提交
377
        self._base_dir = ''
R
Rongfeng Fu 已提交
378
        servers = list(servers)
O
oceanbase-admin 已提交
379
        self.servers = servers
R
Rongfeng Fu 已提交
380
        self._original_servers = servers # 保证顺序
O
oceanbase-admin 已提交
381 382 383 384
        for server in servers:
            self._server_conf[server] = {}
            self._cache_server[server] = None
        self._deploy_config = None
R
Rongfeng Fu 已提交
385
        self._depends = {}
R
Rongfeng Fu 已提交
386
        self.parser = parser
F
v1.5.0  
frf12 已提交
387
        self._has_package_pattern = None
F
v1.6.0  
frf12 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
        self._object_hash = None

    if sys.version_info.major == 2:
        def __hash__(self):
            if self._object_hash is None:
                m_sum = hashlib.md5()
                m_sum.update(str(self.package_hash).encode('utf-8'))
                m_sum.update(str(self.get_global_conf()).encode('utf-8'))
                for server in self.servers:
                    m_sum.update(str(self.get_server_conf(server)).encode('utf-8'))
                m_sum.update(str(self.depends).encode('utf-8'))
                self._object_hash = int(''.join(['%03d' % ord(v) for v in m_sum.digest()]))
            return self._object_hash
    else:
        def __hash__(self):
            if self._object_hash is None:
                m_sum = hashlib.md5()
                m_sum.update(str(self.package_hash).encode('utf-8'))
                m_sum.update(str(self.get_global_conf()).encode('utf-8'))
                for server in self.servers:
                    m_sum.update(str(self.get_server_conf(server)).encode('utf-8'))
                m_sum.update(str(self.depends).encode('utf-8'))
                self._object_hash = (int(''.join(['%03d' % v for v in m_sum.digest()])))
            return self._object_hash
O
oceanbase-admin 已提交
412 413 414 415

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

R
Rongfeng Fu 已提交
419 420 421 422 423 424 425 426 427 428
    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 已提交
429 430 431
    def set_deploy_config(self, _deploy_config):
        if self._deploy_config is None:
            self._deploy_config = _deploy_config
F
v1.5.0  
frf12 已提交
432
            self.set_base_dir(self._deploy_config.get_base_dir())
O
oceanbase-admin 已提交
433 434
            return True
        return False
F
v1.5.0  
frf12 已提交
435 436 437 438 439 440 441 442

    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 已提交
443 444 445 446 447 448 449 450
    @property
    def original_servers(self):
        return self._original_servers

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

R
Rongfeng Fu 已提交
451 452 453 454 455 456 457
    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 已提交
458 459 460 461 462 463
    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 已提交
464 465 466 467
    def apply_inner_config(self, config):
        self._inner_config = config
        self._clear_cache_server()

R
Rongfeng Fu 已提交
468
    def add_depend(self, name, cluster_conf):
R
Rongfeng Fu 已提交
469 470 471 472
        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 已提交
473 474
        self._depends[name] = cluster_conf

F
v1.6.0  
frf12 已提交
475 476 477
    def add_depend_component(self, depend_component_name):
        return self._deploy_config.add_depend_for_component(self.name, depend_component_name, save=False)

R
Rongfeng Fu 已提交
478 479 480 481
    def del_depend(self, name, component_name):
        if component_name in self._depends:
            del self._depends[component_name]

R
Rongfeng Fu 已提交
482
    def get_depend_servers(self, name):
R
Rongfeng Fu 已提交
483 484 485 486 487
        if name not in self._depends:
            return None
        cluster_config = self._depends[name]
        return deepcopy(cluster_config.original_servers)
        
R
Rongfeng Fu 已提交
488
    def get_depend_config(self, name, server=None):
R
Rongfeng Fu 已提交
489 490 491 492 493
        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 已提交
494

O
oceanbase-admin 已提交
495 496 497
    def update_server_conf(self, server, key, value, save=True):
        if self._deploy_config is None:
            return False
R
Rongfeng Fu 已提交
498 499
        if server not in self._server_conf:
            return False
F
v1.6.0  
frf12 已提交
500 501
        if self._temp_conf and key in self._temp_conf:
            value = self._temp_conf[key].param_type(value).value
O
oceanbase-admin 已提交
502 503 504 505 506 507 508 509 510 511
        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
F
v1.6.0  
frf12 已提交
512 513
        if self._temp_conf and key in self._temp_conf:
            value = self._temp_conf[key].param_type(value).value
O
oceanbase-admin 已提交
514 515
        if not self._deploy_config.update_component_global_conf(self.name, key, value, save):
            return False
R
Rongfeng Fu 已提交
516
        self._update_global_conf(key, value)
O
oceanbase-admin 已提交
517 518 519 520 521
        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 已提交
522 523
    def _update_global_conf(self, key, value):
        self._original_global_conf[key] = value
F
v1.6.0  
frf12 已提交
524 525
        if self._global_conf:
            self._global_conf[key] = value
R
Rongfeng Fu 已提交
526

F
v1.5.0  
frf12 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    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 已提交
544 545 546
    def get_unconfigured_require_item(self, server):
        items = []
        config = self.get_server_conf(server)
R
Rongfeng Fu 已提交
547 548 549 550 551 552 553
        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 已提交
554 555 556
        return items

    def get_server_conf_with_default(self, server):
R
Rongfeng Fu 已提交
557 558
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
559 560 561 562 563 564 565 566
        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 已提交
567 568
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
569 570 571 572 573 574 575 576
        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 已提交
577 578
        if server not in self._server_conf:
            return None
O
oceanbase-admin 已提交
579 580 581 582 583 584 585 586 587 588 589
        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 已提交
590
            if self._temp_conf[key].require and self._temp_conf[key].default is not None:
O
oceanbase-admin 已提交
591
                self._default_conf[key] = self._temp_conf[key].default
F
v1.5.0  
frf12 已提交
592 593
        self._global_conf = None
        self._clear_cache_server()
O
oceanbase-admin 已提交
594

F
v1.6.0  
frf12 已提交
595 596 597 598 599 600 601
    def _apply_temp_conf(self, conf):
        if self._temp_conf:
            for key in conf:
                if key in self._temp_conf:
                    conf[key] = self._temp_conf[key].param_type(conf[key]).value
        return conf

R
Rongfeng Fu 已提交
602 603 604 605 606
    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 已提交
607

R
Rongfeng Fu 已提交
608 609 610
    def check_param(self):
        error = []
        if self._temp_conf:
F
v1.5.0  
frf12 已提交
611
            error += self._check_param(self.get_global_conf())
R
Rongfeng Fu 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
            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 已提交
627
    def set_global_conf(self, conf):
R
Rongfeng Fu 已提交
628
        self._original_global_conf = deepcopy(conf)
F
v1.5.0  
frf12 已提交
629
        self._global_conf = None
R
Rongfeng Fu 已提交
630
        self._clear_cache_server()
O
oceanbase-admin 已提交
631

F
v1.5.0  
frf12 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644
    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 已提交
645 646 647
    def add_server_conf(self, server, conf):
        if server not in self.servers:
            self.servers.append(server)
R
Rongfeng Fu 已提交
648 649
        if server not in self._original_servers:
            self._original_servers.append(server)
O
oceanbase-admin 已提交
650 651 652 653
        self._server_conf[server] = conf
        self._cache_server[server] = None

    def get_global_conf(self):
F
v1.5.0  
frf12 已提交
654 655 656
        if self._global_conf is None:
            self._global_conf = deepcopy(self._default_conf)
            self._global_conf.update(self._get_include_config('config', {}))
F
v1.6.0  
frf12 已提交
657 658 659
            if self._original_global_conf:
                self._global_conf.update(self._original_global_conf)
            self._global_conf = self._apply_temp_conf(self._global_conf)
O
oceanbase-admin 已提交
660 661
        return self._global_conf

F
v1.5.0  
frf12 已提交
662 663 664 665 666 667
    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 "
F
v1.6.0  
frf12 已提交
668
                "and set environment variables {}".format(RsyncConfig.RSYNC, ENV_BASE_DIR))
F
v1.5.0  
frf12 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
        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 已提交
759 760 761 762
    def get_server_conf(self, server):
        if server not in self._server_conf:
            return None
        if self._cache_server[server] is None:
F
v1.6.0  
frf12 已提交
763
            conf = self._apply_temp_conf(deepcopy(self._inner_config.get(server.name, {})))
F
v1.5.0  
frf12 已提交
764
            conf.update(self.get_global_conf())
F
v1.6.0  
frf12 已提交
765
            conf.update(self._apply_temp_conf(self._server_conf[server]))
O
oceanbase-admin 已提交
766 767 768
            self._cache_server[server] = conf
        return self._cache_server[server]

R
Rongfeng Fu 已提交
769 770 771
    def get_original_global_conf(self):
        return self._original_global_conf

R
Rongfeng Fu 已提交
772 773 774
    def get_original_server_conf(self, server):
        return self._server_conf.get(server)

O
oceanbase-admin 已提交
775 776 777 778 779 780 781 782 783 784 785 786

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 已提交
787
    STATUS_UPRADEING = 'upgrading'
O
oceanbase-admin 已提交
788 789 790 791 792 793 794 795 796 797


class DeployConfigStatus(Enum):

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


F
v1.5.0  
frf12 已提交
798 799 800 801 802 803
class  DeployInstallMode(object):

    LN = 'ln'
    CP = 'cp'


O
oceanbase-admin 已提交
804 805
class DeployInfo(object):

R
Rongfeng Fu 已提交
806
    def __init__(self, name, status, components=OrderedDict(), config_status=DeployConfigStatus.UNCHNAGE):
O
oceanbase-admin 已提交
807 808 809 810 811 812 813 814 815 816 817 818
        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 已提交
819
class DeployConfig(SafeStdio):
O
oceanbase-admin 已提交
820

F
v1.5.0  
frf12 已提交
821
    def __init__(self, yaml_path, yaml_loader=yaml, inner_config=None, config_parser_manager=None, stdio=None):
O
oceanbase-admin 已提交
822 823
        self._user = None
        self.unuse_lib_repository = False
R
Rongfeng Fu 已提交
824
        self.auto_create_tenant = False
R
Rongfeng Fu 已提交
825
        self._inner_config = inner_config
R
Rongfeng Fu 已提交
826
        self.components = OrderedDict()
O
oceanbase-admin 已提交
827 828 829
        self._src_data = None
        self.yaml_path = yaml_path
        self.yaml_loader = yaml_loader
R
Rongfeng Fu 已提交
830
        self.config_parser_manager = config_parser_manager if config_parser_manager else DEFAULT_CONFIG_PARSER_MANAGER
F
v1.5.0  
frf12 已提交
831 832
        self.stdio = stdio
        self._ignore_include_error = False
R
Rongfeng Fu 已提交
833
        if self.config_parser_manager is None:
F
v1.6.0  
frf12 已提交
834
            raise ParserError('ConfigParserManager Not Set')
O
oceanbase-admin 已提交
835 836 837 838 839 840
        self._load()

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

R
Rongfeng Fu 已提交
841 842 843 844 845 846 847 848 849 850 851 852
    @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 已提交
853

R
Rongfeng Fu 已提交
854
        self._inner_config = inner_config
F
v1.5.0  
frf12 已提交
855 856 857 858 859
        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 已提交
860

O
oceanbase-admin 已提交
861 862 863 864 865 866 867
    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 已提交
868 869 870 871 872 873 874
    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 已提交
875 876 877 878 879 880 881 882 883 884 885 886
    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 已提交
887

R
Rongfeng Fu 已提交
888 889 890 891 892 893 894 895 896 897
        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 已提交
898
    def _load(self):
F
v1.6.0  
frf12 已提交
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
        try:
            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])
        except:
            pass
O
oceanbase-admin 已提交
928 929 930
        if not self.user:
            self.set_user_conf(UserConfig())

F
v1.5.0  
frf12 已提交
931 932 933 934 935 936 937
    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 "
F
v1.6.0  
frf12 已提交
938
            "and set environment variables {}".format('include', ENV_BASE_DIR))
F
v1.5.0  
frf12 已提交
939 940 941 942 943 944 945 946 947 948
        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 已提交
949 950 951 952 953 954 955 956 957
    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.6.0  
frf12 已提交
958

R
Rongfeng Fu 已提交
959 960 961 962 963
    def _dump_inner_config(self):
        if self.inner_config:
            self._separate_config()
            self.inner_config.dump()

O
oceanbase-admin 已提交
964 965 966
    def _dump(self):
        try:
            with open(self.yaml_path, 'w') as f:
R
Rongfeng Fu 已提交
967
                self._dump_inner_config()
O
oceanbase-admin 已提交
968 969 970
                self.yaml_loader.dump(self._src_data, f)
            return True
        except:
R
Rongfeng Fu 已提交
971 972
            import logging
            logging.exception('')
O
oceanbase-admin 已提交
973 974 975 976 977 978
            pass
        return False

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

F
v1.5.0  
frf12 已提交
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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    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 已提交
1020 1021 1022
    def set_user_conf(self, conf):
        self._user = conf

R
Rongfeng Fu 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    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 已提交
1051 1052 1053 1054 1055 1056
    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 已提交
1057 1058
        component_config = cluster_config.parser.get_server_src_conf(cluster_config, self._src_data[component_name], server)
        component_config[key] = value
O
oceanbase-admin 已提交
1059 1060 1061 1062 1063
        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 已提交
1064 1065 1066
        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 已提交
1067 1068
        return self.dump() if save else True

R
Rongfeng Fu 已提交
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    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 已提交
1081
        else:
R
Rongfeng Fu 已提交
1082 1083 1084 1085 1086 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
            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 已提交
1116 1117 1118 1119 1120 1121


class Deploy(object):

    DEPLOY_STATUS_FILE = '.data'
    DEPLOY_YAML_NAME = 'config.yaml'
R
Rongfeng Fu 已提交
1122
    INNER_CONFIG_NAME = 'inner_config.yaml'
R
Rongfeng Fu 已提交
1123
    UPRADE_META_NAME = '.upgrade'
O
oceanbase-admin 已提交
1124

R
Rongfeng Fu 已提交
1125
    def __init__(self, config_dir, config_parser_manager=None, stdio=None):
O
oceanbase-admin 已提交
1126 1127 1128 1129 1130
        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 已提交
1131
        self.config_parser_manager = config_parser_manager
R
Rongfeng Fu 已提交
1132
        self._uprade_meta = None
O
oceanbase-admin 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

    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 已提交
1149 1150 1151 1152
    @staticmethod
    def get_upgrade_meta_path(path):
        return os.path.join(path, Deploy.UPRADE_META_NAME)

R
Rongfeng Fu 已提交
1153 1154 1155 1156
    @staticmethod
    def get_inner_config_path(path):
        return os.path.join(path, Deploy.INNER_CONFIG_NAME)

O
oceanbase-admin 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    @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 已提交
1171
                        ConfigUtil.get_value_from_dict(data, 'components', OrderedDict()),
O
oceanbase-admin 已提交
1172 1173 1174 1175 1176 1177
                        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 已提交
1178 1179
    def _load_deploy_config(self, path):
        yaml_loader = YamlLoader(stdio=self.stdio)
F
v1.5.0  
frf12 已提交
1180
        deploy_config = DeployConfig(path, yaml_loader=yaml_loader, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
R
Rongfeng Fu 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        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 已提交
1193

R
Rongfeng Fu 已提交
1194 1195 1196 1197 1198
    @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 已提交
1199 1200 1201
    @property
    def deploy_config(self):
        if self._config is None:
R
Rongfeng Fu 已提交
1202 1203
            path = self.get_deploy_yaml_path(self.config_dir)
            self._config = self._load_deploy_config(path)
O
oceanbase-admin 已提交
1204 1205
        return self._config

R
Rongfeng Fu 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    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 已提交
1226
    def apply_temp_deploy_config(self):
R
Rongfeng Fu 已提交
1227
        self.stdio and getattr(self.stdio, 'verbose', print)('%s apply temp config' % self.name)
O
oceanbase-admin 已提交
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
        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 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    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 已提交
1308 1309
    def update_component_repository(self, repository):
        if not self.deploy_config.update_component_package_hash(repository.name, repository.hash, repository.version):
R
Rongfeng Fu 已提交
1310
            return False
R
Rongfeng Fu 已提交
1311
        self.use_model(repository.name, repository)
R
Rongfeng Fu 已提交
1312 1313 1314 1315 1316 1317 1318
        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 已提交
1319
                self.update_component_repository(dest_repository)
R
Rongfeng Fu 已提交
1320 1321 1322
            return True
        return False

O
oceanbase-admin 已提交
1323 1324
    def update_deploy_status(self, status):
        if isinstance(status, DeployStatus):
R
Rongfeng Fu 已提交
1325 1326 1327 1328 1329
            if self._update_deploy_status(status):
                if DeployStatus.STATUS_DESTROYED == status:
                    self.deploy_info.components = {}
                    self._dump_deploy_info()
                return True
O
oceanbase-admin 已提交
1330 1331 1332 1333
        return False

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

R
Rongfeng Fu 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
    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 已提交
1351

R
Rongfeng Fu 已提交
1352 1353 1354 1355 1356 1357 1358
    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 已提交
1359
    def _format_paraser_name(self, style):
R
Rongfeng Fu 已提交
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
        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 已提交
1372
            clz_name = self._format_paraser_name(style)
R
Rongfeng Fu 已提交
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
            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 已提交
1407
            raise ParserError('Unsupported configuration style: %s %s' % (component, style))
R
Rongfeng Fu 已提交
1408 1409
        return parser

O
oceanbase-admin 已提交
1410 1411 1412 1413 1414

class DeployManager(Manager):

    RELATIVE_PATH = 'cluster/'
    
R
Rongfeng Fu 已提交
1415
    def __init__(self, home_path, lock_manager=None, stdio=None):
O
oceanbase-admin 已提交
1416
        super(DeployManager, self).__init__(home_path, stdio)
R
Rongfeng Fu 已提交
1417
        self.lock_manager = lock_manager
R
Rongfeng Fu 已提交
1418
        self.config_parser_manager = ConfigParserManager(home_path, stdio)
R
Rongfeng Fu 已提交
1419 1420 1421 1422 1423 1424 1425 1426

    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 已提交
1427

R
Rongfeng Fu 已提交
1428
    def get_deploy_configs(self, read_only=True):
O
oceanbase-admin 已提交
1429
        configs = []
R
Rongfeng Fu 已提交
1430 1431
        for name in os.listdir(self.path):
            path = os.path.join(self.path, name)
O
oceanbase-admin 已提交
1432
            if os.path.isdir(path):
R
Rongfeng Fu 已提交
1433
                self._lock(name, read_only)
R
Rongfeng Fu 已提交
1434
                configs.append(Deploy(path, config_parser_manager=self.config_parser_manager, stdio=self.stdio))
O
oceanbase-admin 已提交
1435 1436
        return configs

R
Rongfeng Fu 已提交
1437 1438
    def get_deploy_config(self, name, read_only=False):
        self._lock(name, read_only)
O
oceanbase-admin 已提交
1439 1440
        path = os.path.join(self.path, name)
        if os.path.isdir(path):
R
Rongfeng Fu 已提交
1441
            return Deploy(path, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
O
oceanbase-admin 已提交
1442 1443 1444
        return None

    def create_deploy_config(self, name, src_yaml_path):
R
Rongfeng Fu 已提交
1445
        self._lock(name)
O
oceanbase-admin 已提交
1446 1447 1448 1449
        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 已提交
1450
            return Deploy(config_dir, config_parser_manager=self.config_parser_manager, stdio=self.stdio)
O
oceanbase-admin 已提交
1451 1452 1453 1454 1455
        else:
            self._rm(config_dir)
            return None
        
    def remove_deploy_config(self, name):
R
Rongfeng Fu 已提交
1456
        self._lock(name)
O
oceanbase-admin 已提交
1457 1458
        config_dir = os.path.join(self.path, name)
        self._rm(config_dir)