2019-11-15 15:47:40 +00:00
|
|
|
import logging
|
2019-04-17 01:28:07 +00:00
|
|
|
import os
|
|
|
|
import docker
|
|
|
|
|
|
|
|
from restic_volume_backup.config import Config
|
|
|
|
|
2019-11-15 15:47:40 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2019-04-17 02:38:15 +00:00
|
|
|
|
2019-04-18 01:52:28 +00:00
|
|
|
def run(image: str = None, command: str = None, volumes: dict = None,
|
2019-12-03 03:21:27 +00:00
|
|
|
environment: dict = None, labels: dict = None, source_container_id: str = None):
|
2019-11-15 15:47:40 +00:00
|
|
|
logger.info("Starting backup container")
|
2019-04-17 01:45:51 +00:00
|
|
|
config = Config()
|
|
|
|
client = docker.DockerClient(base_url=config.docker_base_url)
|
2019-04-17 01:28:07 +00:00
|
|
|
|
|
|
|
container = client.containers.run(
|
2019-04-17 02:38:15 +00:00
|
|
|
image,
|
|
|
|
command,
|
2019-04-18 01:52:28 +00:00
|
|
|
labels=labels,
|
2019-12-03 03:21:27 +00:00
|
|
|
# auto_remove=True, # We remove the container further down
|
2019-04-17 01:28:07 +00:00
|
|
|
detach=True,
|
2019-11-12 11:39:49 +00:00
|
|
|
environment=environment,
|
2019-04-17 18:20:52 +00:00
|
|
|
volumes=volumes,
|
2019-12-03 03:21:27 +00:00
|
|
|
network_mode=f'container:{source_container_id}', # Reuse original container's network stack.
|
2019-04-17 01:28:07 +00:00
|
|
|
working_dir=os.getcwd(),
|
2019-04-18 05:22:59 +00:00
|
|
|
tty=True,
|
2019-04-17 01:28:07 +00:00
|
|
|
)
|
|
|
|
|
2019-11-15 15:47:40 +00:00
|
|
|
logger.info("Backup process container: %s", container.name)
|
2019-04-18 05:22:59 +00:00
|
|
|
log_generator = container.logs(stdout=True, stderr=True, stream=True, follow=True)
|
2019-11-15 15:47:40 +00:00
|
|
|
|
|
|
|
def readlines(stream):
|
|
|
|
"""Read stream line by line"""
|
|
|
|
while True:
|
|
|
|
line = ""
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
line += next(stream).decode()
|
|
|
|
if line.endswith('\n'):
|
|
|
|
break
|
|
|
|
except StopIteration:
|
|
|
|
break
|
|
|
|
if line:
|
2019-11-26 12:04:30 +00:00
|
|
|
yield line.rstrip()
|
2019-11-15 15:47:40 +00:00
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
2019-04-18 05:22:59 +00:00
|
|
|
with open('backup.log', 'w') as fd:
|
2019-11-15 15:47:40 +00:00
|
|
|
for line in readlines(log_generator):
|
2019-04-18 05:22:59 +00:00
|
|
|
fd.write(line)
|
2019-11-26 18:46:59 +00:00
|
|
|
fd.write('\n')
|
2019-11-15 15:47:40 +00:00
|
|
|
logger.info(line)
|
|
|
|
|
2019-04-18 05:22:59 +00:00
|
|
|
|
|
|
|
container.reload()
|
2019-12-03 06:36:48 +00:00
|
|
|
logger.debug("Container ExitCode %s", container.attrs['State']['ExitCode'])
|
2019-04-18 05:22:59 +00:00
|
|
|
container.remove()
|
2019-12-03 06:36:48 +00:00
|
|
|
|
|
|
|
return container.attrs['State']['ExitCode']
|