1 # vim: set encoding=utf-8 et sw=4 sts=4 :
4 from mako.template import Template
5 from mako.runtime import Context
10 import cPickle as pickle
15 from seqtools import Sequence
21 from dispatcher import handler, HandlerError
23 class HandlerError(RuntimeError): pass
24 def handler(f): return f # NOP for testing
28 __ALL__ = ('DnsHandler',)
33 pickle_zones = 'zones'
35 config_filename = 'named.conf'
36 zone_filename = 'zoneX.zone'
37 zone_filename_ext = '.zone'
39 template_dir = path.join(path.dirname(__file__), 'templates')
42 class Error(HandlerError):
44 Error(command) -> Error instance :: Base DnsHandler exception class.
46 All exceptions raised by the DnsHandler inherits from this one, so you can
47 easily catch any DnsHandler exception.
49 message - A descriptive error message.
52 def __init__(self, message):
53 r"Initialize the Error object. See class documentation for more info."
54 self.message = message
59 class ZoneError(Error, KeyError):
61 ZoneError(zonename) -> ZoneError instance
63 This is the base exception for all zone related errors.
66 def __init__(self, zonename):
67 r"Initialize the object. See class documentation for more info."
68 self.message = 'Zone error: "%s"' % zonename
71 class ZoneNotFoundError(ZoneError):
73 ZoneNotFoundError(hostname) -> ZoneNotFoundError instance
75 This exception is raised when trying to operate on a zone that doesn't
79 def __init__(self, zonename):
80 r"Initialize the object. See class documentation for more info."
81 self.message = 'zone not found: "%s"' % zonename
84 class ZoneAlreadyExistsError(ZoneError):
86 ZoneAlreadyExistsError(hostname) -> ZoneAlreadyExistsError instance
88 This exception is raised when trying to add a zonename that already exists.
91 def __init__(self, zonename):
92 r"Initialize the object. See class documentation for more info."
93 self.message = 'Zone already exists: "%s"' % zonename
96 class HostError(Error, KeyError):
98 HostError(hostname) -> HostError instance
100 This is the base exception for all host related errors.
103 def __init__(self, hostname):
104 r"Initialize the object. See class documentation for more info."
105 self.message = 'Host error: "%s"' % hostname
107 class HostAlreadyExistsError(HostError):
109 HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance
111 This exception is raised when trying to add a hostname that already exists.
114 def __init__(self, hostname):
115 r"Initialize the object. See class documentation for more info."
116 self.message = 'Host already exists: "%s"' % hostname
118 class HostNotFoundError(HostError):
120 HostNotFoundError(hostname) -> HostNotFoundError instance
122 This exception is raised when trying to operate on a hostname that doesn't
126 def __init__(self, hostname):
127 r"Initialize the object. See class documentation for more info."
128 self.message = 'Host not found: "%s"' % hostname
131 class MailExchangeError(Error, KeyError):
133 MailExchangeError(hostname) -> MailExchangeError instance
135 This is the base exception for all mail exchange related errors.
138 def __init__(self, mx):
139 r"Initialize the object. See class documentation for more info."
140 self.message = 'Mail Exchange error: "%s"' % mx
143 class MailExchangeAlreadyExistsError(MailExchangeError):
145 MailExchangeAlreadyExistsError(hostname) -> MailExchangeAlreadyExistsError instance
147 This exception is raised when trying to add a mail exchange that already exists.
150 def __init__(self, mx):
151 r"Initialize the object. See class documentation for more info."
152 self.message = 'Mail Exchange already exists: "%s"' % mx
155 class MailExchangeNotFoundError(MailExchangeError):
157 MailExchangeNotFoundError(hostname) -> MailExchangeNotFoundError instance
159 This exception is raised when trying to operate on a mail exchange that doesn't
163 def __init__(self, mx):
164 r"Initialize the object. See class documentation for more info."
165 self.message = 'Mail Exchange not found: "%s"' % mx
169 class NameServerError(Error, KeyError):
171 NameServerError(ns) -> NameServerError instance
173 This is the base exception for all name server related errors.
176 def __init__(self, ns):
177 r"Initialize the object. See class documentation for more info."
178 self.message = 'Name Server error: "%s"' % ns
180 class NameServerAlreadyExistsError(NameServerError):
182 NameServerAlreadyExistsError(hostname) -> NameServerAlreadyExistsError instance
184 This exception is raised when trying to add a name server that already exists.
187 def __init__(self, ns):
188 r"Initialize the object. See class documentation for more info."
189 self.message = 'Name server already exists: "%s"' % ns
191 class NameServerNotFoundError(NameServerError):
193 NameServerNotFoundError(hostname) -> NameServerNotFoundError instance
195 This exception is raised when trying to operate on a name server that doesn't
199 def __init__(self, ns):
200 r"Initialize the object. See class documentation for more info."
201 self.message = 'Mail Exchange not found: "%s"' % ns
204 class ParameterError(Error, KeyError):
206 ParameterError(paramname) -> ParameterError instance
208 This is the base exception for all DhcpHandler parameters related errors.
211 def __init__(self, paramname):
212 r"Initialize the object. See class documentation for more info."
213 self.message = 'Parameter error: "%s"' % paramname
215 class ParameterNotFoundError(ParameterError):
217 ParameterNotFoundError(hostname) -> ParameterNotFoundError instance
219 This exception is raised when trying to operate on a parameter that doesn't
223 def __init__(self, paramname):
224 r"Initialize the object. See class documentation for more info."
225 self.message = 'Parameter not found: "%s"' % paramname
227 class Host(Sequence):
228 def __init__(self, name, ip):
233 return (self.name, self.ip)
236 def __init__(self,zones):
240 def add(self, name, hostname, ip):
241 if not name in self.zones:
242 raise ZoneNotFoundError(name)
243 if hostname in self.zones[name].hosts:
244 raise HostAlreadyExistsError(hostname)
245 self.zones[name].hosts[hostname] = Host(hostname, ip)
246 self.zones[name].mod = True
249 def update(self, name, hostname, ip):
250 if not name in self.zones:
251 raise ZoneNotFoundError(name)
252 if not hostname in self.zones[name].hosts:
253 raise HostNotFoundError(name)
254 self.zones[name].hosts[hostname].ip = ip
255 self.zones[name].mod = True
258 def delete(self, name, hostname):
259 if not name in self.zones:
260 raise ZoneNotFoundError(name)
261 if not hostname in self.zones[name].hosts:
262 raise HostNotFoundError(name)
263 del self.zones[name].hosts[hostname]
264 self.zones[name].mod = True
268 return self.zones.keys()
272 return self.zones.values()
275 class MailExchange(Sequence):
277 def __init__(self, mx, prio):
282 return (self.mx, self.prio)
284 class MailExchangeHandler:
286 def __init__(self, zones):
290 def add(self, zonename, mx, prio):
291 if not zonename in self.zones:
292 raise ZoneNotFoundError(zonename)
293 if mx in self.zones[zonename].mxs:
294 raise MailExchangeAlreadyExistsError(mx)
295 self.zones[zonename].mxs[mx] = MailExchange(mx, prio)
296 self.zones[zonename].mod = True
299 def update(self, zonename, mx, prio):
300 if not zonename in self.zones:
301 raise ZoneNotFoundError(zonename)
302 if not mx in self.zones[zonename].mxs:
303 raise MailExchangeNotFoundError(mx)
304 self.zones[zonename].mxs[mx].prio = prio
305 self.zones[zonename].mod = True
308 def delete(self, zonename, mx):
309 if not zonename in self.zones:
310 raise ZoneNotFoundError(zonename)
311 if not mx in self.zones[zonename].mxs:
312 raise MailExchangeNotFoundError(mx)
313 del self.zones[zonename].mxs[mx]
314 self.zones[zonename].mod = True
318 return self.zones.keys()
322 return self.zones.values()
325 class NameServer(Sequence):
327 def __init__(self, name):
333 class NameServerHandler:
335 def __init__(self, zones):
339 def add(self, zone, ns):
340 if not zone in self.zones:
341 raise ZoneNotFoundError(zone)
342 if ns in self.zones[zone].nss:
343 raise NameServerAlreadyExistsError(ns)
344 self.zones[zone].nss[ns] = NameServer(ns)
345 self.zones[zone].mod = True
348 def delete(self, zone, ns):
349 if not zone in self.zones:
350 raise ZoneNotFoundError(zone)
351 if not ns in self.zones[zone].nss:
352 raise NameServerNotFoundError(ns)
353 del self.zones[zone].nss[ns]
354 self.zones[zone].mod = True
358 return self.zones.keys()
362 return self.zones.values()
365 class Zone(Sequence):
366 def __init__(self, name):
376 return (self.name, self.hosts, self.mxs, self.nss)
380 r"""ZoneHandler(zones) -> ZoneHandler instance :: Handle a list of zones.
382 This class is a helper for DnsHandler to do all the work related to zone
385 zones - A dictionary with string keys (zone name) and Zone instances values.
387 def __init__(self, zones):
392 if name in self.zones:
393 if self.zones[name].dele = True:
394 self.zones[name].dele = False
396 raise ZoneAlreadyExistsError(name)
397 self.zones[name] = Zone(name)
398 self.zones[name].mod = True
399 self.zones[name].new = True
403 def delete(self, name):
404 r"delete(name) -> None :: Delete a zone from the zone list."
405 if not name in self.zones:
406 raise ZoneNotFoundError(name)
407 self.zones[name].dele = True
411 return self.zones.keys()
415 return self.zones.values()
418 r"""DnsHandler([pickle_dir[, config_dir]]) -> DnsHandler instance.
420 Handles DNS service commands for the dns program.
422 pickle_dir - Directory where to write the persistent configuration data.
424 config_dir - Directory where to store de generated configuration files.
426 Both defaults to the current working directory.
429 def __init__(self, pickle_dir='.', config_dir='.'):
430 r"Initialize DnsHandler object, see class documentation for details."
431 self.pickle_dir = pickle_dir
432 self.config_dir = config_dir
433 c_filename = path.join(template_dir, config_filename)
434 z_filename = path.join(template_dir, zone_filename)
435 self.config_template = Template(filename=c_filename)
436 self.zone_template = Template(filename=z_filename)
448 self.host = HostHandler(self.zones)
449 self.zone = ZoneHandler(self.zones)
450 self.mx = MailExchangeHandler(self.zones)
451 self.ns = NameServerHandler(self.zones)
455 def set(self, param, value):
456 r"set(param, value) -> None :: Set a DNS parameter."
457 if not param in self.vars:
458 raise ParameterNotFoundError(param)
459 self.vars[param] = value
463 def get(self, param):
464 r"get(param) -> None :: Get a DNS parameter."
465 if not param in self.vars:
466 raise ParameterNotFoundError(param)
467 return self.vars[param]
471 return self.vars.keys()
475 return self.vars.values()
479 r"start() -> None :: Start the DNS service."
480 #esto seria para poner en una interfaz
481 #y seria el hook para arrancar el servicio
486 r"stop() -> None :: Stop the DNS service."
487 #esto seria para poner en una interfaz
488 #y seria el hook para arrancar el servicio
493 r"restart() -> None :: Restart the DNS service."
494 #esto seria para poner en una interfaz
495 #y seria el hook para arrancar el servicio
500 r"reload() -> None :: Reload the configuration of the DNS service."
501 #esto seria para poner en una interfaz
502 #y seria el hook para arrancar el servicio
507 r"commit() -> None :: Commit the changes and reload the DNS service."
508 #esto seria para poner en una interfaz
509 #y seria que hace el pickle deberia llamarse
510 #al hacerse un commit
517 r"rollback() -> None :: Discard the changes not yet commited."
521 r"_dump() -> None :: Dump all persistent data to pickle files."
522 # XXX podría ir en una clase base
523 self._dump_var(self.vars, pickle_vars)
524 self._dump_var(self.zones, pickle_zones)
527 r"_load() -> None :: Load all persistent data from pickle files."
528 # XXX podría ir en una clase base
529 self.vars = self._load_var(pickle_vars)
530 self.zones = self._load_var(pickle_zones)
532 def _pickle_filename(self, name):
533 r"_pickle_filename() -> string :: Construct a pickle filename."
534 # XXX podría ir en una clase base
535 return path.join(self.pickle_dir, name) + pickle_ext
537 def _dump_var(self, var, name):
538 r"_dump_var() -> None :: Dump a especific variable to a pickle file."
539 # XXX podría ir en una clase base
540 pkl_file = file(self._pickle_filename(name), 'wb')
541 pickle.dump(var, pkl_file, 2)
544 def _load_var(self, name):
545 r"_load_var() -> object :: Load a especific pickle file."
546 # XXX podría ir en una clase base
547 return pickle.load(file(self._pickle_filename(name)))
549 def _write_config(self):
550 r"_write_config() -> None :: Generate all the configuration files."
551 # XXX podría ir en una clase base, ver como generalizar variables a
552 # reemplazar en la template
554 delete_zones = list()
555 for a_zone in self.zones.values():
558 # TODO freeze de la zona
559 print 'Freezing zone ' + a_zone.name + zone_filename_ext
560 zone_out_file = file(path.join(self.config_dir, a_zone.name + zone_filename_ext), 'w')
564 hosts = a_zone.hosts.values(),
565 mxs = a_zone.mxs.values(),
566 nss = a_zone.nss.values()
568 self.zone_template.render_context(ctx)
569 zone_out_file.close()
572 # TODO unfreeze de la zona
573 print 'Unfreezing zone ' + a_zone.name + zone_filename_ext
578 #borro el archivo .zone
581 unlink(path.join(self.config_dir, a_zone.name + zone_filename_ext))
583 #la excepcion pude darse en caso que haga un add de una zona y
584 #luego el del, como no hice commit, no se crea el archivo
586 delete_zones.append(a_zone.name)
588 for z in delete_zones:
592 cfg_out_file = file(path.join(self.config_dir, config_filename), 'w')
593 ctx = Context(cfg_out_file, zones=self.zones.values(), **self.vars)
594 self.config_template.render_context(ctx)
597 print 'Restarting service'
601 if __name__ == '__main__':
605 dns.set('isp_dns1','la_garcha.com')
606 dns.set('bind_addr1','localhost')
607 dns.zone.add('zona_loca.com')
608 #dns.zone.update('zona_loca.com','ns1.dominio.com')
610 dns.host.add('zona_loca.com','hostname_loco','192.168.0.23')
611 dns.host.update('zona_loca.com','hostname_loco','192.168.0.66')
613 dns.host.add('zona_loca.com','hostname_kuak','192.168.0.23')
614 dns.host.delete('zona_loca.com','hostname_kuak')
616 dns.host.add('zona_loca.com','hostname_kuang','192.168.0.24')
617 dns.host.add('zona_loca.com','hostname_chan','192.168.0.25')
618 dns.host.add('zona_loca.com','hostname_kaine','192.168.0.26')
620 dns.mx.add('zona_loca.com','mx1.sarasa.com',10)
621 dns.mx.update('zona_loca.com','mx1.sarasa.com',20)
622 dns.mx.add('zona_loca.com','mx2.sarasa.com',30)
623 dns.mx.add('zona_loca.com','mx3.sarasa.com',40)
624 dns.mx.delete('zona_loca.com','mx3.sarasa.com')
626 dns.ns.add('zona_loca.com','ns1.jua.com')
627 dns.ns.add('zona_loca.com','ns2.jua.com')
628 dns.ns.add('zona_loca.com','ns3.jua.com')
629 dns.ns.delete('zona_loca.com','ns3.jua.com')
631 dns.zone.add('zona_oscura')
633 dns.host.add('zona_oscura','hostname_a','192.168.0.24')
634 dns.host.add('zona_oscura','hostname_b','192.168.0.25')
635 dns.host.add('zona_oscura','hostname_c','192.168.0.26')
637 dns.zone.delete('zona_oscura')
642 print dns.zone.show() + '\n'
644 print dns.host.show()
648 dns.zone.update('zone-sarasa','lalal')
649 except ZoneNotFoundError, inst:
650 print 'Error: ', inst
653 dns.zone.delete('zone-sarasa')
654 except ZoneNotFoundError, inst:
655 print 'Error: ', inst
658 dns.zone.add('zona_loca.com','ns1.dom.com','ns2.dom.com')
659 except ZoneAlreadyExistsError, inst:
660 print 'Error: ', inst
664 dns.host.update('zone-sarasa','kuak','192.68')
665 except ZoneNotFoundError, inst:
666 print 'Error: ', inst
669 dns.host.update('zona_loca.com','kuak','192.68')
670 except HostNotFoundError, inst:
671 print 'Error: ', inst
674 dns.host.delete('zone-sarasa','lala')
675 except ZoneNotFoundError, inst:
676 print 'Error: ', inst
679 dns.host.delete('zona_loca.com','lala')
680 except HostNotFoundError, inst:
681 print 'Error: ', inst
684 dns.host.add('zona','hostname_loco','192.168.0.23')
685 except ZoneNotFoundError, inst:
686 print 'Error: ', inst
689 dns.host.add('zona_loca.com','hostname_loco','192.168.0.23')
690 except HostAlreadyExistsError, inst:
691 print 'Error: ', inst