# vim: set encoding=utf-8 et sw=4 sts=4 :
-from mako.template import Template
-from mako.runtime import Context
+# TODO COMMENT
from os import path
from os import unlink
+from new import instancemethod
-try:
- import cPickle as pickle
-except ImportError:
- import pickle
-try:
- from dispatcher import handler
-except ImportError:
- def handler(f): return f # NOP for testing
+from seqtools import Sequence
+from dispatcher import handler, HandlerError, Handler
+from services.util import Restorable, ConfigWriter, call
+from services.util import InitdHandler, TransactionalHandler, ParametersHandler
-__ALL__ = ('DnsHandler',)
-
-pickle_ext = '.pkl'
-
-pickle_vars = 'vars'
-pickle_zones = 'zones'
-
-config_filename = 'named.conf'
-zone_filename = 'zoneX.zone'
-zone_filename_ext = '.zone'
+__ALL__ = ('DnsHandler', 'Error',
+ 'ZoneError', 'ZoneNotFoundError', 'ZoneAlreadyExistsError',
+ 'HostError', 'HostAlreadyExistsError', 'HostNotFoundError',
+ 'MailExchangeError', 'MailExchangeAlreadyExistsError',
+ 'MailExchangeNotFoundError', 'NameServerError',
+ 'NameServerAlreadyExistsError', 'NameServerNotFoundError')
template_dir = path.join(path.dirname(__file__), 'templates')
-class Error(RuntimeError):
+class Error(HandlerError):
r"""
- Error(command) -> Error instance :: Base DhcpHandler exception class.
+ Error(command) -> Error instance :: Base DnsHandler exception class.
- All exceptions raised by the DhcpHandler inherits from this one, so you can
- easily catch any DhcpHandler exception.
+ All exceptions raised by the DnsHandler inherits from this one, so you can
+ easily catch any DnsHandler exception.
message - A descriptive error message.
"""
class ZoneError(Error, KeyError):
r"""
- ZoneError(hostname) -> ZoneError instance
+ ZoneError(zonename) -> ZoneError instance
This is the base exception for all zone related errors.
"""
class ZoneNotFoundError(ZoneError):
r"""
- ZoneNotFoundError(zonename) -> ZoneNotFoundError instance
+ ZoneNotFoundError(hostname) -> ZoneNotFoundError instance
- This exception is raised when trying to operate on a zonename that doesn't
+ This exception is raised when trying to operate on a zone that doesn't
exists.
"""
- def __init__(self, hostname):
+ def __init__(self, zonename):
r"Initialize the object. See class documentation for more info."
- self.message = 'zone not found: "%s"' % hostname
+ self.message = 'zone not found: "%s"' % zonename
class ZoneAlreadyExistsError(ZoneError):
class MailExchangeError(Error, KeyError):
r"""
- HostError(hostname) -> HostError instance
+ MailExchangeError(hostname) -> MailExchangeError instance
- This is the base exception for all host related errors.
+ This is the base exception for all mail exchange related errors.
"""
def __init__(self, mx):
r"Initialize the object. See class documentation for more info."
self.message = 'Mail Exchange error: "%s"' % mx
+
class MailExchangeAlreadyExistsError(MailExchangeError):
r"""
- HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance
+ MailExchangeAlreadyExistsError(hostname) -> MailExchangeAlreadyExistsError instance
- This exception is raised when trying to add a hostname that already exists.
+ This exception is raised when trying to add a mail exchange that already exists.
"""
def __init__(self, mx):
r"Initialize the object. See class documentation for more info."
self.message = 'Mail Exchange already exists: "%s"' % mx
+
class MailExchangeNotFoundError(MailExchangeError):
r"""
- HostNotFoundError(hostname) -> HostNotFoundError instance
+ MailExchangeNotFoundError(hostname) -> MailExchangeNotFoundError instance
- This exception is raised when trying to operate on a hostname that doesn't
+ This exception is raised when trying to operate on a mail exchange that doesn't
exists.
"""
class NameServerError(Error, KeyError):
r"""
- HostError(hostname) -> HostError instance
+ NameServerError(ns) -> NameServerError instance
- This is the base exception for all host related errors.
+ This is the base exception for all name server related errors.
"""
def __init__(self, ns):
class NameServerAlreadyExistsError(NameServerError):
r"""
- HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance
+ NameServerAlreadyExistsError(hostname) -> NameServerAlreadyExistsError instance
- This exception is raised when trying to add a hostname that already exists.
+ This exception is raised when trying to add a name server that already exists.
"""
def __init__(self, ns):
r"Initialize the object. See class documentation for more info."
- self.message = 'Mail Exchange already exists: "%s"' % ns
+ self.message = 'Name server already exists: "%s"' % ns
class NameServerNotFoundError(NameServerError):
r"""
- HostNotFoundError(hostname) -> HostNotFoundError instance
+ NameServerNotFoundError(hostname) -> NameServerNotFoundError instance
- This exception is raised when trying to operate on a hostname that doesn't
+ This exception is raised when trying to operate on a name server that doesn't
exists.
"""
r"Initialize the object. See class documentation for more info."
self.message = 'Parameter not found: "%s"' % paramname
-class Host:
+class Host(Sequence):
def __init__(self, name, ip):
self.name = name
self.ip = ip
-class HostHandler:
+ def as_tuple(self):
+ return (self.name, self.ip)
+
+class HostHandler(Handler):
def __init__(self,zones):
self.zones = zones
- @handler
+ @handler(u'Adds a host to a zone')
def add(self, name, hostname, ip):
if not name in self.zones:
raise ZoneNotFoundError(name)
self.zones[name].hosts[hostname] = Host(hostname, ip)
self.zones[name].mod = True
- @handler
+ @handler(u'Updates a host ip in a zone')
def update(self, name, hostname, ip):
if not name in self.zones:
raise ZoneNotFoundError(name)
self.zones[name].hosts[hostname].ip = ip
self.zones[name].mod = True
- @handler
+ @handler(u'Deletes a host from a zone')
def delete(self, name, hostname):
- r"delete(name) -> None :: Delete a zone from the zone list."
if not name in self.zones:
raise ZoneNotFoundError(name)
if not hostname in self.zones[name].hosts:
del self.zones[name].hosts[hostname]
self.zones[name].mod = True
- @handler
+ @handler(u'Lists hosts')
def list(self):
- r"""list() -> CSV string :: List all the hostnames.
-
- The list is returned as a single CSV line with all the hostnames.
- """
- #return ','.join(self.zones)
+ return self.zones.keys()
- @handler
+ @handler(u'Get insormation about all hosts')
def show(self):
- r"""show() -> CSV string :: List all the complete hosts information.
+ return self.zones.values()
- The hosts are returned as a CSV list with each host in a line, like:
- hostname,ip,mac
- """
- output = ''
- for z in self.zones.values():
- for h in z.hosts.values():
- output += z.name + ',' + h.name + ',' + h.ip + '\n'
- return output
-
-class MailExchange:
+class MailExchange(Sequence):
def __init__(self, mx, prio):
self.mx = mx
self.prio = prio
-class MailExchangeHandler:
+ def as_tuple(self):
+ return (self.mx, self.prio)
+
+class MailExchangeHandler(Handler):
def __init__(self, zones):
self.zones = zones
- @handler
+ @handler(u'Adds a mail exchange to a zone')
def add(self, zonename, mx, prio):
if not zonename in self.zones:
raise ZoneNotFoundError(zonename)
self.zones[zonename].mxs[mx] = MailExchange(mx, prio)
self.zones[zonename].mod = True
- @handler
+ @handler(u'Updates a mail exchange priority')
def update(self, zonename, mx, prio):
if not zonename in self.zones:
raise ZoneNotFoundError(zonename)
self.zones[zonename].mxs[mx].prio = prio
self.zones[zonename].mod = True
- @handler
+ @handler(u'Deletes a mail exchange from a zone')
def delete(self, zonename, mx):
if not zonename in self.zones:
raise ZoneNotFoundError(zonename)
del self.zones[zonename].mxs[mx]
self.zones[zonename].mod = True
- @handler
+ @handler(u'Lists mail exchangers')
def list(self):
- r"""list() -> CSV string :: List all the hostnames.
+ return self.zones.keys()
- The list is returned as a single CSV line with all the hostnames.
- """
- return ','.join(self.zones)
-
- @handler
+ @handler(u'Get information about all mail exchangers')
def show(self):
- r"""show() -> CSV string :: List all the complete hosts information.
-
- The hosts are returned as a CSV list with each host in a line, like:
- hostname,ip,mac
- """
- zones = self.zones.values()
- return '\n'.join('%s,%s,%s' % (z.name, z.ns1, z.ns2) for z in zones)
+ return self.zones.values()
-class NameServer:
+class NameServer(Sequence):
def __init__(self, name):
self.name = name
+ def as_tuple(self):
+ return (self.name)
-class NameServerHandler:
+class NameServerHandler(Handler):
def __init__(self, zones):
self.zones = zones
+ @handler(u'Adds a name server to a zone')
def add(self, zone, ns):
if not zone in self.zones:
raise ZoneNotFoundError(zone)
self.zones[zone].nss[ns] = NameServer(ns)
self.zones[zone].mod = True
+ @handler(u'Deletes a name server from a zone')
def delete(self, zone, ns):
if not zone in self.zones:
raise ZoneNotFoundError(zone)
del self.zones[zone].nss[ns]
self.zones[zone].mod = True
-class Zone:
- def __init__(self, name, ns1, ns2):
+ @handler(u'Lists name servers')
+ def list(self):
+ return self.zones.keys()
+
+ @handler(u'Get information about all name servers')
+ def show(self):
+ return self.zones.values()
+
+
+class Zone(Sequence):
+ def __init__(self, name):
self.name = name
- self.ns1 = ns1
- self.ns2 = ns2
self.hosts = dict()
self.mxs = dict()
self.nss = dict()
+ self.new = False
self.mod = False
self.dele = False
-class ZoneHandler:
+ def as_tuple(self):
+ return (self.name, self.hosts, self.mxs, self.nss)
+
+class ZoneHandler(Handler):
r"""ZoneHandler(zones) -> ZoneHandler instance :: Handle a list of zones.
def __init__(self, zones):
self.zones = zones
- @handler
- def add(self, name, ns1, ns2=None):
+ @handler(u'Adds a zone')
+ def add(self, name):
if name in self.zones:
- raise ZoneAlreadyExistsError(name)
- self.zones[name] = Zone(name, ns1, ns2)
+ if self.zones[name].dele == True:
+ self.zones[name].dele = False
+ else:
+ raise ZoneAlreadyExistsError(name)
+ self.zones[name] = Zone(name)
self.zones[name].mod = True
+ self.zones[name].new = True
- @handler
- def update(self, name, ns1=None, ns2=None):
- if not name in self.zones:
- raise ZoneNotFoundError(name)
- if self.zones[name].dele:
- raise ZoneNotFoundError(name)
- if ns1 is not None:
- self.zones[name].ns1 = ns1
- if ns2 is not None:
- self.zones[name].ns2 = ns2
- self.zones[name].mod = True
- @handler
+ @handler(u'Deletes a zone')
def delete(self, name):
r"delete(name) -> None :: Delete a zone from the zone list."
if not name in self.zones:
raise ZoneNotFoundError(name)
self.zones[name].dele = True
- @handler
+ @handler(u'Lists zones')
def list(self):
- r"""list() -> CSV string :: List all the hostnames.
-
- The list is returned as a single CSV line with all the hostnames.
- """
- return ','.join(self.zones)
+ return self.zones.keys()
- @handler
+ @handler(u'Get information about all zones')
def show(self):
- r"""show() -> CSV string :: List all the complete hosts information.
+ return self.zones.values()
- The hosts are returned as a CSV list with each host in a line, like:
- hostname,ip,mac
- """
- zones = self.zones.values()
- return '\n'.join('%s,%s,%s' % (z.name, z.ns1, z.ns2) for z in zones)
-
-class DnsHandler:
+class DnsHandler(Restorable, ConfigWriter, InitdHandler, TransactionalHandler,
+ ParametersHandler):
r"""DnsHandler([pickle_dir[, config_dir]]) -> DnsHandler instance.
Handles DNS service commands for the dns program.
Both defaults to the current working directory.
"""
- def __init__(self, pickle_dir='.', config_dir='.'):
- r"Initialize DnsHandler object, see class documentation for details."
- self.pickle_dir = pickle_dir
- self.config_dir = config_dir
- c_filename = path.join(template_dir, config_filename)
- z_filename = path.join(template_dir, zone_filename)
- self.config_template = Template(filename=c_filename)
- self.zone_template = Template(filename=z_filename)
- try :
- self._load()
- except IOError:
- self.zones = dict()
- self.vars = dict(
+ _initd_name = 'bind'
+
+ _persistent_vars = ('params', 'zones')
+
+ _restorable_defaults = dict(
+ zones = dict(),
+ params = dict(
isp_dns1 = '',
isp_dns2 = '',
bind_addr1 = '',
bind_addr2 = ''
- )
+ ),
+ )
+ _config_writer_files = ('named.conf', 'zoneX.zone')
+ _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
+
+ def __init__(self, pickle_dir='.', config_dir='.'):
+ r"Initialize DnsHandler object, see class documentation for details."
+ self._persistent_dir = pickle_dir
+ self._config_writer_cfg_dir = config_dir
+ self.mod = False
+ self._config_build_templates()
+ self._restore()
self.host = HostHandler(self.zones)
self.zone = ZoneHandler(self.zones)
self.mx = MailExchangeHandler(self.zones)
self.ns = NameServerHandler(self.zones)
- @handler
- def set(self, param, value):
- r"set(param, value) -> None :: Set a DHCP parameter."
- if not param in self.vars:
- raise ParameterNotFoundError(param)
- self.vars[param] = value
-
- @handler
- def get(self, param):
- r"get(param) -> None :: Get a DHCP parameter."
- if not param in self.vars:
- raise ParameterNotFoundError(param)
- return self.vars[param]
-
- @handler
- def list(self):
- r"""list() -> CSV string :: List all the parameter names.
-
- The list is returned as a single CSV line with all the names.
- """
- return ','.join(self.vars)
+ def _zone_filename(self, zone):
+ return zone.name + '.zone'
- @handler
- def show(self):
- r"""show() -> CSV string :: List all the parameters (with their values).
-
- The parameters are returned as a CSV list with each parameter in a
- line, like:
- name,value
- """
- return '\n'.join(('%s,%s' % (k, v) for (k, v) in self.vars.items()))
-
- @handler
- def start(self):
- r"start() -> None :: Start the DNS service."
- #esto seria para poner en una interfaz
- #y seria el hook para arrancar el servicio
- pass
-
- @handler
- def stop(self):
- r"stop() -> None :: Stop the DNS service."
- #esto seria para poner en una interfaz
- #y seria el hook para arrancar el servicio
- pass
-
- @handler
- def restart(self):
- r"restart() -> None :: Restart the DNS service."
- #esto seria para poner en una interfaz
- #y seria el hook para arrancar el servicio
- pass
-
- @handler
- def reload(self):
- r"reload() -> None :: Reload the configuration of the DNS service."
- #esto seria para poner en una interfaz
- #y seria el hook para arrancar el servicio
- pass
-
- @handler
- def commit(self):
- r"commit() -> None :: Commit the changes and reload the DNS service."
- #esto seria para poner en una interfaz
- #y seria que hace el pickle deberia llamarse
- #al hacerse un commit
- self._dump()
- self._write_config()
- self.reload()
-
- @handler
- def rollback(self):
- r"rollback() -> None :: Discard the changes not yet commited."
- self._load()
-
- def _dump(self):
- r"_dump() -> None :: Dump all persistent data to pickle files."
- # XXX podría ir en una clase base
- self._dump_var(self.vars, pickle_vars)
- self._dump_var(self.zones, pickle_zones)
-
- def _load(self):
- r"_load() -> None :: Load all persistent data from pickle files."
- # XXX podría ir en una clase base
- self.vars = self._load_var(pickle_vars)
- self.zones = self._load_var(pickle_zones)
-
- def _pickle_filename(self, name):
- r"_pickle_filename() -> string :: Construct a pickle filename."
- # XXX podría ir en una clase base
- return path.join(self.pickle_dir, name) + pickle_ext
-
- def _dump_var(self, var, name):
- r"_dump_var() -> None :: Dump a especific variable to a pickle file."
- # XXX podría ir en una clase base
- pkl_file = file(self._pickle_filename(name), 'wb')
- pickle.dump(var, pkl_file, 2)
- pkl_file.close()
-
- def _load_var(self, name):
- r"_load_var() -> object :: Load a especific pickle file."
- # XXX podría ir en una clase base
- return pickle.load(file(self._pickle_filename(name)))
+ def _get_config_vars(self, config_file):
+ return dict(zones=self.zones.values(), **self.params)
def _write_config(self):
r"_write_config() -> None :: Generate all the configuration files."
- # XXX podría ir en una clase base, ver como generalizar variables a
- # reemplazar en la template
- #archivos de zona
delete_zones = list()
for a_zone in self.zones.values():
if a_zone.mod:
- # TODO freeze de la zona
- zone_out_file = file(path.join(self.config_dir, a_zone.name + zone_filename_ext), 'w')
- ctx = Context(
- zone_out_file,
+ if not a_zone.new:
+ # TODO freeze de la zona
+ call(('dns', 'freeze', a_zone.name))
+ vars = dict(
zone = a_zone,
hosts = a_zone.hosts.values(),
mxs = a_zone.mxs.values(),
nss = a_zone.nss.values()
- )
- self.zone_template.render_context(ctx)
- zone_out_file.close()
+ )
+ self._write_single_config('zoneX.zone',
+ self._zone_filename(a_zone), vars)
a_zone.mod = False
- # TODO unfreeze de la zona
+ if not a_zone.new:
+ # TODO unfreeze de la zona
+ call(('dns', 'unfreeze', a_zone.name))
+ else :
+ self.mod = True
+ a_zone.new = False
if a_zone.dele:
#borro el archivo .zone
try:
- unlink(path.join(self.config_dir, a_zone.name + zone_filename_ext))
+ self.mod = True
+ unlink(self._zone_filename(a_zone))
except OSError:
#la excepcion pude darse en caso que haga un add de una zona y
#luego el del, como no hice commit, no se crea el archivo
for z in delete_zones:
del self.zones[z]
#archivo general
- cfg_out_file = file(path.join(self.config_dir, config_filename), 'w')
- ctx = Context(cfg_out_file, zones=self.zones.values(), **self.vars)
- self.config_template.render_context(ctx)
- cfg_out_file.close()
-
-
+ if self.mod:
+ self._write_single_config('named.conf')
+ self.mod = False
+ self.reload()
if __name__ == '__main__':
dns.set('isp_dns1','la_garcha.com')
dns.set('bind_addr1','localhost')
- dns.zone.add('zona_loca.com','ns1,dom.com','ns2.dominio.com')
- dns.zone.update('zona_loca.com','ns1.dominio.com')
+ dns.zone.add('zona_loca.com')
+ #dns.zone.update('zona_loca.com','ns1.dominio.com')
dns.host.add('zona_loca.com','hostname_loco','192.168.0.23')
dns.host.update('zona_loca.com','hostname_loco','192.168.0.66')
dns.ns.add('zona_loca.com','ns3.jua.com')
dns.ns.delete('zona_loca.com','ns3.jua.com')
- dns.zone.add('zona_oscura','ns1.lala.com')
+ dns.zone.add('zona_oscura')
dns.host.add('zona_oscura','hostname_a','192.168.0.24')
dns.host.add('zona_oscura','hostname_b','192.168.0.25')
dns.commit()
- print 'ZONAS :'
- print dns.zone.show() + '\n'
- print 'HOSTS :'
- print dns.host.show()
+ print 'ZONAS :', dns.zone.show()
+ print 'HOSTS :', dns.host.show()
#test zone errors
- try:
- dns.zone.update('zone-sarasa','lalal')
- except ZoneNotFoundError, inst:
- print 'Error: ', inst
+ #try:
+ # dns.zone.update('zone-sarasa','lalal')
+ #except ZoneNotFoundError, inst:
+ # print 'Error: ', inst
try:
dns.zone.delete('zone-sarasa')
except ZoneNotFoundError, inst:
print 'Error: ', inst
- try:
- dns.zone.add('zona_loca.com','ns1.dom.com','ns2.dom.com')
- except ZoneAlreadyExistsError, inst:
- print 'Error: ', inst
+ #try:
+ # dns.zone.add('zona_loca.com','ns1.dom.com','ns2.dom.com')
+ #except ZoneAlreadyExistsError, inst:
+ # print 'Error: ', inst
#test hosts errors
try: