-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.py
445 lines (401 loc) · 17.9 KB
/
actions.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import datetime
import os
import shutil
import sys
from datetime import date
from enum import Enum
import yaml
from functional import seq
from PyInquirer import Separator, prompt
import constants
from constants import BColors
class Config:
def __init__(self, config_id, database, dumpFolder, databaseUser, databasePassword, isDocker=False, dockerContainerName=None, dockerPort=None):
self.config_id = config_id
self.database = database
self.dumpFolder = dumpFolder
self.databaseUser = databaseUser
self.databasePassword = databasePassword
self.isDocker = isDocker
self.dockerContainerName = dockerContainerName
self.dockerPort = dockerPort
class ChoiceGroups(Enum):
DATABASE_ACTIONS = 'Database actions'
CONFIG_ACTIONS = 'Configuration actions'
OTHER = 'Other'
def __init__(self, title):
self.title = title
class Choices(Enum):
RESTORE_DUMP = ChoiceGroups.DATABASE_ACTIONS, lambda config: 'Restore a dump', lambda config: restoreDump(config)
CREATE_DUMP = ChoiceGroups.DATABASE_ACTIONS, lambda config: 'Create a dump from ' + config.database, lambda config: createDump(config)
CLEAN_DB = ChoiceGroups.DATABASE_ACTIONS, lambda config: 'Make ' + config.database + ' empty.', lambda config: cleanDatabase(config)
LIST_DUMPS = ChoiceGroups.DATABASE_ACTIONS, lambda config: 'List all dumps in ' + config.dumpFolder, lambda config: listDumps(config)
INIT_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Initialize the configuration file', lambda config: initConfig()
CHANGE_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Change the current configuration', lambda config: changeConfig()
SHOW_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Show all configurations', lambda config: showAllConfig()
SHOW_CURRENT_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Show current configuration', lambda config: showConfig(config)
ADD_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Add a configuration', lambda config: addConfig()
EDIT_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Edit a configuration', lambda config: editConfig()
REMOVE_CONFIG = ChoiceGroups.CONFIG_ACTIONS, lambda config: 'Remove a configuration', lambda config: removeConfig(config)
EXIT = ChoiceGroups.OTHER, lambda config: 'Exit', lambda config: exit()
def __init__(self, group, title, function):
self.group = group
self.title = title
self.function = function
@staticmethod
def objects(config):
grouped_choices = seq(Choices) \
.group_by(lambda c: c.group)
questions = []
for choiceGroup in list(ChoiceGroups):
group = grouped_choices.find(lambda x: x[0] == choiceGroup)
group_questions = seq(group[1]) \
.map(lambda c: {
'name': c.title(config),
'value': c
})
questions.append(Separator('-' * 7 + ' ' + group[0].title + ' ' + '-' * 7))
questions.extend(group_questions)
questions.append(Separator(' '))
return questions
def logError(msg):
print(BColors.RED + 'ERROR: ' + msg + BColors.NC)
def getConfigFilePath():
current_dir = os.path.dirname(sys.argv[0])
return os.path.join(current_dir, 'config.yml')
def loadConfig():
config_file_path = getConfigFilePath()
if not os.path.exists(config_file_path):
initConfig()
with open(getConfigFilePath(), 'r') as stream:
try:
configs=yaml.safe_load(stream)
configToUse=configs.get(constants.configToUseVarName)
return extractConfigToUse(configToUse, configs)
except yaml.YAMLError as exc:
logError(str(exc))
def extractConfigToUse(configToUse, configs):
if configToUse is None:
logError('Config to use is not set in configuration')
changeConfig()
return loadConfig()
if configToUse not in configs:
logError('Could not find config ' + str(configToUse) + ' in configurations: ' + str(seq(configs.keys()).filter(lambda key: key != constants.configToUseVarName)))
changeConfig()
return loadConfig()
return Config(
configToUse,
configs[configToUse]['database'],
configs[configToUse]['dumpFolder'],
configs[configToUse]['databaseUser'],
configs[configToUse]['databasePassword'],
configs[configToUse].get('isDocker', False),
configs[configToUse].get('dockerContainerName', None),
configs[configToUse].get('dockerPort', None)
)
def showMenu(config):
print('Current configuration: ' + BColors.RED + str(config.config_id) + BColors.NC)
questions = {
'type': 'list',
'name': 'choice',
'message': 'What do you want to do?',
'choices': Choices.objects(config)
}
answers = prompt(questions, style=constants.style)
if bool(answers):
return answers['choice']
def getDumps(config):
def getCreatedDate(config, file):
created_date_float = os.path.getctime(os.path.join(config.dumpFolder, file))
created_date = datetime.datetime.fromtimestamp(created_date_float).strftime("%m/%d/%Y, %H:%M:%S")
return created_date
return seq(os.listdir(config.dumpFolder)) \
.filter(lambda file: file.endswith(".sql")) \
.order_by(lambda file: os.path.getctime(os.path.join(config.dumpFolder, file))) \
.map(lambda file: (file, getCreatedDate(config, file))) \
.to_dict()
def listDumps(config):
for dump, created_date in getDumps(config).items():
print(created_date + ' ' + dump)
def showAllConfig():
with open(getConfigFilePath(), 'r') as stream:
configs = yaml.safe_load(stream)
all_configs = seq(configs.keys()).filter(lambda key: key != constants.configToUseVarName).map(lambda key: (key, extractConfigToUse(key, configs))).to_dict()
for key, config in all_configs.items():
print(BColors.LIGHT_BLUE + 'Configuration: ' + str(key))
print(BColors.CYAN + 'database:' + str(config.database))
print(BColors.CYAN + 'dumpFolder:' + str(config.dumpFolder))
print(BColors.CYAN + 'databaseUser:' + str(config.databaseUser))
print(BColors.CYAN + 'databasePassword:' + str(config.databasePassword) + BColors.NC)
print(BColors.CYAN + 'isDocker:' + str(config.isDocker) + BColors.NC)
if config.isDocker:
print(BColors.CYAN + 'dockerPort:' + str(config.dockerPort) + BColors.NC)
print(BColors.CYAN + 'dockerContainerName:' + str(config.dockerContainerName) + BColors.NC)
print()
def showConfig(config):
print()
print(BColors.LIGHT_BLUE + 'Using configuration:')
print(BColors.CYAN + '- database:' + str(config.database))
print(BColors.CYAN + '- dumpFolder:' + str(config.dumpFolder))
print(BColors.CYAN + '- databaseUser:' + str(config.databaseUser))
print(BColors.CYAN + '- databasePassword:' + str(config.databasePassword) + BColors.NC)
print(BColors.CYAN + '- isDocker:' + str(config.isDocker) + BColors.NC)
if config.isDocker:
print(BColors.CYAN + '- dockerPort:' + str(config.dockerPort) + BColors.NC)
print(BColors.CYAN + '- dockerContainerName:' + str(config.dockerContainerName) + BColors.NC)
def restoreDump(config):
dumps_dict = getDumps(config)
dumps_choices = seq(dumps_dict.keys()) \
.map(lambda key: {
'name': dumps_dict[key] + ' ' + key,
'value': key
})
if dumps_choices:
questions = {
'type': 'list',
'name': 'dump',
'message': 'What dump would you like to restore?',
'choices': dumps_choices
}
answers = prompt(questions, style=constants.style)
# Keyboard interrupt -> answers is empty
if bool(answers):
print('Cleaning the current database...')
cleanDatabase(config)
dump_to_restore = os.path.join(config.dumpFolder, answers['dump'])
print('This can take a while depending on the size of the dump...')
# docker exec -i mysql_slims_66 sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD" slimsdb66 ' < /Users/dekeyzer/Documents/DbDumps/SLIMS/6.6/slims65_start.sql
if config.isDocker:
os.system("docker exec -i %s sh -c 'exec mysql -uroot -p\"$MYSQL_ROOT_PASSWORD\" %s ' < %s" % (config.dockerContainerName, config.database, dump_to_restore))
else:
os.system("mysql -u %s -p%s %s < %s" % (config.databaseUser, config.databasePassword, config.database, dump_to_restore))
else:
logError("No dumps found in '%s'" % config.dumpFolder)
def createDump(config):
now = date.today().strftime("%b-%d-%Y")
questions = {
'type': 'input',
'name': 'dump_name',
'message': "Name of the dump (will automatically be affixed by the current date and extension '_%s.sql')" % (now)
}
answers = prompt(questions, style=constants.style)
if bool(answers):
dump_location = config.dumpFolder + '/' + answers['dump_name'] + '_' + now + '.sql'
if config.isDocker:
os.system("docker exec %s sh -c 'exec mysqldump -uroot -p\"$MYSQL_ROOT_PASSWORD\" %s' > %s" % (config.dockerContainerName, config.database, dump_location))
else:
os.system("mysqldump -u %s -p%s %s > %s" % (config.databaseUser, config.databasePassword, config.database, dump_location))
def cleanDatabase(config):
if config.isDocker:
questions = {
'type': 'confirm',
'message': 'Are you sure you want to drop the ' + config.database,
'name': 'continue',
}
answers = prompt(questions, style=constants.style)
if not answers['continue']:
return
else:
os.system("docker exec %s sh -c 'exec mysqladmin -uroot -p\"$MYSQL_ROOT_PASSWORD\" -f drop %s'" % (config.dockerContainerName, config.database))
os.system("docker exec %s sh -c 'exec mysqladmin -uroot -p\"$MYSQL_ROOT_PASSWORD\" create %s'" % (config.dockerContainerName, config.database))
else:
os.system("mysqladmin -u %s -p%s drop %s" % (config.databaseUser, config.databasePassword, config.database))
os.system("mysqladmin -u %s -p%s create %s" % (config.databaseUser, config.databasePassword, config.database))
def askWhichConfiguration(configs, question):
def getChoiceObject(key, currentConfig):
if key == currentConfig:
name = str(key) + ' (current configuration)'
else:
name = str(key)
return {
'name': name,
'value': key
}
configurations = seq(configs.keys()).filter(lambda key: key != constants.configToUseVarName).map(lambda key: getChoiceObject(key, configs.get(constants.configToUseVarName)))
if not configurations:
logError("No configurations found, please add one")
addConfig()
return None
questions = {
'type': 'list',
'name': 'configuration',
'message': question,
'choices': configurations
}
return prompt(questions, style=constants.style)
def changeConfig():
config_file = getConfigFilePath()
with open(config_file, 'r') as stream:
configs = yaml.safe_load(stream)
answers = askWhichConfiguration(configs, 'What configuration do you want to use?')
if bool(answers):
configs[constants.configToUseVarName] = answers['configuration']
with open(config_file, 'w') as f:
yaml.dump(configs, f)
else:
exit()
def removeConfig(config):
config_file = getConfigFilePath()
with open(config_file, 'r') as stream:
configs = yaml.safe_load(stream)
answers = askWhichConfiguration(configs, 'What configuration do you want to remove?')
if bool(answers):
del configs[answers['configuration']]
with open(config_file, 'w') as f:
yaml.dump(configs, f)
def editConfig():
config_file = getConfigFilePath()
with open(config_file, 'r') as stream:
configs = yaml.safe_load(stream)
answers = askWhichConfiguration(configs, 'What configuration do you want to edit?')
if bool(answers):
chosen_config = answers['configuration']
config_object = extractConfigToUse(chosen_config, configs)
questions = [
{
'type': 'input',
'name': 'config_key',
'message': 'Configuration key:',
'default': chosen_config
},
{
'type': 'input',
'name': 'database',
'message': 'Database:',
'default': config_object.database
},
{
'type': 'input',
'name': 'dump_folder',
'message': 'Dump folder:',
'default': config_object.dumpFolder,
'validate': lambda val: os.path.isdir(val) or 'Directory does not exist'
},
{
'type': 'input',
'name': 'database_user',
'message': 'Database user:',
'default': config_object.databaseUser
},
{
'type': 'input',
'name': 'database_password',
'message': 'Database password:',
'default': config_object.databasePassword
},
{
'type': 'confirm',
'message': 'Is this a docker configuration',
'name': 'isDocker',
'default': config_object.isDocker,
},
{
'type': 'input',
'message': 'What is the docker container\'s name?',
'name': 'dockerContainerName',
'default': config_object.dockerContainerName,
'when': lambda answers: answers['isDocker']
},
{
'type': 'input',
'message': 'On what port is the docker container running?',
'name': 'dockerPort',
'default': config_object.dockerPort,
'when': lambda answers: answers['isDocker']
}
]
edited_config = prompt(questions, style=constants.style)
if bool(edited_config):
new_config = {
'database': edited_config['database'],
'databasePassword': edited_config['database_password'],
'databaseUser': edited_config['database_user'],
'dumpFolder': edited_config['dump_folder'],
'isDocker': edited_config['isDocker'],
'dockerContainerName': edited_config['dockerContainerName'],
'dockerPort': edited_config['dockerPort']
}
configs[chosen_config] = new_config
with open(config_file, 'w') as f:
yaml.dump(configs, f)
def addConfig():
config_file = getConfigFilePath()
questions = [
{
'type': 'input',
'name': 'config_key',
'message': 'Configuration key:',
},
{
'type': 'input',
'name': 'database',
'message': 'Database:',
},
{
'type': 'input',
'name': 'dump_folder',
'message': 'Dump folder:',
'validate': lambda val: os.path.isdir(val) or 'Directory does not exist'
},
{
'type': 'input',
'name': 'database_user',
'message': 'Database user:'
},
{
'type': 'input',
'name': 'database_password',
'message': 'Database password:'
},
{
'type': 'confirm',
'message': 'Is this a docker configuration',
'name': 'isDocker',
'default': False,
},
{
'type': 'input',
'message': 'What is the docker container\'s name?',
'name': 'dockerContainerName',
'when': lambda answers: answers['isDocker']
},
{
'type': 'input',
'message': 'On what port is the docker container running?',
'name': 'dockerPort',
'when': lambda answers: answers['isDocker']
}
]
answers = prompt(questions, style=constants.style)
if bool(answers):
with open(config_file, 'r') as stream:
configs = yaml.safe_load(stream)
new_config = {
'database': answers['database'],
'databasePassword': answers['database_password'],
'databaseUser': answers['database_user'],
'dumpFolder': answers['dump_folder'],
'isDocker': answers['isDocker'],
'dockerContainerName': answers['dockerContainerName'],
'dockerPort': answers['dockerPort']
}
configs[answers['config_key']] = new_config
with open(config_file, 'w') as f:
yaml.dump(configs, f)
else:
exit()
def initConfig():
current_dir = os.path.dirname(sys.argv[0])
config_file = os.path.join(current_dir, 'config.yml')
if os.path.exists(config_file):
questions = {
'type': 'confirm',
'message': 'WARNING: This will overwrite your configuration file which is not empty. Do you want to continue?',
'name': 'continue',
'default': False
}
answers = prompt(questions, style=constants.style)
if not answers['continue']:
return
new_config_file = open(config_file, "w")
new_config_file.write(constants.configToUseVarName + ': ')