]> git.llucax.com Git - software/pymin.git/blob - pymin/services/ip/__init__.py
Support for inactive devices added in IPHandler.
[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
6 from pymin.seqtools import Sequence
7 from pymin.dispatcher import handler, HandlerError, Handler
8 from pymin.services.util import Restorable, ConfigWriter, InitdHandler, \
9                                 TransactionalHandler, SubHandler, call, \
10                                 get_network_devices, ListComposedSubHandler, \
11                                 DictComposedSubHandler, Device, Address, ExecutionError
12
13 __ALL__ = ('IpHandler',)
14
15 # TODO: convertir HopHandler a ComposedSubHandler
16
17 class HopError(HandlerError):
18
19     def __init__(self, hop):
20         self.message = u'Hop error : "%s"' % hop
21
22 class HopNotFoundError(HopError):
23
24     def __init__(self, hop):
25         self.message = u'Hop not found : "%s"' % hop
26
27 class HopAlreadyExistsError(HopError):
28
29     def __init__(self, hop):
30         self.message = u'Hop already exists : "%s"' % hop
31
32
33 class Hop(Sequence):
34
35     def __init__(self, gateway, device):
36         self.gateway = gateway
37         self.device = device
38
39     def as_tuple(self):
40         return (self.gateway, self.device)
41
42     def __cmp__(self, other):
43         if self.gateway == other.gateway \
44                 and self.device == other.device:
45             return 0
46         return cmp(id(self), id(other))
47
48 class HopHandler(Handler):
49
50     def __init__(self, parent):
51         self.parent = parent
52
53     @handler('Adds a hop : add <gateway> <device>')
54     def add(self, gw, dev):
55         if not dev in self.parent.devices:
56             raise DeviceNotFoundError(device)
57         h = Hop(gw, dev)
58         try:
59             self.parent.hops.index(h)
60             raise HopAlreadyExistsError(gw  + '->' + dev)
61         except ValueError:
62             self.parent.hops.append(h)
63
64     @handler(u'Deletes a hop : delete <gateway> <device>')
65     def delete(self, gw, dev):
66         if not dev in self.parent.devices:
67             raise DeviceNotFoundError(device)
68         h = Hop(gw, dev)
69         try:
70             self.parent.hops.remove(h)
71         except ValueError:
72             raise HopNotFoundError(gw + '->' + dev)
73
74     @handler(u'Lists hops : list <dev>')
75     def list(self, device):
76         try:
77             k = self.parent.hops.keys()
78         except ValueError:
79             k = list()
80         return k
81
82     @handler(u'Get information about all hops: show <dev>')
83     def show(self, device):
84         try:
85             k = self.parent.hops.values()
86         except ValueError:
87             k = list()
88         return k
89
90 class Route(Sequence):
91     def __init__(self, net_addr, prefix, gateway):
92         self.net_addr = net_addr
93         self.prefix = prefix
94         self.gateway = gateway
95     def update(self, net_addr=None, prefix=None, gateway=None):
96         if net_addr is not None: self.net_addr = net_addr
97         if prefix is not None: self.prefix = prefix
98         if gateway is not None: self.gateway = gateway
99     def as_tuple(self):
100         return(self.net_addr, self.prefix, self.gateway)
101
102 class RouteHandler(ListComposedSubHandler):
103     handler_help = u"Manage IP routes"
104     _comp_subhandler_cont = 'devices'
105     _comp_subhandler_attr = 'routes'
106     _comp_subhandler_class = Route
107
108
109 class AddressHandler(DictComposedSubHandler):
110     handler_help = u"Manage IP addresses"
111     _comp_subhandler_cont = 'devices'
112     _comp_subhandler_attr = 'addrs'
113     _comp_subhandler_class = Address
114
115
116 class DeviceHandler(SubHandler):
117
118     handler_help = u"Manage network devices"
119
120     def __init__(self, parent):
121         # FIXME remove templates to execute commands
122         from mako.template import Template
123         self.parent = parent
124         template_dir = path.join(path.dirname(__file__), 'templates')
125         dev_fn = path.join(template_dir, 'device')
126         self.device_template = Template(filename=dev_fn)
127
128     @handler(u'Bring the device up')
129     def up(self, name):
130         if name in self.parent.devices:
131             call(self.device_template.render(dev=name, action='up'), shell=True)
132         else:
133             raise DeviceNotFoundError(name)
134
135     @handler(u'Bring the device down')
136     def down(self, name):
137         if name in self.parent.devices:
138             call(self.device_template.render(dev=name, action='down'), shell=True)
139         else:
140             raise DeviceNotFoundError(name)
141
142     @handler(u'List all devices')
143     def list(self):
144         return self.parent.devices.keys()
145
146     @handler(u'Get information about a device')
147     def show(self):
148         return self.parent.devices.items()
149
150 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
151
152     handler_help = u"Manage IP devices, addresses, routes and hops"
153
154     _persistent_attrs = ('devices','hops')
155
156     _restorable_defaults = dict(
157                             devices=get_network_devices(),
158                             hops = list()
159                             )
160
161     _config_writer_files = ('device', 'ip_add', 'ip_del', 'ip_flush',
162                             'route_add', 'route_del', 'route_flush', 'hop')
163     _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
164
165     def __init__(self, pickle_dir='.', config_dir='.'):
166         r"Initialize DhcpHandler object, see class documentation for details."
167         self._persistent_dir = pickle_dir
168         self._config_writer_cfg_dir = config_dir
169         self._config_build_templates()
170         self._restore()
171         self._write_config()
172         self.addr = AddressHandler(self)
173         self.route = RouteHandler(self)
174         self.dev = DeviceHandler(self)
175         self.hop = HopHandler(self)
176
177     def _write_config(self):
178         r"_write_config() -> None :: Execute all commands."
179         for device in self.devices.values():
180             if device.active:
181                 self._write_config_for_device(device)
182         self._write_hops()
183
184     def _write_hops(self):
185         r"_write_hops() -> None :: Execute all hops."
186         if self.hops:
187             try:
188                 call('ip route del default', shell=True)
189             except ExecutionError, e:
190                 print e
191             try:
192                 #get hops for active devices
193                 active_hops = dict()
194                 for h in self.hops:
195                     if h.device in self.devices:
196                         if self.devices[h.device].active
197                             active_hops.append(h)
198                 call(self._render_config('hop', dict(
199                     hops = active_hops,
200                         )
201                 ), shell=True)
202             except ExecutionError, e:
203                 print e
204
205     def _write_config_for_device(self, device):
206         r"_write_config_for_device(self, device) -> None :: Execute all commands for a device."
207         try:
208             call(self._render_config('route_flush', dict(dev=device.name)), shell=True)
209         except ExecutionError, e:
210             print e
211         try:
212             call(self._render_config('ip_flush', dict(dev=device.name)), shell=True)
213         except ExecutionError, e:
214             print e
215         for address in device.addrs.values():
216             broadcast = address.broadcast
217             if broadcast is None:
218                 broadcast = '+'
219             try:
220                 call(self._render_config('ip_add', dict(
221                     dev = device.name,
222                     addr = address.ip,
223                     netmask = address.netmask,
224                     peer = address.peer,
225                     broadcast = broadcast,
226                     )
227                 ), shell=True)
228             except ExecutionError, e:
229                 print e
230         for route in device.routes:
231             try:
232                 call(self._render_config('route_add', dict(
233                         dev = device.name,
234                         net_addr = route.net_addr,
235                         prefix = route.prefix,
236                         gateway = route.gateway,
237                     )
238                 ), shell=True)
239             except ExecutionError, e:
240                 print e
241
242     def handle_timer(self):
243         self.refresh_devices()
244
245
246     def refresh_devices(self):
247         devices = get_network_devices()
248         #add not registered and active devices
249         go_active = False
250         for k,v in devices.items():
251             if k not in self.devices:
252                 self.devices[k] = v
253             else if not self.devices[k].active
254                 self.active = True
255                 go_active = True
256                 self._write_config_for_device(self.devices[k])
257         if go_active:
258             self._write_hops()
259         #mark inactive devices
260         for k in self.devices.keys():
261             if k not in devices:
262                 self.devices[k].active = False
263
264
265
266 if __name__ == '__main__':
267
268     ip = IpHanlder()
269     print '----------------------'
270     ip.hop.add('201.21.32.53','eth0')
271     ip.hop.add('205.65.65.25','eth1')
272     ip.commit()
273     ip.dev.up('eth0')
274     ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
275     ip.addr.add('eth0','192.168.0.26','24')
276     ip.commit()
277     ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
278     ip.route.add('eth0','192.168.0.5','24','192.168.0.1')
279     ip.commit()
280     ip.hop.delete('201.21.32.53','eth0')
281     ip.route.clear('eth0')
282     ip.commit()
283
284
285