Source

rsync_backup / rsync_backup_daemon.py

# -*- coding: ascii
"""
daemon process based backup for interactive backups

scenario:
* linux based server running this script as daemon process
* windows PC with smb network message service for notificiations
* windows PC triggers backup by creating SIGNAL_FILE
* server notifies PC about start of backup
* server notifies PC about end of backup

author: Thomas Waldmann
license: BSD
"""

import os
import time
import subprocess

from rsync_backup import backup
from exec_cmd import exec_shell as cmd
from fs import mount_pathes, umount_pathes, mount, umount
from smb import send_msg

SIGNAL_FILE = "BACKUP.SIG"
LOG_FILE = "BACKUP-LOG.TXT"

BACKUP_DEV = "-L BACKUP"  # anything acceptable as 1st mount param
BACKUP_MOUNTPOINT = "/mnt/backup"

PATHES = ["/bin", "/etc", ]
ROOTFS = "/rootfs"

SRC = ROOTFS
DST = BACKUP_MOUNTPOINT
GENERATIONS = 3

MSG_HOST = "gw-pc" # smb hostname for notifications


def pre_backup():
    """do stuff before the backup begins"""
    #send_msg("backup starts in 60s...", MSG_HOST)
    time.sleep(60)
    mount(BACKUP_DEV, BACKUP_MOUNTPOINT)
    mount_pathes(PATHES, ROOTFS)


def post_backup():
    """do stuff after the backup finished"""
    umount_pathes(PATHES, ROOTFS)
    umount(BACKUP_MOUNTPOINT)
    #send_msg("backup ended", MSG_HOST)


def do_backup():
    with open(LOG_FILE, "a") as logfile:
        try:
            pre_backup()
            backup(SRC, DST, GENERATIONS, stdout=logfile, stderr=subprocess.STDOUT)
            post_backup()
        except Exception as err:
            #send_msg("backup crashed!", MSG_HOST)
            logfile.write("Backup crashed, Exception:\n")
            logfile.write(str(err))
            raise


def daemon():
    """poll whether SIGNAL_FILE to exist, if so: start backup, repeat"""
    while True:
        if os.path.exists(SIGNAL_FILE):
            os.remove(SIGNAL_FILE)
            do_backup()
        time.sleep(10)


if __name__ == "__main__":
    daemon()