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"""get(name) -> CSV string :: List all the information of a host.
155 The host is returned as a CSV list of: hostname,ip,mac
157 if not name in self.hosts:
158 raise HostNotFoundError(name)
160 return '%s,%s,%s' % (h.name, h.ip, h.mac)
164 r"""list() -> CSV string :: List all the hostnames.
166 The list is returned as a single CSV line with all the hostnames.
168 return ','.join(self.hosts)
172 r"""show() -> CSV string :: List all the complete hosts information.
174 The hosts are returned as a CSV list with each host in a line, like:
177 hosts = self.hosts.values()
178 return '\n'.join('%s,%s,%s' % (h.name, h.ip, h.mac) for h in hosts)
181 r"""DhcpHandler([pickle_dir[, config_dir]]) -> DhcpHandler instance.
183 Handles DHCP service commands for the dhcpd program.
185 pickle_dir - Directory where to write the persistent configuration data.
187 config_dir - Directory where to store de generated configuration files.
189 Both defaults to the current working directory.
192 def __init__(self, pickle_dir='.', config_dir='.'):
193 r"Initialize DhcpHandler object, see class documentation for details."
194 self.pickle_dir = pickle_dir
195 self.config_dir = config_dir
196 filename = path.join(template_dir, config_filename)
197 self.template = Template(filename=filename)
201 # This is the first time the handler is used, create a basic
202 # setup using some nice defaults
205 domain_name = 'example.com',
206 dns_1 = 'ns1.example.com',
207 dns_2 = 'ns2.example.com',
208 net_address = '192.168.0.0',
209 net_mask = '255.255.255.0',
210 net_start = '192.168.0.100',
211 net_end = '192.168.0.200',
212 net_gateway = '192.168.0.1',
216 self.host = HostHandler(self.hosts)
219 def set(self, param, value):
220 r"set(param, value) -> None :: Set a DHCP parameter."
221 if not param in self.vars:
222 raise ParameterNotFoundError(param)
223 self.vars[param] = value
226 def get(self, param):
227 r"get(param) -> None :: Get a DHCP parameter."
228 if not param in self.vars:
229 raise ParameterNotFoundError(param)
230 return self.vars[param]
234 r"""list() -> CSV string :: List all the parameter names.
236 The list is returned as a single CSV line with all the names.
238 return ','.join(self.vars)
242 r"""show() -> CSV string :: List all the parameters (with their values).
244 The parameters are returned as a CSV list with each parameter in a
248 return '\n'.join(('%s,%s' % (k, v) for (k, v) in self.vars.items()))
252 r"start() -> None :: Start the DHCP service."
253 #esto seria para poner en una interfaz
254 #y seria el hook para arrancar el servicio
259 r"stop() -> None :: Stop the DHCP service."
260 #esto seria para poner en una interfaz
261 #y seria el hook para arrancar el servicio
266 r"restart() -> None :: Restart the DHCP service."
267 #esto seria para poner en una interfaz
268 #y seria el hook para arrancar el servicio
273 r"reload() -> None :: Reload the configuration of the DHCP service."
274 #esto seria para poner en una interfaz
275 #y seria el hook para arrancar el servicio
280 r"commit() -> None :: Commit the changes and reload the DHCP service."
281 #esto seria para poner en una interfaz
282 #y seria que hace el pickle deberia llamarse
283 #al hacerse un commit
290 r"rollback() -> None :: Discard the changes not yet commited."
294 r"_dump() -> None :: Dump all persistent data to pickle files."
295 # XXX podría ir en una clase base
296 self._dump_var(self.vars, pickle_vars)
297 self._dump_var(self.hosts, pickle_hosts)
300 r"_load() -> None :: Load all persistent data from pickle files."
301 # XXX podría ir en una clase base
302 self.vars = self._load_var(pickle_vars)
303 self.hosts = self._load_var(pickle_hosts)
305 def _pickle_filename(self, name):
306 r"_pickle_filename() -> string :: Construct a pickle filename."
307 # XXX podría ir en una clase base
308 return path.join(self.pickle_dir, name) + pickle_ext
310 def _dump_var(self, var, name):
311 r"_dump_var() -> None :: Dump a especific variable to a pickle file."
312 # XXX podría ir en una clase base
313 pkl_file = file(self._pickle_filename(name), 'wb')
314 pickle.dump(var, pkl_file, 2)
317 def _load_var(self, name):
318 r"_load_var() -> object :: Load a especific pickle file."
319 # XXX podría ir en una clase base
320 return pickle.load(file(self._pickle_filename(name)))
322 def _write_config(self):
323 r"_write_config() -> None :: Generate all the configuration files."
324 # XXX podría ir en una clase base, ver como generalizar variables a
325 # reemplazar en la template
326 out_file = file(path.join(self.config_dir, config_filename), 'w')
327 ctx = Context(out_file, hosts=self.hosts.values(), **self.vars)
328 self.template.render_context(ctx)
331 if __name__ == '__main__':
335 dhcp_handler = DhcpHandler()
339 print 'Variables:', dhcp_handler.list()
340 print dhcp_handler.show()
342 print 'Hosts:', dhcp_handler.host.list()
343 print dhcp_handler.host.show()
348 dhcp_handler.host.add('my_name','192.168.0.102','00:12:ff:56')
350 dhcp_handler.host.update('my_name','192.168.0.192','00:12:ff:56')
352 dhcp_handler.host.add('nico','192.168.0.188','00:00:00:00')
354 dhcp_handler.set('domain_name','baryon.com.ar')
357 dhcp_handler.set('sarasa','baryon.com.ar')
361 dhcp_handler.commit()
365 for f in (pickle_vars + pickle_ext, pickle_hosts + pickle_ext,