1 # vim: set encoding=utf-8 et sw=4 sts=4 :
5 from seqtools import Sequence
6 from dispatcher import Handler, handler, HandlerError
7 from services.util import Restorable, ConfigWriter
8 from services.util import InitdHandler, TransactionalHandler
10 __ALL__ = ('DhcpHandler', 'Error', 'HostError', 'HostAlreadyExistsError',
11 'HostNotFoundError', 'ParameterError', 'ParameterNotFoundError')
13 class Error(HandlerError):
15 Error(message) -> Error instance :: Base DhcpHandler exception class.
17 All exceptions raised by the DhcpHandler inherits from this one, so you can
18 easily catch any DhcpHandler exception.
20 message - A descriptive error message.
23 def __init__(self, message):
24 r"Initialize the Error object. See class documentation for more info."
25 self.message = message
30 class HostError(Error, KeyError):
32 HostError(hostname) -> HostError instance
34 This is the base exception for all host related errors.
37 def __init__(self, hostname):
38 r"Initialize the object. See class documentation for more info."
39 self.message = 'Host error: "%s"' % hostname
41 class HostAlreadyExistsError(HostError):
43 HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance
45 This exception is raised when trying to add a hostname that already exists.
48 def __init__(self, hostname):
49 r"Initialize the object. See class documentation for more info."
50 self.message = 'Host already exists: "%s"' % hostname
52 class HostNotFoundError(HostError):
54 HostNotFoundError(hostname) -> HostNotFoundError instance
56 This exception is raised when trying to operate on a hostname that doesn't
60 def __init__(self, hostname):
61 r"Initialize the object. See class documentation for more info."
62 self.message = 'Host not found: "%s"' % hostname
64 class ParameterError(Error, KeyError):
66 ParameterError(paramname) -> ParameterError instance
68 This is the base exception for all DhcpHandler parameters related errors.
71 def __init__(self, paramname):
72 r"Initialize the object. See class documentation for more info."
73 self.message = 'Parameter error: "%s"' % paramname
75 class ParameterNotFoundError(ParameterError):
77 ParameterNotFoundError(hostname) -> ParameterNotFoundError instance
79 This exception is raised when trying to operate on a parameter that doesn't
83 def __init__(self, paramname):
84 r"Initialize the object. See class documentation for more info."
85 self.message = 'Parameter not found: "%s"' % paramname
89 r"""Host(name, ip, mac) -> Host instance :: Class representing a host.
91 name - Host name, should be a fully qualified name, but no checks are done.
92 ip - IP assigned to the hostname.
93 mac - MAC address to associate to the hostname.
96 def __init__(self, name, ip, mac):
97 r"Initialize Host object, see class documentation for details."
103 r"Return a tuple representing the host."
104 return (self.name, self.ip, self.mac)
106 class HostHandler(Handler):
107 r"""HostHandler(hosts) -> HostHandler instance :: Handle a list of hosts.
109 This class is a helper for DhcpHandler to do all the work related to hosts
112 hosts - A dictionary with string keys (hostnames) and Host instances values.
115 def __init__(self, hosts):
116 r"Initialize HostHandler object, see class documentation for details."
119 @handler(u'Add a new host.')
120 def add(self, name, ip, mac):
121 r"add(name, ip, mac) -> None :: Add a host to the hosts list."
122 if name in self.hosts:
123 raise HostAlreadyExistsError(name)
124 self.hosts[name] = Host(name, ip, mac)
126 @handler(u'Update a host.')
127 def update(self, name, ip=None, mac=None):
128 r"update(name[, ip[, mac]]) -> None :: Update a host of the hosts list."
129 if not name in self.hosts:
130 raise HostNotFoundError(name)
132 self.hosts[name].ip = ip
134 self.hosts[name].mac = mac
136 @handler(u'Delete a host.')
137 def delete(self, name):
138 r"delete(name) -> None :: Delete a host of the hosts list."
139 if not name in self.hosts:
140 raise HostNotFoundError(name)
143 @handler(u'Get information about a host.')
145 r"get(name) -> Host :: List all the information of a host."
146 if not name in self.hosts:
147 raise HostNotFoundError(name)
148 return self.hosts[name]
150 @handler(u'List hosts.')
152 r"list() -> tuple :: List all the hostnames."
153 return self.hosts.keys()
155 @handler(u'Get information about all hosts.')
157 r"show() -> list of Hosts :: List all the complete hosts information."
158 return self.hosts.values()
160 class DhcpHandler(Restorable, ConfigWriter, InitdHandler, TransactionalHandler):
161 r"""DhcpHandler([pickle_dir[, config_dir]]) -> DhcpHandler instance.
163 Handles DHCP service commands for the dhcpd program.
165 pickle_dir - Directory where to write the persistent configuration data.
167 config_dir - Directory where to store de generated configuration files.
169 Both defaults to the current working directory.
172 _initd_name = 'dhcpd'
174 _persistent_vars = ('vars', 'hosts')
176 _restorable_defaults = dict(
179 domain_name = 'example.com',
180 dns_1 = 'ns1.example.com',
181 dns_2 = 'ns2.example.com',
182 net_address = '192.168.0.0',
183 net_mask = '255.255.255.0',
184 net_start = '192.168.0.100',
185 net_end = '192.168.0.200',
186 net_gateway = '192.168.0.1',
190 _config_writer_files = 'dhcpd.conf'
191 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
193 def __init__(self, pickle_dir='.', config_dir='.'):
194 r"Initialize DhcpHandler object, see class documentation for details."
195 self._persistent_dir = pickle_dir
196 self._config_writer_cfg_dir = config_dir
197 self._config_build_templates()
199 self.host = HostHandler(self.hosts)
201 def _get_config_vars(self, config_file):
202 return dict(hosts=self.hosts.values(), **self.vars)
204 @handler(u'Set a DHCP parameter.')
205 def set(self, param, value):
206 r"set(param, value) -> None :: Set a DHCP parameter."
207 if not param in self.vars:
208 raise ParameterNotFoundError(param)
209 self.vars[param] = value
211 @handler(u'Get a DHCP parameter.')
212 def get(self, param):
213 r"get(param) -> None :: Get a DHCP parameter."
214 if not param in self.vars:
215 raise ParameterNotFoundError(param)
216 return self.vars[param]
218 @handler(u'List all available DHCP parameters.')
220 r"list() -> tuple :: List all the parameter names."
221 return self.vars.keys()
223 @handler(u'Get all DHCP parameters, with their values.')
225 r"show() -> (key, value) tuples :: List all the parameters."
226 return self.vars.items()
228 if __name__ == '__main__':
236 print 'Variables:', h.list()
239 print 'Hosts:', h.host.list()
245 h.host.add('my_name','192.168.0.102','00:12:ff:56')
247 h.host.update('my_name','192.168.0.192','00:12:ff:56')
249 h.host.add('nico','192.168.0.188','00:00:00:00')
251 h.set('domain_name','baryon.com.ar')
254 h.set('sarasa','baryon.com.ar')
262 os.system('rm -f *.pkl ' + ' '.join(h._config_writer_files))