v7.3: graceful shutdown/restart with countdown, custom/scheduled notifications, update guard, file jail, security hardening, experimental tab removed

This commit is contained in:
Reditus committed 2026-09-21 14:51:37 +01:00
1 parent aee4028f5c
commit 54d9d5db25
31 files changed
+2764 -2363

No files matched your search

+8 -1
View File
@@ -802,6 +802,13 @@ class AdminService:
token = os.environ.get('DUNE_BROADCAST_TOKEN',
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
# Duration is interpolated into Erlang code: force an int in range.
try:
duration = max(5, min(300, int(duration)))
except (TypeError, ValueError):
duration = 30
# Escape the token for the Erlang double-quoted binary literal.
token_esc = str(token).replace('\\', '\\\\').replace('"', '\\"')
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
@@ -809,7 +816,7 @@ class AdminService:
f'Title = base64:decode(<<"{title_b64}">>), '
f'Body = base64:decode(<<"{message_b64}">>), '
f'Duration = {duration}, '
f'Token = <<"{token}">>, '
f'Token = <<"{token_esc}">>, '
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
+56 -22
View File
@@ -1,9 +1,11 @@
"""Backup service - backup creation, restore orchestration, backup management"""
import base64
import ipaddress
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
@@ -24,6 +26,16 @@ class BackupError(Exception):
pass
# Backup names are always created as backup-DD-MM-YYYY_HHMMSS. Anything else
# (e.g. '../../...') is rejected so names can never escape the backup dir
# or break out of remote shell commands.
BACKUP_NAME_RE = re.compile(r"^backup-\d{2}-\d{2}-\d{4}_\d{6}$")
def is_valid_backup_name(name):
return bool(name and BACKUP_NAME_RE.fullmatch(str(name)))
class BackupService:
BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
@@ -388,6 +400,9 @@ class BackupService:
return {}
def delete_backup(self, name):
if not is_valid_backup_name(name):
logger.warning(f'Backup: rejected invalid backup name: {name!r}')
return False
path = self._backup_path(f'{name}.tar.gz')
if os.path.exists(path):
os.remove(path)
@@ -397,6 +412,8 @@ class BackupService:
return True
def verify_backup(self, name, password=''):
if not is_valid_backup_name(name):
return {'success': False, 'error': 'Invalid backup name'}
path = self._backup_path(f'{name}.tar.gz')
if not os.path.exists(path):
return {'success': False, 'error': 'Backup not found'}
@@ -444,6 +461,8 @@ class BackupService:
# ── Restore Orchestration ─────────────────────────────────────────
def restore_preview(self, name):
if not is_valid_backup_name(name):
return {'success': False, 'error': 'Invalid backup name'}
path = self._backup_path(f'{name}.tar.gz')
if not os.path.exists(path):
return {'success': False, 'error': 'Backup not found'}
@@ -493,6 +512,8 @@ class BackupService:
return {'success': False, 'error': str(e)}
def start_restore(self, backup_name, options):
if not is_valid_backup_name(backup_name):
return {'success': False, 'error': 'Invalid backup name'}
ssh_user = self.settings.get('server', {}).get('user', 'dune')
ssh_key = self.settings.get('server', {}).get('ssh_key', '')
vm_ip = self.settings.get('server', {}).get('host', '')
@@ -589,7 +610,8 @@ class BackupService:
try:
with open(upload_path, 'rb') as f:
b64_data = base64.b64encode(f.read()).decode()
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > /tmp/restore-{backup_name}.tar.gz', timeout=300)
remote_archive = f'/tmp/restore-{backup_name}.tar.gz'
r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > {shlex.quote(remote_archive)}', timeout=300)
if r.returncode != 0:
raise BackupError(f'Upload failed: {r.stderr}')
complete_step('Uploading backup archive to new VM', True)
@@ -607,10 +629,11 @@ class BackupService:
# Step 2: Extract archive on VM
add_step('Extracting backup archive on VM')
try:
restore_dir = f'/tmp/restore-{backup_name}'
r = ssh_cmd(
f'mkdir -p /tmp/restore-{backup_name} && '
f'cd /tmp/restore-{backup_name} && '
f'tar xzf /tmp/restore-{backup_name}.tar.gz --strip-components=1',
f'mkdir -p {shlex.quote(restore_dir)} && '
f'cd {shlex.quote(restore_dir)} && '
f'tar xzf {shlex.quote(remote_archive)} --strip-components=1',
timeout=60)
if r.returncode != 0:
raise BackupError(f'Extract failed: {r.stderr}')
@@ -624,8 +647,9 @@ class BackupService:
try:
d = f'/tmp/restore-{backup_name}'
for fname in ['secrets.yaml', 'configmaps.yaml']:
manifest = f'{d}/k8s-manifests/{fname}'
r = ssh_cmd(
f'sudo kubectl apply -n {ns} -f {d}/k8s-manifests/{fname} 2>/dev/null || true',
f'sudo kubectl apply -n {shlex.quote(str(ns))} -f {shlex.quote(manifest)} 2>/dev/null || true',
timeout=30)
if r.returncode != 0:
logger.warning(f'Could not apply {fname}: {r.stderr}')
@@ -638,8 +662,9 @@ class BackupService:
add_step('Applying battlegroup CRD')
try:
d = f'/tmp/restore-{backup_name}'
crd = f'{d}/k8s-manifests/battlegroup-crd.yaml'
r = ssh_cmd(
f'sudo kubectl apply -f {d}/k8s-manifests/battlegroup-crd.yaml', timeout=60)
f'sudo kubectl apply -f {shlex.quote(crd)}', timeout=60)
if r.returncode != 0:
raise BackupError(r.stderr)
complete_step('Applying battlegroup CRD', True)
@@ -650,7 +675,7 @@ class BackupService:
try:
for i in range(30):
r = ssh_cmd(
f'sudo kubectl get pods -n {ns} --no-headers 2>/dev/null | '
f'sudo kubectl get pods -n {shlex.quote(str(ns))} --no-headers 2>/dev/null | '
f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15)
if r.returncode == 0 and r.stdout.strip():
count = int(r.stdout.strip())
@@ -667,7 +692,7 @@ class BackupService:
try:
for i in range(30):
r = ssh_cmd(
f'sudo kubectl get pods -n {ns} -l role=db --no-headers '
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db --no-headers '
f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1',
timeout=15)
if 'Running' in r.stdout:
@@ -684,7 +709,7 @@ class BackupService:
add_step('Importing game database')
try:
r = ssh_cmd(
f'cd /tmp/restore-{backup_name} && '
f'cd {shlex.quote(restore_dir)} && '
f'/home/dune/.dune/bin/battlegroup import',
timeout=600)
if r.returncode != 0:
@@ -708,9 +733,9 @@ class BackupService:
if dash_sql_content:
b64_sql = base64.b64encode(dash_sql_content).decode()
r = ssh_cmd(
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
f'echo {shlex.quote(b64_sql)} | base64 -d | '
f'sudo kubectl exec -n {ns} -i $dbpod -- psql -U postgres -d dune',
f'sudo kubectl exec -n {shlex.quote(str(ns))} -i $dbpod -- psql -U postgres -d dune',
timeout=120)
if r.returncode != 0:
logger.warning(f'Dashboard DB restore warning: {r.stderr}')
@@ -728,8 +753,8 @@ class BackupService:
"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA dashboard TO dune;"
"GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA dashboard TO dune;")
r = ssh_cmd(
f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && '
f'sudo kubectl exec -n {ns} $dbpod -- psql -U postgres -d dune '
f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && '
f'sudo kubectl exec -n {shlex.quote(str(ns))} $dbpod -- psql -U postgres -d dune '
f'-c {shlex.quote(sql)}', timeout=30)
if r.returncode != 0:
logger.warning(f'Dashboard schema ownership warning: {r.stderr}')
@@ -741,15 +766,20 @@ class BackupService:
if opts.get('restore_ping_fix', True) and opts.get('new_ip'):
add_step('Applying HOST_DATACENTER ping fix')
try:
try:
new_ip = str(ipaddress.ip_address(str(opts['new_ip']).strip()))
except ValueError:
raise BackupError(f'Invalid IP address: {opts.get("new_ip")!r}')
r = ssh_cmd('hostname', timeout=10)
hostname = r.stdout.strip()
new_ip = opts['new_ip']
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,253}', hostname):
raise BackupError(f'Unexpected hostname: {hostname!r}')
for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']:
full_name = f'{ns}-{deploy_suffix}'
ssh_cmd(
f'sudo kubectl set env deploy/{full_name} -n {ns} '
f'HOST_DATACENTER_ID={hostname} '
f'HOST_DATACENTER_IP_ADDRESS={new_ip}',
f'sudo kubectl set env deploy/{shlex.quote(full_name)} -n {shlex.quote(str(ns))} '
f'HOST_DATACENTER_ID={shlex.quote(hostname)} '
f'HOST_DATACENTER_IP_ADDRESS={shlex.quote(new_ip)}',
timeout=30)
complete_step('Applying HOST_DATACENTER ping fix', True)
except Exception as e:
@@ -762,21 +792,24 @@ class BackupService:
pw = self.settings.get('rabbitmq', {}).get('password', '')
for side in ['admin', 'game']:
pod_r = ssh_cmd(
f'sudo kubectl get pods -n {ns} -o name | grep mq-{side}-sts | head -1',
f'sudo kubectl get pods -n {shlex.quote(str(ns))} -o name | grep mq-{side}-sts | head -1',
timeout=15)
if pod_r.returncode != 0 or not pod_r.stdout.strip():
logger.warning(f'No mq-{side} pod found')
continue
pod = pod_r.stdout.strip()
if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', pod):
logger.warning(f'Skipping unexpected pod name: {pod!r}')
continue
for cmd in [
f'rabbitmqctl add_user dashboard_admin {pw}',
f'rabbitmqctl add_user dashboard_admin {shlex.quote(str(pw))}',
f'rabbitmqctl set_user_tags dashboard_admin administrator',
f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"',
f'rabbitmqctl eval '
f'\'application:set_env(rabbit, auth_backends, '
f'[rabbit_auth_backend_cache, rabbit_auth_backend_internal]).\'',
]:
ssh_cmd(f'sudo kubectl exec -n {ns} {pod} -- {cmd}', timeout=15)
ssh_cmd(f'sudo kubectl exec -n {shlex.quote(str(ns))} {shlex.quote(pod)} -- {cmd}', timeout=15)
complete_step('Re-creating RMQ dashboard_admin user on both instances', True)
except Exception as e:
complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e))
@@ -786,7 +819,8 @@ class BackupService:
add_step('Restoring dashboard settings.yaml locally')
try:
d = f'/tmp/restore-{backup_name}'
r = ssh_cmd(f'cat {d}/settings.yaml', timeout=15)
settings_file = f'{d}/settings.yaml'
r = ssh_cmd(f'cat {shlex.quote(settings_file)}', timeout=15)
if r.returncode == 0 and r.stdout.strip():
local_settings = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
@@ -802,7 +836,7 @@ class BackupService:
# Step 10: Cleanup
add_step('Cleaning up temporary files on VM')
try:
ssh_cmd(f'rm -rf /tmp/restore-{backup_name} /tmp/restore-{backup_name}.tar.gz',
ssh_cmd(f'rm -rf {shlex.quote(restore_dir)} {shlex.quote(remote_archive)}',
timeout=15)
complete_step('Cleaning up temporary files on VM', True)
except Exception as e:
+19 -7
View File
@@ -1,12 +1,16 @@
"""Director service - battlegroup director API and ConfigMap management."""
import ipaddress
import json
import logging
import shlex
import time
import urllib.error
import urllib.request
import configparser
import io
import base64
import re
from typing import Any, Dict, Optional
logger = logging.getLogger(__name__)
@@ -48,11 +52,19 @@ class DirectorService:
for line in (out or '').split('\n'):
line = line.strip()
if 'bgd-svc' in line:
svc_name = line.split('/')[-1]
svc_name = line.split('/')[-1].strip()
if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', svc_name or ''):
logger.warning("Director: unexpected svc name %r", svc_name)
continue
ip_out, ip_err, ip_rc = self.k8s.run(
f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10)
f'get svc {shlex.quote(svc_name)} -o jsonpath={{.spec.clusterIP}}', timeout=10)
if ip_rc == 0 and ip_out:
ip = ip_out.strip()
try:
ipaddress.ip_address(ip)
except ValueError:
logger.warning("Director: unexpected cluster IP %r", ip)
continue
logger.info("Director: resolved BGD svc cluster IP %s", ip)
return f'http://{ip}:{_BGD_CONTAINER_PORT}'
logger.warning("Director: no BGD service found in namespace %s", self.namespace)
@@ -108,7 +120,7 @@ class DirectorService:
svc_url = f"{self._bgd_svc_url}{path}"
logger.debug("Director SSH fallback: %s %s", method, svc_url)
if method == 'GET':
out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout)
out, err, rc = self.ssh.run(f'wget -qO- {shlex.quote(svc_url)}', timeout=timeout)
else:
body_bytes = None
if raw_data and isinstance(data, str):
@@ -117,14 +129,14 @@ class DirectorService:
body_bytes = json.dumps(data).encode()
body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else ''
tmp = f'/tmp/director_{int(time.time())}_{id(self)}'
self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5)
self.ssh.run(f'echo {shlex.quote(body_b64)} | base64 -d > {shlex.quote(tmp)}', timeout=5)
try:
out, err, rc = self.ssh.run(
f'wget -qO- --post-file={tmp} '
f'--header="Content-Type: application/json" {svc_url}',
f'wget -qO- --post-file={shlex.quote(tmp)} '
f'--header="Content-Type: application/json" {shlex.quote(svc_url)}',
timeout=timeout)
finally:
self.ssh.run(f'rm -f {tmp}', timeout=5)
self.ssh.run(f'rm -f {shlex.quote(tmp)}', timeout=5)
if rc == 0 and out:
return out
logger.warning("Director SSH fallback failed (rc=%d): %s",
+28 -1
View File
@@ -1,6 +1,7 @@
"""Kubernetes service - kubectl operations via SSH"""
import logging
import shlex
logger = logging.getLogger(__name__)
@@ -11,7 +12,7 @@ class K8sService:
self.namespace = namespace
def run(self, kubectl_command, timeout=30):
full_cmd = f'sudo kubectl {kubectl_command} -n {self.namespace}'
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}'
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
result = self.ssh.run(full_cmd, timeout=timeout)
out, err, rc = result
@@ -30,6 +31,32 @@ class K8sService:
logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}")
return pods
def get_running_game_pods(self):
"""List game server pods (sg-*-pod-*) currently in Running phase.
Used as the "server is online" signal, e.g. to block battlegroup
updates while players could be connected.
Returns:
List of running game pod names, [] when none running,
or None when pod status could not be determined.
"""
out, err, rc = self.run(
'get pods --no-headers -o custom-columns=NAME:.metadata.name,STATUS:.status.phase')
if rc != 0:
logger.warning(f"Could not get pod statuses: {err[:100] if err else 'no error'}")
return None
running = []
for line in (out or '').strip().split('\n'):
parts = line.strip().split()
if len(parts) < 2:
continue
name, phase = parts[0], parts[1]
if phase == 'Running' and '-sg-' in name and '-pod-' in name:
running.append(name)
logger.debug(f"Found {len(running)} running game pods in namespace {self.namespace}")
return running
def find_pod_by_pattern(self, pattern):
pods = self.get_pods()
for pod in pods:
+497
View File
@@ -0,0 +1,497 @@
"""Lifecycle service - graceful shutdown/start/restart with in-game countdown.
Notification path reuses the Experimental In-Game Broadcast
(AdminService.send_global_broadcast) - no duplicate RMQ code.
Countdown (seconds before action -> spoken label -> broadcast duration):
15m, 10m, 5m, 3m, 2m, 1m, 30s -> duration 10
10s -> duration 5 (so it does not overlap the final 1s notice)
1s -> final "now" notice, duration 10
Scheduled restarts use the same marks but say "Scheduled restart in X ...".
"""
import copy
import json
import logging
import os
import threading
import time
from datetime import datetime, timedelta
from app.services.schedule_util import (
SCHEDULE_MODES,
clean_days,
clean_times,
compute_next_run as util_compute_next_run,
parse_hhmm,
parse_when,
)
logger = logging.getLogger(__name__)
# (seconds_before_action, spoken label, broadcast duration seconds)
COUNTDOWN_MARKS = [
(900, '15 minutes', 10),
(600, '10 minutes', 10),
(300, '5 minutes', 10),
(180, '3 minutes', 10),
(120, '2 minutes', 10),
(60, '1 minute', 10),
(30, '30 seconds', 10),
(10, '10 seconds', 5),
]
FINAL_MARK_SECONDS = 1
FINAL_DURATION = 10
FULL_COUNTDOWN_SECONDS = 900
# A mark that became due within the last N seconds is sent immediately
# (covers thread startup delay, e.g. the first 15-minute notice at job start).
# Marks older than this were missed while the dashboard was down: skipped.
MARK_GRACE_SECONDS = 60
def _default_state_dir():
return os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
def default_schedule():
return {
'enabled': False,
'mode': 'daily',
'daily_times': ['05:00'],
'weekly_days': [6],
'weekly_times': ['05:00'],
'monthly_days': [1],
'monthly_time': '05:00',
'once_at': '',
'next_run': '',
'last_started_for': '',
}
class LifecycleService:
"""Owns one active countdown at a time + the restart schedule file."""
def __init__(self, ssh_service, admin_service, settings, state_dir=None):
self.ssh = ssh_service
self.admin = admin_service
self.settings = settings or {}
self.state_dir = state_dir or _default_state_dir()
os.makedirs(self.state_dir, exist_ok=True)
self._lock = threading.Lock()
self._active = None
self._cancel_event = threading.Event()
self._thread = None
# ── schedule persistence ──────────────────────────────────────────
def _schedule_path(self):
return os.path.join(self.state_dir, 'lifecycle-schedule.json')
def get_schedule(self):
cfg = default_schedule()
try:
with open(self._schedule_path()) as f:
stored = json.load(f) or {}
for key in cfg:
if key in stored:
cfg[key] = stored[key]
except FileNotFoundError:
pass
except Exception as e:
logger.warning(f'Lifecycle: could not read schedule: {e}')
return cfg
def _save_schedule(self, cfg):
with open(self._schedule_path(), 'w') as f:
json.dump(cfg, f, indent=2)
def update_schedule(self, data):
"""Validate + store schedule, recompute next_run. Returns stored cfg."""
cfg = self.get_schedule()
data = dict(data or {})
if 'enabled' in data:
cfg['enabled'] = bool(data['enabled'])
if 'mode' in data:
mode = str(data['mode']).strip().lower()
if mode not in SCHEDULE_MODES:
raise ValueError(f'Invalid mode: {mode!r}')
cfg['mode'] = mode
if 'daily_times' in data:
cfg['daily_times'] = self._clean_times(data['daily_times'])
if 'weekly_times' in data:
cfg['weekly_times'] = self._clean_times(data['weekly_times'])
if 'weekly_days' in data:
cfg['weekly_days'] = self._clean_days(data['weekly_days'], 0, 6)
if 'monthly_days' in data:
cfg['monthly_days'] = self._clean_days(data['monthly_days'], 1, 31)
if 'monthly_time' in data:
parse_hhmm(data['monthly_time'])
cfg['monthly_time'] = str(data['monthly_time']).strip()
if 'once_at' in data:
cfg['once_at'] = str(data['once_at'] or '').strip()
if cfg['once_at']:
try:
parse_when(cfg['once_at'])
except ValueError:
raise ValueError('One-shot date/time is not valid.')
# Mode-specific sanity so a bad form cannot arm a silent never-fire job.
if cfg['mode'] == 'daily' and not cfg['daily_times']:
raise ValueError('Daily mode needs at least one time (HH:MM).')
if cfg['mode'] == 'weekly' and (not cfg['weekly_days'] or not cfg['weekly_times']):
raise ValueError('Weekly mode needs days and at least one time.')
if cfg['mode'] == 'monthly' and (not cfg['monthly_days'] or not cfg['monthly_time']):
raise ValueError('Monthly mode needs days of month and a time.')
if cfg['mode'] == 'once' and not cfg['once_at']:
raise ValueError('One-shot mode needs a date/time.')
cfg['next_run'] = self.compute_next_run(cfg)
# Arming a new schedule must not replay an old occurrence marker.
if 'next_run' in cfg and cfg.get('last_started_for') == cfg['next_run']:
cfg['last_started_for'] = ''
self._save_schedule(cfg)
return cfg
@staticmethod
def _clean_times(values):
return clean_times(values)
@staticmethod
def _clean_days(values, low, high):
return clean_days(values, low, high)
def compute_next_run(self, cfg=None, now=None):
"""Next action time as ISO string, or '' when nothing upcoming."""
return util_compute_next_run(cfg or self.get_schedule(), now)
def set_enabled(self, enabled):
"""Flip the enabled flag only; all schedule settings are preserved."""
cfg = self.get_schedule()
cfg['enabled'] = bool(enabled)
cfg['next_run'] = self.compute_next_run(cfg)
if cfg.get('last_started_for') == cfg['next_run']:
cfg['last_started_for'] = ''
self._save_schedule(cfg)
return cfg
def clear_schedule(self):
"""Disarm the schedule but keep mode/times/days settings.
Clears the armed one-shot date, any pending next_run and the
last-fired marker; the configured mode, times and days are kept
so the schedule can be re-enabled without re-typing everything.
"""
cfg = self.get_schedule()
cfg['enabled'] = False
cfg['once_at'] = ''
cfg['next_run'] = ''
cfg['last_started_for'] = ''
self._save_schedule(cfg)
return cfg
# ── active countdown ──────────────────────────────────────────────
def status(self):
with self._lock:
if not self._active:
return {'active': False}
active = copy.deepcopy(self._active)
active['active'] = True
active['now'] = time.time()
return active
def start_shutdown(self, reason='manual', context=''):
return self._start('shutdown', time.time() + FULL_COUNTDOWN_SECONDS,
reason, context)
def start_restart(self, reason='manual', context=''):
return self._start('restart', time.time() + FULL_COUNTDOWN_SECONDS,
reason, context)
def start_restart_at(self, action_at, reason='scheduled', context=''):
return self._start('restart', float(action_at), reason, context)
def _start(self, kind, action_at, reason, context):
if kind not in ('shutdown', 'restart'):
return {'success': False, 'error': f'Unknown action: {kind}'}
with self._lock:
if self._active:
return {'success': False,
'error': f"A {self._active['kind']} countdown is already running"}
self._cancel_event.clear()
self._active = {
'kind': kind,
'reason': reason,
'context': context or '',
'started_at': time.time(),
'action_at': float(action_at),
'status': 'countdown',
'sent': [],
'log': [],
'error': '',
}
thread = threading.Thread(target=self._run_countdown, daemon=True)
self._thread = thread
thread.start()
action_iso = datetime.fromtimestamp(float(action_at)).isoformat()
logger.info(f'Lifecycle: {kind} countdown started ({reason}) -> {action_iso}')
return {'success': True, 'kind': kind,
'action_at': datetime.fromtimestamp(float(action_at)).isoformat()}
def cancel(self):
with self._lock:
if not self._active:
return {'success': False, 'error': 'No active countdown'}
if self._active.get('status') in ('executing', 'completed', 'failed'):
return {'success': False,
'error': 'Countdown already finished executing and cannot be cancelled'}
kind = self._active['kind']
reason = self._active.get('reason', 'manual')
context = self._active.get('context', '')
self._active['status'] = 'cancelling'
self._cancel_event.set()
thread = self._thread
if thread and thread.is_alive():
thread.join(timeout=30)
with self._lock:
self._active = None
self._thread = None
self._cancel_event.clear()
logger.info(f'Lifecycle: {kind} countdown cancelled')
# Tell players in-game so they know the shutdown/restart is off.
# The countdown thread itself stays silent on cancel: this is the
# single place the cancellation notice is sent (no duplicates).
notice_ok, notice_detail = self._cancellation_notice(kind, reason, context)
result = {'success': True, 'kind': kind,
'notice_sent': bool(notice_ok), 'notice': str(notice_detail)[:300]}
if not notice_ok:
logger.warning(f'Lifecycle: cancellation notice failed: {notice_detail}')
return result
def _cancellation_notice(self, kind, reason, context):
"""In-game broadcast announcing the countdown was cancelled."""
if kind == 'shutdown':
title = 'Server Shutdown'
message = 'Shutdown called off - the server is staying online.'
elif reason == 'scheduled':
context_suffix = f' ({context})' if context else ''
title = 'Scheduled Server Restart'
message = (f'Scheduled restart{context_suffix} called off - '
f'staying online.')
else:
title = 'Server Restart'
message = 'Restart called off - the server is staying online.'
try:
return self.admin.send_global_broadcast(title, message, 10)
except Exception as e:
logger.error(f'Lifecycle cancellation-notice error: {e}')
return False, str(e)
def _wait_until(self, target_ts):
"""Sleep until target_ts, waking early on cancel (1s slices)."""
while True:
if self._cancel_event.is_set():
return False
remaining = float(target_ts) - time.time()
if remaining <= 0:
return True
self._cancel_event.wait(timeout=min(1.0, remaining))
if self._cancel_event.is_set():
return False
def _run_countdown(self):
with self._lock:
active = self._active
if not active:
return
kind = active['kind']
reason = active.get('reason', 'manual')
context = active.get('context', '')
action_at = float(active['action_at'])
scheduled = (reason == 'scheduled')
for seconds_before, label, duration in COUNTDOWN_MARKS:
mark_at = action_at - seconds_before
now = time.time()
if now >= mark_at:
if now - mark_at <= MARK_GRACE_SECONDS:
# Due right now (e.g. the first notice at job start):
# send immediately instead of waiting.
pass
else:
# Missed while the dashboard was down: skip the stale mark.
self._record_sent(label, True, 'skipped (past due)')
continue
elif not self._wait_until(mark_at):
self._finish_cancelled()
return
title, message = self._message_for(kind, label, duration, scheduled, context,
final=False)
ok, detail = self._broadcast(title, message, duration)
self._record_sent(label, ok, detail)
if not ok:
# Keep counting down: a missed notice must not strand players
# without the final warning, but the miss is visible in status.
logger.warning(f'Lifecycle: broadcast failed at {label}: {detail}')
if not self._wait_until(action_at - FINAL_MARK_SECONDS):
self._finish_cancelled()
return
final_label = 'shutting down now' if kind == 'shutdown' else 'restarting now'
if scheduled and kind == 'restart':
final_label = 'scheduled restart starting now'
title, message = self._message_for(kind, final_label, FINAL_DURATION,
scheduled, context, final=True)
ok, detail = self._broadcast(title, message, FINAL_DURATION)
self._record_sent('now', ok, detail)
# Small buffer so the final notice is visible before the stop/restart.
time.sleep(2)
if self._cancel_event.is_set():
self._finish_cancelled()
return
self._set_status('executing')
ok, detail = self._execute(kind)
with self._lock:
if self._active:
self._active['status'] = 'completed' if ok else 'failed'
self._active['error'] = '' if ok else detail
self._active['completed_at'] = time.time()
self._active['log'].append(f'action: {detail}')
finished = copy.deepcopy(self._active)
# Leave the finished record briefly for the UI poll, then clear.
self._active = None
self._thread = None
logger.info(f"Lifecycle: {kind} finished ok={ok}: {detail}")
return finished
def _finish_cancelled(self):
with self._lock:
if self._active:
self._active['status'] = 'cancelled'
self._active = None
self._thread = None
self._cancel_event.clear()
logger.info('Lifecycle: countdown cancelled during wait')
def _set_status(self, status):
with self._lock:
if self._active:
self._active['status'] = status
def _record_sent(self, label, ok, detail):
with self._lock:
if self._active is not None:
self._active['sent'].append(
{'mark': label, 'ok': bool(ok), 'detail': str(detail)[:200],
'at': time.time()})
@staticmethod
def _message_for(kind, label, duration, scheduled, context, final=False):
context_suffix = f' ({context})' if scheduled and context else ''
if kind == 'shutdown':
if final:
return ('Server Shutdown', 'Shutting down now - see you soon!')
return ('Server Shutdown',
f'Heads up - the server is shutting down in {label}. '
f'Get somewhere safe!')
# restart
if final:
if scheduled:
return ('Scheduled Server Restart',
f'Scheduled restart starting now{context_suffix} - back shortly!')
return ('Server Restart', 'Restarting now - back shortly!')
if scheduled:
return ('Scheduled Server Restart',
f'Heads up - scheduled restart in {label}{context_suffix}. '
f'Get somewhere safe!')
return ('Server Restart',
f'Heads up - server restart in {label}. Get somewhere safe!')
def _broadcast(self, title, message, duration):
try:
return self.admin.send_global_broadcast(title, message, int(duration))
except Exception as e:
logger.error(f'Lifecycle broadcast error: {e}')
return False, str(e)
def _execute(self, kind):
script = (self.settings.get('kubernetes', {}) or {}).get(
'battlegroup_script', '/home/dune/.dune/bin/battlegroup')
action = 'stop' if kind == 'shutdown' else 'restart'
try:
out, err, rc = self.ssh.run(f'{script} {action}', timeout=300)
detail = (out or '') + (err or '')
detail = detail.strip() or f'{action} completed'
if rc != 0:
return False, f'{action} failed (rc={rc}): {detail[:500]}'
return True, detail[:1000]
except Exception as e:
return False, str(e)
# ── scheduler tick (called from factory background thread) ─────────
def describe_context(self, cfg=None):
cfg = cfg or self.get_schedule()
mode = cfg.get('mode', 'daily')
if mode == 'once':
return 'one-time'
if mode == 'daily':
return 'daily ' + ', '.join(cfg.get('daily_times') or [])
if mode == 'weekly':
day_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days = ', '.join(day_names[d] for d in (cfg.get('weekly_days') or []))
return f"weekly {days} {', '.join(cfg.get('weekly_times') or [])}"
if mode == 'monthly':
return (f"monthly day {', '.join(str(d) for d in (cfg.get('monthly_days') or []))} "
f"{cfg.get('monthly_time', '')}")
return mode
def check_and_fire(self, now=None):
"""Start the countdown when inside the 15-minute window before next_run."""
cfg = self.get_schedule()
if not cfg.get('enabled'):
return None
next_run = cfg.get('next_run') or self.compute_next_run(cfg, now)
if not next_run:
return None
# Keep next_run fresh if the mode changed underneath us.
if cfg.get('next_run') != next_run:
cfg['next_run'] = next_run
self._save_schedule(cfg)
try:
action_at = parse_when(next_run).timestamp()
except ValueError:
return None
now_ts = time.time() if now is None else now.timestamp()
if cfg.get('last_started_for') == next_run:
return None
with self._lock:
if self._active:
return None
if now_ts < action_at - FULL_COUNTDOWN_SECONDS:
return None
if now_ts > action_at + 120:
# Missed window (dashboard was down): roll forward, do not fire late.
cfg['last_started_for'] = next_run
cfg['next_run'] = self.compute_next_run(cfg, datetime.now())
self._save_schedule(cfg)
logger.warning(f'Lifecycle: missed scheduled restart for {next_run}, rolled forward')
return None
context = self.describe_context(cfg)
result = self.start_restart_at(action_at, reason='scheduled', context=context)
if result.get('success'):
cfg['last_started_for'] = next_run
# Advance to the occurrence *after* this one, not after now.
anchor = datetime.fromtimestamp(action_at) + timedelta(seconds=1)
cfg['next_run'] = self.compute_next_run(cfg, anchor)
self._save_schedule(cfg)
logger.info(f'Lifecycle: scheduled restart countdown started for {next_run}')
return result
return None
+136
View File
@@ -0,0 +1,136 @@
"""Shared schedule helpers: validation + next-run computation.
Used by the restart lifecycle scheduler and the custom-notification
scheduler. All times are server-local naive datetimes. ISO strings from
`<input type="datetime-local">` ("YYYY-MM-DDTHH:MM") and UTC ("...Z")
strings are both accepted.
"""
import logging
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
SCHEDULE_MODES = ('once', 'daily', 'weekly', 'monthly')
def parse_hhmm(value):
"""Parse 'HH:MM' -> (hour, minute), raising ValueError when invalid."""
parts = str(value or '').strip().split(':')
if len(parts) != 2:
raise ValueError(f'Invalid time: {value!r} (expected HH:MM)')
hour, minute = int(parts[0]), int(parts[1])
if not (0 <= hour <= 23 and 0 <= minute <= 59):
raise ValueError(f'Invalid time: {value!r}')
return hour, minute
def clean_times(values):
"""Validate a list of 'HH:MM' strings; returns sorted unique list."""
if isinstance(values, str):
values = [values]
cleaned = []
for value in values or []:
value = str(value).strip()
if not value:
continue
parse_hhmm(value)
if value not in cleaned:
cleaned.append(value)
return sorted(cleaned)
def clean_days(values, low, high):
"""Validate a list of integer days in [low, high]; sorted unique list."""
if isinstance(values, (int, str)):
values = [values]
cleaned = []
for value in values or []:
try:
day = int(value)
except (TypeError, ValueError):
raise ValueError(f'Invalid day: {value!r}')
if not (low <= day <= high):
raise ValueError(f'Day out of range: {value!r}')
if day not in cleaned:
cleaned.append(day)
return sorted(cleaned)
def parse_when(raw):
"""Parse an ISO datetime string -> naive server-local datetime."""
dt = datetime.fromisoformat(str(raw).strip())
if dt.tzinfo is not None:
dt = dt.astimezone().replace(tzinfo=None)
return dt
def next_once(cfg, now):
raw = str(cfg.get('once_at') or '').strip()
if not raw:
return ''
candidate = parse_when(raw)
return candidate.isoformat() if candidate > now else ''
def next_daily_weekly(now, days, times):
cleaned_times = []
for value in times or []:
try:
cleaned_times.append(parse_hhmm(value))
except ValueError:
continue
if not cleaned_times:
return ''
best = None
for offset in range(8):
base = datetime(now.year, now.month, now.day) + timedelta(days=offset)
if days is not None and base.weekday() not in days:
continue
for hour, minute in cleaned_times:
candidate = base.replace(hour=hour, minute=minute, second=0, microsecond=0)
if candidate <= now:
continue
if best is None or candidate < best:
best = candidate
return best.isoformat() if best else ''
def next_monthly(now, cfg, time_key='monthly_time', days_key='monthly_days'):
try:
hour, minute = parse_hhmm(cfg.get(time_key, '05:00'))
except ValueError:
return ''
month_days = set(cfg.get(days_key) or [])
if not month_days:
return ''
# Scan day-by-day (covers varying month lengths without dateutil).
base = datetime(now.year, now.month, now.day)
for offset in range(1, 370):
day = base + timedelta(days=offset)
if day.day not in month_days:
continue
candidate = day.replace(hour=hour, minute=minute, second=0, microsecond=0)
if candidate > now:
return candidate.isoformat()
return ''
def compute_next_run(cfg, now=None):
"""Next action time as ISO string, or '' when nothing upcoming."""
cfg = cfg or {}
now = now or datetime.now()
mode = cfg.get('mode', 'daily')
try:
if mode == 'once':
return next_once(cfg, now)
if mode == 'daily':
return next_daily_weekly(now, days=None, times=cfg.get('daily_times') or [])
if mode == 'weekly':
return next_daily_weekly(now, days=set(cfg.get('weekly_days') or []),
times=cfg.get('weekly_times') or [])
if mode == 'monthly':
return next_monthly(now, cfg)
except Exception as e:
logger.warning(f'Schedule: next-run calc failed: {e}')
return ''
+251
View File
@@ -0,0 +1,251 @@
"""Scheduled custom notifications - one-off/recurring in-game broadcasts.
Shares schedule validation + next-run computation with the restart
lifecycle scheduler (app/services/schedule_util.py). Delivery reuses the
confirmed In-Game Broadcast path (AdminService.send_global_broadcast).
"""
import json
import logging
import os
import threading
import uuid
from datetime import datetime, timedelta
from app.services.schedule_util import (
SCHEDULE_MODES,
clean_days,
clean_times,
compute_next_run,
parse_hhmm,
parse_when,
)
logger = logging.getLogger(__name__)
MIN_DURATION = 5
MAX_DURATION = 300
DEFAULT_DURATION = 30
# A missed occurrence older than this is rolled forward, never fired late.
MISSED_WINDOW_SECONDS = 3600
def _default_state_dir():
return os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups')
def default_entry():
return {
'id': uuid.uuid4().hex[:8],
'enabled': True,
'title': '',
'message': '',
'duration': DEFAULT_DURATION,
'mode': 'daily',
'daily_times': ['12:00'],
'weekly_days': [6],
'weekly_times': ['12:00'],
'monthly_days': [1],
'monthly_time': '12:00',
'once_at': '',
'next_run': '',
'last_fired_for': '',
}
class ScheduledBroadcastService:
"""Stores + fires scheduled custom notification entries."""
def __init__(self, admin_service, state_dir=None):
self.admin = admin_service
self.state_dir = state_dir or _default_state_dir()
os.makedirs(self.state_dir, exist_ok=True)
self._lock = threading.Lock()
# ── persistence ───────────────────────────────────────────────────
def _path(self):
return os.path.join(self.state_dir, 'broadcast-schedule.json')
def list_entries(self):
try:
with open(self._path()) as f:
stored = json.load(f) or {}
entries = stored.get('entries') or []
return [e for e in entries if isinstance(e, dict)]
except FileNotFoundError:
return []
except Exception as e:
logger.warning(f'ScheduledBroadcast: could not read schedule: {e}')
return []
def _save(self, entries):
with open(self._path(), 'w') as f:
json.dump({'entries': entries}, f, indent=2)
def _find(self, entries, entry_id):
for entry in entries:
if entry.get('id') == entry_id:
return entry
return None
# ── CRUD ──────────────────────────────────────────────────────────
def save_entry(self, data):
"""Create or update an entry; validates, recomputes next_run."""
data = dict(data or {})
with self._lock:
entries = self.list_entries()
entry_id = str(data.get('id') or '').strip()
if entry_id:
entry = self._find(entries, entry_id)
if entry is None:
raise ValueError(f'Unknown scheduled notification: {entry_id!r}')
else:
entry = default_entry()
entries.append(entry)
if 'enabled' in data:
entry['enabled'] = bool(data['enabled'])
for field in ('title', 'message'):
if field in data:
entry[field] = str(data[field] or '').strip()
if 'duration' in data:
try:
duration = int(data['duration'])
except (TypeError, ValueError):
raise ValueError('Duration must be a number of seconds.')
entry['duration'] = max(MIN_DURATION, min(MAX_DURATION, duration))
if 'mode' in data:
mode = str(data['mode']).strip().lower()
if mode not in SCHEDULE_MODES:
raise ValueError(f'Invalid mode: {mode!r}')
entry['mode'] = mode
if 'daily_times' in data:
entry['daily_times'] = clean_times(data['daily_times'])
if 'weekly_times' in data:
entry['weekly_times'] = clean_times(data['weekly_times'])
if 'weekly_days' in data:
entry['weekly_days'] = clean_days(data['weekly_days'], 0, 6)
if 'monthly_days' in data:
entry['monthly_days'] = clean_days(data['monthly_days'], 1, 31)
if 'monthly_time' in data:
parse_hhmm(data['monthly_time'])
entry['monthly_time'] = str(data['monthly_time']).strip()
if 'once_at' in data:
entry['once_at'] = str(data['once_at'] or '').strip()
if entry['once_at']:
try:
parse_when(entry['once_at'])
except ValueError:
raise ValueError('One-shot date/time is not valid.')
if not entry['title'] or not entry['message']:
raise ValueError('Title and message are required.')
mode = entry['mode']
if mode == 'daily' and not entry['daily_times']:
raise ValueError('Daily mode needs at least one time (HH:MM).')
if mode == 'weekly' and (not entry['weekly_days'] or not entry['weekly_times']):
raise ValueError('Weekly mode needs days and at least one time.')
if mode == 'monthly' and (not entry['monthly_days'] or not entry['monthly_time']):
raise ValueError('Monthly mode needs days of month and a time.')
if mode == 'once' and not entry['once_at']:
raise ValueError('One-shot mode needs a date/time.')
entry['next_run'] = compute_next_run(entry)
if entry.get('last_fired_for') == entry['next_run']:
entry['last_fired_for'] = ''
self._save(entries)
logger.info(f"ScheduledBroadcast: saved entry {entry['id']} "
f"enabled={entry['enabled']} next={entry['next_run']}")
return dict(entry)
def delete_entry(self, entry_id):
with self._lock:
entries = self.list_entries()
kept = [e for e in entries if e.get('id') != entry_id]
if len(kept) == len(entries):
return False
self._save(kept)
logger.info(f'ScheduledBroadcast: deleted entry {entry_id}')
return True
def set_enabled(self, entry_id, enabled):
"""Flip enabled only; message + schedule settings are preserved."""
with self._lock:
entries = self.list_entries()
entry = self._find(entries, entry_id)
if entry is None:
raise ValueError(f'Unknown scheduled notification: {entry_id!r}')
entry['enabled'] = bool(enabled)
entry['next_run'] = compute_next_run(entry)
if entry.get('last_fired_for') == entry['next_run']:
entry['last_fired_for'] = ''
self._save(entries)
return dict(entry)
# ── scheduler tick (called from factory background thread) ─────────
def check_and_fire(self, now=None):
"""Send every due entry once. Returns list of fired entry summaries."""
now_dt = now or datetime.now()
now_ts = now_dt.timestamp()
fired = []
with self._lock:
entries = self.list_entries()
changed = False
for entry in entries:
if not entry.get('enabled'):
continue
next_run = entry.get('next_run') or compute_next_run(entry, now_dt)
if not next_run:
continue
if entry.get('next_run') != next_run:
entry['next_run'] = next_run
changed = True
if entry.get('last_fired_for') == next_run:
continue
try:
action_ts = parse_when(next_run).timestamp()
except ValueError:
continue
if now_ts < action_ts:
continue
if now_ts > action_ts + MISSED_WINDOW_SECONDS:
# Dashboard was down: roll forward, never fire late.
entry['last_fired_for'] = next_run
if entry['mode'] == 'once':
entry['enabled'] = False
entry['next_run'] = ''
else:
entry['next_run'] = compute_next_run(entry, now_dt)
changed = True
logger.warning(
f"ScheduledBroadcast: missed {entry['id']} for {next_run}, rolled forward")
continue
ok, detail = self._send(entry)
entry['last_fired_for'] = next_run
if entry['mode'] == 'once':
# One-shot fires exactly once, settings are kept for reuse.
entry['enabled'] = False
entry['next_run'] = ''
else:
anchor = datetime.fromtimestamp(action_ts) + timedelta(seconds=1)
entry['next_run'] = compute_next_run(entry, anchor)
changed = True
fired.append({'id': entry['id'], 'success': bool(ok),
'detail': str(detail)[:300]})
logger.info(f"ScheduledBroadcast: fired {entry['id']} "
f"for {next_run} ok={ok}")
if changed:
self._save(entries)
return fired
def _send(self, entry):
try:
return self.admin.send_global_broadcast(
entry['title'], entry['message'], int(entry.get('duration') or 30))
except Exception as e:
logger.error(f'ScheduledBroadcast send error: {e}')
return False, str(e)