77 lines
1.8 KiB
Python
Executable File
77 lines
1.8 KiB
Python
Executable File
# announce.py
|
|
from zeroconf import ServiceInfo, Zeroconf
|
|
import socket
|
|
import re
|
|
import sys
|
|
import time
|
|
import signal
|
|
|
|
SERVICE_TYPE = "_influxdb2._tcp.local."
|
|
PORT = 8086
|
|
|
|
# ---------------- helpers ----------------
|
|
def get_lan_ip() -> str:
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
s.connect(("8.8.8.8", 80))
|
|
ip = s.getsockname()[0]
|
|
finally:
|
|
s.close()
|
|
return ip
|
|
|
|
def mdns_safe_hostname(name: str) -> str:
|
|
name = name.strip().lower()
|
|
name = re.sub(r"[^a-z0-9-]", "-", name)
|
|
name = re.sub(r"-{2,}", "-", name)
|
|
name = name.strip("-") or "host"
|
|
return name
|
|
|
|
# ---------------- main ----------------
|
|
stop = False
|
|
def handle_signal(sig, frame):
|
|
global stop
|
|
stop = True
|
|
|
|
def main():
|
|
raw_host = socket.gethostname()
|
|
host = mdns_safe_hostname(raw_host)
|
|
|
|
try:
|
|
ip = get_lan_ip()
|
|
except Exception as e:
|
|
sys.exit(1)
|
|
|
|
server_fqdn = f"{host}.local."
|
|
instance_name = f"influxdb2-{host}.{SERVICE_TYPE}"
|
|
|
|
txt = {"role": "primary", "path": "/", "ver": "1.0.0"}
|
|
|
|
info = ServiceInfo(
|
|
type_=SERVICE_TYPE,
|
|
name=instance_name,
|
|
addresses=[socket.inet_aton(ip)],
|
|
port=PORT,
|
|
properties=txt,
|
|
server=server_fqdn,
|
|
)
|
|
|
|
zc = Zeroconf()
|
|
signal.signal(signal.SIGINT, handle_signal)
|
|
signal.signal(signal.SIGTERM, handle_signal)
|
|
|
|
try:
|
|
# hier kannst du evtl. in ein Logfile schreiben, statt print
|
|
print(f"Announce {instance_name} @ {ip}:{PORT}")
|
|
zc.register_service(info)
|
|
while not stop:
|
|
time.sleep(1)
|
|
finally:
|
|
try:
|
|
zc.unregister_service(info)
|
|
finally:
|
|
zc.close()
|
|
print("Zeroconf: beendet.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|