_cmd.py 44.0 KB
Newer Older
R
Rongfeng Fu 已提交
1

O
oceanbase-admin 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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 sys
import time
import logging
from logging import handlers
from uuid import uuid1 as uuid
R
Rongfeng Fu 已提交
30
from optparse import OptionParser, OptionGroup, BadOptionError, Option
O
oceanbase-admin 已提交
31 32 33 34

from core import ObdHome
from _stdio import IO
from log import Logger
R
Rongfeng Fu 已提交
35
from _errno import DOC_LINK_MSG, LockError
O
oceanbase-admin 已提交
36 37 38 39
from tool import DirectoryUtil, FileUtil


ROOT_IO = IO(1)
R
Rongfeng Fu 已提交
40
VERSION = u'<VERSION>'
R
Rongfeng Fu 已提交
41 42 43
REVISION = '<CID>'
BUILD_BRANCH = '<B_BRANCH>'
BUILD_TIME = '<B_TIME>'
R
Rongfeng Fu 已提交
44
DEBUG = True if '<DEBUG>' else False
O
oceanbase-admin 已提交
45 46


R
Rongfeng Fu 已提交
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
class AllowUndefinedOptionParser(OptionParser):

    def __init__(self,
                usage=None,
                option_list=None,
                option_class=Option,
                version=None,
                conflict_handler="error",
                description=None,
                formatter=None,
                add_help_option=True,
                prog=None,
                epilog=None,
                allow_undefine=True):
        OptionParser.__init__(
            self, usage, option_list, option_class, version, conflict_handler,
            description, formatter, add_help_option, prog, epilog
        )
        self.allow_undefine = allow_undefine

    def warn(self, msg, file=None):
        print ('warn: %s' % msg)

    def _process_long_opt(self, rargs, values):
        try:
F
v1.4.0  
frf12 已提交
72
            value = rargs[0]
R
Rongfeng Fu 已提交
73 74 75
            OptionParser._process_long_opt(self, rargs, values)
        except BadOptionError as e:
            if self.allow_undefine:
F
v1.4.0  
frf12 已提交
76 77
                key = e.opt_str
                value = value[len(key)+1:]
F
frf12 已提交
78
                setattr(values, key.strip('-').replace('-', '_'), value if value != '' else True)
R
Rongfeng Fu 已提交
79 80 81 82 83 84
                return self.warn(e)
            else:
                raise e

    def _process_short_opts(self, rargs, values):
        try:
F
v1.4.0  
frf12 已提交
85
            value = rargs[0]
R
Rongfeng Fu 已提交
86 87 88
            OptionParser._process_short_opts(self, rargs, values)
        except BadOptionError as e:
            if self.allow_undefine:
F
v1.4.0  
frf12 已提交
89 90
                key = e.opt_str
                value = value[len(key)+1:]
F
frf12 已提交
91
                setattr(values, key.strip('-').replace('-', '_'), value if value != '' else True)
R
Rongfeng Fu 已提交
92 93 94 95 96
                return self.warn(e)
            else:
                raise e


O
oceanbase-admin 已提交
97 98 99 100 101 102 103 104 105 106
class BaseCommand(object):

    def __init__(self, name, summary):
        self.name = name
        self.summary = summary
        self.args = []
        self.cmds = []
        self.opts = {}
        self.prev_cmd = ''
        self.is_init = False
R
Rongfeng Fu 已提交
107 108
        self.hidden = False
        self.parser = AllowUndefinedOptionParser(add_help_option=False)
R
Rongfeng Fu 已提交
109 110
        self.parser.add_option('-h', '--help', action='callback', callback=self._show_help, help='Show help and exit.')
        self.parser.add_option('-v', '--verbose', action='callback', callback=self._set_verbose, help='Activate verbose output.')
O
oceanbase-admin 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

    def _set_verbose(self, *args, **kwargs):
        ROOT_IO.set_verbose_level(0xfffffff)

    def init(self, cmd, args):
        if self.is_init is False:
            self.prev_cmd = cmd
            self.args = args
            self.is_init = True
            self.parser.prog = self.prev_cmd
            option_list = self.parser.option_list[2:]
            option_list.append(self.parser.option_list[0])
            option_list.append(self.parser.option_list[1])
            self.parser.option_list = option_list
        return self

    def parse_command(self):
        self.opts, self.cmds = self.parser.parse_args(self.args)
        return self.opts

    def do_command(self):
        raise NotImplementedError

    def _show_help(self, *args, **kwargs):
        ROOT_IO.print(self._mk_usage())
        self.parser.exit(1)

    def _mk_usage(self):
        return self.parser.format_help()


class ObdCommand(BaseCommand):

    OBD_PATH = os.path.join(os.environ.get('OBD_HOME', os.getenv('HOME')), '.obd')
R
Rongfeng Fu 已提交
145
    OBD_INSTALL_PRE = os.environ.get('OBD_INSTALL_PRE', '/')
R
Rongfeng Fu 已提交
146
    OBD_DEV_MODE_FILE = '.dev_mode'
O
oceanbase-admin 已提交
147 148 149 150 151 152 153

    def init_home(self):
        version_path = os.path.join(self.OBD_PATH, 'version')
        need_update = True
        version_fobj = FileUtil.open(version_path, 'a+', stdio=ROOT_IO)
        version_fobj.seek(0)
        version = version_fobj.read()
R
Rongfeng Fu 已提交
154
        if VERSION != version:
R
Rongfeng Fu 已提交
155 156 157 158 159 160
            for part in ['plugins', 'config_parser', 'mirror/remote']:
                obd_part_dir = os.path.join(self.OBD_PATH, part)
                if DirectoryUtil.mkdir(self.OBD_PATH):
                    root_part_path = os.path.join(self.OBD_INSTALL_PRE, 'usr/obd/', part)
                    if os.path.exists(root_part_path):
                        DirectoryUtil.copy(root_part_path, obd_part_dir, ROOT_IO)
O
oceanbase-admin 已提交
161 162 163 164 165 166
            version_fobj.seek(0)
            version_fobj.truncate()
            version_fobj.write(VERSION)
            version_fobj.flush()
        version_fobj.close()

R
Rongfeng Fu 已提交
167 168 169 170 171 172 173 174 175 176 177 178
    @property
    def dev_mode_path(self):
        return os.path.join(self.OBD_PATH, self.OBD_DEV_MODE_FILE)

    @property
    def dev_mode(self):
        return os.path.exists(self.dev_mode_path)

    def parse_command(self):
        self.parser.allow_undefine = self.dev_mode
        return super(ObdCommand, self).parse_command()

O
oceanbase-admin 已提交
179 180 181
    def do_command(self):
        self.parse_command()
        self.init_home()
R
Rongfeng Fu 已提交
182 183
        trace_id = uuid()
        ret = False
O
oceanbase-admin 已提交
184 185 186 187 188 189
        try:
            log_dir = os.path.join(self.OBD_PATH, 'log')
            DirectoryUtil.mkdir(log_dir)
            log_path = os.path.join(log_dir, 'obd')
            logger = Logger('obd')
            handler = handlers.TimedRotatingFileHandler(log_path, when='midnight', interval=1, backupCount=30)
R
Rongfeng Fu 已提交
190
            handler.setFormatter(logging.Formatter("[%%(asctime)s.%%(msecs)03d] [%s] [%%(levelname)s] %%(message)s" % trace_id, "%Y-%m-%d %H:%M:%S"))
O
oceanbase-admin 已提交
191 192
            logger.addHandler(handler)
            ROOT_IO.trace_logger = logger
R
Rongfeng Fu 已提交
193
            obd = ObdHome(self.OBD_PATH, self.dev_mode, ROOT_IO)
O
oceanbase-admin 已提交
194
            ROOT_IO.track_limit += 1
R
Rongfeng Fu 已提交
195 196
            ROOT_IO.verbose('cmd: %s' % self.cmds)
            ROOT_IO.verbose('opts: %s' % self.opts)
R
Rongfeng Fu 已提交
197
            ret = self._do_command(obd)
R
Rongfeng Fu 已提交
198 199
            if not ret:
                ROOT_IO.print(DOC_LINK_MSG)
O
oceanbase-admin 已提交
200 201
        except NotImplementedError:
            ROOT_IO.exception('command \'%s\' is not implemented' % self.prev_cmd)
R
Rongfeng Fu 已提交
202
        except LockError:
R
Rongfeng Fu 已提交
203
            ROOT_IO.exception('Another app is currently holding the obd lock.')
O
oceanbase-admin 已提交
204 205 206
        except SystemExit:
            pass
        except:
R
Rongfeng Fu 已提交
207 208
            e = sys.exc_info()[1]
            ROOT_IO.exception('Running Error: %s' % e)
R
Rongfeng Fu 已提交
209 210
        if DEBUG:
            ROOT_IO.print('Trace ID: %s' % trace_id)
R
Rongfeng Fu 已提交
211
        return ret
O
oceanbase-admin 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224

    def _do_command(self, obd):
        raise NotImplementedError


class MajorCommand(BaseCommand):

    def __init__(self, name, summary):
        super(MajorCommand, self).__init__(name, summary)
        self.commands = {}

    def _mk_usage(self):
        if self.commands:
R
Rongfeng Fu 已提交
225
            usage = ['%s <command> [options]\n\nAvailable commands:\n' % self.prev_cmd]
O
oceanbase-admin 已提交
226 227 228
            commands = [x for x in self.commands.values() if not (hasattr(x, 'hidden') and x.hidden)]
            commands.sort(key=lambda x: x.name)
            for command in commands:
R
Rongfeng Fu 已提交
229 230
                if command.hidden is False:
                    usage.append("%-14s %s\n" % (command.name, command.summary))
O
oceanbase-admin 已提交
231 232 233 234 235 236 237 238
            self.parser.set_usage('\n'.join(usage))
        return super(MajorCommand, self)._mk_usage()

    def do_command(self):
        if not self.is_init:
            ROOT_IO.error('%s command not init' % self.prev_cmd)
            raise SystemExit('command not init')
        if len(self.args) < 1:
R
Rongfeng Fu 已提交
239
            ROOT_IO.print('You need to give some commands.\n\nTry `obd --help` for more information.')
O
oceanbase-admin 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
            self._show_help()
            return False
        base, args = self.args[0], self.args[1:]
        if base not in self.commands:
            self.parse_command()
            self._show_help()
            return False
        cmd = '%s %s' % (self.prev_cmd, base)
        ROOT_IO.track_limit += 1
        return self.commands[base].init(cmd, args).do_command()
        
    def register_command(self, command):
        self.commands[command.name] = command


R
Rongfeng Fu 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311


class HiddenObdCommand(ObdCommand):

    def __init__(self, name, summary):
        super(HiddenObdCommand, self).__init__(name, summary)
        self.hidden = self.dev_mode is False


class HiddenMajorCommand(MajorCommand, HiddenObdCommand):

    pass


class DevCommand(HiddenObdCommand):

    def do_command(self):
        if self.hidden:
            ROOT_IO.error('`%s` is a developer command. Please start the developer mode first.\nUse `obd devmode enable` to start the developer mode' % self.prev_cmd)
            return False
        return super(DevCommand, self).do_command()


class DevModeEnableCommand(HiddenObdCommand):

    def __init__(self):
        super(DevModeEnableCommand, self).__init__('enable', 'Enable Dev Mode')

    def _do_command(self, obd):
        from tool import FileUtil
        if FileUtil.open(self.dev_mode_path, _type='w', stdio=obd.stdio):
            obd.stdio.print("Dev Mode: ON")
            return True
        return False


class DevModeDisableCommand(HiddenObdCommand):

    def __init__(self):
        super(DevModeDisableCommand, self).__init__('disable', 'Disable Dev Mode')

    def _do_command(self, obd):
        from tool import FileUtil
        if FileUtil.rm(self.dev_mode_path, stdio=obd.stdio):
            obd.stdio.print("Dev Mode: OFF")
            return True
        return False


class DevModeMajorCommand(HiddenMajorCommand):

    def __init__(self):
        super(DevModeMajorCommand, self).__init__('devmode', 'Developer mode switch')
        self.register_command(DevModeEnableCommand())
        self.register_command(DevModeDisableCommand())


O
oceanbase-admin 已提交
312 313 314
class MirrorCloneCommand(ObdCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
315
        super(MirrorCloneCommand, self).__init__('clone', 'Clone an RPM package to the local mirror repository.')
R
Rongfeng Fu 已提交
316
        self.parser.add_option('-f', '--force', action='store_true', help="Force clone, overwrite the mirror.")
O
oceanbase-admin 已提交
317 318 319

    def init(self, cmd, args):
        super(MirrorCloneCommand, self).init(cmd, args)
R
Rongfeng Fu 已提交
320
        self.parser.set_usage('%s [mirror path] [options]' % self.prev_cmd)
O
oceanbase-admin 已提交
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
        return self

    def _do_command(self, obd):
        if self.cmds:
            for src in self.cmds:
                if not obd.add_mirror(src, self.opts):
                    return False
            return True
        else:
            return self._show_help()


class MirrorCreateCommand(ObdCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
336
        super(MirrorCreateCommand, self).__init__('create', 'Create a local mirror by using the local binary file.')
O
oceanbase-admin 已提交
337
        self.parser.conflict_handler = 'resolve'
R
Rongfeng Fu 已提交
338 339 340 341 342
        self.parser.add_option('-n', '--name', type='string', help="Mirror name.")
        self.parser.add_option('-t', '--tag', type='string', help="Mirror tags. Multiple tags are separated with commas.")
        self.parser.add_option('-V', '--version', type='string', help="Mirror version.")
        self.parser.add_option('-p','--path', type='string', help="Mirror path. [./]", default='./')
        self.parser.add_option('-f', '--force', action='store_true', help="Force create, overwrite the mirror.")
O
oceanbase-admin 已提交
343 344 345 346 347 348 349 350 351
        self.parser.conflict_handler = 'error'

    def _do_command(self, obd):
        return obd.create_repository(self.opts)


class MirrorListCommand(ObdCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
352
        super(MirrorListCommand, self).__init__('list', 'List mirrors.')
O
oceanbase-admin 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

    def show_pkg(self, name, pkgs):
        ROOT_IO.print_list(
            pkgs, 
            ['name', 'version', 'release', 'arch', 'md5'], 
            lambda x: [x.name, x.version, x.release, x.arch, x.md5],
            title='%s Package List' % name
        )

    def _do_command(self, obd):
        if self.cmds:
            name = self.cmds[0]
            if name == 'local':
                pkgs = obd.mirror_manager.local_mirror.get_all_pkg_info()
                self.show_pkg(name, pkgs)
                return True
            else:
R
Rongfeng Fu 已提交
370
                repos = obd.mirror_manager.get_mirrors(is_enabled=None)
O
oceanbase-admin 已提交
371
                for repo in repos:
R
Rongfeng Fu 已提交
372
                    if repo.section_name == name:
R
Rongfeng Fu 已提交
373 374 375
                        if not repo.enabled:
                            ROOT_IO.error('Mirror repository %s is disabled.' % name)
                            return False
O
oceanbase-admin 已提交
376 377 378 379 380 381
                        pkgs = repo.get_all_pkg_info()
                        self.show_pkg(name, pkgs)
                        return True
                ROOT_IO.error('No such mirror repository: %s' % name)
                return False
        else:
R
Rongfeng Fu 已提交
382
            repos = obd.mirror_manager.get_mirrors(is_enabled=None)
O
oceanbase-admin 已提交
383
            ROOT_IO.print_list(
R
Rongfeng Fu 已提交
384 385 386
                repos,
                ['SectionName', 'Type', 'Enabled','Update Time'], 
                lambda x: [x.section_name, x.mirror_type.value, x.enabled, time.strftime("%Y-%m-%d %H:%M", time.localtime(x.repo_age))],
O
oceanbase-admin 已提交
387 388 389 390 391 392 393 394
                title='Mirror Repository List'
            )
        return True


class MirrorUpdateCommand(ObdCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
395
        super(MirrorUpdateCommand, self).__init__('update', 'Update remote mirror information.')
O
oceanbase-admin 已提交
396 397 398
    
    def _do_command(self, obd):
        success = True
R
Rongfeng Fu 已提交
399 400 401
        current = int(time.time())
        mirrors = obd.mirror_manager.get_remote_mirrors()
        for mirror in mirrors:
O
oceanbase-admin 已提交
402
            try:
R
Rongfeng Fu 已提交
403 404
                if mirror.enabled and mirror.repo_age < current:
                    success = mirror.update_mirror() and success
O
oceanbase-admin 已提交
405 406 407
            except:
                success = False
                ROOT_IO.stop_loading('fail')
R
Rongfeng Fu 已提交
408
                ROOT_IO.exception('Fail to synchronize mirorr (%s)' % mirror.name)
O
oceanbase-admin 已提交
409 410 411
        return success


R
Rongfeng Fu 已提交
412 413 414 415 416 417 418
class MirrorEnableCommand(ObdCommand):

    def __init__(self):
        super(MirrorEnableCommand, self).__init__('enable', 'Enable remote mirror repository.')
    
    def _do_command(self, obd):
        name = self.cmds[0]
R
Rongfeng Fu 已提交
419
        return obd.mirror_manager.set_remote_mirror_enabled(name, True)
R
Rongfeng Fu 已提交
420 421 422 423 424 425 426 427 428


class MirrorDisableCommand(ObdCommand):

    def __init__(self):
        super(MirrorDisableCommand, self).__init__('disable', 'Disable remote mirror repository.')
    
    def _do_command(self, obd):
        name = self.cmds[0]
R
Rongfeng Fu 已提交
429
        return obd.mirror_manager.set_remote_mirror_enabled(name, False)
R
Rongfeng Fu 已提交
430 431


O
oceanbase-admin 已提交
432 433 434
class MirrorMajorCommand(MajorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
435
        super(MirrorMajorCommand, self).__init__('mirror', 'Manage a component repository for OBD.')
O
oceanbase-admin 已提交
436 437 438 439
        self.register_command(MirrorListCommand())
        self.register_command(MirrorCloneCommand())
        self.register_command(MirrorCreateCommand())
        self.register_command(MirrorUpdateCommand())
R
Rongfeng Fu 已提交
440 441
        self.register_command(MirrorEnableCommand())
        self.register_command(MirrorDisableCommand())
O
oceanbase-admin 已提交
442 443


R
Rongfeng Fu 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
class RepositoryListCommand(ObdCommand):

    def __init__(self):
        super(RepositoryListCommand, self).__init__('list', 'List local repository.')

    def show_repo(self, repos, name=None):
        ROOT_IO.print_list(
            repos,
            ['name', 'version', 'release', 'arch', 'md5', 'tags'], 
            lambda x: [x.name, x.version, x.release, x.arch, x.md5, ', '.join(x.tags)],
            title='%s Local Repository List' % name if name else ''
        )

    def _do_command(self, obd):
        name = self.cmds[0] if self.cmds else None
        repos = obd.repository_manager.get_repositories_view(name)
        self.show_repo(repos, name)
        return True


class RepositoryMajorCommand(MajorCommand):

    def __init__(self):
        super(RepositoryMajorCommand, self).__init__('repo', 'Manage local repository for OBD.')
        self.register_command(RepositoryListCommand())


O
oceanbase-admin 已提交
471 472 473 474
class ClusterMirrorCommand(ObdCommand):

    def init(self, cmd, args):
        super(ClusterMirrorCommand, self).init(cmd, args)
R
Rongfeng Fu 已提交
475
        self.parser.set_usage('%s <deploy name> [options]' % self.prev_cmd)
O
oceanbase-admin 已提交
476 477 478
        return self


R
Rongfeng Fu 已提交
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
class ClusterConfigStyleChange(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterConfigStyleChange, self).__init__('chst', 'Change Deployment Configuration Style')
        self.parser.add_option('-c', '--components', type='string', help="List the components. Multiple components are separated with commas.")
        self.parser.add_option('--style', type='string', help="Preferred Style")

    def _do_command(self, obd):
        if self.cmds:
            return obd.change_deploy_config_style(self.cmds[0], self.opts)
        else:
            return self._show_help()



class ClusterCheckForOCPChange(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterCheckForOCPChange, self).__init__('check4ocp', 'Check Whether OCP Can Take Over Configurations in Use')
        self.parser.add_option('-c', '--components', type='string', help="List the components. Multiple components are separated with commas.")
        self.parser.add_option('-V', '--version', type='string', help="OCP Version", default='3.1.1')

    def _do_command(self, obd):
        if self.cmds:
            return obd.check_for_ocp(self.cmds[0], self.opts)
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
508 509 510 511 512 513 514
class ClusterAutoDeployCommand(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterAutoDeployCommand, self).__init__('autodeploy', 'Deploy a cluster automatically by using a simple configuration file.')
        self.parser.add_option('-c', '--config', type='string', help="Path to the configuration file.")
        self.parser.add_option('-f', '--force', action='store_true', help="Force autodeploy, overwrite the home_path.")
        self.parser.add_option('-U', '--unuselibrepo', '--ulp', action='store_true', help="Disable OBD from installing the libs mirror automatically.")
A
Amber Zhang 已提交
515
        self.parser.add_option('-A', '--auto-create-tenant', '--act', action='store_true', help="Automatically create a tenant named `test` by using all the available resource of the cluster.")
R
Rongfeng Fu 已提交
516 517 518 519 520 521 522 523 524 525 526 527 528 529
        self.parser.add_option('--force-delete', action='store_true', help="Force delete, delete the registered cluster.")
        self.parser.add_option('-s', '--strict-check', action='store_true', help="Throw errors instead of warnings when check fails.")

    def _do_command(self, obd):
        if self.cmds:
            name = self.cmds[0]
            if obd.genconfig(name, self.opts):
                self.opts.config = ''
                return obd.deploy_cluster(name, self.opts) and obd.start_cluster(name, self.cmds[1:], self.opts)
            return False        
        else:
            return self._show_help()


O
oceanbase-admin 已提交
530 531 532
class ClusterDeployCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
533 534 535 536
        super(ClusterDeployCommand, self).__init__('deploy', 'Deploy a cluster by using the current deploy configuration or a deploy yaml file.')
        self.parser.add_option('-c', '--config', type='string', help="Path to the configuration yaml file.")
        self.parser.add_option('-f', '--force', action='store_true', help="Force deploy, overwrite the home_path.", default=False)
        self.parser.add_option('-U', '--unuselibrepo', '--ulp', action='store_true', help="Disable OBD from installing the libs mirror automatically.")
A
Amber Zhang 已提交
537
        self.parser.add_option('-A', '--auto-create-tenant', '--act', action='store_true', help="Automatically create a tenant named `test` by using all the available resource of the cluster.")
O
oceanbase-admin 已提交
538 539 540 541 542 543 544 545 546 547 548 549
        # self.parser.add_option('-F', '--fuzzymatch', action='store_true', help="enable fuzzy match when search package")

    def _do_command(self, obd):
        if self.cmds:
            return obd.deploy_cluster(self.cmds[0], self.opts)
        else:
            return self._show_help()


class ClusterStartCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
550 551 552 553 554
        super(ClusterStartCommand, self).__init__('start', 'Start a deployed cluster.')
        self.parser.add_option('-s', '--servers', type='string', help="List the started servers. Multiple servers are separated with commas.")
        self.parser.add_option('-c', '--components', type='string', help="List the started components. Multiple components are separated with commas.")
        self.parser.add_option('-f', '--force-delete', action='store_true', help="Force delete, delete the registered cluster.")
        self.parser.add_option('-S', '--strict-check', action='store_true', help="Throw errors instead of warnings when check fails.")
R
Rongfeng Fu 已提交
555
        self.parser.add_option('--without-parameter', '--wop', action='store_true', help='Start without parameters.')
O
oceanbase-admin 已提交
556 557 558 559 560 561 562 563 564 565 566

    def _do_command(self, obd):
        if self.cmds:
            return obd.start_cluster(self.cmds[0], self.cmds[1:], self.opts)
        else:
            return self._show_help()


class ClusterStopCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
567 568
        super(ClusterStopCommand, self).__init__('stop', 'Stop a started cluster.')
        self.parser.add_option('-s', '--servers', type='string', help="List the started servers. Multiple servers are separated with commas.")
R
Rongfeng Fu 已提交
569
        self.parser.add_option('-c', '--components', type='string', help="List the stoped components. Multiple components are separated with commas.")
O
oceanbase-admin 已提交
570 571 572

    def _do_command(self, obd):
        if self.cmds:
R
Rongfeng Fu 已提交
573
            return obd.stop_cluster(self.cmds[0], self.opts)
O
oceanbase-admin 已提交
574 575 576 577 578 579 580
        else:
            return self._show_help()


class ClusterDestroyCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
581 582
        super(ClusterDestroyCommand, self).__init__('destroy', 'Destroy a deployed cluster.')
        self.parser.add_option('-f', '--force-kill', action='store_true', help="Force kill the running observer process in the working directory.")
O
oceanbase-admin 已提交
583 584 585 586 587 588 589 590 591 592 593

    def _do_command(self, obd):
        if self.cmds:
            return obd.destroy_cluster(self.cmds[0], self.opts)
        else:
            return self._show_help()


class ClusterDisplayCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
594
        super(ClusterDisplayCommand, self).__init__('display', 'Display the information for a cluster.')
O
oceanbase-admin 已提交
595 596 597 598 599 600 601 602 603 604 605

    def _do_command(self, obd):
        if self.cmds:
            return obd.display_cluster(self.cmds[0])
        else:
            return self._show_help()


class ClusterRestartCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
606 607
        super(ClusterRestartCommand, self).__init__('restart', 'Restart a started cluster.')
        self.parser.add_option('-s', '--servers', type='string', help="List the started servers. Multiple servers are separated with commas.")
R
Rongfeng Fu 已提交
608
        self.parser.add_option('-c', '--components', type='string', help="List the restarted components. Multiple components are separated with commas.")
R
Rongfeng Fu 已提交
609
        self.parser.add_option('--with-parameter', '--wp', action='store_true', help='Restart with parameters.')
O
oceanbase-admin 已提交
610 611 612

    def _do_command(self, obd):
        if self.cmds:
R
Rongfeng Fu 已提交
613 614
            if not getattr(self.opts, 'with_parameter', False):
                setattr(self.opts, 'without_parameter', True)
R
Rongfeng Fu 已提交
615
            return obd.restart_cluster(self.cmds[0], self.opts)
O
oceanbase-admin 已提交
616 617 618 619 620 621 622
        else:
            return self._show_help()


class ClusterRedeployCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
623 624
        super(ClusterRedeployCommand, self).__init__('redeploy', 'Redeploy a started cluster.')
        self.parser.add_option('-f', '--force-kill', action='store_true', help="Force kill the running observer process in the working directory.")
O
oceanbase-admin 已提交
625 626 627

    def _do_command(self, obd):
        if self.cmds:
R
Rongfeng Fu 已提交
628
            return obd.redeploy_cluster(self.cmds[0], self.opts)
O
oceanbase-admin 已提交
629 630 631 632 633 634 635
        else:
            return self._show_help()


class ClusterReloadCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
636
        super(ClusterReloadCommand, self).__init__('reload', 'Reload a started cluster.')
O
oceanbase-admin 已提交
637 638 639 640 641 642 643 644 645 646 647

    def _do_command(self, obd):
        if self.cmds:
            return obd.reload_cluster(self.cmds[0])
        else:
            return self._show_help()


class ClusterListCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
648
        super(ClusterListCommand, self).__init__('list', 'List all the deployments.')
O
oceanbase-admin 已提交
649 650 651 652 653 654 655 656 657 658 659

    def _do_command(self, obd):
        if self.cmds:
            return self._show_help()
        else:
            return obd.list_deploy()


class ClusterEditConfigCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
660
        super(ClusterEditConfigCommand, self).__init__('edit-config', 'Edit the configuration file for a specific deployment.')
O
oceanbase-admin 已提交
661 662 663 664 665 666 667 668

    def _do_command(self, obd):
        if self.cmds:
            return obd.edit_deploy_config(self.cmds[0])
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
class ClusterChangeRepositoryCommand(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterChangeRepositoryCommand, self).__init__('change-repo', 'Change repository for a deployed component')
        self.parser.add_option('-c', '--component', type='string', help="Component name to change repository.")
        self.parser.add_option('--hash', type='string', help="Repository's hash")
        self.parser.add_option('-f', '--force', action='store_true', help="force change even start failed.")

    def _do_command(self, obd):
        if self.cmds:
            return obd.change_repository(self.cmds[0], self.opts)
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
684 685 686
class CLusterUpgradeCommand(ClusterMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
687
        super(CLusterUpgradeCommand, self).__init__('upgrade', 'Upgrade a cluster.')
R
Rongfeng Fu 已提交
688 689 690 691 692 693
        self.parser.add_option('-c', '--component', type='string', help="Component name to upgrade.")
        self.parser.add_option('-V', '--version', type='string', help="Target version.")
        self.parser.add_option('--skip-check', action='store_true', help="Skip all the possible checks.")
        self.parser.add_option('--usable', type='string', help="Hash list for priority mirrors, separated with `,`.", default='')
        self.parser.add_option('--disable', type='string', help="Hash list for disabled mirrors, separated with `,`.", default='')
        self.parser.add_option('-e', '--executer-path', type='string', help="Executer path.", default=os.path.join(ObdCommand.OBD_INSTALL_PRE, 'usr/obd/lib/executer'))
R
Rongfeng Fu 已提交
694 695 696 697 698 699 700

    def _do_command(self, obd):
        if self.cmds:
            return obd.upgrade_cluster(self.cmds[0], self.opts)
        else:
            return self._show_help()

R
Rongfeng Fu 已提交
701 702 703 704 705

class ClusterTenantCreateCommand(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterTenantCreateCommand, self).__init__('create', 'Create a tenant.')
R
Rongfeng Fu 已提交
706 707 708 709 710 711 712 713 714
        self.parser.add_option('-n', '--tenant-name', type='string', help="The tenant name. The default tenant name is [test].", default='test')
        self.parser.add_option('--max-cpu', type='float', help="Max CPU unit number.")
        self.parser.add_option('--min-cpu', type='float', help="Mind CPU unit number.")
        self.parser.add_option('--max-memory', type='int', help="Max memory unit size.")
        self.parser.add_option('--min-memory', type='int', help="Min memory unit size.")
        self.parser.add_option('--max-disk-size', type='int', help="Max disk unit size.")
        self.parser.add_option('--max-iops', type='int', help="Max IOPS unit number. [128].", default=128)
        self.parser.add_option('--min-iops', type='int', help="Min IOPS unit number.")
        self.parser.add_option('--max-session-num', type='int', help="Max session unit number. [64].", default=64)
R
Rongfeng Fu 已提交
715 716 717 718
        self.parser.add_option('--unit-num', type='int', help="Pool unit number.")
        self.parser.add_option('-z', '--zone-list', type='string', help="Tenant zone list.")
        self.parser.add_option('--charset', type='string', help="Tenant charset.")
        self.parser.add_option('--collate', type='string', help="Tenant COLLATE.")
R
Rongfeng Fu 已提交
719
        self.parser.add_option('--replica-num', type='int', help="Tenant replica number.")
R
Rongfeng Fu 已提交
720 721
        self.parser.add_option('--logonly-replica-num', type='int', help="Tenant logonly replica number.")
        self.parser.add_option('--tablegroup', type='string', help="Tenant tablegroup.")
R
Rongfeng Fu 已提交
722
        self.parser.add_option('--primary-zone', type='string', help="Tenant primary zone. [RANDOM].", default='RANDOM')
R
Rongfeng Fu 已提交
723
        self.parser.add_option('--locality', type='string', help="Tenant locality.")
R
Rongfeng Fu 已提交
724
        self.parser.add_option('-s', '--variables', type='string', help="Set the variables for the system tenant. [ob_tcp_invited_nodes='%'].", default="ob_tcp_invited_nodes='%'")
R
Rongfeng Fu 已提交
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

    def _do_command(self, obd):
        if self.cmds:
            return obd.create_tenant(self.cmds[0], self.opts)
        else:
            return self._show_help()


class ClusterTenantDropCommand(ClusterMirrorCommand):

    def __init__(self):
        super(ClusterTenantDropCommand, self).__init__('drop', 'Drop a tenant.')
        self.parser.add_option('-n', '--tenant-name', type='string', help="Tenant name.")

    def _do_command(self, obd):
        if self.cmds:
            return obd.drop_tenant(self.cmds[0], self.opts)
        else:
            return self._show_help()


class ClusterTenantCommand(MajorCommand):

    def __init__(self):
        super(ClusterTenantCommand, self).__init__('tenant', 'Create or drop a tenant.')
        self.register_command(ClusterTenantCreateCommand())
        self.register_command(ClusterTenantDropCommand())


O
oceanbase-admin 已提交
754 755 756
class ClusterMajorCommand(MajorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
757
        super(ClusterMajorCommand, self).__init__('cluster', 'Deploy and manage a cluster.')
R
Rongfeng Fu 已提交
758 759
        self.register_command(ClusterCheckForOCPChange())
        self.register_command(ClusterConfigStyleChange())
R
Rongfeng Fu 已提交
760
        self.register_command(ClusterAutoDeployCommand())
O
oceanbase-admin 已提交
761 762 763 764 765 766 767 768 769 770
        self.register_command(ClusterDeployCommand())
        self.register_command(ClusterStartCommand())
        self.register_command(ClusterStopCommand())
        self.register_command(ClusterDestroyCommand())
        self.register_command(ClusterDisplayCommand())
        self.register_command(ClusterListCommand())
        self.register_command(ClusterRestartCommand())
        self.register_command(ClusterRedeployCommand())
        self.register_command(ClusterEditConfigCommand())
        self.register_command(ClusterReloadCommand())
R
Rongfeng Fu 已提交
771
        self.register_command(CLusterUpgradeCommand())
R
Rongfeng Fu 已提交
772
        self.register_command(ClusterChangeRepositoryCommand())
R
Rongfeng Fu 已提交
773
        self.register_command(ClusterTenantCommand())
O
oceanbase-admin 已提交
774 775 776 777 778 779


class TestMirrorCommand(ObdCommand):

    def init(self, cmd, args):
        super(TestMirrorCommand, self).init(cmd, args)
R
Rongfeng Fu 已提交
780
        self.parser.set_usage('%s <deploy name> [options]' % self.prev_cmd)
O
oceanbase-admin 已提交
781 782 783 784 785 786
        return self


class MySQLTestCommand(TestMirrorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
787 788
        super(MySQLTestCommand, self).__init__('mysqltest', 'Run a mysqltest for a deployment.')
        self.parser.add_option('--component', type='string', help='Components for mysqltest.')
R
Rongfeng Fu 已提交
789 790 791 792 793 794 795 796
        self.parser.add_option('--test-server', type='string', help='The server for mysqltest. By default, the first root server in the component is the mysqltest server.')
        self.parser.add_option('--user', type='string', help='Username for a test. [admin]', default='admin')
        self.parser.add_option('--password', type='string', help='Password for a test. [admin]', default='admin')
        self.parser.add_option('--database', type='string', help='Database for a test. [test]', default='test')
        self.parser.add_option('--mysqltest-bin', type='string', help='Mysqltest bin path. [/u01/obclient/bin/mysqltest]', default='/u01/obclient/bin/mysqltest')
        self.parser.add_option('--obclient-bin', type='string', help='OBClient bin path. [obclient]', default='obclient')
        self.parser.add_option('--test-dir', type='string', help='Test case file directory. [./mysql_test/t]', default='./mysql_test/t')
        self.parser.add_option('--result-dir', type='string', help='Result case file directory. [./mysql_test/r]', default='./mysql_test/r')
F
v1.4.0  
frf12 已提交
797
        self.parser.add_option('--record', action='store_true', help='record mysqltest execution results', default=False)
R
Rongfeng Fu 已提交
798 799 800 801
        self.parser.add_option('--record-dir', type='string', help='The directory of the result file for mysqltest.')
        self.parser.add_option('--log-dir', type='string', help='The log file directory. [./log]', default='./log')
        self.parser.add_option('--tmp-dir', type='string', help='Temporary directory for mysqltest. [./tmp]', default='./tmp')
        self.parser.add_option('--var-dir', type='string', help='Var directory to use when run mysqltest. [./var]', default='./var')
O
oceanbase-admin 已提交
802
        self.parser.add_option('--test-set', type='string', help='test list, use `,` interval')
R
Rongfeng Fu 已提交
803
        self.parser.add_option('--test-pattern', type='string', help='Pattern for test file.')
R
Rongfeng Fu 已提交
804
        self.parser.add_option('--suite', type='string', help='Suite list. Multiple suites are separated with commas.')
R
Rongfeng Fu 已提交
805 806 807
        self.parser.add_option('--suite-dir', type='string', help='Suite case directory. [./mysql_test/test_suite]', default='./mysql_test/test_suite')
        self.parser.add_option('--init-sql-dir', type='string', help='Initiate sql directory. [../]', default='../')
        self.parser.add_option('--init-sql-files', type='string', help='Initiate sql file list.Multiple files are separated with commas.')
R
Rongfeng Fu 已提交
808
        self.parser.add_option('--need-init', action='store_true', help='Execute the init SQL file.', default=False)
R
Rongfeng Fu 已提交
809 810 811
        self.parser.add_option('--auto-retry', action='store_true', help='Auto retry when fails.', default=False)
        self.parser.add_option('--all', action='store_true', help='Run all suite-dir cases.', default=False)
        self.parser.add_option('--psmall', action='store_true', help='Run psmall cases.', default=False)
O
oceanbase-admin 已提交
812 813 814 815 816 817 818 819 820
        # self.parser.add_option('--java', action='store_true', help='use java sdk', default=False)

    def _do_command(self, obd):
        if self.cmds:
            return obd.mysqltest(self.cmds[0], self.opts)
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
821 822 823 824
class SysBenchCommand(TestMirrorCommand):

    def __init__(self):
        super(SysBenchCommand, self).__init__('sysbench', 'Run sysbench for a deployment.')
R
Rongfeng Fu 已提交
825 826
        self.parser.add_option('--component', type='string', help='Components for test.')
        self.parser.add_option('--test-server', type='string', help='The server for test. By default, the first root server in the component is the test server.')
R
Rongfeng Fu 已提交
827 828 829 830 831 832
        self.parser.add_option('--user', type='string', help='Username for a test. [root]', default='root')
        self.parser.add_option('--password', type='string', help='Password for a test.')
        self.parser.add_option('--tenant', type='string', help='Tenant for a test. [test]', default='test')
        self.parser.add_option('--database', type='string', help='Database for a test. [test]', default='test')
        self.parser.add_option('--obclient-bin', type='string', help='OBClient bin path. [obclient]', default='obclient')
        self.parser.add_option('--sysbench-bin', type='string', help='Sysbench bin path. [sysbench]', default='sysbench')
R
Rongfeng Fu 已提交
833
        self.parser.add_option('--script-name', type='string', help='Sysbench lua script file name. [oltp_point_select]', default='oltp_point_select.lua')
R
Rongfeng Fu 已提交
834 835 836 837 838 839 840 841 842 843
        self.parser.add_option('--sysbench-script-dir', type='string', help='The directory of the sysbench lua script file. [/usr/sysbench/share/sysbench]', default='/usr/sysbench/share/sysbench')
        self.parser.add_option('--table-size', type='int', help='Number of data initialized per table. [20000]', default=20000)
        self.parser.add_option('--tables', type='int', help='Number of initialization tables. [30]', default=30)
        self.parser.add_option('--threads', type='int', help='Number of threads to use. [32]', default=16)
        self.parser.add_option('--time', type='int', help='Limit for total execution time in seconds. [60]', default=60)
        self.parser.add_option('--interval', type='int', help='Periodically report intermediate statistics with a specified time interval in seconds. 0 disables intermediate reports. [10]', default=10)
        self.parser.add_option('--events', type='int', help='Limit for total number of events.')
        self.parser.add_option('--rand-type', type='string', help='Random numbers distribution {uniform,gaussian,special,pareto}.')
        self.parser.add_option('--percentile', type='int', help='Percentile to calculate in latency statistics. Available values are 1-100. 0 means to disable percentile calculations.')
        self.parser.add_option('--skip-trx', dest='{on/off}', type='string', help='Open or close a transaction in a read-only test. ')
R
Rongfeng Fu 已提交
844
        self.parser.add_option('-O', '--optimization', type='int', help='optimization level {0/1}', default=1)
R
Rongfeng Fu 已提交
845 846 847 848 849 850 851 852

    def _do_command(self, obd):
        if self.cmds:
            return obd.sysbench(self.cmds[0], self.opts)
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
853 854 855 856 857 858 859 860 861 862 863
class TPCHCommand(TestMirrorCommand):

    def __init__(self):
        super(TPCHCommand, self).__init__('tpch', 'Run a TPC-H test for a deployment.')
        self.parser.add_option('--component', type='string', help='Components for a test.')
        self.parser.add_option('--test-server', type='string', help='The server for a test. By default, the first root server in the component is the test server.')
        self.parser.add_option('--user', type='string', help='Username for a test. [root]', default='root')
        self.parser.add_option('--password', type='string', help='Password for a test.')
        self.parser.add_option('--tenant', type='string', help='Tenant for a test. [test]', default='test')
        self.parser.add_option('--database', type='string', help='Database for a test. [test]', default='test')
        self.parser.add_option('--obclient-bin', type='string', help='OBClient bin path. [obclient]', default='obclient')
R
Rongfeng Fu 已提交
864
        self.parser.add_option('--dbgen-bin', type='string', help='dbgen bin path. [/usr/tpc-h-tools/tpc-h-tools/bin/dbgen]', default='/usr/tpc-h-tools/tpc-h-tools/bin/dbgen')
R
Rongfeng Fu 已提交
865 866 867 868 869 870 871
        self.parser.add_option('-s', '--scale-factor', type='int', help='Set Scale Factor (SF) to <n>. [1] ', default=1)
        self.parser.add_option('--tmp-dir', type='string', help='The temporary directory for executing TPC-H. [./tmp]', default='./tmp')
        self.parser.add_option('--ddl-path', type='string', help='Directory for DDL files.')
        self.parser.add_option('--tbl-path', type='string', help='Directory for tbl files.')
        self.parser.add_option('--sql-path', type='string', help='Directory for SQL files.')
        self.parser.add_option('--remote-tbl-dir', type='string', help='Directory for the tbl on target observers. Make sure that you have read and write access to the directory when you start observer.')
        self.parser.add_option('--disable-transfer', '--dt', action='store_true', help='Disable the transfer. When enabled, OBD will use the tbl files under remote-tbl-dir instead of transferring local tbl files to remote remote-tbl-dir.')
R
Rongfeng Fu 已提交
872
        self.parser.add_option('--dss-config', type='string', help='Directory for dists.dss. [/usr/tpc-h-tools/tpc-h-tools]', default='/usr/tpc-h-tools/tpc-h-tools/')
R
Rongfeng Fu 已提交
873 874 875 876 877 878 879 880 881 882
        self.parser.add_option('-O', '--optimization', type='int', help='Optimization level {0/1}. [1]', default=1)
        self.parser.add_option('--test-only', action='store_true', help='Only testing SQLs are executed. No initialization is executed.')

    def _do_command(self, obd):
        if self.cmds:
            return obd.tpch(self.cmds[0], self.opts)
        else:
            return self._show_help()


R
Rongfeng Fu 已提交
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
class TPCCCommand(TestMirrorCommand):

    def __init__(self):
        super(TPCCCommand, self).__init__('tpcc', 'Run a TPC-C test for a deployment.')
        self.parser.add_option('--component', type='string', help='Components for a test.')
        self.parser.add_option('--test-server', type='string', help='The server for a test. By default, the first root server in the component is the test server.')
        self.parser.add_option('--user', type='string', help='Username for a test. [root]', default='root')
        self.parser.add_option('--password', type='string', help='Password for a test.')
        self.parser.add_option('--tenant', type='string', help='Tenant for a test. [test]', default='test')
        self.parser.add_option('--database', type='string', help='Database for a test. [test]', default='test')
        self.parser.add_option('--obclient-bin', type='string', help='OBClient bin path. [obclient]', default='obclient')
        self.parser.add_option('--java-bin', type='string', help='Java bin path. [java]', default='java')
        self.parser.add_option('--tmp-dir', type='string', help='The temporary directory for executing TPC-C. [./tmp]', default='./tmp')
        self.parser.add_option('--bmsql-dir', type='string', help='The directory of BenchmarkSQL.')
        self.parser.add_option('--bmsql-jar', type='string', help='BenchmarkSQL jar path.')
        self.parser.add_option('--bmsql-libs', type='string', help='BenchmarkSQL libs path.')
        self.parser.add_option('--bmsql-sql-dir', type='string', help='The directory of BenchmarkSQL sql scripts.')
        self.parser.add_option('--warehouses', type='int', help='The number of warehouses.')
        self.parser.add_option('--load-workers', type='int', help='The number of workers to load data.')
        self.parser.add_option('--terminals', type='int', help='The number of terminals.')
        self.parser.add_option('--run-mins', type='int', help='To run for specified minutes.', default=10)
        self.parser.add_option('--test-only', action='store_true', help='Only testing SQLs are executed. No initialization is executed.')
        self.parser.add_option('-O', '--optimization', type='int', help='Optimization level {0/1/2}. [1] 0 - No optimization. 1 - Optimize some of the parameters which do not need to restart servers. 2 - Optimize all the parameters and maybe RESTART SERVERS for better performance.', default=1)

    def _do_command(self, obd):
        if self.cmds:
            return obd.tpcc(self.cmds[0], self.opts)
        else:
            return self._show_help()
        

O
oceanbase-admin 已提交
914 915 916
class TestMajorCommand(MajorCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
917
        super(TestMajorCommand, self).__init__('test', 'Run test for a running deployment.')
O
oceanbase-admin 已提交
918
        self.register_command(MySQLTestCommand())
R
Rongfeng Fu 已提交
919
        self.register_command(SysBenchCommand())
R
Rongfeng Fu 已提交
920
        self.register_command(TPCHCommand())
F
v1.4.0  
frf12 已提交
921
        self.register_command(TPCCCommand())
O
oceanbase-admin 已提交
922 923 924 925 926 927 928 929


class BenchMajorCommand(MajorCommand):

    def __init__(self):
        super(BenchMajorCommand, self).__init__('bench', '')


R
Rongfeng Fu 已提交
930 931 932
class UpdateCommand(ObdCommand):

    def __init__(self):
R
Rongfeng Fu 已提交
933
        super(UpdateCommand, self).__init__('update', 'Update OBD.')
R
Rongfeng Fu 已提交
934 935 936

    def do_command(self):
        if os.getuid() != 0:
R
Rongfeng Fu 已提交
937
            ROOT_IO.error('To update OBD, you must be a root user.')
R
Rongfeng Fu 已提交
938 939 940 941
            return False
        return super(UpdateCommand, self).do_command()

    def _do_command(self, obd):
R
Rongfeng Fu 已提交
942
        return obd.update_obd(VERSION, self.OBD_INSTALL_PRE)
R
Rongfeng Fu 已提交
943 944


O
oceanbase-admin 已提交
945 946 947 948
class MainCommand(MajorCommand):

    def __init__(self):
        super(MainCommand, self).__init__('obd', '')
R
Rongfeng Fu 已提交
949
        self.register_command(DevModeMajorCommand())
O
oceanbase-admin 已提交
950 951
        self.register_command(MirrorMajorCommand())
        self.register_command(ClusterMajorCommand())
R
Rongfeng Fu 已提交
952
        self.register_command(RepositoryMajorCommand())
O
oceanbase-admin 已提交
953
        self.register_command(TestMajorCommand())
R
Rongfeng Fu 已提交
954
        self.register_command(UpdateCommand())
O
oceanbase-admin 已提交
955
        self.parser.version = '''OceanBase Deploy: %s
R
Rongfeng Fu 已提交
956 957 958
REVISION: %s
BUILD_BRANCH: %s
BUILD_TIME: %s
O
oceanbase-admin 已提交
959 960 961
Copyright (C) 2021 OceanBase
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
R
Rongfeng Fu 已提交
962
There is NO WARRANTY, to the extent permitted by law.''' % (VERSION, REVISION, BUILD_BRANCH, BUILD_TIME)
O
oceanbase-admin 已提交
963 964 965 966 967 968 969 970 971 972 973
        self.parser._add_version_option()

if __name__ == '__main__':
    defaultencoding = 'utf-8'
    if sys.getdefaultencoding() != defaultencoding:
        try:
            from imp import reload
        except:
            pass
        reload(sys)
        sys.setdefaultencoding(defaultencoding)
R
Rongfeng Fu 已提交
974
    sys.path.append(os.path.join(ObdCommand.OBD_INSTALL_PRE, 'usr/obd/lib/site-packages'))
O
oceanbase-admin 已提交
975 976 977 978 979
    ROOT_IO.track_limit += 2
    if MainCommand().init('obd', sys.argv[1:]).do_command():
        ROOT_IO.exit(0)
    ROOT_IO.exit(1)