|
| 1 | +import json |
| 2 | +import os |
| 3 | +import re |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import time |
| 7 | + |
| 8 | + |
| 9 | +def connect_container_stdout(): |
| 10 | + # Piraeus shares the pod PID namespace, so /proc/1 belongs to the sandbox. |
| 11 | + with open("/proc/self/cgroup") as stream: |
| 12 | + cgroup = stream.read() |
| 13 | + candidates = [] |
| 14 | + for pid in os.listdir("/proc"): |
| 15 | + if not pid.isdigit(): |
| 16 | + continue |
| 17 | + try: |
| 18 | + with open("/proc/" + pid + "/cgroup") as stream: |
| 19 | + same_container = stream.read() == cgroup |
| 20 | + with open("/proc/" + pid + "/comm") as stream: |
| 21 | + is_java = stream.read().strip() == "java" |
| 22 | + if same_container and is_java: |
| 23 | + candidates.append(pid) |
| 24 | + except OSError: |
| 25 | + continue |
| 26 | + if len(candidates) != 1: |
| 27 | + raise RuntimeError("unique-satellite-java-required") |
| 28 | + fd = os.open("/proc/" + candidates[0] + "/fd/1", os.O_WRONLY | os.O_APPEND) |
| 29 | + try: |
| 30 | + os.dup2(fd, 1) |
| 31 | + os.dup2(fd, 2) |
| 32 | + finally: |
| 33 | + os.close(fd) |
| 34 | + |
| 35 | + |
| 36 | +def log(event, **fields): |
| 37 | + print(json.dumps(dict(event=event, **fields), sort_keys=True), flush=True) |
| 38 | + |
| 39 | + |
| 40 | +def parse_status(text): |
| 41 | + data = json.loads(text) |
| 42 | + if type(data) is not list: |
| 43 | + raise ValueError("status-list-required") |
| 44 | + result = {} |
| 45 | + for resource in data: |
| 46 | + if type(resource) is not dict: |
| 47 | + raise ValueError("resource-object-required") |
| 48 | + name = resource.get("name") |
| 49 | + if type(name) is not str or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,254}", name): |
| 50 | + raise ValueError("invalid-resource-name") |
| 51 | + if name in result or resource.get("role") not in ("Primary", "Secondary"): |
| 52 | + raise ValueError("duplicate-name-or-unknown-role") |
| 53 | + devices = resource.get("devices") |
| 54 | + if type(devices) is not list or not devices: |
| 55 | + raise ValueError("devices-required") |
| 56 | + volumes = set() |
| 57 | + for device in devices: |
| 58 | + if type(device) is not dict or type(device.get("open")) is not bool: |
| 59 | + raise ValueError("explicit-open-boolean-required") |
| 60 | + volume = device.get("volume") |
| 61 | + if type(volume) is not int or volume < 0 or volume in volumes: |
| 62 | + raise ValueError("invalid-volume") |
| 63 | + volumes.add(volume) |
| 64 | + result[name] = resource |
| 65 | + return result |
| 66 | + |
| 67 | + |
| 68 | +def eligible(resource): |
| 69 | + # A pod restart must leave mounted volumes and their Primary role intact. |
| 70 | + return resource["role"] == "Secondary" and all(device["open"] is False for device in resource["devices"]) |
| 71 | + |
| 72 | + |
| 73 | +def read_status(name=None, timeout=4): |
| 74 | + args = ["/usr/sbin/drbdsetup", "status"] |
| 75 | + if name is not None: |
| 76 | + args.append(name) |
| 77 | + args.append("--json") |
| 78 | + result = subprocess.run(args, capture_output=True, text=True, timeout=timeout) |
| 79 | + if result.returncode != 0: |
| 80 | + raise RuntimeError("status-command-failed") |
| 81 | + return parse_status(result.stdout) |
| 82 | + |
| 83 | + |
| 84 | +def main(): |
| 85 | + if sys.argv[1:] not in ([], ["--execute"]): |
| 86 | + raise ValueError("unsupported-arguments") |
| 87 | + execute = sys.argv[1:] == ["--execute"] |
| 88 | + deadline = time.monotonic() + 60 |
| 89 | + initial = read_status() |
| 90 | + for name, resource in initial.items(): |
| 91 | + if not eligible(resource): |
| 92 | + log("skip-in-use", resource=name, role=resource["role"]) |
| 93 | + continue |
| 94 | + remaining = deadline - time.monotonic() |
| 95 | + if remaining < 1: |
| 96 | + raise RuntimeError("hook-deadline") |
| 97 | + current = read_status(name, timeout=min(4, remaining)) |
| 98 | + if set(current) != {name}: |
| 99 | + raise ValueError("resource-read-mismatch") |
| 100 | + if not eligible(current[name]): |
| 101 | + log("skip-state-changed", resource=name) |
| 102 | + continue |
| 103 | + if not execute: |
| 104 | + log("would-down", resource=name) |
| 105 | + continue |
| 106 | + remaining = deadline - time.monotonic() |
| 107 | + if remaining < 1: |
| 108 | + raise RuntimeError("hook-deadline") |
| 109 | + log("down-start", resource=name) |
| 110 | + result = subprocess.run( |
| 111 | + ["/usr/sbin/drbdsetup", "down", name], |
| 112 | + stdout=subprocess.DEVNULL, |
| 113 | + stderr=subprocess.DEVNULL, |
| 114 | + timeout=min(10, remaining), |
| 115 | + ) |
| 116 | + if result.returncode != 0: |
| 117 | + raise RuntimeError("down-command-failed") |
| 118 | + log("down-finished", resource=name) |
| 119 | + log("finished", execute=execute, resources=len(initial)) |
| 120 | + |
| 121 | + |
| 122 | +if __name__ == "__main__": |
| 123 | + try: |
| 124 | + connect_container_stdout() |
| 125 | + main() |
| 126 | + except Exception as error: |
| 127 | + log("abort-no-further-actions", error_type=type(error).__name__) |
| 128 | + sys.exit(1) |
0 commit comments