main.py 2.19 KB
Newer Older
jacomme's avatar
jacomme committed
1
#!/usr/bin/env python3
2
import os
moamoak's avatar
moamoak committed
3
from configparser import ConfigParser
4
import logging
moamoak's avatar
moamoak committed
5
import socket
moamoak's avatar
moamoak committed
6
7
8

from re2oapi import Re2oAPIClient

9
10
11
12
13
14
15
16
17
18
19
20
LOG_LEVEL = logging.INFO

logger = logging.getLogger()
logger.setLevel(LOG_LEVEL)
formatter = logging.Formatter('%(levelname)s :: %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
stream_handler.setLevel(LOG_LEVEL)
logger.addHandler(stream_handler)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

moamoak's avatar
moamoak committed
21
config = ConfigParser()
22
config.read(os.path.join(BASE_DIR, 'config.ini'))
moamoak's avatar
moamoak committed
23

moamoak's avatar
moamoak committed
24
25
26
27
28
api_hostname = config.get('Re2o', 'hostname')
api_password = config.get('Re2o', 'password')
api_username = config.get('Re2o', 'username')

def regen_dhcp(api_client):
moamoak's avatar
moamoak committed
29
30
    host_mac_ip = {}

jacomme's avatar
jacomme committed
31
    for hmi in api_client.list("dhcp/hostmacip/"):
nanoy's avatar
nanoy committed
32
33
34
35
36
37
        if 'ipv4' in hmi:
            if hmi['extension'] not in host_mac_ip.keys():
                host_mac_ip[hmi['extension']] = []
            host_mac_ip[hmi['extension']].append((hmi['hostname'],
                                                  hmi['mac_address'],
                                                  hmi['ipv4']))
moamoak's avatar
moamoak committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51

    template = ("host {hostname}{extension} {{\n"
                "    hardware ethernet {mac_address};\n"
                "    fixed-address {ipv4};\n"
                "}}")

    for extension, hmi_list in host_mac_ip.items():
        dhcp_leases_content = '\n\n'.join(template.format(
                hostname=hostname,
                extension=extension,
                mac_address=mac_address,
                ipv4=ipv4
            ) for hostname, mac_address, ipv4 in hmi_list)

52
        filename = os.path.join(BASE_DIR, 'generated/dhcp{extension}.list'.format(extension=extension))
moamoak's avatar
moamoak committed
53
54
        with open(filename, 'w+') as f:
            f.write(dhcp_leases_content)
moamoak's avatar
moamoak committed
55

moamoak's avatar
moamoak committed
56
57
58
59
api_client = Re2oAPIClient(api_hostname, api_username, api_password)

client_hostname = socket.gethostname().split('.', 1)[0]

60
61
62
63
64
for service in api_client.list("services/regen", params=dict(hostname=client_hostname)):
    if service['service_name'] == 'dhcp' and service['need_regen']:
        logger.info("Regenerating service dhcp")
        regen_dhcp(api_client)
        api_client.patch(service['api_url'], data={'need_regen': False})