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
12 from seqtools import Sequence
17 from dispatcher import handler, HandlerError
20 class HandlerError(RuntimeError): pass
21 def handler(f): return f
23 __ALL__ = ('IpHandler',)
26 pickle_devices = 'devs'
28 template_dir = path.join(path.dirname(__file__), 'templates')
29 command_filename = 'command'
32 device_com = 'device.command'
33 ip_add_com = 'ip_add.command'
34 ip_del_com = 'ip_del.command'
35 ip_flush_com = 'ip_flush.command'
36 route_add_com = 'route_add.command'
37 route_del_com = 'route_del.command'
38 route_flush_com = 'route_flush.command'
40 class Error(HandlerError):
42 Error(command) -> Error instance :: Base IpHandler exception class.
44 All exceptions raised by the IpHandler inherits from this one, so you can
45 easily catch any IpHandler exception.
47 message - A descriptive error message.
50 def __init__(self, message):
51 r"Initialize the Error object. See class documentation for more info."
52 self.message = message
57 class DeviceError(Error):
59 def __init__(self, device):
60 self.message = 'Device error : "%s"' % device
62 class DeviceNotFoundError(DeviceError):
64 def __init__(self, device):
65 self.message = 'Device not found : "%s"' % device
67 class AddressError(Error):
69 def __init__(self, addr):
70 self.message = 'Address error : "%s"' % addr
72 class AddressNotFoundError(AddressError):
74 def __init__(self, address):
75 self.message = 'Address not found : "%s"' % address
77 class AddressAlreadyExistsError(AddressError):
79 def __init__(self, address):
80 self.message = 'Address already exists : "%s"' % address
82 class RouteError(Error):
84 def __init__(self, route):
85 self.message = 'Route error : "%s"' % route
87 class RouteNotFoundError(RouteError):
89 def __init__(self, route):
90 self.message = 'Route not found : "%s"' % route
92 class RouteAlreadyExistsError(RouteError):
94 def __init__(self, route):
95 self.message = 'Route already exists : "%s"' % route
97 class Route(Sequence):
99 def __init__(self, net_addr, prefix, gateway):
100 self.net_addr = net_addr
102 self.gateway = gateway
105 return(self.addr, self.prefix, self.gateway)
109 def __init__(self, devices, config_dir, ip_handler):
110 self.devices = devices
111 route_add_fn = path.join(template_dir, route_add_com)
112 route_del_fn = path.join(template_dir, route_del_com)
113 route_flush_fn = path.join(template_dir, route_flush_com)
114 self.route_add_template = Template(filename=route_add_fn)
115 self.route_del_template = Template(filename=route_del_fn)
116 self.route_flush_template = Template(filename=route_flush_fn)
117 self.config_dir = config_dir
118 self.ip_handler = ip_handler
121 def add(self, device, net_addr, prefix, gateway):
122 if not device in self.devices:
123 raise DeviceNotFoundError(device)
124 r = Route(net_addr, prefix, gateway)
126 self.devices[device].routes.index(r)
127 raise RouteAlreadyExistsError(net_addr + '/' + prefix + '->' + gateway)
129 out_file = file(path.join(self.config_dir, command_filename), 'w')
130 ctx = Context(out_file, dev=device, net_addr=net_addr, prefix=prefix, gateway=gateway)
131 self.route_add_template.render_context(ctx)
133 execute_command(self.config_dir)
134 self.devices[device].routes.append(r)
135 self.ip_handler.commit()
139 def delete(self, device, net_addr, prefix, gateway):
140 if not device in self.devices:
141 raise DeviceNotFoundError(device)
142 r = Route(net_addr, prefix, gateway)
144 #i = self.devices[device].routes.index(r)
145 #out_file = file(path.join(self.config_dir, command_filename), 'w')
146 #ctx = Context(out_file, dev=device, net_addr=net_addr, prefix=prefix, gateway=gateway)
147 #self.route_add_template.render_context(ctx)
149 #execute_command(self.config_dir)
150 #self.devices[device].routes.append(r)
151 #self.ip_handler.commit()
154 #raise RouteNotFoundError(net_addr + '/' + prefix + '->' + gateway)
157 def flush(self, device):
158 if not device in self.devices:
159 raise DeviceNotFoundError(device)
160 out_file = file(path.join(self.config_dir, command_filename), 'w')
161 ctx = Context(out_file, dev=device)
162 self.route_flush_template.render_context(ctx)
164 execute_command(self.config_dir)
165 self.devices[device].routes = list()
166 self.ip_handler.commit()
169 def list(self, device):
171 k = self.devices[device].routes.keys()
179 k = self.devices[device].routes.values()
184 class Address(Sequence):
186 def __init__(self, ip, prefix, broadcast):
189 self.broadcast = broadcast
192 return (self.ip, self.prefix, self.broadcast)
194 class AddressHandler:
196 def __init__(self, devices, config_dir, ip_handler):
197 self.devices = devices
198 self.config_dir = config_dir
199 ip_add_fn = path.join(template_dir, ip_add_com)
200 ip_del_fn = path.join(template_dir, ip_del_com)
201 ip_flush_fn = path.join(template_dir, ip_flush_com)
202 self.ip_add_template = Template(filename=ip_add_fn)
203 self.ip_del_template = Template(filename=ip_del_fn)
204 self.ip_flush_template = Template(filename=ip_flush_fn)
205 self.ip_handler = ip_handler
209 def add(self, device, ip, prefix, broadcast='+'):
210 if not device in self.devices:
211 raise DeviceNotFoundError(device)
212 if ip in self.devices[device].addrs:
213 raise AddressAlreadyExistsError(ip)
214 out_file = file(path.join(self.config_dir, command_filename), 'w')
215 ctx = Context(out_file, dev=device, addr=ip, prefix=prefix, broadcast=broadcast)
216 self.ip_add_template.render_context(ctx)
218 execute_command(self.config_dir)
219 self.devices[device].addrs[ip] = Address(ip, prefix, broadcast)
220 self.ip_handler.commit()
223 def delete(self, device, ip):
224 if not device in self.devices:
225 raise DeviceNotFoundError(device)
226 if not ip in self.devices[device].addrs:
227 raise AddressNotFoundError(ip)
228 out_file = file(path.join(self.config_dir, command_filename), 'w')
229 ctx = Context(out_file, dev=device, addr=ip, prefix=self.devices[device].addrs[ip].prefix)
230 self.ip_del_template.render_context(ctx)
232 execute_command(self.config_dir)
233 del self.devices[device].addrs[ip]
234 self.ip_handler.commit()
238 def flush(self, device):
239 if not device in self.devices:
240 raise DeviceNotFoundError(device)
241 out_file = file(path.join(self.config_dir, command_filename), 'w')
242 ctx = Context(out_file, dev=device)
243 self.ip_flush_template.render_context(ctx)
245 execute_command(self.config_dir)
246 self.devices[device].addrs = dict()
247 self.ip_handler.commit()
251 def list(self, device):
253 k = self.devices[device].addrs.keys()
259 def show(self, device):
261 k = self.devices[device].addrs.values()
266 class Device(Sequence):
268 def __init__(self, name):
274 return (self.name, self.addrs, self.routes)
278 def __init__(self, devices, config_dir = '.'):
279 self.devices = devices
280 dev_fn = path.join(template_dir, device_com)
281 self.device_template = Template(filename=dev_fn)
282 self.config_dir = config_dir
286 if name in self.devices:
287 out_file = file(path.join(self.config_dir, command_filename), 'w')
288 ctx = Context(out_file, dev=name, action='up')
289 self.device_template.render_context(ctx)
291 execute_command(self.config_dir)
293 raise DeviceNotFoundError(name)
296 def down(self, name):
297 if name in self.devices:
298 out_file = file(path.join(self.config_dir, command_filename), 'w')
299 ctx = Context(out_file, dev=name, action='down')
300 self.device_template.render_context(ctx)
302 execute_command(self.config_dir)
304 raise DeviceNotFoundError(name)
308 return self.devices.keys()
312 return self.devices.items()
314 def execute_command(config_dir):
315 out_file = file(path.join(config_dir, command_filename), 'r')
316 print out_file.read()
321 def __init__(self, pickle_dir='.', config_dir='.'):
322 r"Initialize DhcpHandler object, see class documentation for details."
324 self.pickle_dir = pickle_dir
325 self.config_dir = config_dir
330 # This is the first time the handler is used, create a basic
331 # setup using some nice defaults
337 self.addr = AddressHandler(self.devices, config_dir, self)
338 self.route = RouteHandler(self.devices, config_dir, self)
339 self.dev = DeviceHandler(self.devices, config_dir)
343 r"commit() -> None :: Commit the changes and reload the DHCP service."
344 #esto seria para poner en una interfaz
345 #y seria que hace el pickle deberia llamarse
346 #al hacerse un commit
352 r"rollback() -> None :: Discard the changes not yet commited."
356 r"_dump() -> None :: Dump all persistent data to pickle files."
357 # XXX podría ir en una clase base
358 self._dump_var(self.devices, pickle_devices)
362 r"_load() -> None :: Load all persistent data from pickle files."
363 # XXX podría ir en una clase base
364 self.devices = self._load_var(pickle_devices)
366 def _pickle_filename(self, name):
367 r"_pickle_filename() -> string :: Construct a pickle filename."
368 # XXX podría ir en una clase base
369 return path.join(self.pickle_dir, name) + pickle_ext
371 def _dump_var(self, var, name):
372 r"_dump_var() -> None :: Dump a especific variable to a pickle file."
373 # XXX podría ir en una clase base
374 pkl_file = file(self._pickle_filename(name), 'wb')
375 pickle.dump(var, pkl_file, 2)
378 def _load_var(self, name):
379 r"_load_var() -> object :: Load a especific pickle file."
380 # XXX podría ir en una clase base
381 return pickle.load(file(self._pickle_filename(name)))
383 def _write_config(self):
384 r"_write_config() -> None :: Execute all commands."
390 if __name__ == '__main__':
396 ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
397 ip.addr.add('eth0','192.168.0.26','24')
399 ip.addr.flush('eth0')
400 ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
401 ip.route.flush('eth0')
402 #ip.addr.delete('eth0','192.168.0.23')
403 #ip.addr.delete('eth0','192.168.0.26')