]> git.llucax.com Git - software/pymin.git/blob - pymin/services/ip/__init__.py
Merge branch 'master' of or3st3s@baryon.com.ar:workspace/pymin into suse
[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
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 class Address(Sequence):
109     def __init__(self, ip, netmask, broadcast=None):
110         self.ip = ip
111         self.netmask = netmask
112         self.broadcast = broadcast
113     def update(self, netmask=None, broadcast=None):
114         if netmask is not None: self.netmask = netmask
115         if broadcast is not None: self.broadcast = broadcast
116     def as_tuple(self):
117         return (self.ip, self.netmask, self.broadcast)
118
119 class AddressHandler(DictComposedSubHandler):
120     handler_help = u"Manage IP addresses"
121     _comp_subhandler_cont = 'devices'
122     _comp_subhandler_attr = 'addrs'
123     _comp_subhandler_class = Address
124
125 class Device(Sequence):
126     def __init__(self, name, mac):
127         self.name = name
128         self.mac = mac
129         self.addrs = dict()
130         self.routes = list()
131     def as_tuple(self):
132         return (self.name, self.mac)
133
134 class DeviceHandler(SubHandler):
135
136     handler_help = u"Manage network devices"
137
138     def __init__(self, parent):
139         # FIXME remove templates to execute commands
140         from mako.template import Template
141         self.parent = parent
142         template_dir = path.join(path.dirname(__file__), 'templates')
143         dev_fn = path.join(template_dir, 'device')
144         self.device_template = Template(filename=dev_fn)
145
146     @handler(u'Bring the device up')
147     def up(self, name):
148         if name in self.parent.devices:
149             call(self.device_template.render(dev=name, action='up'), shell=True)
150         else:
151             raise DeviceNotFoundError(name)
152
153     @handler(u'Bring the device down')
154     def down(self, name):
155         if name in self.parent.devices:
156             call(self.device_template.render(dev=name, action='down'), shell=True)
157         else:
158             raise DeviceNotFoundError(name)
159
160     @handler(u'List all devices')
161     def list(self):
162         return self.parent.devices.keys()
163
164     @handler(u'Get information about a device')
165     def show(self):
166         return self.parent.devices.items()
167
168 class IpHandler(Restorable, ConfigWriter, TransactionalHandler):
169
170     handler_help = u"Manage IP devices, addresses, routes and hops"
171
172     _persistent_attrs = ('devices','hops')
173
174     _restorable_defaults = dict(
175                             devices=dict((dev, Device(dev, mac))
176                                 for (dev, mac) in get_network_devices().items()),
177                             hops = list()
178                             )
179
180     _config_writer_files = ('device', 'ip_add', 'ip_del', 'ip_flush',
181                             'route_add', 'route_del', 'route_flush', 'hop')
182     _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
183
184     def __init__(self, pickle_dir='.', config_dir='.'):
185         r"Initialize DhcpHandler object, see class documentation for details."
186         self._persistent_dir = pickle_dir
187         self._config_writer_cfg_dir = config_dir
188         self._config_build_templates()
189         self._restore()
190         self._write_config()
191         self.addr = AddressHandler(self)
192         self.route = RouteHandler(self)
193         self.dev = DeviceHandler(self)
194         self.hop = HopHandler(self)
195
196     def _write_config(self):
197         r"_write_config() -> None :: Execute all commands."
198         for device in self.devices.values():
199             call(self._render_config('route_flush', dict(dev=device.name)), shell=True)
200             call(self._render_config('ip_flush', dict(dev=device.name)), shell=True)
201             for address in device.addrs.values():
202                 broadcast = address.broadcast
203                 if broadcast is None:
204                     broadcast = '+'
205                 call(self._render_config('ip_add', dict(
206                         dev = device.name,
207                         addr = address.ip,
208                         netmask = address.netmask,
209                         broadcast = broadcast,
210                     )
211                 ), shell=True)
212             for route in device.routes:
213                 call(self._render_config('route_add', dict(
214                         dev = device.name,
215                         net_addr = route.net_addr,
216                         prefix = route.prefix,
217                         gateway = route.gateway,
218                     )
219                 ), shell=True)
220
221         if self.hops:
222             call('ip route del default', shell=True)
223             call(self._render_config('hop', dict(
224                         hops = self.hops,
225                     )
226                  ), shell=True)
227
228
229     def handle_timer(self):
230         self.refresh_devices()
231
232
233     def refresh_devices(self):
234         devices = get_network_devices()
235         #add not registered devices
236         for k,v in devices.items():
237             if k not in self.devices:
238                 self.devices[k] = Device(k,v)
239         #delete dead devices
240         for k in self.devices.keys():
241             if k not in devices:
242                 del self.devices[k]
243
244
245
246 if __name__ == '__main__':
247
248     ip = IpHanlder()
249     print '----------------------'
250     ip.hop.add('201.21.32.53','eth0')
251     ip.hop.add('205.65.65.25','eth1')
252     ip.commit()
253     ip.dev.up('eth0')
254     ip.addr.add('eth0','192.168.0.23','24','192.168.255.255')
255     ip.addr.add('eth0','192.168.0.26','24')
256     ip.commit()
257     ip.route.add('eth0','192.168.0.0','24','192.168.0.1')
258     ip.route.add('eth0','192.168.0.5','24','192.168.0.1')
259     ip.commit()
260     ip.hop.delete('201.21.32.53','eth0')
261     ip.route.clear('eth0')
262     ip.commit()
263
264
265