Skip to content
Snippets Groups Projects
Commit 60d96645 authored by Samichou's avatar Samichou
Browse files

README.md added, written in markdown. backup_data.json removed....

README.md added, written in markdown. backup_data.json removed. start_rotation.py modified to check for exceptions and close the config file correctly. Comments written in english dor both scripts.
parent 9a01887d
No related branches found
No related tags found
1 merge request!7[TX-INFRA-P18] Add images for pica-backupv2 and backup-rotation
......@@ -17,7 +17,6 @@ VOLUME ["/config"]
COPY start_rotation.py start_rotation.py
COPY backup_data.json /config/backup_data.json
RUN touch /crontab.conf && \
chmod +x start_rotation.py
RUN touch /crontab.conf
CMD /start_rotation.py && cron && crontab /crontab.conf && tail -f /etc/crontab
# Configuration
Le fichier backup_data.json recense les informations sur les différents services mis en place sur la machine et les informations nécessaires pour lancer les rotations sur ces services.
## Structure
* Nom du service : Contient une structure de données contenant les informations relatives au service telles qu'indiquées ci-dessous
* "Host" : Indique l'hôte de la base de données
* "Port" : Indique le port pour se connecter au service
* "Database" : Indique le nom de la base de données
* "Folder" : Indique le nom du dossier de backup utilisé par le script de backup et de rotation
* "Cron" : Indique la fréquence de temps à laquelle les backups sont effectués par le script de rotation au format cron
* "Backup-rota" : Contient les paramètres pour la rotation des backups dans une structure de données comme indiqué ci-dessous
* "Hour" : nombre de backups horaires à conserver
* "Day" : nombre de backups quotidiens à conserver
* "Week" : nombre de backups hebdomadaires à conserver
* "Month": nombre de backups mensuels à conserver
## Exemple
```
{
"wekan":
{
"Host": "wekan-db",
"Port": "27017",
"Database": "wekan",
"Type": "mongo",
"Folder": "wekan",
"Cron" : "0 * * * *",
"Init-Backup" : "0",
"Backup-rota":
{
"Hour" : 24,
"Day" : 7,
"Week" : 4,
"Month" : 12
}
},
"etherpad":
{
"Host": "etherpad-db",
"Port": "3306",
"User": "root",
"Password": "lolilolilol",
"Database": "--all-databases",
"Type": "mysql",
"Folder": "etherpad",
"Cron" : "0 * * * *",
"Options" : "--single-transaction",
"Init-Backup" : "0",
"Backup-rota":
{
"Hour" : 24,
"Day" : 7,
"Week" : 4,
"Month" : 12
}
}
}
```
##Exemple d'implémentation dans le docker-compose
```
##############################
####### Backup rotation ######
##############################
pica-backup-rotation:
image: backup-rotation
container_name: pica-backup-rotation
volumes:
- /DATA/BACKUP/:/backup
- /DATA/CONFIG:/config
```
* /DATA/BACKUP : Dossier contenant les backups à effecter
* /DATA/CONFIG : Dossier contenant le fichier .json de données
......@@ -10,8 +10,7 @@ def main(argv):
folder = False
numberOfBackups = False
# On récupère les paramètres passés et on vérifie que les paramètres -f
# et -n existent bien.
# Checks if the correct parameters were given when launched via command line
try:
opts, args = getopt.getopt(argv, "f:n:")
except getopt.GetoptError:
......@@ -19,21 +18,21 @@ def main(argv):
sys.exit(2)
for opt, arg in opts:
if opt in ('-f'):
# -f doit contenir le chemin d'un dossier existant
# -f must be a folder
if os.path.isdir(arg):
folder = arg
else:
print('Please specify a valid path for argument -f <folder>.')
sys.exit(2)
elif opt in ('-n'):
# -n doit être un entier
# -n must be an integer
try:
numberOfBackups = int(arg)
except ValueError:
print('Please specify a valid number for argument -n <number of backups>.')
if folder and numberOfBackups:
i = 0
# On génère des fichiers vides comportant comme nom la date actuellement moins la valeur de i en heures
# Creates numberOfBackups empty files named with the name of the service + the current date minus number of iterations
start = time.time()
while(i < numberOfBackups):
d = datetime.today() - timedelta(hours=i)
......@@ -45,7 +44,7 @@ def main(argv):
time_elapsed = end - start
print('[' + folder + '/' + ']')
# Affichage du temps de génération du script en secondes
# Displays the time needed to generate all files
print(str(i) + ' files generated in ' + str(time_elapsed) + ' seconds.')
if __name__ == "__main__":
......
......@@ -4,16 +4,14 @@ import sys
import json
from crontab import CronTab
# Définition des paramètres
# Setting constants
BACKUP_FOLDER = '/backup'
CONFIG_FOLDER = '/config'
CONFIG_FILE = 'backup_data.json'
PATH_TO_CONFIG = CONFIG_FOLDER + '/' + CONFIG_FILE
#
# Garde-fou : Test d'existence des dossiers à manipuler
#
# Checks if the config file and folders can be accessed
if not(os.path.exists(BACKUP_FOLDER) and os.path.exists(CONFIG_FOLDER)):
sys.stderr.write('Err: BACKUP_FOLDER or CONFIG_FOLDER doesn\'t exist. \n')
......@@ -23,35 +21,36 @@ if not(os.path.isfile(PATH_TO_CONFIG)):
sys.stderr.write('Err: ' + PATH_TO_CONFIG + ' not found. \n')
sys.exit()
# Création d'une table Cron pour enregistrer les tâches à effectuer
# Creates a cron table
cron = CronTab(user="root")
cron.remove_all()
# Récupération des informations de configuration depuis un fichier .json
services_list = json.load(open(PATH_TO_CONFIG))
#Traitement de chaque service : ajout des informations
#pour la rotation spécfiques à chaque service
for service in services_list:
backup_rota = services_list[service]["Backup-rota"]
rotation_cmd = "/usr/local/bin/rotate-backups -H " +str(backup_rota["Hour"]) + " -d " + \
str(backup_rota["Day"]) + " -w " + str(backup_rota["Week"]) + " -m " + str(backup_rota["Month"]) + " " + \
BACKUP_FOLDER + "/" + services_list[service]["Folder"]
job = cron.new(command=rotation_cmd, user = 'root')
job.setall(services_list[service]["Cron"])
if job.is_valid():
job.enable()
else:
sys.stderr.write('Err: syntax error in ' + CONFIG_FILE)
sys.exit()
for job in cron:
print (cron)
#Ecriture des jobs cron dans la crontab système
# Pulls information about the services from the config file
try:
with open(PATH_TO_CONFIG) as json_file:
services_list = json.load(open(json_file))
#For each service in the config file, creates a new cron job
for service in services_list:
backup_rota = services_list[service]["Backup-rota"]
rotation_cmd = "/usr/local/bin/rotate-backups -H " +str(backup_rota["Hour"]) + " -d " + \
str(backup_rota["Day"]) + " -w " + str(backup_rota["Week"]) + " -m " + str(backup_rota["Month"]) + " " + \
BACKUP_FOLDER + "/" + services_list[service]["Folder"]
job = cron.new(command=rotation_cmd, user = 'root')
job.setall(services_list[service]["Cron"])
if job.is_valid():
job.enable()
else:
sys.stderr.write('Err: syntax error in ' + CONFIG_FILE)
sys.exit()
for job in cron:
print (cron)
except:
sys.stderr.write('Err: while opening JSON config file.\n')
#Write the cron jobs to the system crontab
cron.write("/crontab.conf")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment