84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
import docker
|
|
import restic
|
|
import yaml
|
|
import configparser
|
|
|
|
|
|
bindingIncludePattern = None
|
|
bindingExcludePattern = None
|
|
remoteHost = None
|
|
remoteUser = None
|
|
repository = None
|
|
passwordFile = None
|
|
|
|
|
|
def read_config_file(filepath: str = "configuration.ini"):
|
|
parser = configparser.ConfigParser()
|
|
parser.read(filepath)
|
|
global bindingIncludePattern
|
|
global bindingExcludePattern
|
|
global remoteHost
|
|
global remoteUser
|
|
global repository
|
|
global passwordFile
|
|
bindingIncludePattern = parser["backandup"]["bindincludepattern"]
|
|
bindingExcludePattern = parser["backandup"]["bindexcludepattern"]
|
|
remoteHost = parser["restic"]["remotehost"]
|
|
remoteUser = parser["restic"]["remoteuser"]
|
|
repository = parser["restic"]["repository"]
|
|
passwordFile = parser["restic"]["passwordfile"]
|
|
|
|
|
|
def do_backup(dirpath: str, tags: str = None):
|
|
restic.repository = f"sftp:{remoteUser}@{remoteHost}:/{repository}"
|
|
restic.password_file = passwordFile
|
|
if tags is None:
|
|
restic.backup(paths=[dirpath])
|
|
else:
|
|
restic.backup(paths=[dirpath], tags=[])
|
|
|
|
|
|
def backup_ct_binds(ct: docker.models.containers.Container, includepattern: str | list = None,
|
|
excludepattern: str | list = None):
|
|
if ct.attrs['HostConfig']['Binds'] is None:
|
|
print(" Nothing to backup")
|
|
return 0
|
|
if type(includepattern) is str:
|
|
includepattern = [includepattern]
|
|
if type(excludepattern) is str:
|
|
excludepattern = [excludepattern]
|
|
if includepattern is None:
|
|
includepattern = ["NOPATTERNTOINCLUDEXXXXXX"]
|
|
if excludepattern is None:
|
|
excludepattern = ["NOPATTERNTOEXCLUDEXXXXXX"]
|
|
for BindMount in ct.attrs['HostConfig']['Binds']:
|
|
BindPath = BindMount.split(":")[0]
|
|
print(f" {BindPath}")
|
|
# Si on matche au moins 1 pattern d'inclusion ET aucun pattern d'exclusion
|
|
if any(x in BindPath for x in includepattern) and not any(x in BindPath for x in excludepattern):
|
|
do_backup(BindPath)
|
|
else:
|
|
print(" not a directory to backup")
|
|
return 0
|
|
|
|
|
|
def stop_backup_restart_container(ct: docker.models.containers.Container):
|
|
print(ct.name)
|
|
dorestart = False
|
|
if ct.attrs['State']['Status'] == 'running':
|
|
print(" stop the container")
|
|
dorestart = True
|
|
ct.stop()
|
|
backup_ct_binds(ct, bindingIncludePattern, bindingExcludePattern)
|
|
if dorestart:
|
|
print(" start the container")
|
|
ct.start()
|
|
return 0
|
|
|
|
# Press the green button in the gutter to run the script.
|
|
if __name__ == '__main__':
|
|
dockerhost = docker.from_env()
|
|
read_config_file()
|
|
for container in dockerhost.containers.list(all=True):
|
|
stop_backup_restart_container(container)
|