Compare commits
2
Commits
c2740c9542
...
0bbc4ce440
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0bbc4ce440 | ||
|
|
3c1589bd0c |
No files matched your search
+84
-51
@@ -67,9 +67,12 @@ def lock_exclusive(fp):
|
|||||||
|
|
||||||
|
|
||||||
def resolve_repo_host_dir(host_name=None):
|
def resolve_repo_host_dir(host_name=None):
|
||||||
host = host_name or socket.gethostname().split('.')[0]
|
try:
|
||||||
candidate = Path(__file__).resolve().parent / 'hosts' / host
|
host = host_name or socket.gethostname().split('.')[0]
|
||||||
return candidate if candidate.is_dir() else None
|
candidate = Path(__file__).resolve().parent / 'hosts' / host
|
||||||
|
return candidate if candidate.is_dir() else None
|
||||||
|
except (OSError, PermissionError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def load_host_config(path=DEFAULT_HOST_CONFIG, host_name=None):
|
def load_host_config(path=DEFAULT_HOST_CONFIG, host_name=None):
|
||||||
@@ -95,12 +98,15 @@ def load_host_config(path=DEFAULT_HOST_CONFIG, host_name=None):
|
|||||||
if host_dir:
|
if host_dir:
|
||||||
candidates.append(host_dir / 'host.json')
|
candidates.append(host_dir / 'host.json')
|
||||||
for candidate in candidates:
|
for candidate in candidates:
|
||||||
if candidate.is_file():
|
try:
|
||||||
with candidate.open(encoding='utf-8') as fp:
|
if candidate.is_file():
|
||||||
data = json.load(fp)
|
with candidate.open(encoding='utf-8') as fp:
|
||||||
if isinstance(data, dict):
|
data = json.load(fp)
|
||||||
default.update(data)
|
if isinstance(data, dict):
|
||||||
break
|
default.update(data)
|
||||||
|
break
|
||||||
|
except (OSError, PermissionError):
|
||||||
|
continue
|
||||||
return default
|
return default
|
||||||
|
|
||||||
|
|
||||||
@@ -117,9 +123,12 @@ def load_targets_config(path=DEFAULT_TARGETS_CONFIG, host_name=None):
|
|||||||
candidates.append(host_dir / 'targets.json')
|
candidates.append(host_dir / 'targets.json')
|
||||||
candidates.append(Path(__file__).resolve().parent / 'targets.json')
|
candidates.append(Path(__file__).resolve().parent / 'targets.json')
|
||||||
for candidate in candidates:
|
for candidate in candidates:
|
||||||
if candidate.is_file():
|
try:
|
||||||
with candidate.open(encoding='utf-8') as fp:
|
if candidate.is_file():
|
||||||
return json.load(fp)
|
with candidate.open(encoding='utf-8') as fp:
|
||||||
|
return json.load(fp)
|
||||||
|
except (OSError, PermissionError):
|
||||||
|
continue
|
||||||
return {'schemaVersion': 1, 'hosts': {}, 'targets': {}}
|
return {'schemaVersion': 1, 'hosts': {}, 'targets': {}}
|
||||||
|
|
||||||
|
|
||||||
@@ -218,10 +227,16 @@ def notification_counts(config):
|
|||||||
return len(config['webhooks']), int(bool(kuma['overall_push_url'])), sum(bool(v) for v in kuma['job_push_urls'].values())
|
return len(config['webhooks']), int(bool(kuma['overall_push_url'])), sum(bool(v) for v in kuma['job_push_urls'].values())
|
||||||
|
|
||||||
|
|
||||||
def nas_mount_ready(mountpoint=None, source=None, fstype=None):
|
def nas_mount_ready(mountpoint=None, source=None, fstype=None, host_cfg=None):
|
||||||
|
if host_cfg:
|
||||||
|
mountpoint = mountpoint or host_cfg.get('nas_mount')
|
||||||
|
source = source or host_cfg.get('nas_source')
|
||||||
|
fstype = fstype or host_cfg.get('nas_fstype')
|
||||||
mountpoint = mountpoint or NAS_MOUNT
|
mountpoint = mountpoint or NAS_MOUNT
|
||||||
source = source or NAS_SOURCE
|
source = source or NAS_SOURCE
|
||||||
fstype = fstype or 'nfs4'
|
fstype = fstype or 'nfs4'
|
||||||
|
if not mountpoint or not source:
|
||||||
|
return True
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
['findmnt', '--mountpoint', mountpoint, '--types', fstype, '--source', source],
|
['findmnt', '--mountpoint', mountpoint, '--types', fstype, '--source', source],
|
||||||
@@ -232,31 +247,39 @@ def nas_mount_ready(mountpoint=None, source=None, fstype=None):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def legacy_schedules():
|
def legacy_schedules(host_cfg=None):
|
||||||
"""Stateful detection of active legacy schedules and conflicting running services."""
|
"""Stateful detection of active legacy schedules and conflicting running services configured in host.json."""
|
||||||
|
cfg = host_cfg or load_host_config()
|
||||||
|
cron_users = cfg.get('cron_users', ['root', 'lars'])
|
||||||
|
cron_pattern = cfg.get('conflict_cron_pattern', r'/home/lars/(?:db-[\w-]+\.sh|backupPaperlessData\.sh)')
|
||||||
|
conflict_services = cfg.get('conflict_services', ['raspiBackup.service'])
|
||||||
|
conflict_timers = cfg.get('conflict_timers', ['paperless-data-backup.timer', 'borgmatic.timer'])
|
||||||
|
|
||||||
found = []
|
found = []
|
||||||
for user in ('root', 'lars'):
|
if cron_pattern:
|
||||||
try:
|
for user in cron_users:
|
||||||
p = subprocess.run(['crontab', '-u', user, '-l'], capture_output=True, text=True, timeout=8)
|
try:
|
||||||
except (OSError, subprocess.TimeoutExpired):
|
p = subprocess.run(['crontab', '-u', user, '-l'], capture_output=True, text=True, timeout=8)
|
||||||
continue
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
for line in p.stdout.splitlines():
|
|
||||||
stripped = line.strip()
|
|
||||||
if stripped.startswith('#') or not stripped:
|
|
||||||
continue
|
continue
|
||||||
if re.search(r'/home/lars/(?:db-[\w-]+\.sh|backupPaperlessData\.sh)', stripped):
|
for line in p.stdout.splitlines():
|
||||||
found.append(f'{user} crontab: {stripped}')
|
stripped = line.strip()
|
||||||
# Stateful coordination with raspiBackup: only block if raspiBackup.service is currently active/running.
|
if stripped.startswith('#') or not stripped:
|
||||||
try:
|
continue
|
||||||
rb_active = subprocess.run(
|
if re.search(cron_pattern, stripped):
|
||||||
['systemctl', 'is-active', 'raspiBackup.service'],
|
found.append(f'{user} crontab: {stripped}')
|
||||||
capture_output=True, text=True, timeout=8,
|
# Stateful coordination with conflicting services (e.g. raspiBackup.service): only block if currently active/running.
|
||||||
).stdout.strip()
|
for service in conflict_services:
|
||||||
if rb_active in ('active', 'activating', 'reloading'):
|
try:
|
||||||
found.append(f'raspiBackup.service: active={rb_active}')
|
svc_active = subprocess.run(
|
||||||
except (OSError, subprocess.TimeoutExpired):
|
['systemctl', 'is-active', service],
|
||||||
pass
|
capture_output=True, text=True, timeout=8,
|
||||||
for timer in ('paperless-data-backup.timer', 'borgmatic.timer'):
|
).stdout.strip()
|
||||||
|
if svc_active in ('active', 'activating', 'reloading'):
|
||||||
|
found.append(f'{service}: active={svc_active}')
|
||||||
|
except (OSError, subprocess.TimeoutExpired):
|
||||||
|
pass
|
||||||
|
for timer in conflict_timers:
|
||||||
try:
|
try:
|
||||||
enabled = subprocess.run(['systemctl', 'is-enabled', timer], capture_output=True, text=True, timeout=8).stdout.strip()
|
enabled = subprocess.run(['systemctl', 'is-enabled', timer], capture_output=True, text=True, timeout=8).stdout.strip()
|
||||||
active = subprocess.run(['systemctl', 'is-active', timer], capture_output=True, text=True, timeout=8).stdout.strip()
|
active = subprocess.run(['systemctl', 'is-active', timer], capture_output=True, text=True, timeout=8).stdout.strip()
|
||||||
@@ -283,20 +306,23 @@ def script_issues(job):
|
|||||||
return issues
|
return issues
|
||||||
|
|
||||||
|
|
||||||
def check(jobs, max_parallel, notify):
|
def check(jobs, max_parallel, notify, host_cfg=None):
|
||||||
print(f'Backup-Orchestrator {VERSION}: INSPECTION ONLY (no backups, no schedule changes)')
|
cfg = host_cfg or load_host_config()
|
||||||
|
mountpoint = cfg.get('nas_mount', NAS_MOUNT)
|
||||||
|
source = cfg.get('nas_source', NAS_SOURCE)
|
||||||
|
print(f'Backup-Orchestrator {VERSION} (host={cfg.get("hostname", socket.gethostname())}): INSPECTION ONLY (no backups, no schedule changes)')
|
||||||
print(f'Parallel limit per phase: {max_parallel}')
|
print(f'Parallel limit per phase: {max_parallel}')
|
||||||
for job in jobs:
|
for job in jobs:
|
||||||
issues = script_issues(job)
|
issues = script_issues(job)
|
||||||
state = 'enabled' if job['enabled'] else 'disabled'
|
state = 'enabled' if job['enabled'] else 'disabled'
|
||||||
print(f"phase {job['phase']:>2} {job['id']:<24} {state:<8} {job['timeout_seconds']:>5}s {job['script']} [{', '.join(issues) if issues else 'OK'}]")
|
print(f"phase {job['phase']:>2} {job['id']:<24} {state:<8} {job['timeout_seconds']:>5}s {job['script']} [{', '.join(issues) if issues else 'OK'}]")
|
||||||
conflicts = legacy_schedules()
|
conflicts = legacy_schedules(cfg)
|
||||||
print('\nLegacy schedules:')
|
print('\nLegacy schedules:')
|
||||||
for line in conflicts:
|
for line in conflicts:
|
||||||
print(' ACTIVE: ' + line)
|
print(' ACTIVE: ' + line)
|
||||||
if not conflicts:
|
if not conflicts:
|
||||||
print(' None detected (best effort)')
|
print(' None detected (best effort)')
|
||||||
print(f'\nNAS mount {NAS_MOUNT}: {"OK" if nas_mount_ready() else "NOT AVAILABLE"} (expected {NAS_SOURCE})')
|
print(f'\nNAS mount {mountpoint}: {"OK" if nas_mount_ready(host_cfg=cfg) else "NOT AVAILABLE"} (expected {source})')
|
||||||
a, b, c = notification_counts(notify)
|
a, b, c = notification_counts(notify)
|
||||||
print(f'Notifications configured: webhooks={a}, Kuma overall={b}, Kuma jobs={c} (tokens hidden)')
|
print(f'Notifications configured: webhooks={a}, Kuma overall={b}, Kuma jobs={c} (tokens hidden)')
|
||||||
print('Same phase: parallel; next phase starts after all members complete.')
|
print('Same phase: parallel; next phase starts after all members complete.')
|
||||||
@@ -551,17 +577,20 @@ def execute_one(job, folder, hub):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def live_run(jobs, args):
|
def live_run(jobs, args, host_cfg=None):
|
||||||
if not jobs:
|
if not jobs:
|
||||||
print('Nothing enabled; no backups executed.')
|
print('Nothing enabled; no backups executed.')
|
||||||
return 0
|
return 0
|
||||||
if os.environ.get(CUTOVER_ENV) != 'YES':
|
if os.environ.get(CUTOVER_ENV) != 'YES':
|
||||||
print(f'REFUSED: Set {CUTOVER_ENV}=YES only after testing scripts and coordinating existing schedules.', file=sys.stderr)
|
print(f'REFUSED: Set {CUTOVER_ENV}=YES only after testing scripts and coordinating existing schedules.', file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
if not nas_mount_ready():
|
cfg = host_cfg or load_host_config(host_name=getattr(args, 'host', None))
|
||||||
print(f'REFUSED: {NAS_MOUNT} is not mounted from {NAS_SOURCE}', file=sys.stderr)
|
mountpoint = cfg.get('nas_mount', NAS_MOUNT)
|
||||||
|
source = cfg.get('nas_source', NAS_SOURCE)
|
||||||
|
if not nas_mount_ready(host_cfg=cfg):
|
||||||
|
print(f'REFUSED: {mountpoint} is not mounted from {source}', file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
conflicts = legacy_schedules()
|
conflicts = legacy_schedules() if host_cfg is None else legacy_schedules(cfg)
|
||||||
if conflicts:
|
if conflicts:
|
||||||
print('REFUSED: existing scheduled backups could overlap this run:', file=sys.stderr)
|
print('REFUSED: existing scheduled backups could overlap this run:', file=sys.stderr)
|
||||||
for issue in conflicts:
|
for issue in conflicts:
|
||||||
@@ -1071,9 +1100,10 @@ def check_compatibility(verification, target_name, targets_cfg, current_host=Non
|
|||||||
dump_migrations = extract_migrations_from_sql_dump(verification['dump_path'])
|
dump_migrations = extract_migrations_from_sql_dump(verification['dump_path'])
|
||||||
|
|
||||||
if code_migrations is None:
|
if code_migrations is None:
|
||||||
app_dir = Path(tcfg.get('app_dir', ''))
|
app_dir = Path(tcfg.get('app_dir', tcfg.get('compose_dir', '')))
|
||||||
mig_dir = app_dir / 'backend' / 'migrations'
|
mig_rel = tcfg.get('migrations_dir', 'backend/migrations')
|
||||||
if mig_dir.is_dir():
|
mig_dir = app_dir / mig_rel if app_dir and str(app_dir) != '.' else Path('')
|
||||||
|
if mig_dir and mig_dir.is_dir():
|
||||||
code_migrations = discover_code_migrations(mig_dir)
|
code_migrations = discover_code_migrations(mig_dir)
|
||||||
|
|
||||||
schema_relation = 'UNKNOWN'
|
schema_relation = 'UNKNOWN'
|
||||||
@@ -1324,13 +1354,15 @@ def execute_recovery_command(mode, args, targets_cfg):
|
|||||||
result_file = folder / 'adapter-result.json'
|
result_file = folder / 'adapter-result.json'
|
||||||
log_file = folder / 'recovery.log'
|
log_file = folder / 'recovery.log'
|
||||||
|
|
||||||
adapter_dir = Path(tcfg.get('adapter_dir', '/etc/backup-orchestrator/scripts/shinkan'))
|
app_id = tcfg.get('application', 'app')
|
||||||
|
adapter_dir = Path(tcfg.get('adapter_dir', f'/etc/backup-orchestrator/scripts/{app_id}'))
|
||||||
if not adapter_dir.is_dir():
|
if not adapter_dir.is_dir():
|
||||||
adapter_dir = Path(__file__).resolve().parent / 'scripts' / 'shinkan'
|
adapter_dir = Path(__file__).resolve().parent / 'scripts' / app_id
|
||||||
|
|
||||||
dump_path = plan_doc['recovery_point']['dump_path']
|
dump_path = plan_doc['recovery_point']['dump_path']
|
||||||
if mode == 'restore-test':
|
if mode == 'restore-test':
|
||||||
script = adapter_dir / 'shinkan-restore-test'
|
custom_script = tcfg.get('restore_test_script')
|
||||||
|
script = Path(custom_script) if custom_script and Path(custom_script).is_file() else (adapter_dir / f'{app_id}-restore-test')
|
||||||
extra = ['--dump', dump_path, '--result', str(result_file)]
|
extra = ['--dump', dump_path, '--result', str(result_file)]
|
||||||
if getattr(args, 'playwright', False):
|
if getattr(args, 'playwright', False):
|
||||||
extra.append('--playwright')
|
extra.append('--playwright')
|
||||||
@@ -1338,7 +1370,8 @@ def execute_recovery_command(mode, args, targets_cfg):
|
|||||||
extra.append('--keep')
|
extra.append('--keep')
|
||||||
cmd = _build_script_cmd(script, extra)
|
cmd = _build_script_cmd(script, extra)
|
||||||
else:
|
else:
|
||||||
script = adapter_dir / 'shinkan-restore'
|
custom_script = tcfg.get('restore_script')
|
||||||
|
script = Path(custom_script) if custom_script and Path(custom_script).is_file() else (adapter_dir / f'{app_id}-restore')
|
||||||
extra = [
|
extra = [
|
||||||
'--target', target_name, '--dump', dump_path,
|
'--target', target_name, '--dump', dump_path,
|
||||||
'--result', str(result_file), '--sessions', args.sessions,
|
'--result', str(result_file), '--sessions', args.sessions,
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ class OrchestratorTests(unittest.TestCase):
|
|||||||
self.root = Path(self.temp.name)
|
self.root = Path(self.temp.name)
|
||||||
self.patches = [patch.object(app, 'legacy_schedules', return_value=[]),
|
self.patches = [patch.object(app, 'legacy_schedules', return_value=[]),
|
||||||
patch.object(app, 'nas_mount_ready', return_value=True),
|
patch.object(app, 'nas_mount_ready', return_value=True),
|
||||||
|
patch.object(app, 'load_host_config', return_value={'hostname':'test-host', 'nas_mount':'/backup', 'nas_source':'192.168.2.63:/volume1/Backup_Paperless'}),
|
||||||
patch.dict(os.environ, {'BACKUP_ORCHESTRATOR_CUTOVER_APPROVED':'YES'})]
|
patch.dict(os.environ, {'BACKUP_ORCHESTRATOR_CUTOVER_APPROVED':'YES'})]
|
||||||
for p in self.patches:
|
for p in self.patches:
|
||||||
p.start()
|
p.start()
|
||||||
|
|||||||
Reference in new issue
Block a user