X-Git-Url: https://git.llucax.com/software/pymin.git/blobdiff_plain/b8c5dbd52084b9a710c9881e327449f9eaec0bdb..7cd50fbc836fa07396e60b41bc169649c38e3153:/services/dhcp/__init__.py diff --git a/services/dhcp/__init__.py b/services/dhcp/__init__.py index 46b7d81..b728162 100644 --- a/services/dhcp/__init__.py +++ b/services/dhcp/__init__.py @@ -8,6 +8,18 @@ try: except ImportError: import pickle +try: + from seqtools import Sequence +except ImportError: + # NOP for testing + class Sequence: pass +try: + from dispatcher import handler, HandlerError +except ImportError: + # NOP for testing + class HandlerError(RuntimeError): pass + def handler(f): return f + __ALL__ = ('DhcpHandler',) pickle_ext = '.pkl' @@ -18,7 +30,82 @@ config_filename = 'dhcpd.conf' template_dir = path.join(path.dirname(__file__), 'templates') -class Host: +class Error(HandlerError): + r""" + Error(command) -> Error instance :: Base DhcpHandler exception class. + + All exceptions raised by the DhcpHandler inherits from this one, so you can + easily catch any DhcpHandler exception. + + message - A descriptive error message. + """ + + def __init__(self, message): + r"Initialize the Error object. See class documentation for more info." + self.message = message + + def __str__(self): + return self.message + +class HostError(Error, KeyError): + r""" + HostError(hostname) -> HostError instance + + This is the base exception for all host related errors. + """ + + def __init__(self, hostname): + r"Initialize the object. See class documentation for more info." + self.message = 'Host error: "%s"' % hostname + +class HostAlreadyExistsError(HostError): + r""" + HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance + + This exception is raised when trying to add a hostname that already exists. + """ + + def __init__(self, hostname): + r"Initialize the object. See class documentation for more info." + self.message = 'Host already exists: "%s"' % hostname + +class HostNotFoundError(HostError): + r""" + HostNotFoundError(hostname) -> HostNotFoundError instance + + This exception is raised when trying to operate on a hostname that doesn't + exists. + """ + + def __init__(self, hostname): + r"Initialize the object. See class documentation for more info." + self.message = 'Host not found: "%s"' % hostname + +class ParameterError(Error, KeyError): + r""" + ParameterError(paramname) -> ParameterError instance + + This is the base exception for all DhcpHandler parameters related errors. + """ + + def __init__(self, paramname): + r"Initialize the object. See class documentation for more info." + self.message = 'Parameter error: "%s"' % paramname + +class ParameterNotFoundError(ParameterError): + r""" + ParameterNotFoundError(hostname) -> ParameterNotFoundError instance + + This exception is raised when trying to operate on a parameter that doesn't + exists. + """ + + def __init__(self, paramname): + r"Initialize the object. See class documentation for more info." + self.message = 'Parameter not found: "%s"' % paramname + + +class Host(Sequence): r"""Host(name, ip, mac) -> Host instance :: Class representing a host. name - Host name, should be a fully qualified name, but no checks are done. @@ -32,6 +119,10 @@ class Host: self.ip = ip self.mac = mac + def as_tuple(self): + r"Return a tuple representing the host." + return (self.name, self.ip, self.mac) + class HostHandler: r"""HostHandler(hosts) -> HostHandler instance :: Handle a list of hosts. @@ -45,43 +136,56 @@ class HostHandler: r"Initialize HostHandler object, see class documentation for details." self.hosts = hosts + @handler def add(self, name, ip, mac): r"add(name, ip, mac) -> None :: Add a host to the hosts list." - # XXX deberia indexar por hostname o por ip? o por mac? :) - # o por nada... Puedo tener un nombre con muchas IPs? Una IP con muchos - # nombres? Una MAC con muchas IP? una MAC con muchos nombre? Etc... + if name in self.hosts: + raise HostAlreadyExistsError(name) self.hosts[name] = Host(name, ip, mac) + @handler def update(self, name, ip=None, mac=None): r"update(name[, ip[, mac]]) -> None :: Update a host of the hosts list." if not name in self.hosts: - raise KeyError('Host not found') + raise HostNotFoundError(name) if ip is not None: self.hosts[name].ip = ip if mac is not None: self.hosts[name].mac = mac + @handler def delete(self, name): r"delete(name) -> None :: Delete a host of the hosts list." if not name in self.hosts: - raise KeyError('Host not found') + raise HostNotFoundError(name) del self.hosts[name] + @handler + def get(self, name): + r"""get(name) -> CSV string :: List all the information of a host. + + The host is returned as a CSV list of: hostname,ip,mac + """ + if not name in self.hosts: + raise HostNotFoundError(name) + return self.hosts[name] + + @handler 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.hosts) + return self.hosts.keys() + @handler 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 """ - hosts = self.hosts.values() - return '\n'.join('%s,%s,%s' % (h.name, h.ip, h.mac) for h in hosts) + return self.hosts.values() class DhcpHandler: r"""DhcpHandler([pickle_dir[, config_dir]]) -> DhcpHandler instance. @@ -121,19 +225,29 @@ class DhcpHandler: self._write_config() self.host = HostHandler(self.hosts) + @handler def set(self, param, value): r"set(param, value) -> None :: Set a DHCP parameter." if not param in self.vars: - raise KeyError('Parameter ' + param + ' not found') + 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) + return self.vars.keys() + @handler def show(self): r"""show() -> CSV string :: List all the parameters (with their values). @@ -141,32 +255,37 @@ class DhcpHandler: line, like: name,value """ - return '\n'.join(('%s,%s' % (k, v) for (k, v) in self.vars.items())) + return self.vars.items() + @handler def start(self): r"start() -> None :: Start the DHCP 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 DHCP 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 DHCP 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 DHCP 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 DHCP service." #esto seria para poner en una interfaz @@ -176,6 +295,7 @@ class DhcpHandler: self._write_config() self.reload() + @handler def rollback(self): r"rollback() -> None :: Discard the changes not yet commited." self._load() @@ -200,7 +320,9 @@ class DhcpHandler: 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 - pickle.dump(var, file(self._pickle_filename(name), 'wb'), 2) + 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." @@ -214,6 +336,7 @@ class DhcpHandler: out_file = file(path.join(self.config_dir, config_filename), 'w') ctx = Context(out_file, hosts=self.hosts.values(), **self.vars) self.template.render_context(ctx) + out_file.close() if __name__ == '__main__':