diff dns.py @ 318:2136320eb94d

dhcp_graph watcher
author drewp@bigasterisk.com
date Wed, 16 Oct 2024 20:47:04 -0700
parents 828d3f4da54b
children 2e6dbebb2cb3
line wrap: on
line diff
--- a/dns.py	Mon Sep 23 01:09:32 2024 -0700
+++ b/dns.py	Wed Oct 16 20:47:04 2024 -0700
@@ -1,10 +1,9 @@
+import subprocess
 from io import StringIO
-import subprocess
-from typing import cast
 
 import pyinfra
 from pyinfra import host
-from pyinfra.operations import files, systemd, server
+from pyinfra.operations import files, server, systemd
 
 
 def dnsmasq_instance(net_name,
@@ -66,6 +65,44 @@
     dnsmasq_instance('10.5', house_iface='unused', dhcp_range='unused',
                      listen_address='unused')  # only works after wireguard is up
 # move out of this file- it's not dns
+
+def watchLeasesFile():
+    """summary:
+    1. dnsmasq_10.2 leases an address and writes to /opt/dnsmasq/10.2/leases
+    2. dhcp_graph_watch.path notices that change
+    3. dhcp_graph_update.service posts /opt/dnsmasq/10.2/leases to dhcp_graph (k8s deploy)
+    4. dhcp_graph serves the data as rdf
+    """
+    dhcp_graph_url = "http://10.5.0.7:8005"
+    leases = "/opt/dnsmasq/10.2/leases"
+    files.put(dest='/etc/systemd/system/dhcp_graph_watch.path', src=StringIO(f'''
+[Unit]
+Description=dhcp leases file changed- run dhcp_graph_update
+After=localfs.target
+
+[Path]
+PathModified={leases}
+Unit=dhcp_graph_update.service
+
+[Install]
+WantedBy=multi-user.target
+'''))
+
+    files.put(dest='/etc/systemd/system/dhcp_graph_update.service', src=StringIO(f'''
+[Unit]
+Description=Send new dhcp leases content to dhcp_graph
+After=network.target
+
+[Service]
+Type=oneshot
+ExecStart=/usr/bin/curl -s {dhcp_graph_url}/leases -H "content-type: text/plain" --data-binary "@{leases}"
+
+[Install]
+WantedBy=multi-user.target
+'''))
+    systemd.service(service='dhcp_graph_watch.path', enabled=True, restarted=True, daemon_reload=True)
+    systemd.service(service='dhcp_graph_update.service', enabled=True, restarted=True, daemon_reload=True)
+
 if host.name == 'pipe':
     rpi_net_boot()
     files.directory(path='/opt/dnsmasq')
@@ -75,10 +112,12 @@
                      listen_address='10.2.0.3',
                      dhcp_hosts_filename='templates/dnsmasq/dhcp_hosts.j2')
     out = '/opt/dnsmasq/10.2'
-    # This mtail is for dhcp command counts and errors. Another monitor in lanscape/ reads the leases file.
+    # This mtail is for dhcp command counts and errors.
     files.put(src='files/dnsmasq/metrics.mtail', dest=f'{out}/metrics.mtail')
     files.put(src='files/dnsmasq/run_mtail.sh', dest=f'{out}/run_mtail.sh')
 
+    watchLeasesFile()
+
     files.put(src='files/dnsmasq/dnsmasq-mtail.service', dest='/etc/systemd/system/dnsmasq-mtail.service')
     systemd.service(service='dnsmasq-mtail', enabled=True, restarted=True, daemon_reload=True)