docker_images/backups/rsyncvolumes/plan.tpl.py

76 lines
1.7 KiB
Python

# -*- coding: utf-8 -*-
from zipfile import ZipFile, ZIP_DEFLATED
from datetime import datetime
from os import walk, unlink
from os.path import join as osjoin
from os.path import isfile
from glob import glob
# Backup plan for Docker volumes
# ::::::::::::::::::::::::::::::
#
# Keep :
#
# - all saves the last week
# - one save per week the last month
# - one save per month the last year
# Volumes Backup
# ==============
dt = datetime.now()
zipname = '{0}.zip'.format(dt.strftime('%Y-%m-%d_%Hh%Mm%Ss'))
zippath = '${DEST}' + zipname
# Zip files
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in walk(path):
for file in files:
pfile = osjoin(root, file)
if isfile(pfile):
ziph.write(pfile)
f = ZipFile(zippath, 'w', ZIP_DEFLATED, allowZip64=True)
zipdir('${DEST}/volumes', f)
f.close()
# Filter all obsolete save files
# ==============================
def notkeep(fname):
fname = fname.split('/')[-1]
ds = fname.split('_')
if len(ds) <= 1:
return False
ds = ds[0]
d = datetime.strptime(ds, '%Y-%m-%d')
delta = dt - d
if delta.days > 180:
return True
elif delta.days > 15:
if (d.day != 1):
return True
elif delta.days > 2:
if (d.weekday() != 0) and (d.day != 1):
return True
else:
return False
# Filters zip files and keeps only legitimate ones
# ================================================
files = glob('${DEST}/*.zip')
backups_to_remove = filter(notkeep, files)
if len(backups_to_remove) > 0:
print('Save files outdated, will be deleted : \n\n* ' +
'\n* '.join(backups_to_remove))
for b in backups_to_remove:
unlink(b)