Files
cti/installer/debian/check-nginx-ports
2026-10-14 23:05:02 +03:30

64 lines
2.5 KiB
Python

#!/usr/bin/python3
"""Report foreign listeners before restarting Nginx; never terminate them."""
import re
import subprocess
import sys
from pathlib import Path
def conflicts(config, listeners, control_group, read_cgroup):
ports = set()
for address in re.findall(r"^\s*listen\s+([^;\s]+)", config, re.MULTILINE):
if address.startswith("unix:"):
continue
port = address.rsplit(":", 1)[-1]
if port.isdigit():
ports.add(int(port))
foreign = []
for line in listeners.splitlines():
fields = line.split()
if len(fields) < 4:
continue
port = fields[3].rsplit(":", 1)[-1]
if not port.isdigit() or int(port) not in ports:
continue
pids = re.findall(r"pid=(\d+)", line)
owned = bool(pids) and bool(control_group)
for pid in pids:
try:
owned = owned and any(
entry.split(":", 2)[-1] == control_group
or entry.split(":", 2)[-1].startswith(control_group + "/")
for entry in read_cgroup(pid).splitlines())
except OSError:
owned = False
if not owned:
foreign.append(line)
return foreign
def main():
try:
config = subprocess.run(["/usr/sbin/nginx", "-T"], capture_output=True,
text=True, check=True, timeout=15).stdout
listeners = subprocess.run(["/usr/bin/ss", "-H", "-ltnp"], capture_output=True,
text=True, check=True, timeout=10).stdout
group = subprocess.run(["/usr/bin/systemctl", "show", "nginx.service",
"--property=ControlGroup", "--value"], capture_output=True,
text=True, check=True, timeout=10).stdout.strip()
foreign = conflicts(config, listeners, group,
lambda pid: Path(f"/proc/{pid}/cgroup").read_text())
if foreign:
print("Nginx cannot start: its configured TCP ports are occupied by other processes.", file=sys.stderr)
print("\n".join(foreign), file=sys.stderr)
print("Resolve these listeners or change the CTI web ports, then rerun the installer.", file=sys.stderr)
return 1
return 0
except (OSError, subprocess.SubprocessError) as error:
print(f"Cannot inspect Nginx port ownership: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())