On utilise un champ ldap_name pour savoir quelle classe doit être utilisée pour instancier quel objet/attribut LDAP.

Et comme ça on fiche à la poubelle le dégueulasse globals() et on décorrelle les noms
des classes des noms LDAP.
This commit is contained in:
Vincent Le Gallic 2013-05-15 23:00:17 +02:00
parent 294f7ce949
commit c392a2a986
3 changed files with 391 additions and 170 deletions

View file

@ -69,162 +69,162 @@ def preattr(val):
# Presque identique à celle dans ldap_crans.py
def service_to_restart(conn, new=None, args=[], start=0):
"""
start indique la date (en secondes depuis epoch) à partir du
moment cette action sera effectuée.
"""
start indique la date (en secondes depuis epoch) à partir du
moment cette action sera effectuée.
Si new = None retourne la liste des services à redémarrer.
Si new = None retourne la liste des services à redémarrer.
Si new est fourni, mais ne commence pas par '-', on ajoute
le service à la liste avec les arguments args (args doit être
une liste).
Si new est fourni, mais ne commence pas par '-', on ajoute
le service à la liste avec les arguments args (args doit être
une liste).
Si new commence par '-', on supprime le service si son start
est dans le futur.
Si new commence par '-', on supprime le service si son start
est dans le futur.
Si new commence par '--', on supprime le service sans condition.
"""
if new: new = preattr(new)[1]
Si new commence par '--', on supprime le service sans condition.
"""
if new: new = preattr(new)[1]
# Quels services sont déjà à redémarrer ?
serv = {} # { service: [ arguments ] }
serv_dates = {} # { service: [ dates de restart ] }
services = []
for s in conn.search_s(services_dn, 1, 'objectClass=service'):
s = s[1]
serv[s['cn'][0]] = s.get('args', [])
serv_dates[s['cn'][0]] = s.get('start', [])
services.append(Service(s['cn'][0], s.get('args', []), s.get('start', [])))
# Quels services sont déjà à redémarrer ?
serv = {} # { service: [ arguments ] }
serv_dates = {} # { service: [ dates de restart ] }
services = []
for s in conn.search_s(services_dn, 1, 'objectClass=service'):
s = s[1]
serv[s['cn'][0]] = s.get('args', [])
serv_dates[s['cn'][0]] = s.get('start', [])
services.append(Service(s['cn'][0], s.get('args', []), s.get('start', [])))
# Retourne la liste des services à redémarrer
if not new: return services
# Retourne la liste des services à redémarrer
if not new: return services
# Effacement d'un service
if new[0] == '-':
if new[1] == '-':
# Double -- on enlève quelque soit la date
remove_dn = 'cn=%s,%s' % (new[2:], services_dn)
else:
# On enlève uniquement si la date est passée
remove_dn = 'cn=%s,%s' % (new[1:], services_dn)
if not serv.has_key(new[1:]):
# Existe pas => rien à faire
return
keep_date = []
for date in serv_dates[new[1:]]:
if time.time() < int(date):
keep_date.append(date)
if keep_date:
mods = [{'start': serv_dates[new[1:]]}, { 'start': keep_date }]
conn.modify_s(remove_dn, ldap.modlist.modifyModlist(*mods))
remove_dn = None
if remove_dn:
# Suppression
try: conn.delete_s(remove_dn)
except: pass
# Si n'existe pas => Erreur mais le résultat est là.
return
serv_dn = 'cn=%s,%s' % (new, services_dn)
# Conversion avant stockage dans la base
if isinstance(args, basestring):
args = [args]
args = map(lambda x:preattr(x)[1], args)
try:
start = [int(start)]
except TypeError:
pass
start = map(lambda x:preattr(x)[1], start)
if new in serv.keys():
modlist = []
new_args = []
# Nouveaux arguments ?
for arg in args:
if arg not in serv[new]:
new_args.append(arg)
if new_args:
modlist += ldap.modlist.modifyModlist({'args': serv[new]},
{'args': serv[new] + new_args})
new_date = []
# Nouvelle date ?
for date in start:
if date not in serv_dates[new]:
new_date.append(date)
if new_date:
modlist += ldap.modlist.modifyModlist({'start': serv_dates[new]},
{'start': serv_dates[new] + new_date})
if modlist:
try:
conn.modify_s(serv_dn, modlist)
except ldap.TYPE_OR_VALUE_EXISTS:
# Pas grave
pass
# else rien à faire
# Effacement d'un service
if new[0] == '-':
if new[1] == '-':
# Double -- on enlève quelque soit la date
remove_dn = 'cn=%s,%s' % (new[2:], services_dn)
else:
# Entrée non présente -> ajout
modlist = ldap.modlist.addModlist({ 'objectClass': 'service',
'cn': new,
'args': args,
'start': start })
# On enlève uniquement si la date est passée
remove_dn = 'cn=%s,%s' % (new[1:], services_dn)
if not serv.has_key(new[1:]):
# Existe pas => rien à faire
return
keep_date = []
for date in serv_dates[new[1:]]:
if time.time() < int(date):
keep_date.append(date)
if keep_date:
mods = [{'start': serv_dates[new[1:]]}, { 'start': keep_date }]
conn.modify_s(remove_dn, ldap.modlist.modifyModlist(*mods))
remove_dn = None
if remove_dn:
# Suppression
try: conn.delete_s(remove_dn)
except: pass
# Si n'existe pas => Erreur mais le résultat est là.
return
serv_dn = 'cn=%s,%s' % (new, services_dn)
# Conversion avant stockage dans la base
if isinstance(args, basestring):
args = [args]
args = map(lambda x:preattr(x)[1], args)
try:
start = [int(start)]
except TypeError:
pass
start = map(lambda x:preattr(x)[1], start)
if new in serv.keys():
modlist = []
new_args = []
# Nouveaux arguments ?
for arg in args:
if arg not in serv[new]:
new_args.append(arg)
if new_args:
modlist += ldap.modlist.modifyModlist({'args': serv[new]},
{'args': serv[new] + new_args})
new_date = []
# Nouvelle date ?
for date in start:
if date not in serv_dates[new]:
new_date.append(date)
if new_date:
modlist += ldap.modlist.modifyModlist({'start': serv_dates[new]},
{'start': serv_dates[new] + new_date})
if modlist:
try:
conn.add_s(serv_dn, modlist)
except ldap.ALREADY_EXISTS:
# Existe déja => rien à faire
conn.modify_s(serv_dn, modlist)
except ldap.TYPE_OR_VALUE_EXISTS:
# Pas grave
pass
# else rien à faire
else:
# Entrée non présente -> ajout
modlist = ldap.modlist.addModlist({ 'objectClass': 'service',
'cn': new,
'args': args,
'start': start })
try:
conn.add_s(serv_dn, modlist)
except ldap.ALREADY_EXISTS:
# Existe déja => rien à faire
pass
def services_to_restart(conn, old_attrs={}, new_attrs={}):
"""Détermine quels sont les services à reconfigurer"""
old_attrs_c = dict((attributs.CRANS_ATTRIBUTES[key], value) for key,value in old_attrs.items() if key in attributs.CRANS_ATTRIBUTES.keys() and value)
new_attrs_c = dict((attributs.CRANS_ATTRIBUTES[key], value) for key,value in new_attrs.items() if key in attributs.CRANS_ATTRIBUTES.keys() and value)
"""Détermine quels sont les services à reconfigurer"""
old_attrs_c = dict((attributs.AttributeFactory.get(key), value) for key,value in old_attrs.items() if attributs.AttributeFactory.get(key, fallback=None) != None and value)
new_attrs_c = dict((attributs.AttributeFactory.get(key), value) for key,value in new_attrs.items() if attributs.AttributeFactory.get(key, fallback=None) != None and value)
created_attr = [ attr for name in new_attrs_c.keys() if not name in old_attrs_c.keys() for attr in new_attrs_c[name]]
deleted_attr = [ attr for name in old_attrs_c.keys() if not name in new_attrs_c.keys() for attr in old_attrs_c[name]]
updated_attr = [ (old_attrs_c[name], new_attrs_c[name],
created_attr = [ attr for name in new_attrs_c.keys() if not name in old_attrs_c.keys() for attr in new_attrs_c[name]]
deleted_attr = [ attr for name in old_attrs_c.keys() if not name in new_attrs_c.keys() for attr in old_attrs_c[name]]
updated_attr = [ (old_attrs_c[name], new_attrs_c[name],
[ i for i in old_attrs_c[name] if i.value not in [ j.value for j in new_attrs_c[name]]],
[ i for i in new_attrs_c[name] if i.value not in [ j.value for j in old_attrs_c[name]]],
) for name in set(new_attrs_c.keys()).intersection(old_attrs_c.keys()) if old_attrs_c[name][-1].value != new_attrs_c[name][-1].value ]
updated_attr_new = [ i for j in updated_attr for i in j[3]]
updated_attr_old = [ i for j in updated_attr for i in j[2]]
) for name in set(new_attrs_c.keys()).intersection(old_attrs_c.keys()) if old_attrs_c[name][-1].value != new_attrs_c[name][-1].value ]
updated_attr_new = [ i for j in updated_attr for i in j[3]]
updated_attr_old = [ i for j in updated_attr for i in j[2]]
services_to_restart = {}
for attr in [ attr for l in [created_attr, deleted_attr, updated_attr_new ] for attr in l]:
for service in attrs_to_services.get(attr.__class__, []):
services_to_restart[service] = services_to_restart.get(service, []) + [attr]
services_to_restart = {}
for attr in [ attr for l in [created_attr, deleted_attr, updated_attr_new ] for attr in l]:
for service in attrs_to_services.get(attr.__class__, []):
services_to_restart[service] = services_to_restart.get(service, []) + [attr]
for service in services_to_restart.keys():
for attr in services_to_restart[service]:
start = 0
arg = set()
if service in services_to_args.keys():
arg = arg.union(services_to_args[service](attr))
if attr in updated_attr_new:
for old_attr in updated_attr_old:
if attr.__class__ == old_attr.__class__:
arg = arg.union(services_to_args[service](old_attr))
for service in services_to_restart.keys():
for attr in services_to_restart[service]:
start = 0
arg = set()
if service in services_to_args.keys():
arg = arg.union(services_to_args[service](attr))
if attr in updated_attr_new:
for old_attr in updated_attr_old:
if attr.__class__ == old_attr.__class__:
arg = arg.union(services_to_args[service](old_attr))
# Cas du dhcp
if attr.__class__ in services_to_attrs['dhcp']:
dhcp=dydhcp()
if old_attrs.get('ipHostNumber', []) and old_attrs.get('macAddress', []):
if new_attrs.get('ipHostNumber', []) and new_attrs.get('macAddress', []):
if str(old_attrs['ipHostNumber'][0]) != str(new_attrs['ipHostNumber'][0]) or str(old_attrs['macAddress'][0]) != str(new_attrs['macAddress'][0]):
dhcp.del_host(str(old_attrs['ipHostNumber'][0]), str(old_attrs['macAddress'][0]))
dhcp.add_host(str(new_attrs['ipHostNumber'][0]), str(new_attrs['macAddress'][0]), str(new_attrs['host'][0]))
else:
# Cas du dhcp
if attr.__class__ in services_to_attrs['dhcp']:
dhcp=dydhcp()
if old_attrs.get('ipHostNumber', []) and old_attrs.get('macAddress', []):
if new_attrs.get('ipHostNumber', []) and new_attrs.get('macAddress', []):
if str(old_attrs['ipHostNumber'][0]) != str(new_attrs['ipHostNumber'][0]) or str(old_attrs['macAddress'][0]) != str(new_attrs['macAddress'][0]):
dhcp.del_host(str(old_attrs['ipHostNumber'][0]), str(old_attrs['macAddress'][0]))
elif new_attrs.get('ipHostNumber', []) and new_attrs.get('macAddress', []):
dhcp.add_host(str(new_attrs['ipHostNumber'][0]), str(new_attrs['macAddress'][0]), str(new_attrs['host'][0]))
dhcp.add_host(str(new_attrs['ipHostNumber'][0]), str(new_attrs['macAddress'][0]), str(new_attrs['host'][0]))
else:
dhcp.del_host(str(old_attrs['ipHostNumber'][0]), str(old_attrs['macAddress'][0]))
elif new_attrs.get('ipHostNumber', []) and new_attrs.get('macAddress', []):
dhcp.add_host(str(new_attrs['ipHostNumber'][0]), str(new_attrs['macAddress'][0]), str(new_attrs['host'][0]))
if service in services_to_time.keys():
start = services_to_time[service](attr)
#print "%s,%s,%s" % (service, arg, start)
service_to_restart(conn, service, list(arg), start)
if service in services_to_time.keys():
start = services_to_time[service](attr)
#print "%s,%s,%s" % (service, arg, start)
service_to_restart(conn, service, list(arg), start)