forked from anubia/py_pg_tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restorer.py
229 lines (190 loc) · 9.07 KB
/
restorer.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
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import os # To check the existance of some files
import re # To work with regular expressions
import subprocess # To execute commands in the shell
from const.const import Messenger
from const.const import Default
from date_tools.date_tools import DateTools
from logger.logger import Logger
from replicator import Replicator
class Restorer:
# An object with connection parameters to connect to PostgreSQL
connecter = None
logger = None # Logger to show and log some messages
db_backup = '' # Absolute path of the backup file (of a database)
new_dbname = '' # New name for the database restored in PostgreSQL
def __init__(self, connecter=None, db_backup='', new_dbname='',
logger=None):
if logger:
self.logger = logger
else:
self.logger = Logger()
if connecter:
self.connecter = connecter
else:
self.logger.stop_exe(Messenger.NO_CONNECTION_PARAMS)
if db_backup and os.path.isfile(db_backup):
self.db_backup = db_backup
else:
self.logger.stop_exe(Messenger.NO_BKP_TO_RESTORE)
if new_dbname:
self.new_dbname = new_dbname
else:
self.logger.stop_exe(Messenger.NO_DBNAME_TO_RESTORE)
message = Messenger.DB_RESTORER_VARS.format(
server=self.connecter.server, user=self.connecter.user,
port=self.connecter.port, db_backup=self.db_backup,
new_dbname=self.new_dbname)
self.logger.debug(Messenger.DB_RESTORER_VARS_INTRO)
self.logger.debug(message)
def restore_db_backup(self):
'''
Target:
- restore a database's backup in PostgreSQL.
'''
replicator = Replicator(self.connecter, self.new_dbname,
Default.RESTORING_TEMPLATE, self.logger)
result = self.connecter.allow_db_conn(Default.RESTORING_TEMPLATE)
if result:
replicator.replicate_pg_db()
self.connecter.disallow_db_conn(Default.RESTORING_TEMPLATE)
else:
self.logger.stop_exe(Messenger.ALLOW_DB_CONN_FAIL.format(
dbname=Default.RESTORING_TEMPLATE))
# Regular expression which must match the backup's name
regex = r'.*db_(.+)_(\d{8}_\d{6}_.+)\.(dump|bz2|gz|zip)$'
regex = re.compile(regex)
if re.match(regex, self.db_backup):
# Store the parts of the backup's name (name, date, ext)
parts = regex.search(self.db_backup).groups()
# Store only the extension to know the type of file
ext = parts[2]
else:
self.logger.stop_exe(Messenger.NO_BACKUP_FORMAT)
message = Messenger.BEGINNING_DB_RESTORER.format(
db_backup=self.db_backup, new_dbname=self.new_dbname)
self.logger.highlight('info', message, 'white')
self.logger.info(Messenger.WAIT_PLEASE)
if ext == 'gz':
command = 'gunzip -c {} -k | pg_restore -U {} -h {} -p {} ' \
'-d {}'.format(self.db_backup, self.connecter.user,
self.connecter.server,
self.connecter.port, self.new_dbname)
elif ext == 'bz2':
command = 'bunzip2 -c {} -k | pg_restore -U {} -h {} -p {} ' \
'-d {}'.format(self.db_backup, self.connecter.user,
self.connecter.server,
self.connecter.port, self.new_dbname)
elif ext == 'zip':
command = 'unzip -p {} | pg_restore -U {} -h {} -p {} ' \
'-d {}'.format(self.db_backup, self.connecter.user,
self.connecter.server,
self.connecter.port, self.new_dbname)
else:
command = 'pg_restore -U {} -h {} -p {} -d {} {}'.format(
self.connecter.user, self.connecter.server,
self.connecter.port, self.new_dbname, self.db_backup)
try:
start_time = DateTools.get_current_datetime()
# Make the restauration of the database
result = subprocess.call(command, shell=True)
end_time = DateTools.get_current_datetime()
# Get and show the process' duration
diff = DateTools.get_diff_datetimes(start_time, end_time)
if result != 0:
raise Exception()
message = Messenger.RESTORE_DB_DONE.format(
db_backup=self.db_backup, new_dbname=self.new_dbname,
diff=diff)
self.logger.highlight('info', message, 'green')
self.logger.highlight('info', Messenger.RESTORER_DONE, 'green',
effect='bold')
except Exception as e:
self.logger.debug('Error en la función "restore_db_backup": '
'{}.'.format(str(e)))
message = Messenger.RESTORE_DB_FAIL.format(
db_backup=self.db_backup, new_dbname=self.new_dbname)
self.logger.stop_exe(message)
class RestorerCluster:
# An object with connection parameters to connect to PostgreSQL
connecter = None
logger = None # Logger to show and log some messages
cluster_backup = '' # Absolute path of the backup file (of a cluster)
def __init__(self, connecter=None, cluster_backup='', logger=None):
if logger:
self.logger = logger
else:
self.logger = Logger()
if connecter:
self.connecter = connecter
else:
self.logger.stop_exe(Messenger.NO_CONNECTION_PARAMS)
if cluster_backup and os.path.isfile(cluster_backup):
self.cluster_backup = cluster_backup
else:
self.logger.stop_exe(Messenger.NO_BKP_TO_RESTORE)
message = Messenger.CL_RESTORER_VARS.format(
server=self.connecter.server, user=self.connecter.user,
port=self.connecter.port, cluster_backup=self.cluster_backup)
self.logger.debug(Messenger.CL_RESTORER_VARS_INTRO)
self.logger.debug(message)
def restore_cluster_backup(self):
'''
Target:
- restore a cluster's backup in PostgreSQL. The cluster must have
been created before this process.
'''
# Regular expression which must match the backup's name
regex = r'.*ht_(.+_cluster)_(\d{8}_\d{6}_.+)\.(dump|bz2|gz|zip)$'
regex = re.compile(regex)
if re.match(regex, self.cluster_backup):
# Store the parts of the backup's name (servername, date, ext)
parts = regex.search(self.cluster_backup).groups()
# Store only the extension to know the type of file
ext = parts[2]
else:
Messenger.NO_BACKUP_FORMAT
message = Messenger.BEGINNING_CL_RESTORER.format(
cluster_backup=self.cluster_backup)
self.logger.highlight('info', message, 'white')
self.logger.info(Messenger.WAIT_PLEASE)
# TODO: make dissappear every line about the operation shown in console
if ext == 'gz':
command = 'gunzip -c {} -k | psql postgres -U {} -h {} ' \
'-p {}'.format(
self.cluster_backup, self.connecter.user,
self.connecter.server, self.connecter.port)
elif ext == 'bz2':
command = 'bunzip2 -c {} -k | psql postgres -U {} -h {} ' \
'-p {}'.format(
self.cluster_backup, self.connecter.user,
self.connecter.server, self.connecter.port)
elif ext == 'zip':
command = 'unzip -p {} | psql postgres -U {} -h {} -p {}'.format(
self.cluster_backup, self.connecter.user,
self.connecter.server, self.connecter.port)
else:
command = 'psql postgres -U {} -h {} -p {} < {}'.format(
self.connecter.user, self.connecter.server,
self.connecter.port, self.cluster_backup)
try:
start_time = DateTools.get_current_datetime()
# Make the restauration of the cluster
result = subprocess.call(command, shell=True)
end_time = DateTools.get_current_datetime()
# Get and show the process' duration
diff = DateTools.get_diff_datetimes(start_time, end_time)
if result != 0:
raise Exception()
message = Messenger.RESTORE_CL_DONE.format(
cluster_backup=self.cluster_backup, diff=diff)
self.logger.highlight('info', message, 'green')
self.logger.highlight('info', Messenger.RESTORER_DONE, 'green',
effect='bold')
except Exception as e:
self.logger.debug('Error en la función "restore_cluster_backup": '
'{}.'.format(str(e)))
message = Messenger.RESTORE_CL_FAIL.format(
cluster_backup=self.cluster_backup)
self.logger.stop_exe(message)