#!/usr/bin/python3 import sys import os from pathlib import Path from console_log.config import read_config CONFIG = "/etc/console-log.conf" TARGET = "multi-user.target" DEBUG_MODE = os.getenv("DEBUG") is not None # --- Logging Utility --- def log(msg): tag = "[log-display-generator] " if DEBUG_MODE: print(tag + msg) # --- String Escape --- def systemd_escape_path(path: str) -> str: """ Encode a filesystem path to a systemd unit-compatible string, mimicking `systemd-escape --path`. Rules: - Leading and trailing slashes are ignored. - '/' replaced with '-' - Alphanumeric, '_', and '-' stay as is. - Other chars escaped as \\xHH (hex) """ def escape_char(c): if c.isalnum() or c in ('_', '-'): return c return '\\x{:02x}'.format(ord(c)) # Strip leading/trailing slashes, split by '/' parts = path.strip('/').split('/') escaped_parts = [] for part in parts: escaped = ''.join(escape_char(c) for c in part) escaped_parts.append(escaped) return '-'.join(escaped_parts) # --- Unit Generation --- def write_logpager_unit(block, output_dir, target_name): tty = block["tty"] group = block.get("group", "adm") user = block.get("user", "Debian-console-log") maxfilesize = block.get("maxfilesize", "7000000") tty_path = f"/dev/tty{tty}" file = None for filename in block.get("file", []): log(f"check for {filename}") if os.path.isfile(filename): log(f"{filename} exists") file = filename break if file is None: return source_path = block.get("source_path", "") unit_name = f"console-log-{tty}-{systemd_escape_path(file)}.service" unit_content = f"""# generated by console-log.generator [Unit] Description=page {file} on tty{tty} After={target_name} SourcePath={source_path} [Service] Type=simple ExecStart=/usr/share/console-log/do_console_log --file {file} --maxfilesize {maxfilesize} StandardInput=tty StandardOutput=tty TTYPath={tty_path} Restart=always User={user} Group={group} MemoryMax={maxfilesize} TTYReset=yes TTYVHangup=yes TTYVTDisallocate=yes [Install] WantedBy={target_name} """ unit_path = Path(output_dir) / unit_name unit_path.write_text(unit_content) log(f"Generated unit {unit_name}: {unit_path}") return unit_name def write_chvt_unit(block, output_dir, target_name): log(f"write_chvt_unit: block: {block}") tty = block.get("tty", "") log(f"write_chvt_unit: tty: {tty}") unit_name = f"console-log-chvt-{tty}.service" log(f"write_chvt_unit: unit_name: {unit_name}") source_path = block.get("source_path", "") unit_content = f"""# generated by console-log.generator [Unit] Description=console-log - Switch to virtual console tty{tty} After={target_name} SourcePath={source_path} [Service] Type=oneshot ExecStart=/bin/chvt {tty} StandardOutput=journal StandardError=journal TTYPath=/dev/console [Install] WantedBy={target_name} """ unit_path = Path(output_dir) / unit_name unit_path.write_text(unit_content) log(f"Generated unit {unit_name}: {unit_path}") return unit_name def ensure_symlink(target_name, link_dir): """ Create a symlink in `link_dir` pointing to `../target_name`, if it doesn't already exist. Ensures the parent directory exists. """ os.makedirs(link_dir, exist_ok=True) log(f"makedirs {link_dir} ok") link_path = os.path.join(link_dir, target_name) symlink_target = f"../{target_name}" if not os.path.exists(link_path): log(f"symlink {symlink_target} to {link_path}") os.symlink(symlink_target, link_path) else: log(f"{link_path} already exists") # --- Entry Point --- def main(): if len(sys.argv) != 4: print( "Usage: generator ", file=sys.stderr ) sys.exit(1) output_dir = sys.argv[1] runtime_dir = sys.argv[2] sysconf_dir = sys.argv[3] log(f"Generator started. Output dir: {output_dir}") if not Path(CONFIG).exists(): log(f"Config file not found: {CONFIG}") return link_target_dir = output_dir + "/" + TARGET + ".wants" blocks = read_config(CONFIG) for block in blocks: log(f"processing {block}") filename = write_logpager_unit(block, output_dir, TARGET) if filename: ensure_symlink(filename, link_target_dir) if block.get("chvt"): filename = write_chvt_unit(block, output_dir, TARGET) if filename: ensure_symlink(filename, link_target_dir) log("Generator completed.") if __name__ == "__main__": main()