1 # vim: set encoding=utf-8 et sw=4 sts=4 :
3 from subprocess import Popen, PIPE
5 import logging ; log = logging.getLogger('pymin.services.ip')
7 from pymin.seqtools import Sequence
8 from pymin.dispatcher import handler, HandlerError, Handler
9 from pymin.services.util import Restorable, ConfigWriter, InitdHandler, \
10 TransactionalHandler, SubHandler, call, \
11 get_network_devices, ListComposedSubHandler, \
12 DictComposedSubHandler, Device, Address, \
15 __all__ = ('IpHandler',)
17 # TODO: convertir HopHandler a ComposedSubHandler
19 class HopError(HandlerError):
21 def __init__(self, hop):
22 self.message = u'Hop error : "%s"' % hop
24 class HopNotFoundError(HopError):
26 def __init__(self, hop):
27 self.message = u'Hop not found : "%s"' % hop
29 class HopAlreadyExistsError(HopError):
31 def __init__(self, hop):
32 self.message = u'Hop already exists : "%s"' % hop
37 def __init__(self, gateway, device):
38 self.gateway = gateway
42 return (self.gateway, self.device)
44 def __cmp__(self, other):
45 if self.gateway == other.gateway \
46 and self.device == other.device:
48 return cmp(id(self), id(other))
50 class HopHandler(Handler):
52 def __init__(self, parent):
55 @handler('Adds a hop : add <gateway> <device>')
56 def add(self, gw, dev):
57 if not dev in self.parent.devices:
58 raise DeviceNotFoundError(device)
61 self.parent.hops.index(h)
62 raise HopAlreadyExistsError(gw + '->' + dev)
64 self.parent.hops.append(h)
66 @handler(u'Deletes a hop : delete <gateway> <device>')
67 def delete(self, gw, dev):
68 if not dev in self.parent.devices:
69 raise DeviceNotFoundError(device)
72 self.parent.hops.remove(h)
74 raise HopNotFoundError(gw + '->' + dev)
76 @handler(u'Lists hops : list <dev>')
77 def list(self, device):
79 k = self.parent.hops.keys()
84 @handler(u'Get information about all hops: show <dev>')
85 def show(self, device):
87 k = self.parent.hops.values()
92 class Route(Sequence):
93 def __init__(self, net_addr, prefix, gateway):
94 self.net_addr = net_addr
96 self.gateway = gateway
98 def update(self, net_addr=None, prefix=None, gateway=None):
99 if net_addr is not None: self.net_addr = net_addr
100 if prefix is not None: self.prefix = prefix
101 if gateway is not None: self.gateway = gateway
104 return(self.net_addr, self.prefix, self.gateway)
106 def __cmp__(self, other):
107 if self.net_addr == other.net_addr \
108 and self.prefix == other.prefix \
109 and self.gateway == other.gateway:
111 return cmp(id(self), id(other))
113 class RouteHandler(ListComposedSubHandler):
114 handler_help = u"Manage IP routes"
115 _comp_subhandler_cont = 'devices'
116 _comp_subhandler_attr = 'routes'
117 _comp_subhandler_class = Route
119 @handler(u'Adds a route to : ip route add <net_addr> <prefix> <gateway> [device]')
120 def add(self, net_addr, prefix, gateway, dev=None):
122 ListComposedSubHandler.add(self, dev, net_addr, prefix, gateway)
124 r = Route(net_addr, prefix, gateway)
125 if not r in self.parent.no_device_routes:
126 self.parent.no_device_routes.append(r)
128 @handler("Deletes a route : ip route delete <route_number_in_show> [dev]")
129 def delete(self, index, dev=None):
131 ListComposedSubHandler.delete(self, dev, index)
134 del self.parent.no_device_routes[i]
136 @handler("Shows routes : ip route show [dev]")
137 def show(self, dev=None):
139 return ListComposedSubHandler.show(self, dev)
141 return self.parent.no_device_routes
143 class AddressHandler(DictComposedSubHandler):
144 handler_help = u"Manage IP addresses"
145 _comp_subhandler_cont = 'devices'
146 _comp_subhandler_attr = 'addrs'
147 _comp_subhandler_class = Address
150 class DeviceHandler(SubHandler):
152 handler_help = u"Manage network devices"
154 def __init__(self, parent):
155 log.debug(u'DeviceHandler(%r)', parent)
156 # FIXME remove templates to execute commands
157 from mako.template import Template
159 template_dir = path.join(path.dirname(__file__), 'templates')
160 dev_fn = path.join(template_dir, 'device')
161 self.device_template = Template(filename=dev_fn)
163 @handler(u'Bring the device up')
165 log.debug(u'DeviceHandler.up(%r)', name)
166 if name in self.parent.devices:
167 call(self.device_template.render(dev=name, action='up'), shell=True)
168 #bring up all the route asocitaed to the device
169 for route in self.parent.devices[name].routes:
171 log.debug(u'IpHandler.up: adding %r', route)
172 call(self.parent._render_config('route_add', dict(
174 net_addr = route.net_addr,
175 prefix = route.prefix,
176 gateway = route.gateway,
179 except ExecutionError, e:
180 log.debug(u'IpHandler.up: error adding %r -> %r', route, e)
181 self.parent._bring_up_no_dev_routes()
182 self.parent._restart_services()
184 log.debug(u'DeviceHandler.up: device not found')
185 raise DeviceNotFoundError(name)
187 @handler(u'Bring the device down')
188 def down(self, name):
189 log.debug(u'DeviceHandler.down(%r)', name)
190 if name in self.parent.devices:
191 call(self.device_template.render(dev=name, action='down'), shell=True)
192 self.parent._bring_up_no_dev_routes()
193 self.parent._restart_services()
195 log.debug(u'DeviceHandler.up: device not found')
196 raise DeviceNotFoundError(name)
198 @handler(u'List all devices')
200 log.debug(u'DeviceHandler.list()')
201 return self.parent.devices.keys()
203 @handler(u'Get information about a device')
205 log.debug(u'DeviceHandler.show()')
206 return self.parent.devices.items()
208 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
210 handler_help = u"Manage IP devices, addresses, routes and hops"
212 _persistent_attrs = ('devices','hops','no_device_routes')
214 _restorable_defaults = dict(
215 devices=get_network_devices(),
217 no_device_routes = list(),
220 _config_writer_files = ('device', 'ip_add', 'ip_del', 'ip_flush',
221 'route_add', 'route_del', 'route_flush', 'hop')
222 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
224 def __init__(self, pickle_dir='.', config_dir='.'):
225 r"Initialize DhcpHandler object, see class documentation for details."
226 log.debug(u'IpHandler(%r, %r)', pickle_dir, config_dir)
227 self._persistent_dir = pickle_dir
228 self._config_writer_cfg_dir = config_dir
229 self._config_build_templates()
232 self.addr = AddressHandler(self)
233 self.route = RouteHandler(self)
234 self.dev = DeviceHandler(self)
235 self.hop = HopHandler(self)
236 self.no_device_routes = list()
237 self.services = list()
239 def _write_config(self):
240 r"_write_config() -> None :: Execute all commands."
241 log.debug(u'IpHandler._write_config()')
242 for device in self.devices.values():
243 log.debug(u'IpHandler._write_config: processing device %s', device)
245 self._write_config_for_device(device)
246 self._bring_up_no_dev_routes()
249 def _bring_up_no_dev_routes(self):
250 log.debug(u'IpHandler._bring_up_no_dev_routes()')
251 for route in self.no_device_routes:
253 log.debug(u'IpHandler._bring_up_no_dev_routes: add %r', route)
254 call(self._render_config('route_add', dict(
256 net_addr = route.net_addr,
257 prefix = route.prefix,
258 gateway = route.gateway,
261 except ExecutionError, e:
262 log.debug(u'IpHandler._write_config: error flushing -> %r', e)
264 def _write_hops(self):
265 r"_write_hops() -> None :: Execute all hops."
266 log.debug(u'IpHandler._write_hops()')
268 log.debug(u'IpHandler._write_hops: we have hops: %r', self.hops)
270 log.debug(u'IpHandler._write_hops: flushing default hops')
271 call('ip route del default', shell=True)
272 except ExecutionError, e:
273 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
275 log.debug(u'IpHandler._write_hops: configuring hops')
276 #get hops for active devices
279 if h.device in self.devices:
280 if self.devices[h.device].active:
281 active_hops.append(h)
282 call(self._render_config('hop', dict(
286 except ExecutionError, e:
287 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
289 def _write_config_for_device(self, device):
290 r"_write_config_for_device(self, device) -> None :: Execute commands."
291 log.debug(u'IpHandler._write_config_for_device()')
293 log.debug(u'IpHandler._write_config_for_device: flushing routes...')
294 call(self._render_config('route_flush', dict(dev=device.name)),
296 except ExecutionError, e:
297 log.debug(u'IpHandler._write_config_for_device: error flushing '
300 log.debug(u'IpHandler._write_config_for_device: flushing addrs...')
301 call(self._render_config('ip_flush', dict(dev=device.name)),
303 except ExecutionError, e:
304 log.debug(u'IpHandler._write_config_for_device: error flushing '
306 for address in device.addrs.values():
307 broadcast = address.broadcast
308 if broadcast is None:
311 log.debug(u'IpHandler._write_config_for_device: adding %r',
313 call(self._render_config('ip_add', dict(
316 netmask = address.netmask,
318 broadcast = broadcast,
321 except ExecutionError, e:
322 log.debug(u'IpHandler._write_config_for_device: error adding '
324 for route in device.routes:
326 log.debug(u'IpHandler._write_config_for_device: adding %r',
328 call(self._render_config('route_add', dict(
330 net_addr = route.net_addr,
331 prefix = route.prefix,
332 gateway = route.gateway,
335 except ExecutionError, e:
336 log.debug(u'IpHandler._write_config_for_device: error adding '
339 def handle_timer(self):
340 log.debug(u'IpHandler.handle_timer()')
341 self.refresh_devices()
343 def refresh_devices(self):
344 log.debug(u'IpHandler.update_devices()')
345 devices = get_network_devices()
346 #add not registered and active devices
348 for k,v in devices.items():
349 if k not in self.devices:
350 log.debug(u'IpHandler.update_devices: adding %r', v)
352 elif not self.devices[k].active:
355 self._write_config_for_device(self.devices[k])
358 self._bring_up_no_dev_routes()
359 self._restart_services()
361 #mark inactive devices
362 for k in self.devices.keys():
365 log.debug(u'IpHandler.update_devices: removing %s', k)
366 self.devices[k].active = False
369 self._bring_up_no_dev_routes()
371 def _restart_services(self):
372 for s in self.services:
373 if s._service_running:
376 except ExecutionError:
380 except ExecutionError:
383 #hooks a service to the ip handler, so when
384 #a device is brought up one can restart the service
385 #that need to refresh their device list
386 def device_up_hook(self, serv):
387 if hasattr(serv, 'stop') and hasattr(serv, 'start'):
388 self.services.append(serv)
394 if __name__ == '__main__':
397 level = logging.DEBUG,
398 format = '%(asctime)s %(levelname)-8s %(message)s',
399 datefmt = '%H:%M:%S',
403 print '----------------------'
404 ip.hop.add('201.21.32.53','eth0')
405 ip.hop.add('205.65.65.25','eth1')
408 ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
409 ip.addr.add('eth0','192.168.0.26','24')
411 ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
412 ip.route.add('eth0','192.168.0.5','24','192.168.0.1')
414 ip.hop.delete('201.21.32.53','eth0')
415 ip.route.clear('eth0')