Forked from bienvenidosaez/bck_python_postgres_mega.py
Last active
August 29, 2015 14:17
-
-
Save gollum23/0c2a15b0f174328a8d1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
###################################################################################################### | |
## ## | |
## SCRIPT EN PYTHON PARA EL RESPALDO DE BASES DE DATOS POSTGRES ## | |
## ## | |
## Almacenará tres tipos de copia: ## | |
## - Diarias: el sistema realizará una copia diaria por base de datos y eliminará aquellas ## | |
## que tengan más de N_DAYS_AGO_DIARY_BACKUP días de antiguedad ## | |
## - Semanales: el sistema realizará una copia semanal cada viernes de cada base de datos y ## | |
## eliminará aquellas que tengan más de N_WEEKS_AGO_BACKUP semanas de antiguedad ## | |
## - Mensuales: el sistema realizará una copia mensual los días 1 de cada mes y eliminará ## | |
## aquellas que tengan más de N_MONTHS_AGO_BACKUP meses de antiguedad ## | |
## ## | |
####################################################################################################### | |
from time import gmtime, strftime | |
import subprocess | |
import os | |
import glob | |
import time | |
def log(string): | |
print time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime()) + ': ' + str(string) | |
HOST = 'localhost' # hostname del servidor de postgres | |
DATABASE_LIST = ( | |
{ | |
'name' : 'mydb', | |
'username' : 'myuser', | |
'password' : 'mypass' | |
}, | |
) | |
BACKUP_DIR = '/var/dbbackup/' # directorio para guardar las copias | |
MONTH_DAY = '01' # día del mes para la copia mensual | |
WEEK_DAY = '1' # día de la semana para las copias semanal [1(Monday), 7] | |
N_DAYS_AGO = 2 # nº de copias diarias a almacenar | |
N_WEEKS_AGO = 4 # nº de copias semanas que se almecenarán | |
N_MONTHS_AGO = 12 # nº de copias mensuales que se almacenarán | |
# Si el directorio no existe lo creamos | |
if not os.path.isdir(BACKUP_DIR): | |
os.makedirs(BACKUP_DIR, 0770) | |
dumper = """ pg_dump --no-privileges --no-owner --no-reconnect -h localhost -U %s -Z 9 -f %s -F c %s """ | |
x_days_ago = time.time() - ( 60 * 60 * 24 * N_DAYS_AGO ) | |
x_weeks_ago = time.time() - ( 60 * 60 * 24 * N_WEEKS_AGO * 7) | |
x_montsh_ago = time.time() - ( 60 * 60 * 24 * N_MONTHS_AGO * 30) | |
# Iteramos sobre las bases de datos de las listas | |
for database in DATABASE_LIST: | |
# Seteamos el password como variable de entorno para que pg_dump la coja de ahí | |
os.putenv('PGPASSWORD', database['password']) | |
print("===== START diary backup for %s =====" % database['name']) | |
# Iteramos sobre las copias diarias, este apartado se ejecutará en cada ejecución del fichero | |
glob_list = glob.glob(BACKUP_DIR + database['name'] + '_diary_backup*' + '.pgdump') | |
for file in glob_list: | |
file_info = os.stat(file) | |
if file_info.st_ctime < x_days_ago: | |
log("Delete diary backup: %s" % file) | |
#os.unlink(file) | |
else: | |
log("Keep diary backup: %s" % file) | |
thetime = str(strftime("%Y-%m-%d")) | |
file_name = database['name'] + '_diary_backup_' + thetime + ".sql.pgdump" | |
command = dumper % (database['username'], BACKUP_DIR + file_name, database['name']) | |
log(command) | |
subprocess.call(command, shell=True) | |
print("===== END diary backup for %s =====\n" % database['name']) | |
# Si estamos en el día del mes indicado en la variable MOTH_DAY hay que ejecutar la parte mensual del backup | |
if MONTH_DAY == time.strftime('%d', time.gmtime()): | |
print("===== START month backup for %s =====" % database['name']) | |
# Iteramos sobre las copias mensuales | |
glob_list = glob.glob(BACKUP_DIR + database['name'] + '_month_backup*' + '.pgdump') | |
for file in glob_list: | |
file_info = os.stat(file) | |
if file_info.st_ctime < x_montsh_ago: | |
log("Delete month backup: %s" % file) | |
#os.unlink(file) | |
else: | |
log("Keep month backup: %s" % file) | |
thetime = str(strftime("%Y-%m")) | |
file_name = database['name'] + '_month_backup_' + thetime + ".sql.pgdump" | |
command = dumper % (database['username'], BACKUP_DIR + file_name, database['name']) | |
log(command) | |
subprocess.call(command, shell=True) | |
print("===== END month backup for %s =====\n" % database['name']) | |
# Si estamos en el día de la semanaindicado en la variable WEEK_DAY hay que ejecutar la parte semanal del backup | |
if WEEK_DAY == time.strftime('%u', time.gmtime()): | |
print("\n===== START week backup for %s =====" % database['name']) | |
glob_list = glob.glob(BACKUP_DIR + database['name'] + '_week_backup*' + '.pgdump') | |
for file in glob_list: | |
file_info = os.stat(file) | |
if file_info.st_ctime < x_montsh_ago: | |
log("Delete week backup: %s" % file) | |
#os.unlink(file) | |
else: | |
log("Keep week backup: %s" % file) | |
thetime = str(strftime("%Y-%m-week-%U")) | |
file_name = database['name'] + '_week_backup_' + thetime + ".sql.pgdump" | |
command = dumper % (database['username'], BACKUP_DIR + file_name, database['name']) | |
log(command) | |
subprocess.call(command, shell=True) | |
print("===== END week backup for %s =====\n" % database['name']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment