-
Notifications
You must be signed in to change notification settings - Fork 37
/
admin-tool.py
293 lines (227 loc) · 7.76 KB
/
admin-tool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Built-in Modules
import os
import sys
import textwrap
import getpass
import logging
import argparse
import traceback
import pprint
# 3rd-party Modules
import requests
# Project Modules
from worker.utils import yaml_resources, toolkit
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
CONFIG = yaml_resources.load_config(os.path.join(BASE_PATH, './config.yaml'))
from worker.utils.extra_helpers import RedisHelper, MySQLHelper, PostgreSQLHelper
CACHE_DB = RedisHelper(logging)
DB = None
if CONFIG.get('DB_ENGINE') == 'postgresql':
DB = PostgreSQLHelper(logging)
else:
DB = MySQLHelper(logging)
ADMIN_USER_ID = 'u-admin'
DB_UPGRADE_SEQ_ID = 'UPGRADE_DB_SEQ'
COMMAND_FUNCS = {}
COLOR_MAP = {
'grey' : '\033[0;30m',
'red' : '\033[0;31m',
'green' : '\033[0;32m',
'yellow' : '\033[0;33m',
'blue' : '\033[0;34m',
'magenta': '\033[0;35m',
'cyan' : '\033[0;36m',
}
def colored(s, color=None):
if not color:
color = 'yellow'
color = COLOR_MAP[color]
return color + '{}\033[0m'.format(s)
class CommandCanceled(Exception):
pass
def command(F):
COMMAND_FUNCS[F.__name__] = F
return F
def confirm(force=False):
if force:
return
# 确认
user_input = input('Are you sure you want to do this? (yes/no): ')
if user_input != 'yes':
raise CommandCanceled()
def reset_db_data(table, data):
try:
trans_conn = DB.start_trans()
# 查询数据
sql = DB.create_sql_builder()
sql.SELECT('id')
sql.FROM(table)
sql.WHERE({
'id': data['id'],
})
sql.LIMIT(1)
db_res = DB.trans_query(trans_conn, sql)
if db_res:
# 存在则更新
sql = DB.create_sql_builder()
sql.UPDATE(table)
sql.SET(data)
sql.WHERE({
'id': data['id'],
})
sql.LIMIT(1)
DB.trans_query(trans_conn, sql)
else:
# 不存在则创建新数据
sql = DB.create_sql_builder()
sql.INSERT_INTO(table)
sql.VALUES(data)
DB.trans_query(trans_conn, sql)
except Exception as e:
for line in traceback.format_exc().splitlines():
logging.error(line)
DB.rollback(trans_conn)
raise
else:
DB.commit(trans_conn)
def run_db_sql(raw_sql):
try:
trans_conn = DB.start_trans()
# 执行 SQL
sql = DB.create_sql_builder(raw_sql)
db_res = DB.trans_query(trans_conn, sql)
print('DB Result:')
pprint.pprint(db_res)
except Exception as e:
for line in traceback.format_exc().splitlines():
logging.error(line)
DB.rollback(trans_conn)
raise
else:
DB.commit(trans_conn)
@command
def reset_admin(options):
'''
重置管理员账号
'''
# 等待用户输入数据
username = options.get('admin_username') or input('Enter new Admin username: ')
password = options.get('admin_password') or getpass.getpass(f'Enter new password for [{username}]: ')
password_repeat = options.get('admin_password') or getpass.getpass('Confirm new password: ')
if password != password_repeat:
# 两次输入不一致
raise Exception('Repeated password not match')
if not all([username, password]):
# 存在空内容
raise Exception('Username or password not inputed.')
# 生成新的admin用户数据
str_to_hash = '~{}~{}~{}~'.format(ADMIN_USER_ID, password, CONFIG['SECRET'])
password_hash = toolkit.get_sha512(str_to_hash)
data = {
'id' : ADMIN_USER_ID,
'username' : username,
'passwordHash' : password_hash,
'name' : '系统管理员',
'roles' : 'sa',
'customPrivileges': '*',
'isDisabled' : False,
}
# 确认提示
confirm(options.get('force'))
# 数据入库
reset_db_data('wat_main_user', data)
@command
def reset_upgrade_db_seq(options):
'''
重置数据库升级序号
'''
# 等待用户输入数据
db_upgrade_seq = input('Enter new DB upgrade SEQ: ')
# 生成新的数据库升级序号数据
data = {
'id' : DB_UPGRADE_SEQ_ID,
'value': db_upgrade_seq,
}
# 确认提示
confirm(options.get('force'))
# 数据入库
reset_db_data('wat_main_system_setting', data)
@command
def clear_redis(options):
'''
清空 Redis
'''
# 确认提示
confirm(options.get('force'))
# 清空数据库
CACHE_DB.client.flushdb()
@command
def run_sql(options):
'''
执行 SQL
'''
# 等待用户输入数据
user_input = input('Enter SQL file path, URL or SQL statement: ')
# 获取 SQL 文件
sql = None
if user_input.startswith('http://') or user_input.startswith('https://'):
print(colored('Run SQL from URL'))
resp = requests.get(user_input)
resp.raise_for_status()
sql = resp.text
else:
try:
with open(user_input, 'r') as f:
print(colored('Run SQL from local file'))
sql = f.read()
except FileNotFoundError as e:
print(colored('Run SQL from user input'))
sql = user_input
# 数据入库
run_db_sql(sql)
def main(options):
if not CONFIG.get('_IS_INSTALLED') and not CONFIG.get('_DISABLE_SETUP'):
raise Exception(f"This DataFlux Func is not installed yet, please complete the installation first.\n Default URL is http(s)://<Domain or IP>:{CONFIG.get('WEB_PORT')}/")
command = options.get('command')
command_func = COMMAND_FUNCS.get(command)
if not command_func:
raise Exception(f"No such command: {command}\n Command should be one of {', '.join(COMMAND_FUNCS.keys())}")
command_func(options)
def get_options_by_command_line():
arg_parser = argparse.ArgumentParser(
prog='admin-tool.py',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''
+--------------------------+
| DataFlux Func Admin Tool |
+--------------------------+
This tool should run in the Docker container:
$ docker exec {DataFlux Func Container ID} sh -c 'exec python admin-tool.py --help'
$ docker exec -it {DataFlux Func Container ID} sh -c 'exec python admin-tool.py reset_admin [-f] [--admin-username=<Admin Username>] [--admin-password=<Password>]'
$ docker exec -it {DataFlux Func Container ID} sh -c 'exec python admin-tool.py reset_upgrade_db_seq'
$ docker exec -it {DataFlux Func Container ID} sh -c 'exec python admin-tool.py clear_redis'
$ docker exec -it {DataFlux Func Container ID} sh -c 'exec python admin-tool.py run_sql'
'''))
# 执行操作
arg_parser.add_argument('command', metavar='<Command>', help=', '.join(COMMAND_FUNCS.keys()))
# 免确认
arg_parser.add_argument('-f', '--force', action='store_true', help='Force run, no confirm')
# 重置密码
arg_parser.add_argument('--admin-username', dest='admin_username', help='Admin Username')
arg_parser.add_argument('--admin-password', dest='admin_password', help='Admin Password')
args = vars(arg_parser.parse_args())
args = dict(filter(lambda x: x[1] is not None, args.items()))
return args
if __name__ == '__main__':
options = get_options_by_command_line()
try:
main(options)
except (KeyboardInterrupt, CommandCanceled) as e:
print()
print(colored('Canceled', 'yellow'))
except Exception as e:
print(colored(str(e), 'red'))
else:
print(colored('Done', 'green'))