[trigger] Refactorisation (voir détails) - On passe aux tests
* Pour une plus grande modularité, event a été refactorisé, ce qui a impliqué de réécrire le fonctionnement des services. * Maintenant, y a plus qu'à tester.
This commit is contained in:
parent
3d98882755
commit
d29343392b
7 changed files with 283 additions and 130 deletions
|
@ -9,6 +9,7 @@
|
|||
|
||||
import lc_ldap.shortcuts
|
||||
from gestion.trigger.host import record
|
||||
from gestion.trigger.services.service import BasicService
|
||||
from cranslib.conffile import ConfFile
|
||||
import cranslib.clogger as clogger
|
||||
import gestion.config.dhcp as dhcp_config
|
||||
|
@ -16,11 +17,10 @@ import gestion.secrets_new as secrets_new
|
|||
import socket
|
||||
import gestion.affichage as affichage
|
||||
import os
|
||||
import sys
|
||||
import gestion.iptools as iptools
|
||||
|
||||
from gestion.trigger.pypureomapi import pack_ip, pack_mac, OMAPI_OP_UPDATE
|
||||
from gestion.trigger.pypureomapi import Omapi, OmapiMessage, OmapiError, OmapiErrorNotFound
|
||||
from gestion.trigger.pypureomapi import Omapi, OmapiMessage
|
||||
import struct
|
||||
|
||||
logger = clogger.CLogger("trigger.dhcp", "debug")
|
||||
|
@ -88,69 +88,107 @@ def lease_clean():
|
|||
os.rename(dhcp_config.dhcplease+'.new', dhcp_config.dhcplease)
|
||||
|
||||
@record
|
||||
def dhcp(body={}):
|
||||
"""Regenerates dhcp service taking body into account.
|
||||
class dhcp(BasicService):
|
||||
"""Class responsible of dhcp service.
|
||||
|
||||
"""
|
||||
if body and isinstance(body, dict):
|
||||
for (mac, ip, name) in body.get("add", []):
|
||||
add_dhcp_host(mac, ip, name)
|
||||
for (mac, ip) in body.get("delete", []):
|
||||
delete_dhcp_host(mac, ip)
|
||||
for (rmac, rip, mac, ip, name) in body.get("update", []):
|
||||
delete_dhcp_host(rmac, rip)
|
||||
add_dhcp_host(mac, ip, name)
|
||||
elif body == True:
|
||||
hosts = {}
|
||||
host_template = """
|
||||
host %(nom)s {
|
||||
hardware ethernet %(mac)s;
|
||||
fixed-address %(ip)s;
|
||||
option host-name "%(host)s";
|
||||
|
||||
# Class lookup table to define which changes call which function.
|
||||
changes_trigger = {
|
||||
lc_ldap.attributs.macAddress.ldap_name: (dhcp.send_mac_ip,),
|
||||
lc_ldap.attributs.ipHostNumber.ldap_name: (dhcp.send_mac_ip,),
|
||||
}
|
||||
"""
|
||||
affichage.prettyDoin("Chargement des machines", "...")
|
||||
machines = ldap_conn.allMachines()
|
||||
affichage.prettyDoin("Chargement des machines", "Ok")
|
||||
animation = affichage.Animation(texte="Génération de la configuration",
|
||||
nb_cycles=len(machines),
|
||||
couleur=True,
|
||||
kikoo=True)
|
||||
|
||||
for machine in machines:
|
||||
for net in dhcp_config.reseaux.keys():
|
||||
ip = str(machine['ipHostNumber'][0])
|
||||
mac = str(machine['macAddress'][0])
|
||||
nom = str(machine['host'][0])
|
||||
if '<automatique>' not in [ip, mac] and iptools.AddrInNet(ip, net):
|
||||
d = {'nom' : nom,
|
||||
'host' : nom.split(".", 1)[0],
|
||||
'mac' : mac,
|
||||
'ip' : ip,
|
||||
}
|
||||
try:
|
||||
hosts[net] += host_template % d
|
||||
except:
|
||||
hosts[net] = host_template % d
|
||||
animation.new_step()
|
||||
# Put a \n after the last iteration.
|
||||
animation.end()
|
||||
@classmethod
|
||||
def send_mac_ip(cls, body, diff):
|
||||
"""Computes mac_ip data to send from body and diff
|
||||
|
||||
step = "Enregistrement de la configuration dans les fichiers"
|
||||
affichage.prettyDoin(step, "...")
|
||||
for (net, fichier) in dhcp_config.reseaux.items():
|
||||
with ConfFile(fichier) as configFile:
|
||||
configFile.header("#")
|
||||
if hosts.has_key(net):
|
||||
configFile.write(hosts[net])
|
||||
affichage.prettyDoin(step, "Ok")
|
||||
"""
|
||||
macs = tuple([body[i].get(lc_ldap.attributs.macAddress.ldap_name, [''])[0] for i in xrange(1, 3)])
|
||||
ips = tuple([body[i].get(lc_ldap.attributs.ipHostNumber.ldap_name, [''])[0] for i in xrange(1, 3)])
|
||||
hostnames = tuple([body[i].get(lc_ldap.attributs.host.ldap_name, [''])[0] for i in xrange(1, 3)])
|
||||
|
||||
step = "Nettoyage des fichiers de leases"
|
||||
affichage.prettyDoin(step, "...")
|
||||
try:
|
||||
lease_clean()
|
||||
# Régénération du DHCP :
|
||||
if not macs[0]:
|
||||
# Création d'une nouvelle machine.
|
||||
dhcp = {'add': [(macs[1], ips[1], hostnames[1])]}
|
||||
elif not macs[1]:
|
||||
# Destruction d'une machine.
|
||||
dhcp = {'delete': [(macs[0], ips[0])]}
|
||||
else:
|
||||
# Mise à jour.
|
||||
dhcp = {'update': [(macs[0], ips[0], macs[1], ips[1], hostnames[1])]}
|
||||
return ("dhcp", dhcp)
|
||||
|
||||
@classmethod
|
||||
def regen(cls, body=None):
|
||||
"""Regenerates dhcp service taking body into account.
|
||||
|
||||
"""
|
||||
# http://satyajit.ranjeev.in/2012/01/12/python--dangerous-default-value-as-argument.html
|
||||
# dict are referenced.
|
||||
if body is None:
|
||||
body = {}
|
||||
|
||||
if body and isinstance(body, dict):
|
||||
for (mac, ip, name) in body.get("add", []):
|
||||
add_dhcp_host(mac, ip, name)
|
||||
for (mac, ip) in body.get("delete", []):
|
||||
delete_dhcp_host(mac, ip)
|
||||
for (rmac, rip, mac, ip, name) in body.get("update", []):
|
||||
delete_dhcp_host(rmac, rip)
|
||||
add_dhcp_host(mac, ip, name)
|
||||
elif body == True:
|
||||
hosts = {}
|
||||
host_template = """
|
||||
host %(nom)s {
|
||||
hardware ethernet %(mac)s;
|
||||
fixed-address %(ip)s;
|
||||
option host-name "%(host)s";
|
||||
}
|
||||
"""
|
||||
affichage.prettyDoin("Chargement des machines", "...")
|
||||
machines = ldap_conn.allMachines()
|
||||
affichage.prettyDoin("Chargement des machines", "Ok")
|
||||
animation = affichage.Animation(texte="Génération de la configuration",
|
||||
nb_cycles=len(machines),
|
||||
couleur=True,
|
||||
kikoo=True)
|
||||
|
||||
for machine in machines:
|
||||
for net in dhcp_config.reseaux.keys():
|
||||
ip = str(machine['ipHostNumber'][0])
|
||||
mac = str(machine['macAddress'][0])
|
||||
nom = str(machine['host'][0])
|
||||
if '<automatique>' not in [ip, mac] and iptools.AddrInNet(ip, net):
|
||||
d = {'nom' : nom,
|
||||
'host' : nom.split(".", 1)[0],
|
||||
'mac' : mac,
|
||||
'ip' : ip,
|
||||
}
|
||||
try:
|
||||
hosts[net] += host_template % d
|
||||
except:
|
||||
hosts[net] = host_template % d
|
||||
animation.new_step()
|
||||
# Put a \n after the last iteration.
|
||||
animation.end()
|
||||
|
||||
step = "Enregistrement de la configuration dans les fichiers"
|
||||
affichage.prettyDoin(step, "...")
|
||||
for (net, fichier) in dhcp_config.reseaux.items():
|
||||
with ConfFile(fichier) as configFile:
|
||||
configFile.header("#")
|
||||
if hosts.has_key(net):
|
||||
configFile.write(hosts[net])
|
||||
affichage.prettyDoin(step, "Ok")
|
||||
except:
|
||||
affichage.prettyDoin(step, "Erreur")
|
||||
print "During lease clean, an error occured."
|
||||
raise
|
||||
|
||||
step = "Nettoyage des fichiers de leases"
|
||||
affichage.prettyDoin(step, "...")
|
||||
try:
|
||||
lease_clean()
|
||||
affichage.prettyDoin(step, "Ok")
|
||||
except:
|
||||
affichage.prettyDoin(step, "Erreur")
|
||||
print "During lease clean, an error occured."
|
||||
raise
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue