From 2fe0bfd7344cf7e912085a2a13408cb2a0d1f6a8 Mon Sep 17 00:00:00 2001
From: Quentin Duchemin <quentinduchemin@tuta.io>
Date: Thu, 30 Jan 2020 16:45:23 +0100
Subject: [PATCH] [DBBackupRotation] Pass the CI, add simpler config file

---
 backup-rotation/Dockerfile                | 26 +++++------
 backup-rotation/README.md                 | 56 +++++++++++------------
 backup-rotation/clair-whitelist.yml       |  0
 backup-rotation/config/backup_config.json | 35 ++++++++++++++
 backup-rotation/docker-compose.yml        | 11 +++++
 backup-rotation/start_rotation.py         | 36 +++++++--------
 6 files changed, 103 insertions(+), 61 deletions(-)
 create mode 100644 backup-rotation/clair-whitelist.yml
 create mode 100644 backup-rotation/config/backup_config.json
 create mode 100644 backup-rotation/docker-compose.yml

diff --git a/backup-rotation/Dockerfile b/backup-rotation/Dockerfile
index 12642ab4..f5c6dc19 100644
--- a/backup-rotation/Dockerfile
+++ b/backup-rotation/Dockerfile
@@ -1,21 +1,21 @@
 FROM registry.picasoft.net/pica-debian:stretch
 
-RUN     apt-get update \
-        && apt-get -y upgrade \
-        && apt-get -y install \
-                cron \
-                python3 \
-                python3-pip \
-        && pip3 install \
-                rotate-backups \
-                python-crontab \
-        && rm -rf /var/lib/apt/lists/*
+RUN apt-get update \
+    && apt-get -y upgrade \
+    && apt-get -y install \
+      cron \
+      python3 \
+      python3-pip \
+    && pip3 install \
+      rotate-backups \
+      python-crontab \
+    && rm -rf /var/lib/apt/lists/*
 
 VOLUME  ["/backup"]
 VOLUME  ["/config"]
 
-COPY    start_rotation.py start_rotation.py
+COPY start_rotation.py start_rotation.py
 
-RUN     touch /crontab.conf
+RUN touch /crontab.conf
 
-CMD     /start_rotation.py && cron && crontab /crontab.conf && tail -f /etc/crontab
+CMD /start_rotation.py && cron && crontab /crontab.conf && tail -f /etc/crontab
diff --git a/backup-rotation/README.md b/backup-rotation/README.md
index 1f1a0faf..aa723152 100644
--- a/backup-rotation/README.md
+++ b/backup-rotation/README.md
@@ -1,22 +1,30 @@
-# Configuration
+# Rotation des backups des bases de données
 
-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.
+Picasoft réalise régulièrement des backups de ses bases de données. Le service qui s'occupe des backups ne s'occupe pas de supprimer les backups trop anciens. C'est le but de ce service.
 
-## Structure
+Il est flexible et se configure via des fichiers JSON.
+
+La rotation est effectuée une fois par jour.
+
+## Configuration
+
+Le fichier `config/backup_data.json` recense les informations sur les différents services mis en place sur les machines et les informations nécessaires pour lancer les rotations sur ces services.
+
+Ce fichier **est** le fichier utilisé **en production**. Il est unique et recense les services de toutes les machines. Si les backups sont effectués sur une autre machine virtuelle, alors le dossier spécifié dans la configuration est simplement ignoré.
+
+Il ne doit pas être modifié sur les machines sans être synchronisé avec le dépôt Git.
+
+### 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
+- `Folder` : Indique le nom du dossier de backup utilisé par le script de backup et de rotation
+- `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
+### Exemple
 
 ```json
 {
@@ -60,21 +68,9 @@ Le fichier backup_data.json recense les informations sur les différents service
 }
 ```
 
-## Exemple d'implémentation dans le docker-compose
-
+## Lancement
 
-```yaml
-##############################
-####### Backup rotation ######
-##############################
-  pica-backup-rotation:
-    image: backup-rotation
-    container_name: pica-backup-rotation
-    volumes:
-      - /DATA/BACKUP/:/backup
-      - /DATA/CONFIG:/config
+On se synchronise simplement avec le dépôt et on lance le Docker Compose :
+```
+$ docker-compose up -d
 ```
-
-Avec :
- - `/DATA/BACKUP` : Dossier contenant les backups à effecter
- - `/DATA/CONFIG` : Dossier contenant le fichier .json de données
diff --git a/backup-rotation/clair-whitelist.yml b/backup-rotation/clair-whitelist.yml
new file mode 100644
index 00000000..e69de29b
diff --git a/backup-rotation/config/backup_config.json b/backup-rotation/config/backup_config.json
new file mode 100644
index 00000000..0ac552f4
--- /dev/null
+++ b/backup-rotation/config/backup_config.json
@@ -0,0 +1,35 @@
+{
+  "mattermost":
+    {
+      "Folder": "mattermost",
+      "Backup-Rota":
+          {
+              "Hour" : 24,
+              "Day" : 7,
+              "Week" : 4,
+              "Month" : 12
+          }
+    },
+    "etherpad":
+    {
+      "Folder": "etherpad",
+      "Backup-Rota":
+          {
+              "Hour" : 24,
+              "Day" : 7,
+              "Week" : 4,
+              "Month" : 12
+          }
+    },
+    "wekan":
+      {
+        "Folder": "wekan",
+        "Backup-Rota":
+            {
+                "Hour" : 24,
+                "Day" : 7,
+                "Week" : 4,
+                "Month" : 12
+            }
+      }
+}
diff --git a/backup-rotation/docker-compose.yml b/backup-rotation/docker-compose.yml
new file mode 100644
index 00000000..0a8908bf
--- /dev/null
+++ b/backup-rotation/docker-compose.yml
@@ -0,0 +1,11 @@
+version: "3.7"
+
+services:
+  db-backup-rotation:
+    image: registry.picasoft.net/pica-db-backup-rotation:1.0
+    container_name: db-backup-rotation
+    volumes:
+      - /DATA/BACKUP/:/backup/
+      - ./config:/config
+      - /etc/localtime:/etc/localtime:ro
+    restart: always
diff --git a/backup-rotation/start_rotation.py b/backup-rotation/start_rotation.py
index 326e838b..edd16f02 100755
--- a/backup-rotation/start_rotation.py
+++ b/backup-rotation/start_rotation.py
@@ -5,14 +5,12 @@ import json
 from crontab import CronTab
 
 # Setting constants
-
 BACKUP_FOLDER = '/backup'
 CONFIG_FOLDER = '/config'
 CONFIG_FILE = 'backup_data.json'
 PATH_TO_CONFIG = CONFIG_FOLDER + '/' + CONFIG_FILE
 
 # 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')
     sys.exit()
@@ -22,10 +20,10 @@ if not(os.path.isfile(PATH_TO_CONFIG)):
     sys.exit()
 
 # Creates a cron table
-
 cron = CronTab(user="root")
 cron.remove_all()
 
+print("Building configuration file for backup rotation...\n")
 # Pulls information about the services from the config file
 try:
     with open(PATH_TO_CONFIG) as json_file:
@@ -33,24 +31,26 @@ try:
 
         #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()
+            if os.path.isdir(services_list[service]["Folder"]):
+                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("0 0 * * *")
+                if job.is_valid():
+                    job.enable()
+                else:
+                    sys.stderr.write('Err: syntax error in ' + CONFIG_FILE)
+                    sys.exit()
+                print("Info : Folder {0} scheduled for rotation".format(services_list[service]["Folder"]))
             else:
-                sys.stderr.write('Err: syntax error in ' + CONFIG_FILE)
-                sys.exit()
-
+                print("Warning : Folder {0} does not exist, skipping...".format(services_list[service]["Folder"]))
+        print("\nConfiguration done. Cron jobs enabled : ")
         for job in cron:
-                print (cron)
+            print("\t{0}".format(cron))
 except:
     sys.stderr.write('Err: while opening JSON config file.\n')
 
-#Write the cron jobs to the system crontab
-
+# Write the cron jobs to the system crontab
 cron.write("/crontab.conf")
-
-- 
GitLab