-
Notifications
You must be signed in to change notification settings - Fork 0
/
dhcp.py
67 lines (53 loc) · 1.94 KB
/
dhcp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import subprocess
import db
import logging
import utils
import dhcpconfig
from config import dhcp_reload_interval_sec
from db import create_scoped_session, Switch, SwitchStatus
Session = create_scoped_session()
class DhcpServer:
def __init__(self):
self.shutdown_requested = False
def start(self):
logging.info("Starting DHCP config loop")
self.shutdown_requested = False
while not self.shutdown_requested:
switches = db.query_all_unfinished_switches()
dnsmasq_config = dhcpconfig.generate_config(switches)
with open("dnsmasq.conf", "w") as f:
f.write(dnsmasq_config)
dnsmasq_result = subprocess.run(
[
"sudo",
"timeout",
str(dhcp_reload_interval_sec),
"dnsmasq",
"--no-daemon",
"--conf-file=dnsmasq.conf",
],
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output = dnsmasq_result.stdout
lines = output.splitlines()
ack_lines = [l for l in lines if "DHCPACK" in l]
for line in ack_lines:
mac = line.split()[3].lower()
with Session() as session:
sw = session.query(Switch).filter(Switch.mac == mac).one()
if sw.status < SwitchStatus.DHCP_SUCCESS:
sw.status = SwitchStatus.DHCP_SUCCESS
session.commit()
if len(lines) > 0:
with open("dnsmasq.log", "a") as logfile:
logfile.write("\n".join(lines) + "\n\n")
logging.info("Stopped DHCP config loop")
def stop(self):
self.shutdown_requested = True
if __name__ == "__main__":
db.init_db()
utils.configure_logging()
server = DhcpServer()
server.start()