From 0f4cd64eee698507d1b257f69339d89e25f77f9a Mon Sep 17 00:00:00 2001 From: chapeau Date: Tue, 4 Feb 2020 11:04:35 +0000 Subject: [PATCH 1/2] Generate DHCP files on ip_type and not on extensions --- main.py | 82 ++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 27 deletions(-) diff --git a/main.py b/main.py index e2b8bd7..eb00682 100755 --- a/main.py +++ b/main.py @@ -1,25 +1,17 @@ #!/usr/bin/env python3 -import os from configparser import ConfigParser -import logging import socket from re2oapi import Re2oAPIClient -LOG_LEVEL = logging.INFO +import sys +import os +import subprocess -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__)) +path =(os.path.dirname(os.path.abspath(__file__))) config = ConfigParser() -config.read(os.path.join(BASE_DIR, 'config.ini')) +config.read(path+'/config.ini') api_hostname = config.get('Re2o', 'hostname') api_password = config.get('Re2o', 'password') @@ -29,36 +21,72 @@ def regen_dhcp(api_client): host_mac_ip = {} for hmi in api_client.list("dhcp/hostmacip/"): - 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'])) + if hmi['ip_type'] not in host_mac_ip.keys(): + host_mac_ip[hmi['ip_type']] = [] + host_mac_ip[hmi['ip_type']].append((hmi['hostname'], + hmi['extension'], + hmi['mac_address'], + hmi['ipv4'])) template = ("host {hostname}{extension} {{\n" " hardware ethernet {mac_address};\n" " fixed-address {ipv4};\n" "}}") - for extension, hmi_list in host_mac_ip.items(): + for ip_type, 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) + ) for hostname, extension, mac_address, ipv4 in hmi_list) - filename = os.path.join(BASE_DIR, 'generated/dhcp{extension}.list'.format(extension=extension)) + filename = path+'/generated/dhcp.{ip_type}.list'.format(ip_type=ip_type) with open(filename, 'w+') as f: f.write(dhcp_leases_content) -api_client = Re2oAPIClient(api_hostname, api_username, api_password) +def reload_server(): + """Relance le serveur DHCP.""" + try: + subprocess.check_output( + ['/bin/systemctl', 'restart', 'isc-dhcp-server'], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as err: + print( + "Erreur lors du redémarrage de isc-dhcp-server.\n" + "Code de retour: %s, Sortie:\n%s", + err.returncode, err.output.decode()) + print(err) + + +def check_syntax(): + """Vérifie la configuration du serveur DHCP.""" + try: + subprocess.check_output( + ['/usr/sbin/dhcpd', '-t', '-cf', '/etc/dhcp/dhcpd.conf'], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as err: + print( + "Erreur lors de la vérification de la configuration DHCP.\n" + "Code de retour: %s, Sortie:\n%s", + err.returncode, err.output.decode()) + return False + return True + +api_client = Re2oAPIClient(api_hostname, api_username, api_password, use_tls=True) client_hostname = socket.gethostname().split('.', 1)[0] -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") +for arg in sys.argv: + if arg=="--force": regen_dhcp(api_client) - api_client.patch(service['api_url'], data={'need_regen': False}) + +for service in api_client.list("services/regen/"): + if service['hostname'] == client_hostname and \ + service['service_name'] == 'dhcp' and \ + service['need_regen']: + regen_dhcp(api_client) + if check_syntax(): + api_client.patch(service['api_url'], data={'need_regen': False}) + reload_server() + From 01694fc60445839e7d697a6c4ba70babf44a4120 Mon Sep 17 00:00:00 2001 From: chapeau Date: Tue, 4 Feb 2020 11:51:58 +0000 Subject: [PATCH 2/2] Retrocompatibility --- main.py | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/main.py b/main.py index eb00682..b7a75f1 100755 --- a/main.py +++ b/main.py @@ -18,22 +18,35 @@ api_password = config.get('Re2o', 'password') api_username = config.get('Re2o', 'username') def regen_dhcp(api_client): - host_mac_ip = {} + """Genere les fichiers de zone du DHCP, par extension et par plage d'ip""" + host_mac_ip_ext = {} + host_mac_ip_type = {} - for hmi in api_client.list("dhcp/hostmacip/"): - if hmi['ip_type'] not in host_mac_ip.keys(): - host_mac_ip[hmi['ip_type']] = [] - host_mac_ip[hmi['ip_type']].append((hmi['hostname'], - hmi['extension'], - hmi['mac_address'], - hmi['ipv4'])) + api_res = api_client.list("dhcp/hostmacip/") + + build_hmi(host_mac_ip_ext, api_res, 'extension') + build_hmi(host_mac_ip_type, api_res, 'ip_type') template = ("host {hostname}{extension} {{\n" " hardware ethernet {mac_address};\n" " fixed-address {ipv4};\n" "}}") - for ip_type, hmi_list in host_mac_ip.items(): + generate_file(template, host_mac_ip_ext, "dhcp") + generate_file(template, host_mac_ip_type, "dhcp.ip_type.") + +def build_hmi(host_mac_ip, api_res, key): + for hmi in api_res: + if hmi[key] not in host_mac_ip.keys(): + host_mac_ip[hmi[key]] = [] + host_mac_ip[hmi[key]].append((hmi['hostname'], + hmi['extension'], + hmi['mac_address'], + hmi['ipv4'])) + + +def generate_file(template, host_mac_ip, file_prefix): + for key, hmi_list in host_mac_ip.items(): dhcp_leases_content = '\n\n'.join(template.format( hostname=hostname, extension=extension, @@ -41,10 +54,13 @@ def regen_dhcp(api_client): ipv4=ipv4 ) for hostname, extension, mac_address, ipv4 in hmi_list) - filename = path+'/generated/dhcp.{ip_type}.list'.format(ip_type=ip_type) + filename = path+'/generated/{file_prefix}{key}.list'.format( + key=key, + file_prefix=file_prefix) with open(filename, 'w+') as f: f.write(dhcp_leases_content) + def reload_server(): """Relance le serveur DHCP.""" try: