oceanbase

Форк
0
239 строк · 7.8 Кб
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3

4
from my_error import MyError
5
import sys
6
import os
7
import getopt
8

9
pre_help_str = \
10
"""
11
Help:
12
""" +\
13
sys.argv[0] + """ [OPTIONS]""" +\
14
'\n\n' +\
15
'-I, --help          Display this help and exit.\n' +\
16
'-V, --version       Output version information and exit.\n' +\
17
'-h, --host=name     Connect to host.\n' +\
18
'-P, --port=name     Port number to use for connection.\n' +\
19
'-u, --user=name     User for login.\n' +\
20
'-p, --password=name Password to use when connecting to server. If password is\n' +\
21
'                    not given it\'s empty string "".\n' +\
22
'-t, --timeout=name  Cmd/Query/Inspection execute timeout(s).\n' +\
23
'-m, --module=name   Modules to run. Modules should be a string combined by some of\n' +\
24
'                    the following strings:\n' +\
25
'                    1. begin_upgrade \n' +\
26
'                    2. begin_rolling_upgrade \n' +\
27
'                    3. special_action \n' +\
28
'                    4. health_check \n' +\
29
'                    5. all: default value, run all sub modules above \n' +\
30
'                    that all modules should be run. They are splitted by ",".\n' +\
31
'                    For example: -m all, or --module=begin_upgrade,begin_rolling_upgrade,special_action\n' +\
32
'-l, --log-file=name Log file path. If log file path is not given it\'s ' + os.path.splitext(sys.argv[0])[0] + '.log\n' +\
33
'\n\n' +\
34
'Maybe you want to run cmd like that:\n' +\
35
sys.argv[0] + ' -h 127.0.0.1 -P 3306 -u admin -p admin\n'
36

37
post_help_str = \
38
"""
39
Help:
40
""" +\
41
sys.argv[0] + """ [OPTIONS]""" +\
42
'\n\n' +\
43
'-I, --help          Display this help and exit.\n' +\
44
'-V, --version       Output version information and exit.\n' +\
45
'-h, --host=name     Connect to host.\n' +\
46
'-P, --port=name     Port number to use for connection.\n' +\
47
'-u, --user=name     User for login.\n' +\
48
'-p, --password=name Password to use when connecting to server. If password is\n' +\
49
'                    not given it\'s empty string "".\n' +\
50
'-t, --timeout=name  Cmd/Query/Inspection execute timeout(s).\n' +\
51
'-m, --module=name   Modules to run. Modules should be a string combined by some of\n' +\
52
'                    the following strings:\n' +\
53
'                    1. health_check \n' +\
54
'                    2. end_rolling_upgrade \n' +\
55
'                    3. tenant_upgrade \n' +\
56
'                    4. end_upgrade \n' +\
57
'                    5. post_check \n' +\
58
'                    6. all: default value, run all sub modules above \n' +\
59
'                    that all modules should be run. They are splitted by ",".\n' +\
60
'                    For example: -m all, or --module=health_check,end_rolling_upgrade\n' +\
61
'-l, --log-file=name Log file path. If log file path is not given it\'s ' + os.path.splitext(sys.argv[0])[0] + '.log\n' +\
62
'\n\n' +\
63
'Maybe you want to run cmd like that:\n' +\
64
sys.argv[0] + ' -h 127.0.0.1 -P 3306 -u admin -p admin\n'
65

66
version_str = """version 1.0.0"""
67

68
class Option:
69
  __g_short_name_set = set([])
70
  __g_long_name_set = set([])
71
  __short_name = None
72
  __long_name = None
73
  __is_with_param = None
74
  __is_local_opt = None
75
  __has_value = None
76
  __value = None
77
  def __init__(self, short_name, long_name, is_with_param, is_local_opt, default_value = None):
78
    if short_name in Option.__g_short_name_set:
79
      raise MyError('duplicate option short name: {0}'.format(short_name))
80
    elif long_name in Option.__g_long_name_set:
81
      raise MyError('duplicate option long name: {0}'.format(long_name))
82
    Option.__g_short_name_set.add(short_name)
83
    Option.__g_long_name_set.add(long_name)
84
    self.__short_name = short_name
85
    self.__long_name = long_name
86
    self.__is_with_param = is_with_param
87
    self.__is_local_opt = is_local_opt
88
    self.__has_value = False
89
    if None != default_value:
90
      self.set_value(default_value)
91
  def is_with_param(self):
92
    return self.__is_with_param
93
  def get_short_name(self):
94
    return self.__short_name
95
  def get_long_name(self):
96
    return self.__long_name
97
  def has_value(self):
98
    return self.__has_value
99
  def get_value(self):
100
    return self.__value
101
  def set_value(self, value):
102
    self.__value = value
103
    self.__has_value = True
104
  def is_local_opt(self):
105
    return self.__is_local_opt
106
  def is_valid(self):
107
    return None != self.__short_name and None != self.__long_name and True == self.__has_value and None != self.__value
108

109
g_opts =\
110
[\
111
Option('I', 'help', False, True),\
112
Option('V', 'version', False, True),\
113
Option('h', 'host', True, False),\
114
Option('P', 'port', True, False),\
115
Option('u', 'user', True, False),\
116
Option('t', 'timeout', True, False, 0),\
117
Option('p', 'password', True, False, ''),\
118
# 要跑哪个模块,默认全跑
119
Option('m', 'module', True, False, 'all'),\
120
# 日志文件路径,不同脚本的main函数中中会改成不同的默认值
121
Option('l', 'log-file', True, False)
122
]\
123

124
def change_opt_defult_value(opt_long_name, opt_default_val):
125
  global g_opts
126
  for opt in g_opts:
127
    if opt.get_long_name() == opt_long_name:
128
      opt.set_value(opt_default_val)
129
      return
130

131
def has_no_local_opts():
132
  global g_opts
133
  no_local_opts = True
134
  for opt in g_opts:
135
    if opt.is_local_opt() and opt.has_value():
136
      no_local_opts = False
137
  return no_local_opts
138

139
def check_db_client_opts():
140
  global g_opts
141
  for opt in g_opts:
142
    if not opt.is_local_opt() and not opt.has_value():
143
      raise MyError('option "-{0}" has not been specified, maybe you should run "{1} --help" for help'\
144
          .format(opt.get_short_name(), sys.argv[0]))
145

146
def parse_option(opt_name, opt_val):
147
  global g_opts
148
  for opt in g_opts:
149
    if opt_name in (('-' + opt.get_short_name()), ('--' + opt.get_long_name())):
150
      opt.set_value(opt_val)
151

152
def parse_options(argv):
153
  global g_opts
154
  short_opt_str = ''
155
  long_opt_list = []
156
  for opt in g_opts:
157
    if opt.is_with_param():
158
      short_opt_str += opt.get_short_name() + ':'
159
    else:
160
      short_opt_str += opt.get_short_name()
161
  for opt in g_opts:
162
    if opt.is_with_param():
163
      long_opt_list.append(opt.get_long_name() + '=')
164
    else:
165
      long_opt_list.append(opt.get_long_name())
166
  (opts, args) = getopt.getopt(argv, short_opt_str, long_opt_list)
167
  for (opt_name, opt_val) in opts:
168
    parse_option(opt_name, opt_val)
169
  if has_no_local_opts():
170
    check_db_client_opts()
171

172
def deal_with_local_opt(opt, filename):
173
  if 'help' == opt.get_long_name():
174
    if 'upgrade_pre' == filename:
175
      global pre_help_str
176
      print pre_help_str
177
    elif 'upgrade_post' == filename:
178
      global post_help_str
179
      print post_help_str
180
    else:
181
            raise MyError('not supported filename:{0} for help option'.format(filename))
182
  elif 'version' == opt.get_long_name():
183
    global version_str
184
    print version_str
185

186
def deal_with_local_opts(filename):
187
  global g_opts
188
  if has_no_local_opts():
189
    raise MyError('no local options, can not deal with local options')
190
  else:
191
    for opt in g_opts:
192
      if opt.is_local_opt() and opt.has_value():
193
        deal_with_local_opt(opt, filename)
194
        # 只处理一个
195
        return
196

197
def get_opt_host():
198
  global g_opts
199
  for opt in g_opts:
200
    if 'host' == opt.get_long_name():
201
      return opt.get_value()
202

203
def get_opt_port():
204
  global g_opts
205
  for opt in g_opts:
206
    if 'port' == opt.get_long_name():
207
      return opt.get_value()
208

209
def get_opt_user():
210
  global g_opts
211
  for opt in g_opts:
212
    if 'user' == opt.get_long_name():
213
      return opt.get_value()
214

215
def get_opt_password():
216
  global g_opts
217
  for opt in g_opts:
218
    if 'password' == opt.get_long_name():
219
      return opt.get_value()
220

221
def get_opt_timeout():
222
  global g_opts
223
  for opt in g_opts:
224
    if 'timeout' == opt.get_long_name():
225
      return opt.get_value()
226

227
def get_opt_module():
228
  global g_opts
229
  for opt in g_opts:
230
    if 'module' == opt.get_long_name():
231
      return opt.get_value()
232

233
def get_opt_log_file():
234
  global g_opts
235
  for opt in g_opts:
236
    if 'log-file' == opt.get_long_name():
237
      return opt.get_value()
238

239
#parse_options(sys.argv[1:])
240

241

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.