-
Notifications
You must be signed in to change notification settings - Fork 1
/
__main__.py
166 lines (131 loc) · 5.05 KB
/
__main__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import asyncio
import logging
import subprocess
from datetime import datetime, timedelta
import argparse
from pathlib import Path
import signal
import pcu
from config import load_config
LOG = logging.getLogger(__name__)
def setup_logger(logger_config: dict) -> None:
LOG.debug("Setting up logger...")
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(levelname)s: %(name)s: %(message)s")
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
filename = logger_config.get('filename', 'logfile.log')
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
def handle_termination(signum, frame):
LOG.info(f"terminated by user. Initiating graceful switchoff. Signal: {signum}, Frame: {frame}")
# stop rsync
# disengage
async def init(logger_config: dict):
setup_logger(logger_config)
await pcu.handshake()
signal.signal(signal.SIGINT, handle_termination)
signal.signal(signal.SIGTERM, handle_termination)
async def engage() -> None:
LOG.info("Connect Backup HDD")
LOG.debug("Docking...")
docking_trials = 0
while not await pcu.cmd.dock():
LOG.warning("couldn't dock, try another time.")
docking_trials += 1
if docking_trials == 4: # this is a workaround for issue #25
raise RuntimeError("couldn't dock with two trials")
LOG.debug("Switching HDD power on...")
await pcu.cmd.power.hdd.on()
await asyncio.sleep(10) # workaround for #26
LOG.debug("Mounting HDD...")
subprocess.call(["mount", "/dev/BACKUPHDD"])
async def handle_output(pipe):
while True:
line = await pipe.readline()
if not line:
break
LOG.debug(f"Live Output: {line.decode().rstrip()}")
def resolve_ip(host_name_in_ssh_config: str) -> str:
command = "ssh -G " + host_name_in_ssh_config + " | awk '/^hostname / { print $2 }'"
nas_ip = subprocess.check_output(command, shell=True)
return nas_ip.decode().strip()
async def backup(config: dict):
source = config["rsync_source"]
nas_ip = resolve_ip(host_name_in_ssh_config="nas")
LOG.debug(f"obtained IP Address of NAS: {nas_ip}")
backup_command = [
"rsync",
"-aH",
"--stats",
"--delete",
f"{nas_ip}::{source}/*",
"/media/BackupHDD/backups/current"
]
LOG.debug(f"Backing up with command {' '.join(backup_command)}")
process = await asyncio.create_subprocess_exec(
*backup_command,
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
output_task = asyncio.create_task(handle_output(process.stdout))
LOG.info("Starting Backup...")
await process.wait()
LOG.info("Backup finished.")
await output_task
LOG.debug("Backup output task finished.")
stderr = await process.stderr.read()
if stderr:
LOG.error(f"Fehlerausgabe: {stderr.decode()}")
async def disengage() -> None:
LOG.info("Disconnecting Backup HDD")
LOG.debug("Unmounting HDD...")
subprocess.call(["umount", "/dev/BACKUPHDD"])
LOG.debug("Switching HDD power off...")
await pcu.cmd.power.hdd.off()
await asyncio.sleep(20)
LOG.debug("Undocking...")
await pcu.cmd.undock()
async def wait_before_shutdown(cfg):
try:
sleep_duration = cfg["process"]["seconds_between_backup_end_and_shutdown"]
except KeyError:
sleep_duration = 60
LOG.warning("couldn't get sleep duration from config file, default to 60")
LOG.info(f"waiting for {sleep_duration}s before shutdown")
await asyncio.sleep(sleep_duration)
async def set_wakeup_time() -> None:
LOG.info("Programming PCU. Setting current time and time for next wakeup")
await pcu.set.date.now(datetime.now())
LOG.debug(f"read current time from pcu: {await pcu.get.date.now()}")
await pcu.set.date.wakeup(datetime.now() + timedelta(hours=12))
LOG.debug(f"read wakeup time from pcu: {await pcu.get.date.wakeup()}")
await pcu.set.date.backup(datetime.now() + timedelta(hours=12))
LOG.debug(f"read backup time from pcu: {await pcu.get.date.backup()}")
async def shutdown():
LOG.info("Shutting down...")
await pcu.cmd.shutdown.init()
subprocess.call(["sudo", "/sbin/shutdown", "-h", "now"])
async def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--no-shutdown", default=False, required=False)
parser.add_argument("--config", default="config.yaml", type=str, required=False)
args = parser.parse_args()
cfg = load_config(Path(args.config))
LOG.info(f"loading config file {args.config}")
await init(cfg["logger"])
await engage()
await backup(cfg["backup"])
await disengage()
await wait_before_shutdown(cfg)
await set_wakeup_time()
if not args.no_shutdown:
await shutdown()
if __name__ == "__main__":
asyncio.run(main())