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.service.util import Restorable, ConfigWriter, InitdHandler, \
10 TransactionalHandler, SubHandler, call, \
11 get_network_devices, ListComposedSubHandler, \
12 DictComposedSubHandler, ListSubHandler, \
13 Device, Address, ExecutionError
15 __all__ = ('IpHandler', 'get_service')
18 def get_service(config):
19 return IpHandler(config.ip.pickle_dir, config.ip.config_dir)
24 def __init__(self, gateway, device):
25 self.gateway = gateway
29 return (self.gateway, self.device)
31 def __cmp__(self, other):
32 if self.gateway == other.gateway \
33 and self.device == other.device:
35 return cmp(id(self), id(other))
37 class HopHandler(ListSubHandler):
38 handler_help = u"Manage IP hops"
39 _cont_subhandler_attr = 'hops'
40 _cont_subhandler_class = Hop
42 @handler('Add a hop: add <device> <gateway>')
43 def add(self, dev, gw):
44 if not dev in self.parent.devices:
45 raise DeviceNotFoundError(device)
46 return ListSubHandler.add(self, dev, gw)
49 class Route(Sequence):
50 def __init__(self, net_addr, prefix, gateway):
51 self.net_addr = net_addr
53 self.gateway = gateway
55 def update(self, net_addr=None, prefix=None, gateway=None):
56 if net_addr is not None: self.net_addr = net_addr
57 if prefix is not None: self.prefix = prefix
58 if gateway is not None: self.gateway = gateway
61 return(self.net_addr, self.prefix, self.gateway)
63 def __cmp__(self, other):
64 if self.net_addr == other.net_addr \
65 and self.prefix == other.prefix \
66 and self.gateway == other.gateway:
68 return cmp(id(self), id(other))
70 class RouteHandler(ListComposedSubHandler):
71 handler_help = u"Manage IP routes"
72 _comp_subhandler_cont = 'devices'
73 _comp_subhandler_attr = 'routes'
74 _comp_subhandler_class = Route
76 @handler(u'Adds a route to : ip route add <net_addr> <prefix> <gateway> [device]')
77 def add(self, net_addr, prefix, gateway, dev=None):
79 ListComposedSubHandler.add(self, dev, net_addr, prefix, gateway)
81 r = Route(net_addr, prefix, gateway)
82 if not r in self.parent.no_device_routes:
83 self.parent.no_device_routes.append(r)
85 @handler("Deletes a route : ip route delete <route_number_in_show> [dev]")
86 def delete(self, index, dev=None):
88 ListComposedSubHandler.delete(self, dev, index)
91 del self.parent.no_device_routes[i]
93 @handler("Shows routes : ip route show [dev]")
94 def show(self, dev=None):
96 return ListComposedSubHandler.show(self, dev)
98 return self.parent.no_device_routes
100 class AddressHandler(DictComposedSubHandler):
101 handler_help = u"Manage IP addresses"
102 _comp_subhandler_cont = 'devices'
103 _comp_subhandler_attr = 'addrs'
104 _comp_subhandler_class = Address
107 class DeviceHandler(SubHandler):
109 handler_help = u"Manage network devices"
111 def __init__(self, parent):
112 log.debug(u'DeviceHandler(%r)', parent)
113 # FIXME remove templates to execute commands
114 from mako.template import Template
116 template_dir = path.join(path.dirname(__file__), 'templates')
117 dev_fn = path.join(template_dir, 'device')
118 self.device_template = Template(filename=dev_fn)
120 @handler(u'Bring the device up')
122 log.debug(u'DeviceHandler.up(%r)', name)
123 if name in self.parent.devices:
124 call(self.device_template.render(dev=name, action='up'), shell=True)
125 #bring up all the route asocitaed to the device
126 for route in self.parent.devices[name].routes:
128 log.debug(u'IpHandler.up: adding %r', route)
129 call(self.parent._render_config('route_add', dict(
131 net_addr = route.net_addr,
132 prefix = route.prefix,
133 gateway = route.gateway,
136 except ExecutionError, e:
137 log.debug(u'IpHandler.up: error adding %r -> %r', route, e)
138 self.parent._bring_up_no_dev_routes()
139 self.parent._restart_services()
141 log.debug(u'DeviceHandler.up: device not found')
142 raise DeviceNotFoundError(name)
144 @handler(u'Bring the device down')
145 def down(self, name):
146 log.debug(u'DeviceHandler.down(%r)', name)
147 if name in self.parent.devices:
148 call(self.device_template.render(dev=name, action='down'), shell=True)
149 self.parent._bring_up_no_dev_routes()
150 self.parent._restart_services()
152 log.debug(u'DeviceHandler.up: device not found')
153 raise DeviceNotFoundError(name)
155 @handler(u'List all devices')
157 log.debug(u'DeviceHandler.list()')
158 return self.parent.devices.keys()
160 @handler(u'Get information about a device')
162 log.debug(u'DeviceHandler.show()')
163 return self.parent.devices.items()
165 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
167 handler_help = u"Manage IP devices, addresses, routes and hops"
169 _persistent_attrs = ('devices','hops','no_device_routes')
171 _restorable_defaults = dict(
172 devices=get_network_devices(),
174 no_device_routes = list(),
177 _config_writer_files = ('device', 'ip_add', 'ip_del', 'ip_flush',
178 'route_add', 'route_del', 'route_flush', 'hop')
179 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
181 def __init__(self, pickle_dir='.', config_dir='.'):
182 r"Initialize DhcpHandler object, see class documentation for details."
183 log.debug(u'IpHandler(%r, %r)', pickle_dir, config_dir)
184 self._persistent_dir = pickle_dir
185 self._config_writer_cfg_dir = config_dir
186 self._config_build_templates()
189 self.addr = AddressHandler(self)
190 self.route = RouteHandler(self)
191 self.dev = DeviceHandler(self)
192 self.hop = HopHandler(self)
193 self.no_device_routes = list()
194 self.services = list()
196 def _write_config(self):
197 r"_write_config() -> None :: Execute all commands."
198 log.debug(u'IpHandler._write_config()')
199 for device in self.devices.values():
200 log.debug(u'IpHandler._write_config: processing device %s', device)
202 self._write_config_for_device(device)
203 self._bring_up_no_dev_routes()
206 def _bring_up_no_dev_routes(self):
207 log.debug(u'IpHandler._bring_up_no_dev_routes()')
208 for route in self.no_device_routes:
210 log.debug(u'IpHandler._bring_up_no_dev_routes: add %r', route)
211 call(self._render_config('route_add', dict(
213 net_addr = route.net_addr,
214 prefix = route.prefix,
215 gateway = route.gateway,
218 except ExecutionError, e:
219 log.debug(u'IpHandler._write_config: error flushing -> %r', e)
221 def _write_hops(self):
222 r"_write_hops() -> None :: Execute all hops."
223 log.debug(u'IpHandler._write_hops()')
225 log.debug(u'IpHandler._write_hops: we have hops: %r', self.hops)
227 log.debug(u'IpHandler._write_hops: flushing default hops')
228 call('ip route del default', shell=True)
229 except ExecutionError, e:
230 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
232 log.debug(u'IpHandler._write_hops: configuring hops')
233 #get hops for active devices
236 if h.device in self.devices:
237 if self.devices[h.device].active:
238 active_hops.append(h)
239 call(self._render_config('hop', dict(
243 except ExecutionError, e:
244 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
246 def _write_config_for_device(self, device):
247 r"_write_config_for_device(self, device) -> None :: Execute commands."
248 log.debug(u'IpHandler._write_config_for_device()')
250 log.debug(u'IpHandler._write_config_for_device: flushing routes...')
251 call(self._render_config('route_flush', dict(dev=device.name)),
253 except ExecutionError, e:
254 log.debug(u'IpHandler._write_config_for_device: error flushing '
257 log.debug(u'IpHandler._write_config_for_device: flushing addrs...')
258 call(self._render_config('ip_flush', dict(dev=device.name)),
260 except ExecutionError, e:
261 log.debug(u'IpHandler._write_config_for_device: error flushing '
263 for address in device.addrs.values():
264 broadcast = address.broadcast
265 if broadcast is None:
268 log.debug(u'IpHandler._write_config_for_device: adding %r',
270 call(self._render_config('ip_add', dict(
273 netmask = address.netmask,
275 broadcast = broadcast,
278 except ExecutionError, e:
279 log.debug(u'IpHandler._write_config_for_device: error adding '
281 for route in device.routes:
283 log.debug(u'IpHandler._write_config_for_device: adding %r',
285 call(self._render_config('route_add', dict(
287 net_addr = route.net_addr,
288 prefix = route.prefix,
289 gateway = route.gateway,
292 except ExecutionError, e:
293 log.debug(u'IpHandler._write_config_for_device: error adding '
296 def handle_timer(self):
297 log.debug(u'IpHandler.handle_timer()')
298 self.refresh_devices()
300 def refresh_devices(self):
301 log.debug(u'IpHandler.update_devices()')
302 devices = get_network_devices()
303 #add not registered and active devices
305 for k,v in devices.items():
306 if k not in self.devices:
307 log.debug(u'IpHandler.update_devices: adding %r', v)
309 elif not self.devices[k].active:
312 self._write_config_for_device(self.devices[k])
315 self._bring_up_no_dev_routes()
316 self._restart_services()
318 #mark inactive devices
319 for k in self.devices.keys():
322 log.debug(u'IpHandler.update_devices: removing %s', k)
323 self.devices[k].active = False
326 self._bring_up_no_dev_routes()
328 def _restart_services(self):
329 for s in self.services:
330 if s._service_running:
333 except ExecutionError:
337 except ExecutionError:
340 #hooks a service to the ip handler, so when
341 #a device is brought up one can restart the service
342 #that need to refresh their device list
343 def device_up_hook(self, serv):
344 if hasattr(serv, 'stop') and hasattr(serv, 'start'):
345 self.services.append(serv)
351 if __name__ == '__main__':
354 level = logging.DEBUG,
355 format = '%(asctime)s %(levelname)-8s %(message)s',
356 datefmt = '%H:%M:%S',
360 print '----------------------'
361 ip.hop.add('201.21.32.53','eth0')
362 ip.hop.add('205.65.65.25','eth1')
365 ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
366 ip.addr.add('eth0','192.168.0.26','24')
368 ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
369 ip.route.add('eth0','192.168.0.5','24','192.168.0.1')
371 ip.hop.delete('201.21.32.53','eth0')
372 ip.route.clear('eth0')