1 # vim: set encoding=utf-8 et sw=4 sts=4 :
3 from mako.template import Template
4 from mako.runtime import Context
7 import cPickle as pickle
11 from dispatcher import handler
13 def handler(f): return f # NOP for testing
15 __ALL__ = ('DhcpHandler',)
19 pickle_hosts = 'hosts'
21 config_filename = 'dhcpd.conf'
23 template_dir = path.join(path.dirname(__file__), 'templates')
25 class Error(RuntimeError):
27 Error(command) -> Error instance :: Base DhcpHandler exception class.
29 All exceptions raised by the DhcpHandler inherits from this one, so you can
30 easily catch any DhcpHandler exception.
32 message - A descriptive error message.
35 def __init__(self, message):
36 r"Initialize the Error object. See class documentation for more info."
37 self.message = message
42 class HostError(Error, KeyError):
44 HostError(hostname) -> HostError instance
46 This is the base exception for all host related errors.
49 def __init__(self, hostname):
50 r"Initialize the object. See class documentation for more info."
51 self.message = 'Host error: "%s"' % hostname
53 class HostAlreadyExistsError(HostError):
55 HostAlreadyExistsError(hostname) -> HostAlreadyExistsError instance
57 This exception is raised when trying to add a hostname that already exists.
60 def __init__(self, hostname):
61 r"Initialize the object. See class documentation for more info."
62 self.message = 'Host already exists: "%s"' % hostname
64 class HostNotFoundError(HostError):
66 HostNotFoundError(hostname) -> HostNotFoundError instance
68 This exception is raised when trying to operate on a hostname that doesn't
72 def __init__(self, hostname):
73 r"Initialize the object. See class documentation for more info."
74 self.message = 'Host not found: "%s"' % hostname
76 class ParameterError(Error, KeyError):
78 ParameterError(paramname) -> ParameterError instance
80 This is the base exception for all DhcpHandler parameters related errors.
83 def __init__(self, paramname):
84 r"Initialize the object. See class documentation for more info."
85 self.message = 'Parameter error: "%s"' % paramname
87 class ParameterNotFoundError(ParameterError):
89 ParameterNotFoundError(hostname) -> ParameterNotFoundError instance
91 This exception is raised when trying to operate on a parameter that doesn't
95 def __init__(self, paramname):
96 r"Initialize the object. See class documentation for more info."
97 self.message = 'Parameter not found: "%s"' % paramname
101 r"""Host(name, ip, mac) -> Host instance :: Class representing a host.
103 name - Host name, should be a fully qualified name, but no checks are done.
104 ip - IP assigned to the hostname.
105 mac - MAC address to associate to the hostname.
108 def __init__(self, name, ip, mac):
109 r"Initialize Host object, see class documentation for details."
115 r"""HostHandler(hosts) -> HostHandler instance :: Handle a list of hosts.
117 This class is a helper for DhcpHandler to do all the work related to hosts
120 hosts - A dictionary with string keys (hostnames) and Host instances values.
123 def __init__(self, hosts):
124 r"Initialize HostHandler object, see class documentation for details."
128 def add(self, name, ip, mac):
129 r"add(name, ip, mac) -> None :: Add a host to the hosts list."
130 if name in self.hosts:
131 raise HostAlreadyExistsError(name)
132 self.hosts[name] = Host(name, ip, mac)
135 def update(self, name, ip=None, mac=None):
136 r"update(name[, ip[, mac]]) -> None :: Update a host of the hosts list."
137 if not name in self.hosts:
138 raise HostNotFoundError(name)
140 self.hosts[name].ip = ip
142 self.hosts[name].mac = mac
145 def delete(self, name):
146 r"delete(name) -> None :: Delete a host of the hosts list."
147 if not name in self.hosts:
148 raise HostNotFoundError(name)
153 r"""list() -> CSV string :: List all the hostnames.
155 The list is returned as a single CSV line with all the hostnames.
157 return ','.join(self.hosts)
161 r"""show() -> CSV string :: List all the complete hosts information.
163 The hosts are returned as a CSV list with each host in a line, like:
166 hosts = self.hosts.values()
167 return '\n'.join('%s,%s,%s' % (h.name, h.ip, h.mac) for h in hosts)
170 r"""DhcpHandler([pickle_dir[, config_dir]]) -> DhcpHandler instance.
172 Handles DHCP service commands for the dhcpd program.
174 pickle_dir - Directory where to write the persistent configuration data.
176 config_dir - Directory where to store de generated configuration files.
178 Both defaults to the current working directory.
181 def __init__(self, pickle_dir='.', config_dir='.'):
182 r"Initialize DhcpHandler object, see class documentation for details."
183 self.pickle_dir = pickle_dir
184 self.config_dir = config_dir
185 filename = path.join(template_dir, config_filename)
186 self.template = Template(filename=filename)
190 # This is the first time the handler is used, create a basic
191 # setup using some nice defaults
194 domain_name = 'example.com',
195 dns_1 = 'ns1.example.com',
196 dns_2 = 'ns2.example.com',
197 net_address = '192.168.0.0',
198 net_mask = '255.255.255.0',
199 net_start = '192.168.0.100',
200 net_end = '192.168.0.200',
201 net_gateway = '192.168.0.1',
205 self.host = HostHandler(self.hosts)
208 def set(self, param, value):
209 r"set(param, value) -> None :: Set a DHCP parameter."
210 if not param in self.vars:
211 raise ParameterNotFoundError(param)
212 self.vars[param] = value
216 r"""list() -> CSV string :: List all the parameter names.
218 The list is returned as a single CSV line with all the names.
220 return ','.join(self.vars)
224 r"""show() -> CSV string :: List all the parameters (with their values).
226 The parameters are returned as a CSV list with each parameter in a
230 return '\n'.join(('%s,%s' % (k, v) for (k, v) in self.vars.items()))
234 r"start() -> None :: Start the DHCP service."
235 #esto seria para poner en una interfaz
236 #y seria el hook para arrancar el servicio
241 r"stop() -> None :: Stop the DHCP service."
242 #esto seria para poner en una interfaz
243 #y seria el hook para arrancar el servicio
248 r"restart() -> None :: Restart the DHCP service."
249 #esto seria para poner en una interfaz
250 #y seria el hook para arrancar el servicio
255 r"reload() -> None :: Reload the configuration of the DHCP service."
256 #esto seria para poner en una interfaz
257 #y seria el hook para arrancar el servicio
262 r"commit() -> None :: Commit the changes and reload the DHCP service."
263 #esto seria para poner en una interfaz
264 #y seria que hace el pickle deberia llamarse
265 #al hacerse un commit
272 r"rollback() -> None :: Discard the changes not yet commited."
276 r"_dump() -> None :: Dump all persistent data to pickle files."
277 # XXX podría ir en una clase base
278 self._dump_var(self.vars, pickle_vars)
279 self._dump_var(self.hosts, pickle_hosts)
282 r"_load() -> None :: Load all persistent data from pickle files."
283 # XXX podría ir en una clase base
284 self.vars = self._load_var(pickle_vars)
285 self.hosts = self._load_var(pickle_hosts)
287 def _pickle_filename(self, name):
288 r"_pickle_filename() -> string :: Construct a pickle filename."
289 # XXX podría ir en una clase base
290 return path.join(self.pickle_dir, name) + pickle_ext
292 def _dump_var(self, var, name):
293 r"_dump_var() -> None :: Dump a especific variable to a pickle file."
294 # XXX podría ir en una clase base
295 pkl_file = file(self._pickle_filename(name), 'wb')
296 pickle.dump(var, pkl_file, 2)
299 def _load_var(self, name):
300 r"_load_var() -> object :: Load a especific pickle file."
301 # XXX podría ir en una clase base
302 return pickle.load(file(self._pickle_filename(name)))
304 def _write_config(self):
305 r"_write_config() -> None :: Generate all the configuration files."
306 # XXX podría ir en una clase base, ver como generalizar variables a
307 # reemplazar en la template
308 out_file = file(path.join(self.config_dir, config_filename), 'w')
309 ctx = Context(out_file, hosts=self.hosts.values(), **self.vars)
310 self.template.render_context(ctx)
313 if __name__ == '__main__':
317 dhcp_handler = DhcpHandler()
321 print 'Variables:', dhcp_handler.list()
322 print dhcp_handler.show()
324 print 'Hosts:', dhcp_handler.host.list()
325 print dhcp_handler.host.show()
330 dhcp_handler.host.add('my_name','192.168.0.102','00:12:ff:56')
332 dhcp_handler.host.update('my_name','192.168.0.192','00:12:ff:56')
334 dhcp_handler.host.add('nico','192.168.0.188','00:00:00:00')
336 dhcp_handler.set('domain_name','baryon.com.ar')
339 dhcp_handler.set('sarasa','baryon.com.ar')
343 dhcp_handler.commit()
347 for f in (pickle_vars + pickle_ext, pickle_hosts + pickle_ext,