-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
310 lines (277 loc) · 11.7 KB
/
classes.py
File metadata and controls
310 lines (277 loc) · 11.7 KB
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
# Para script de backup
import os
import mimetypes
import helper
import json
import time
import logging
import subprocess
from datetime import datetime
from operator import itemgetter
# Para notificiar x email
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText
from config import LOGGER_FORMAT, LOG_FILENAME
from config import DRIVE_CONFIG_PATH
from config import MAX_FILES_DUMP_DIR
class IBackup(object):
"""
Interfaz basica para backups de una base de datos especifica.
"""
db_name = None
dump_dir = None
db_username = None
db_password = None
file_path = None
def ejecutar(self):
"""
Realiza dicho backup. Se fija que la cantidad de archivos en el
directorio dumper no superer el numero de archivos maximo especificado
en el archivo DRIVE_CONFIG_PATH.
"""
def subir_archivo(self):
"""
Sube el archivo adonde se desee subir. Chequea que el numero de archivos
en nube ni en disco local no supere el especificado en archivo DRIVE_CONFIG_PATH.
"""
class Notificador(object):
"""
Clase para enviar notificaciones por email. Se usa el mismo usuario para emisor
y receptor.
"""
server = None
usuario = None
def __init__(self, usuario, password):
"""
Inicia el notificador para una cuenta especifica.
"""
self.usuario = usuario
self.server = smtplib.SMTP("smtp.gmail.com:587")
self.server.starttls()
self.server.login(self.usuario, password)
def notificar(self, asunto, mensaje):
"""
Envia el mensaje por email.
"""
fromaddr = '%s@gmail.com' % self.usuario
toaddrs = '%s@gmail.com' % self.usuario
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = asunto
msg.attach(MIMEText(mensaje))
self.server.sendmail(fromaddr, toaddrs, msg.as_string())
def cerrar(self):
"""
Cierra el servicio.
"""
self.server.quit()
class PostgressDriveBackup(IBackup):
"""
Clase para realizar backups de base de datos Postgress y subir a Google
drive.
"""
def __init__(self, db_name, dump_dir, db_username):
"""
Configura parametros para la instancia.
"""
# Logger
logging.basicConfig(
filename=LOG_FILENAME, level=logging.INFO, format=LOGGER_FORMAT)
self.logger = logging.getLogger('Postgres Drive Backup')
# Base de datos
self.db_name = db_name
self.dump_dir = dump_dir
try:
os.stat(self.dump_dir)
except:
os.mkdir(self.dump_dir)
self.db_username = db_username
def ejecutar(self):
"""
Este es el metodo que se utiliza para realizar dicho backup para
una base de datos especifica.
@param db_name: nombre de base de datos.
"""
try:
dumper = " -U %s -Z 9 -f %s -F c %s "
# Usamos una fecha en el nombre para identificar rapidamente cuando
# se hizo
date = datetime.now().strftime('%Y-%m-%d-%H%M%S')
temp_file_name = '%s--%s.sql' % (date, self.db_name)
temp_file_path = os.path.join(self.dump_dir, temp_file_name)
command = 'pg_dump' + \
dumper % (self.db_username, temp_file_path, self.db_name)
subprocess.call(command, shell=True)
subprocess.call('gzip -f ' + temp_file_path, shell=True)
self.bkp_file = temp_file_name + '.gz'
self.file_path = temp_file_path + '.gz'
self.logger.info("Backup de base de datos %s creado en %s." %
(self.bkp_file, self.file_path))
except Exception, e:
self.logger.error('No se pudo crear el backup %s' % (self.db_name))
raise Exception('No se pudo crear el backup %s' % (self.db_name))
# Chequeamos cantidad de archivos en disco
try:
config_file = open(DRIVE_CONFIG_PATH, 'r')
config = json.loads(config_file.read())
except Exception, e:
self.logger.error('Error al abrir el archivo drive_config.json.')
raise Exception('Error al abrir el archivo drive_config.json.')
files = os.listdir(self.dump_dir)
if len(files) > MAX_FILES_DUMP_DIR:
fileData = {}
for fname in files:
path = self.dump_dir + '/' + fname
fileData[path] = os.stat(path).st_mtime
sortedFiles = sorted(fileData.items(), key=itemgetter(1))
os.remove(sortedFiles[0][0])
def subir_archivo(self):
"""
Sube el archivo adonde se desee subir siempre y cuando sea a una cuenta
de Google Drive.
"""
try:
config_file = open(DRIVE_CONFIG_PATH, 'r')
config = json.loads(config_file.read())
except Exception, e:
self.logger.error('Error al abrir el archivo drive_config.json.')
raise Exception('Error al abrir el archivo drive_config.json.')
try:
drive_service = helper.createDriveService(config)
except Exception, e:
self.logger.error(
'No se pudo conectar a la cuenta de Google Drive.')
raise Exception('No se pudo conectar a la cuenta de Google Drive.')
self.logger.info('Autentificacion a Google Driver exitosa')
mimetype_upload_file = mimetypes.guess_type(self.file_path)
upload_file_mimetype = mimetype_upload_file[0]
self.logger.info(
'Subiendo archivo backup %s a Google Drive...' % self.db_name)
try:
file_result = helper.insert_file(
drive_service, config, self.file_path, self.bkp_file, upload_file_mimetype)
except Exception, e:
self.logger.info(
'Ha ocurrido un error al subir el archivo a la cuenta de Google Drive')
raise Exception('Ha ocurrido un error al subir el archivo a la cuenta de Google Drive')
# Si excedemos cantidad de archivos a subir, borramos anteriores
children_files = helper.files_in_folder( drive_service, config['backup_folder_id'] )
if len( children_files ) > config['max_file_in_folder']:
#Remove old backup file
number_delete_file = len(children_files) - config['max_file_in_folder']
count = 0
index_delete_file = len(children_files) -1
while count < number_delete_file:
children_id = children_files[index_delete_file]['id']
self.logger.info( "Removing old file with id " + children_id)
helper.remove_file_from_folder( drive_service, config['backup_folder_id'], children_id )
count +=1
index_delete_file -=1
class MySqlDriveBackup(IBackup):
"""
Clase para realizar backups de base de datos Postgress y subir a Google
drive.
"""
def __init__(self, db_name, dump_dir, db_username, db_password):
"""
Configura parametros para la instancia.
"""
# Logger
logging.basicConfig(
filename=LOG_FILENAME, level=logging.INFO, format=LOGGER_FORMAT)
self.logger = logging.getLogger('Postgres Drive Backup')
# Base de datos
self.db_name = db_name
self.dump_dir = dump_dir
try:
os.stat(self.dump_dir)
except:
os.mkdir(self.dump_dir)
self.db_username = db_username
self.db_password = db_password
def ejecutar(self):
"""
Este es el metodo que se utiliza para realizar dicho backup para
una base de datos especifica.
@param db_name: nombre de base de datos.
"""
try:
dumper = " -U %s -p %s %s "
dumper = " --single-transaction -u %s -p%s %s "
# Usamos una fecha en el nombre para identificar rapidamente cuando
# se hizo
date = datetime.now().strftime('%Y-%m-%d-%H%M%S')
temp_file_name = '%s--%s.sql' % (date, self.db_name)
temp_file_path = os.path.join(self.dump_dir, temp_file_name)
command = 'mysqldump' + \
dumper % (self.db_username, self.db_password, self.db_name) + \
'> ' + temp_file_path
subprocess.call(command, shell=True)
subprocess.call('gzip -f ' + temp_file_path, shell=True)
self.bkp_file = temp_file_name + '.gz'
self.file_path = temp_file_path + '.gz'
self.logger.info("Backup de base de datos %s creado en %s." %
(self.bkp_file, self.file_path))
except Exception, e:
self.logger.error('No se pudo crear el backup %s' % (self.db_name))
raise Exception('No se pudo crear el backup %s' % (self.db_name))
# Chequeamos cantidad de archivos en disco
try:
config_file = open(DRIVE_CONFIG_PATH, 'r')
config = json.loads(config_file.read())
except Exception, e:
self.logger.error('Error al abrir el archivo drive_config.json.')
raise Exception('Error al abrir el archivo drive_config.json.')
files = os.listdir(self.dump_dir)
if len(files) > MAX_FILES_DUMP_DIR:
fileData = {}
for fname in files:
path = self.dump_dir + '/' + fname
fileData[path] = os.stat(path).st_mtime
sortedFiles = sorted(fileData.items(), key=itemgetter(1))
os.remove(sortedFiles[0][0])
def subir_archivo(self):
"""
Sube el archivo adonde se desee subir siempre y cuando sea a una cuenta
de Google Drive.
"""
try:
config_file = open(DRIVE_CONFIG_PATH, 'r')
config = json.loads(config_file.read())
except Exception, e:
self.logger.error('Error al abrir el archivo drive_config.json.')
raise Exception('Error al abrir el archivo drive_config.json.')
try:
drive_service = helper.createDriveService(config)
except Exception, e:
self.logger.error(
'No se pudo conectar a la cuenta de Google Drive.')
raise Exception('No se pudo conectar a la cuenta de Google Drive.')
self.logger.info('Autentificacion a Google Driver exitosa')
mimetype_upload_file = mimetypes.guess_type(self.file_path)
upload_file_mimetype = mimetype_upload_file[0]
self.logger.info(
'Subiendo archivo backup %s a Google Drive...' % self.db_name)
try:
file_result = helper.insert_file(
drive_service, config, self.file_path, self.bkp_file, upload_file_mimetype)
except Exception, e:
self.logger.info(
'Ha ocurrido un error al subir el archivo a la cuenta de Google Drive')
raise Exception('Ha ocurrido un error al subir el archivo a la cuenta de Google Drive')
# Si excedemos cantidad de archivos a subir, borramos anteriores
children_files = helper.files_in_folder( drive_service, config['backup_folder_id'] )
if len( children_files ) > config['max_file_in_folder']:
#Remove old backup file
number_delete_file = len(children_files) - config['max_file_in_folder']
count = 0
index_delete_file = len(children_files) -1
while count < number_delete_file:
children_id = children_files[index_delete_file]['id']
self.logger.info( "Removing old file with id " + children_id)
helper.remove_file_from_folder( drive_service, config['backup_folder_id'], children_id )
count +=1
index_delete_file -=1