]> git.llucax.com Git - software/pymin.git/blob - pymin/services/ip/__init__.py
Remove unused formencode validators imports.
[software/pymin.git] / pymin / services / ip / __init__.py
1 # vim: set encoding=utf-8 et sw=4 sts=4 :
2
3 from subprocess import Popen, PIPE
4 from os import path
5 import logging ; log = logging.getLogger('pymin.services.ip')
6
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, \
13                                 ExecutionError
14
15 __all__ = ('IpHandler',)
16
17 # TODO: convertir HopHandler a ComposedSubHandler
18
19 class HopError(HandlerError):
20
21     def __init__(self, hop):
22         self.message = u'Hop error : "%s"' % hop
23
24 class HopNotFoundError(HopError):
25
26     def __init__(self, hop):
27         self.message = u'Hop not found : "%s"' % hop
28
29 class HopAlreadyExistsError(HopError):
30
31     def __init__(self, hop):
32         self.message = u'Hop already exists : "%s"' % hop
33
34
35 class Hop(Sequence):
36
37     def __init__(self, gateway, device):
38         self.gateway = gateway
39         self.device = device
40
41     def as_tuple(self):
42         return (self.gateway, self.device)
43
44     def __cmp__(self, other):
45         if self.gateway == other.gateway \
46                 and self.device == other.device:
47             return 0
48         return cmp(id(self), id(other))
49
50 class HopHandler(Handler):
51
52     def __init__(self, parent):
53         self.parent = parent
54
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)
59         h = Hop(gw, dev)
60         try:
61             self.parent.hops.index(h)
62             raise HopAlreadyExistsError(gw  + '->' + dev)
63         except ValueError:
64             self.parent.hops.append(h)
65
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)
70         h = Hop(gw, dev)
71         try:
72             self.parent.hops.remove(h)
73         except ValueError:
74             raise HopNotFoundError(gw + '->' + dev)
75
76     @handler(u'Lists hops : list <dev>')
77     def list(self, device):
78         try:
79             k = self.parent.hops.keys()
80         except ValueError:
81             k = list()
82         return k
83
84     @handler(u'Get information about all hops: show <dev>')
85     def show(self, device):
86         try:
87             k = self.parent.hops.values()
88         except ValueError:
89             k = list()
90         return k
91
92 class Route(Sequence):
93     def __init__(self, net_addr, prefix, gateway):
94         self.net_addr = net_addr
95         self.prefix = prefix
96         self.gateway = gateway
97
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
102
103     def as_tuple(self):
104         return(self.net_addr, self.prefix, self.gateway)
105
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:
110             return 0
111         return cmp(id(self), id(other))
112
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
118
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):
121         if dev is not None:
122             ListComposedSubHandler.add(self, dev, net_addr, prefix, gateway)
123         else:
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)
127
128     @handler("Deletes a route : ip route delete <route_number_in_show> [dev]")
129     def delete(self, index, dev=None):
130         if dev is not None:
131             ListComposedSubHandler.delete(self, dev, index)
132         else:
133             i = int(index)
134             del self.parent.no_device_routes[i]
135
136     @handler("Shows routes : ip route show [dev]")
137     def show(self, dev=None):
138         if dev is not None:
139             return ListComposedSubHandler.show(self, dev)
140         else:
141             return self.parent.no_device_routes
142
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
148
149
150 class DeviceHandler(SubHandler):
151
152     handler_help = u"Manage network devices"
153
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
158         self.parent = parent
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)
162
163     @handler(u'Bring the device up')
164     def up(self, name):
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:
170                 try:
171                     log.debug(u'IpHandler.up: adding %r', route)
172                     call(self.parent._render_config('route_add', dict(
173                             dev = name,
174                             net_addr = route.net_addr,
175                             prefix = route.prefix,
176                             gateway = route.gateway,
177                         )
178                     ), shell=True)
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()
183         else:
184             log.debug(u'DeviceHandler.up: device not found')
185             raise DeviceNotFoundError(name)
186
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()
194         else:
195             log.debug(u'DeviceHandler.up: device not found')
196             raise DeviceNotFoundError(name)
197
198     @handler(u'List all devices')
199     def list(self):
200         log.debug(u'DeviceHandler.list()')
201         return self.parent.devices.keys()
202
203     @handler(u'Get information about a device')
204     def show(self):
205         log.debug(u'DeviceHandler.show()')
206         return self.parent.devices.items()
207
208 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
209
210     handler_help = u"Manage IP devices, addresses, routes and hops"
211
212     _persistent_attrs = ('devices','hops','no_device_routes')
213
214     _restorable_defaults = dict(
215                             devices=get_network_devices(),
216                             hops = list(),
217                             no_device_routes = list(),
218                             )
219
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')
223
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()
230         self._restore()
231         self._write_config()
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()
238
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)
244             if device.active:
245                 self._write_config_for_device(device)
246         self._bring_up_no_dev_routes()
247         self._write_hops()
248
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:
252             try:
253                 log.debug(u'IpHandler._bring_up_no_dev_routes: add %r', route)
254                 call(self._render_config('route_add', dict(
255                         dev = None,
256                         net_addr = route.net_addr,
257                         prefix = route.prefix,
258                         gateway = route.gateway,
259                     )
260                 ), shell=True)
261             except ExecutionError, e:
262                 log.debug(u'IpHandler._write_config: error flushing -> %r', e)
263
264     def _write_hops(self):
265         r"_write_hops() -> None :: Execute all hops."
266         log.debug(u'IpHandler._write_hops()')
267         if self.hops:
268             log.debug(u'IpHandler._write_hops: we have hops: %r', self.hops)
269             try:
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)
274             try:
275                 log.debug(u'IpHandler._write_hops: configuring hops')
276                 #get hops for active devices
277                 active_hops = dict()
278                 for h in self.hops:
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(
283                     hops = active_hops,
284                         )
285                 ), shell=True)
286             except ExecutionError, e:
287                 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
288
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()')
292         try:
293             log.debug(u'IpHandler._write_config_for_device: flushing routes...')
294             call(self._render_config('route_flush', dict(dev=device.name)),
295                         shell=True)
296         except ExecutionError, e:
297             log.debug(u'IpHandler._write_config_for_device: error flushing '
298                         u'-> %r', e)
299         try:
300             log.debug(u'IpHandler._write_config_for_device: flushing addrs...')
301             call(self._render_config('ip_flush', dict(dev=device.name)),
302                         shell=True)
303         except ExecutionError, e:
304             log.debug(u'IpHandler._write_config_for_device: error flushing '
305                         u'-> %r', e)
306         for address in device.addrs.values():
307             broadcast = address.broadcast
308             if broadcast is None:
309                 broadcast = '+'
310             try:
311                 log.debug(u'IpHandler._write_config_for_device: adding %r',
312                             address)
313                 call(self._render_config('ip_add', dict(
314                     dev = device.name,
315                     addr = address.ip,
316                     netmask = address.netmask,
317                     peer = address.peer,
318                     broadcast = broadcast,
319                     )
320                 ), shell=True)
321             except ExecutionError, e:
322                 log.debug(u'IpHandler._write_config_for_device: error adding '
323                             u'-> %r', e)
324         for route in device.routes:
325             try:
326                 log.debug(u'IpHandler._write_config_for_device: adding %r',
327                             route)
328                 call(self._render_config('route_add', dict(
329                         dev = device.name,
330                         net_addr = route.net_addr,
331                         prefix = route.prefix,
332                         gateway = route.gateway,
333                     )
334                 ), shell=True)
335             except ExecutionError, e:
336                 log.debug(u'IpHandler._write_config_for_device: error adding '
337                             u'-> %r', e)
338
339     def handle_timer(self):
340         log.debug(u'IpHandler.handle_timer()')
341         self.refresh_devices()
342
343     def refresh_devices(self):
344         log.debug(u'IpHandler.update_devices()')
345         devices = get_network_devices()
346         #add not registered and active devices
347         go_active = False
348         for k,v in devices.items():
349             if k not in self.devices:
350                 log.debug(u'IpHandler.update_devices: adding %r', v)
351                 self.devices[k] = v
352             elif not self.devices[k].active:
353                 self.active = True
354                 go_active = True
355                 self._write_config_for_device(self.devices[k])
356         if go_active:
357             self._write_hops()
358             self._bring_up_no_dev_routes()
359             self._restart_services()
360
361         #mark inactive devices
362         for k in self.devices.keys():
363             go_down = False
364             if k not in devices:
365                 log.debug(u'IpHandler.update_devices: removing %s', k)
366                 self.devices[k].active = False
367                 go_down = True
368             if go_down:
369                 self._bring_up_no_dev_routes()
370
371     def _restart_services(self):
372         for s in self.services:
373             if s._service_running:
374                 try:
375                      s.stop()
376                 except ExecutionError:
377                     pass
378                 try:
379                     s.start()
380                 except ExecutionError:
381                     pass
382
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)
389
390
391
392
393
394 if __name__ == '__main__':
395
396     logging.basicConfig(
397         level   = logging.DEBUG,
398         format  = '%(asctime)s %(levelname)-8s %(message)s',
399         datefmt = '%H:%M:%S',
400     )
401
402     ip = IpHandler()
403     print '----------------------'
404     ip.hop.add('201.21.32.53','eth0')
405     ip.hop.add('205.65.65.25','eth1')
406     ip.commit()
407     ip.dev.up('eth0')
408     ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
409     ip.addr.add('eth0','192.168.0.26','24')
410     ip.commit()
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')
413     ip.commit()
414     ip.hop.delete('201.21.32.53','eth0')
415     ip.route.clear('eth0')
416     ip.commit()
417
418
419