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, ListSubHandler, \
13 Device, Address, ExecutionError
15 __all__ = ('IpHandler',)
20 def __init__(self, gateway, device):
21 self.gateway = gateway
25 return (self.gateway, self.device)
27 def __cmp__(self, other):
28 if self.gateway == other.gateway \
29 and self.device == other.device:
31 return cmp(id(self), id(other))
33 class HopHandler(ListSubHandler):
34 handler_help = u"Manage IP hops"
35 _cont_subhandler_attr = 'hops'
36 _cont_subhandler_class = Hop
38 @handler('Add a hop: add <device> <gateway>')
39 def add(self, dev, gw):
40 if not dev in self.parent.devices:
41 raise DeviceNotFoundError(device)
42 return ListSubHandler.add(self, dev, gw)
45 class Route(Sequence):
46 def __init__(self, net_addr, prefix, gateway):
47 self.net_addr = net_addr
49 self.gateway = gateway
51 def update(self, net_addr=None, prefix=None, gateway=None):
52 if net_addr is not None: self.net_addr = net_addr
53 if prefix is not None: self.prefix = prefix
54 if gateway is not None: self.gateway = gateway
57 return(self.net_addr, self.prefix, self.gateway)
59 def __cmp__(self, other):
60 if self.net_addr == other.net_addr \
61 and self.prefix == other.prefix \
62 and self.gateway == other.gateway:
64 return cmp(id(self), id(other))
66 class RouteHandler(ListComposedSubHandler):
67 handler_help = u"Manage IP routes"
68 _comp_subhandler_cont = 'devices'
69 _comp_subhandler_attr = 'routes'
70 _comp_subhandler_class = Route
72 @handler(u'Adds a route to : ip route add <net_addr> <prefix> <gateway> [device]')
73 def add(self, net_addr, prefix, gateway, dev=None):
75 ListComposedSubHandler.add(self, dev, net_addr, prefix, gateway)
77 r = Route(net_addr, prefix, gateway)
78 if not r in self.parent.no_device_routes:
79 self.parent.no_device_routes.append(r)
81 @handler("Deletes a route : ip route delete <route_number_in_show> [dev]")
82 def delete(self, index, dev=None):
84 ListComposedSubHandler.delete(self, dev, index)
87 del self.parent.no_device_routes[i]
89 @handler("Shows routes : ip route show [dev]")
90 def show(self, dev=None):
92 return ListComposedSubHandler.show(self, dev)
94 return self.parent.no_device_routes
96 class AddressHandler(DictComposedSubHandler):
97 handler_help = u"Manage IP addresses"
98 _comp_subhandler_cont = 'devices'
99 _comp_subhandler_attr = 'addrs'
100 _comp_subhandler_class = Address
103 class DeviceHandler(SubHandler):
105 handler_help = u"Manage network devices"
107 def __init__(self, parent):
108 log.debug(u'DeviceHandler(%r)', parent)
109 # FIXME remove templates to execute commands
110 from mako.template import Template
112 template_dir = path.join(path.dirname(__file__), 'templates')
113 dev_fn = path.join(template_dir, 'device')
114 self.device_template = Template(filename=dev_fn)
116 @handler(u'Bring the device up')
118 log.debug(u'DeviceHandler.up(%r)', name)
119 if name in self.parent.devices:
120 call(self.device_template.render(dev=name, action='up'), shell=True)
121 #bring up all the route asocitaed to the device
122 for route in self.parent.devices[name].routes:
124 log.debug(u'IpHandler.up: adding %r', route)
125 call(self.parent._render_config('route_add', dict(
127 net_addr = route.net_addr,
128 prefix = route.prefix,
129 gateway = route.gateway,
132 except ExecutionError, e:
133 log.debug(u'IpHandler.up: error adding %r -> %r', route, e)
134 self.parent._bring_up_no_dev_routes()
135 self.parent._restart_services()
137 log.debug(u'DeviceHandler.up: device not found')
138 raise DeviceNotFoundError(name)
140 @handler(u'Bring the device down')
141 def down(self, name):
142 log.debug(u'DeviceHandler.down(%r)', name)
143 if name in self.parent.devices:
144 call(self.device_template.render(dev=name, action='down'), shell=True)
145 self.parent._bring_up_no_dev_routes()
146 self.parent._restart_services()
148 log.debug(u'DeviceHandler.up: device not found')
149 raise DeviceNotFoundError(name)
151 @handler(u'List all devices')
153 log.debug(u'DeviceHandler.list()')
154 return self.parent.devices.keys()
156 @handler(u'Get information about a device')
158 log.debug(u'DeviceHandler.show()')
159 return self.parent.devices.items()
161 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
163 handler_help = u"Manage IP devices, addresses, routes and hops"
165 _persistent_attrs = ('devices','hops','no_device_routes')
167 _restorable_defaults = dict(
168 devices=get_network_devices(),
170 no_device_routes = list(),
173 _config_writer_files = ('device', 'ip_add', 'ip_del', 'ip_flush',
174 'route_add', 'route_del', 'route_flush', 'hop')
175 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
177 def __init__(self, pickle_dir='.', config_dir='.'):
178 r"Initialize DhcpHandler object, see class documentation for details."
179 log.debug(u'IpHandler(%r, %r)', pickle_dir, config_dir)
180 self._persistent_dir = pickle_dir
181 self._config_writer_cfg_dir = config_dir
182 self._config_build_templates()
185 self.addr = AddressHandler(self)
186 self.route = RouteHandler(self)
187 self.dev = DeviceHandler(self)
188 self.hop = HopHandler(self)
189 self.no_device_routes = list()
190 self.services = list()
192 def _write_config(self):
193 r"_write_config() -> None :: Execute all commands."
194 log.debug(u'IpHandler._write_config()')
195 for device in self.devices.values():
196 log.debug(u'IpHandler._write_config: processing device %s', device)
198 self._write_config_for_device(device)
199 self._bring_up_no_dev_routes()
202 def _bring_up_no_dev_routes(self):
203 log.debug(u'IpHandler._bring_up_no_dev_routes()')
204 for route in self.no_device_routes:
206 log.debug(u'IpHandler._bring_up_no_dev_routes: add %r', route)
207 call(self._render_config('route_add', dict(
209 net_addr = route.net_addr,
210 prefix = route.prefix,
211 gateway = route.gateway,
214 except ExecutionError, e:
215 log.debug(u'IpHandler._write_config: error flushing -> %r', e)
217 def _write_hops(self):
218 r"_write_hops() -> None :: Execute all hops."
219 log.debug(u'IpHandler._write_hops()')
221 log.debug(u'IpHandler._write_hops: we have hops: %r', self.hops)
223 log.debug(u'IpHandler._write_hops: flushing default hops')
224 call('ip route del default', shell=True)
225 except ExecutionError, e:
226 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
228 log.debug(u'IpHandler._write_hops: configuring hops')
229 #get hops for active devices
232 if h.device in self.devices:
233 if self.devices[h.device].active:
234 active_hops.append(h)
235 call(self._render_config('hop', dict(
239 except ExecutionError, e:
240 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
242 def _write_config_for_device(self, device):
243 r"_write_config_for_device(self, device) -> None :: Execute commands."
244 log.debug(u'IpHandler._write_config_for_device()')
246 log.debug(u'IpHandler._write_config_for_device: flushing routes...')
247 call(self._render_config('route_flush', dict(dev=device.name)),
249 except ExecutionError, e:
250 log.debug(u'IpHandler._write_config_for_device: error flushing '
253 log.debug(u'IpHandler._write_config_for_device: flushing addrs...')
254 call(self._render_config('ip_flush', dict(dev=device.name)),
256 except ExecutionError, e:
257 log.debug(u'IpHandler._write_config_for_device: error flushing '
259 for address in device.addrs.values():
260 broadcast = address.broadcast
261 if broadcast is None:
264 log.debug(u'IpHandler._write_config_for_device: adding %r',
266 call(self._render_config('ip_add', dict(
269 netmask = address.netmask,
271 broadcast = broadcast,
274 except ExecutionError, e:
275 log.debug(u'IpHandler._write_config_for_device: error adding '
277 for route in device.routes:
279 log.debug(u'IpHandler._write_config_for_device: adding %r',
281 call(self._render_config('route_add', dict(
283 net_addr = route.net_addr,
284 prefix = route.prefix,
285 gateway = route.gateway,
288 except ExecutionError, e:
289 log.debug(u'IpHandler._write_config_for_device: error adding '
292 def handle_timer(self):
293 log.debug(u'IpHandler.handle_timer()')
294 self.refresh_devices()
296 def refresh_devices(self):
297 log.debug(u'IpHandler.update_devices()')
298 devices = get_network_devices()
299 #add not registered and active devices
301 for k,v in devices.items():
302 if k not in self.devices:
303 log.debug(u'IpHandler.update_devices: adding %r', v)
305 elif not self.devices[k].active:
308 self._write_config_for_device(self.devices[k])
311 self._bring_up_no_dev_routes()
312 self._restart_services()
314 #mark inactive devices
315 for k in self.devices.keys():
318 log.debug(u'IpHandler.update_devices: removing %s', k)
319 self.devices[k].active = False
322 self._bring_up_no_dev_routes()
324 def _restart_services(self):
325 for s in self.services:
326 if s._service_running:
329 except ExecutionError:
333 except ExecutionError:
336 #hooks a service to the ip handler, so when
337 #a device is brought up one can restart the service
338 #that need to refresh their device list
339 def device_up_hook(self, serv):
340 if hasattr(serv, 'stop') and hasattr(serv, 'start'):
341 self.services.append(serv)
347 if __name__ == '__main__':
350 level = logging.DEBUG,
351 format = '%(asctime)s %(levelname)-8s %(message)s',
352 datefmt = '%H:%M:%S',
356 print '----------------------'
357 ip.hop.add('201.21.32.53','eth0')
358 ip.hop.add('205.65.65.25','eth1')
361 ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
362 ip.addr.add('eth0','192.168.0.26','24')
364 ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
365 ip.route.add('eth0','192.168.0.5','24','192.168.0.1')
367 ip.hop.delete('201.21.32.53','eth0')
368 ip.route.clear('eth0')