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')
26 r"""Host(name, ip, mac) -> Host instance :: Class representing a host.
28 name - Host name, should be a fully qualified name, but no checks are done.
29 ip - IP assigned to the hostname.
30 mac - MAC address to associate to the hostname.
33 def __init__(self, name, ip, mac):
34 r"Initialize Host object, see class documentation for details."
40 r"""HostHandler(hosts) -> HostHandler instance :: Handle a list of hosts.
42 This class is a helper for DhcpHandler to do all the work related to hosts
45 hosts - A dictionary with string keys (hostnames) and Host instances values.
48 def __init__(self, hosts):
49 r"Initialize HostHandler object, see class documentation for details."
53 def add(self, name, ip, mac):
54 r"add(name, ip, mac) -> None :: Add a host to the hosts list."
55 # XXX deberia indexar por hostname o por ip? o por mac? :)
56 # o por nada... Puedo tener un nombre con muchas IPs? Una IP con muchos
57 # nombres? Una MAC con muchas IP? una MAC con muchos nombre? Etc...
58 self.hosts[name] = Host(name, ip, mac)
61 def update(self, name, ip=None, mac=None):
62 r"update(name[, ip[, mac]]) -> None :: Update a host of the hosts list."
63 if not name in self.hosts:
64 raise KeyError('Host not found')
66 self.hosts[name].ip = ip
68 self.hosts[name].mac = mac
71 def delete(self, name):
72 r"delete(name) -> None :: Delete a host of the hosts list."
73 if not name in self.hosts:
74 raise KeyError('Host not found')
79 r"""list() -> CSV string :: List all the hostnames.
81 The list is returned as a single CSV line with all the hostnames.
83 return ','.join(self.hosts)
87 r"""show() -> CSV string :: List all the complete hosts information.
89 The hosts are returned as a CSV list with each host in a line, like:
92 hosts = self.hosts.values()
93 return '\n'.join('%s,%s,%s' % (h.name, h.ip, h.mac) for h in hosts)
96 r"""DhcpHandler([pickle_dir[, config_dir]]) -> DhcpHandler instance.
98 Handles DHCP service commands for the dhcpd program.
100 pickle_dir - Directory where to write the persistent configuration data.
102 config_dir - Directory where to store de generated configuration files.
104 Both defaults to the current working directory.
107 def __init__(self, pickle_dir='.', config_dir='.'):
108 r"Initialize DhcpHandler object, see class documentation for details."
109 self.pickle_dir = pickle_dir
110 self.config_dir = config_dir
111 filename = path.join(template_dir, config_filename)
112 self.template = Template(filename=filename)
116 # This is the first time the handler is used, create a basic
117 # setup using some nice defaults
120 domain_name = 'example.com',
121 dns_1 = 'ns1.example.com',
122 dns_2 = 'ns2.example.com',
123 net_address = '192.168.0.0',
124 net_mask = '255.255.255.0',
125 net_start = '192.168.0.100',
126 net_end = '192.168.0.200',
127 net_gateway = '192.168.0.1',
131 self.host = HostHandler(self.hosts)
134 def set(self, param, value):
135 r"set(param, value) -> None :: Set a DHCP parameter."
136 if not param in self.vars:
137 raise KeyError('Parameter ' + param + ' not found')
138 self.vars[param] = value
142 r"""list() -> CSV string :: List all the parameter names.
144 The list is returned as a single CSV line with all the names.
146 return ','.join(self.vars)
150 r"""show() -> CSV string :: List all the parameters (with their values).
152 The parameters are returned as a CSV list with each parameter in a
156 return '\n'.join(('%s,%s' % (k, v) for (k, v) in self.vars.items()))
160 r"start() -> None :: Start the DHCP service."
161 #esto seria para poner en una interfaz
162 #y seria el hook para arrancar el servicio
167 r"stop() -> None :: Stop the DHCP service."
168 #esto seria para poner en una interfaz
169 #y seria el hook para arrancar el servicio
174 r"restart() -> None :: Restart the DHCP service."
175 #esto seria para poner en una interfaz
176 #y seria el hook para arrancar el servicio
181 r"reload() -> None :: Reload the configuration of the DHCP service."
182 #esto seria para poner en una interfaz
183 #y seria el hook para arrancar el servicio
188 r"commit() -> None :: Commit the changes and reload the DHCP service."
189 #esto seria para poner en una interfaz
190 #y seria que hace el pickle deberia llamarse
191 #al hacerse un commit
198 r"rollback() -> None :: Discard the changes not yet commited."
202 r"_dump() -> None :: Dump all persistent data to pickle files."
203 # XXX podría ir en una clase base
204 self._dump_var(self.vars, pickle_vars)
205 self._dump_var(self.hosts, pickle_hosts)
208 r"_load() -> None :: Load all persistent data from pickle files."
209 # XXX podría ir en una clase base
210 self.vars = self._load_var(pickle_vars)
211 self.hosts = self._load_var(pickle_hosts)
213 def _pickle_filename(self, name):
214 r"_pickle_filename() -> string :: Construct a pickle filename."
215 # XXX podría ir en una clase base
216 return path.join(self.pickle_dir, name) + pickle_ext
218 def _dump_var(self, var, name):
219 r"_dump_var() -> None :: Dump a especific variable to a pickle file."
220 # XXX podría ir en una clase base
221 pkl_file = file(self._pickle_filename(name), 'wb')
222 pickle.dump(var, pkl_file, 2)
225 def _load_var(self, name):
226 r"_load_var() -> object :: Load a especific pickle file."
227 # XXX podría ir en una clase base
228 return pickle.load(file(self._pickle_filename(name)))
230 def _write_config(self):
231 r"_write_config() -> None :: Generate all the configuration files."
232 # XXX podría ir en una clase base, ver como generalizar variables a
233 # reemplazar en la template
234 out_file = file(path.join(self.config_dir, config_filename), 'w')
235 ctx = Context(out_file, hosts=self.hosts.values(), **self.vars)
236 self.template.render_context(ctx)
239 if __name__ == '__main__':
243 dhcp_handler = DhcpHandler()
247 print 'Variables:', dhcp_handler.list()
248 print dhcp_handler.show()
250 print 'Hosts:', dhcp_handler.host.list()
251 print dhcp_handler.host.show()
256 dhcp_handler.host.add('my_name','192.168.0.102','00:12:ff:56')
258 dhcp_handler.host.update('my_name','192.168.0.192','00:12:ff:56')
260 dhcp_handler.host.add('nico','192.168.0.188','00:00:00:00')
262 dhcp_handler.set('domain_name','baryon.com.ar')
265 dhcp_handler.set('sarasa','baryon.com.ar')
269 dhcp_handler.commit()
273 for f in (pickle_vars + pickle_ext, pickle_hosts + pickle_ext,