]> git.llucax.com Git - software/pymin.git/blob - services/ip/handler.py
Remove configuration examples.
[software/pymin.git] / services / ip / handler.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.service.util import Restorable, ConfigWriter, InitdHandler, \
10                                TransactionalHandler, SubHandler, call, \
11                                get_network_devices, ListComposedSubHandler, \
12                                DictComposedSubHandler, ListSubHandler, \
13                                Device, Address, ExecutionError
14
15 __all__ = ('IpHandler')
16
17
18 class Hop(Sequence):
19
20     def __init__(self, gateway, device):
21         self.gateway = gateway
22         self.device = device
23
24     def as_tuple(self):
25         return (self.gateway, self.device)
26
27     def __cmp__(self, other):
28         if self.gateway == other.gateway \
29                 and self.device == other.device:
30             return 0
31         return cmp(id(self), id(other))
32
33 class HopHandler(ListSubHandler):
34     handler_help = u"Manage IP hops"
35     _cont_subhandler_attr = 'hops'
36     _cont_subhandler_class = Hop
37
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)
43
44
45 class Route(Sequence):
46     def __init__(self, net_addr, prefix, gateway):
47         self.net_addr = net_addr
48         self.prefix = prefix
49         self.gateway = gateway
50
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
55
56     def as_tuple(self):
57         return(self.net_addr, self.prefix, self.gateway)
58
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:
63             return 0
64         return cmp(id(self), id(other))
65
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
71
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):
74         if dev is not None:
75             ListComposedSubHandler.add(self, dev, net_addr, prefix, gateway)
76         else:
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)
80
81     @handler("Deletes a route : ip route delete <route_number_in_show> [dev]")
82     def delete(self, index, dev=None):
83         if dev is not None:
84             ListComposedSubHandler.delete(self, dev, index)
85         else:
86             i = int(index)
87             del self.parent.no_device_routes[i]
88
89     @handler("Shows routes : ip route show [dev]")
90     def show(self, dev=None):
91         if dev is not None:
92             return ListComposedSubHandler.show(self, dev)
93         else:
94             return self.parent.no_device_routes
95
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
101
102
103 class DeviceHandler(SubHandler):
104
105     handler_help = u"Manage network devices"
106
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
111         self.parent = parent
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)
115
116     @handler(u'Bring the device up')
117     def up(self, name):
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:
123                 try:
124                     log.debug(u'IpHandler.up: adding %r', route)
125                     call(self.parent._render_config('route_add', dict(
126                             dev = name,
127                             net_addr = route.net_addr,
128                             prefix = route.prefix,
129                             gateway = route.gateway,
130                         )
131                     ), shell=True)
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()
136         else:
137             log.debug(u'DeviceHandler.up: device not found')
138             raise DeviceNotFoundError(name)
139
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()
147         else:
148             log.debug(u'DeviceHandler.up: device not found')
149             raise DeviceNotFoundError(name)
150
151     @handler(u'List all devices')
152     def list(self):
153         log.debug(u'DeviceHandler.list()')
154         return self.parent.devices.keys()
155
156     @handler(u'Get information about a device')
157     def show(self):
158         log.debug(u'DeviceHandler.show()')
159         return self.parent.devices.items()
160
161 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
162
163     handler_help = u"Manage IP devices, addresses, routes and hops"
164
165     _persistent_attrs = ('devices','hops','no_device_routes')
166
167     _restorable_defaults = dict(
168                             devices=get_network_devices(),
169                             hops = list(),
170                             no_device_routes = list(),
171                             )
172
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')
176
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()
183         self._restore()
184         self._write_config()
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()
191
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)
197             if device.active:
198                 self._write_config_for_device(device)
199         self._bring_up_no_dev_routes()
200         self._write_hops()
201
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:
205             try:
206                 log.debug(u'IpHandler._bring_up_no_dev_routes: add %r', route)
207                 call(self._render_config('route_add', dict(
208                         dev = None,
209                         net_addr = route.net_addr,
210                         prefix = route.prefix,
211                         gateway = route.gateway,
212                     )
213                 ), shell=True)
214             except ExecutionError, e:
215                 log.debug(u'IpHandler._write_config: error flushing -> %r', e)
216
217     def _write_hops(self):
218         r"_write_hops() -> None :: Execute all hops."
219         log.debug(u'IpHandler._write_hops()')
220         if self.hops:
221             log.debug(u'IpHandler._write_hops: we have hops: %r', self.hops)
222             try:
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)
227             try:
228                 log.debug(u'IpHandler._write_hops: configuring hops')
229                 #get hops for active devices
230                 active_hops = dict()
231                 for h in self.hops:
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(
236                     hops = active_hops,
237                         )
238                 ), shell=True)
239             except ExecutionError, e:
240                 log.debug(u'IpHandler._write_hops: error adding -> %r', e)
241
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()')
245         try:
246             log.debug(u'IpHandler._write_config_for_device: flushing routes...')
247             call(self._render_config('route_flush', dict(dev=device.name)),
248                         shell=True)
249         except ExecutionError, e:
250             log.debug(u'IpHandler._write_config_for_device: error flushing '
251                         u'-> %r', e)
252         try:
253             log.debug(u'IpHandler._write_config_for_device: flushing addrs...')
254             call(self._render_config('ip_flush', dict(dev=device.name)),
255                         shell=True)
256         except ExecutionError, e:
257             log.debug(u'IpHandler._write_config_for_device: error flushing '
258                         u'-> %r', e)
259         for address in device.addrs.values():
260             broadcast = address.broadcast
261             if broadcast is None:
262                 broadcast = '+'
263             try:
264                 log.debug(u'IpHandler._write_config_for_device: adding %r',
265                             address)
266                 call(self._render_config('ip_add', dict(
267                     dev = device.name,
268                     addr = address.ip,
269                     netmask = address.netmask,
270                     peer = address.peer,
271                     broadcast = broadcast,
272                     )
273                 ), shell=True)
274             except ExecutionError, e:
275                 log.debug(u'IpHandler._write_config_for_device: error adding '
276                             u'-> %r', e)
277         for route in device.routes:
278             try:
279                 log.debug(u'IpHandler._write_config_for_device: adding %r',
280                             route)
281                 call(self._render_config('route_add', dict(
282                         dev = device.name,
283                         net_addr = route.net_addr,
284                         prefix = route.prefix,
285                         gateway = route.gateway,
286                     )
287                 ), shell=True)
288             except ExecutionError, e:
289                 log.debug(u'IpHandler._write_config_for_device: error adding '
290                             u'-> %r', e)
291
292     def handle_timer(self):
293         log.debug(u'IpHandler.handle_timer()')
294         self.refresh_devices()
295
296     def refresh_devices(self):
297         log.debug(u'IpHandler.update_devices()')
298         devices = get_network_devices()
299         #add not registered and active devices
300         go_active = False
301         for k,v in devices.items():
302             if k not in self.devices:
303                 log.debug(u'IpHandler.update_devices: adding %r', v)
304                 self.devices[k] = v
305             elif not self.devices[k].active:
306                 self.active = True
307                 go_active = True
308                 self._write_config_for_device(self.devices[k])
309         if go_active:
310             self._write_hops()
311             self._bring_up_no_dev_routes()
312             self._restart_services()
313
314         #mark inactive devices
315         for k in self.devices.keys():
316             go_down = False
317             if k not in devices:
318                 log.debug(u'IpHandler.update_devices: removing %s', k)
319                 self.devices[k].active = False
320                 go_down = True
321             if go_down:
322                 self._bring_up_no_dev_routes()
323
324     def _restart_services(self):
325         for s in self.services:
326             if s._service_running:
327                 try:
328                      s.stop()
329                 except ExecutionError:
330                     pass
331                 try:
332                     s.start()
333                 except ExecutionError:
334                     pass
335
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)
342
343
344
345
346
347 if __name__ == '__main__':
348
349     logging.basicConfig(
350         level   = logging.DEBUG,
351         format  = '%(asctime)s %(levelname)-8s %(message)s',
352         datefmt = '%H:%M:%S',
353     )
354
355     ip = IpHandler()
356     print '----------------------'
357     ip.hop.add('201.21.32.53','eth0')
358     ip.hop.add('205.65.65.25','eth1')
359     ip.commit()
360     ip.dev.up('eth0')
361     ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
362     ip.addr.add('eth0','192.168.0.26','24')
363     ip.commit()
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')
366     ip.commit()
367     ip.hop.delete('201.21.32.53','eth0')
368     ip.route.clear('eth0')
369     ip.commit()
370
371
372