merge -r 411
[nepi.git] / src / nepi / testbeds / planetlab / interfaces.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from constants import TESTBED_ID
5 import nepi.util.ipaddr2 as ipaddr2
6 import nepi.util.server as server
7 import plcapi
8 import subprocess
9 import os
10 import os.path
11 import random
12 import ipaddr
13 import functools
14
15 import tunproto
16
17 class NodeIface(object):
18     def __init__(self, api=None):
19         if not api:
20             api = plcapi.PLCAPI()
21         self._api = api
22         
23         # Attributes
24         self.primary = True
25
26         # These get initialized at configuration time
27         self.address = None
28         self.lladdr = None
29         self.netprefix = None
30         self.netmask = None
31         self.broadcast = True
32         self._interface_id = None
33
34         # These get initialized when the iface is connected to its node
35         self.node = None
36
37         # These get initialized when the iface is connected to the internet
38         self.has_internet = False
39
40     def __str__(self):
41         return "%s<ip:%s/%s up mac:%s>" % (
42             self.__class__.__name__,
43             self.address, self.netmask,
44             self.lladdr,
45         )
46     
47     __repr__ = __str__
48
49     def add_address(self, address, netprefix, broadcast):
50         raise RuntimeError, "Cannot add explicit addresses to public interface"
51     
52     def pick_iface(self, siblings):
53         """
54         Picks an interface using the PLCAPI to query information about the node.
55         
56         Needs an assigned node.
57         
58         Params:
59             siblings: other NodeIface elements attached to the same node
60         """
61         
62         if self.node is None or self.node._node_id is None:
63             raise RuntimeError, "Cannot pick interface without an assigned node"
64         
65         avail = self._api.GetInterfaces(
66             node_id=self.node._node_id, 
67             is_primary=self.primary,
68             fields=('interface_id','mac','netmask','ip') )
69         
70         used = set([sibling._interface_id for sibling in siblings
71                     if sibling._interface_id is not None])
72         
73         for candidate in avail:
74             candidate_id = candidate['interface_id']
75             if candidate_id not in used:
76                 # pick it!
77                 self._interface_id = candidate_id
78                 self.address = candidate['ip']
79                 self.lladdr = candidate['mac']
80                 self.netprefix = candidate['netmask']
81                 self.netmask = ipaddr2.ipv4_dot2mask(self.netprefix) if self.netprefix else None
82                 return
83         else:
84             raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
85
86     def validate(self):
87         if not self.has_internet:
88             raise RuntimeError, "All external interface devices must be connected to the Internet"
89     
90
91 class _CrossIface(object):
92     def __init__(self, proto, addr, port, cipher):
93         self.tun_proto = proto
94         self.tun_addr = addr
95         self.tun_port = port
96         self.tun_cipher = cipher
97         
98         # Cannot access cross peers
99         self.peer_proto_impl = None
100     
101     def __str__(self):
102         return "%s%r" % (
103             self.__class__.__name__,
104             ( self.tun_proto,
105               self.tun_addr,
106               self.tun_port,
107               self.tun_cipher ) 
108         )
109     
110     __repr__ = __str__
111
112 class TunIface(object):
113     _PROTO_MAP = tunproto.TUN_PROTO_MAP
114     _KIND = 'TUN'
115
116     def __init__(self, api=None):
117         if not api:
118             api = plcapi.PLCAPI()
119         self._api = api
120         
121         # Attributes
122         self.address = None
123         self.netprefix = None
124         self.netmask = None
125         
126         self.up = None
127         self.mtu = None
128         self.snat = False
129         self.txqueuelen = None
130         self.pointopoint = None
131         
132         # Enabled traces
133         self.capture = False
134
135         # These get initialized when the iface is connected to its node
136         self.node = None
137         
138         # These get initialized when the iface is connected to any filter
139         self.filter_module = None
140         
141         # These get initialized when the iface is configured
142         self.external_iface = None
143         
144         # These get initialized when the iface is configured
145         # They're part of the TUN standard attribute set
146         self.tun_port = None
147         self.tun_addr = None
148         self.tun_cipher = "AES"
149         
150         # These get initialized when the iface is connected to its peer
151         self.peer_iface = None
152         self.peer_proto = None
153         self.peer_addr = None
154         self.peer_port = None
155         self.peer_proto_impl = None
156         self._delay_recover = False
157
158         # same as peer proto, but for execute-time standard attribute lookups
159         self.tun_proto = None 
160         
161         
162         # Generate an initial random cryptographic key to use for tunnelling
163         # Upon connection, both endpoints will agree on a common one based on
164         # this one.
165         self.tun_key = ( ''.join(map(chr, [ 
166                     r.getrandbits(8) 
167                     for i in xrange(32) 
168                     for r in (random.SystemRandom(),) ])
169                 ).encode("base64").strip() )        
170         
171
172     def __str__(self):
173         return "%s<ip:%s/%s %s%s%s>" % (
174             self.__class__.__name__,
175             self.address, self.netprefix,
176             " up" if self.up else " down",
177             " snat" if self.snat else "",
178             (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
179         )
180     
181     __repr__ = __str__
182     
183     @property
184     def if_name(self):
185         if self.peer_proto_impl:
186             return self.peer_proto_impl.if_name
187
188     def routes_here(self, route):
189         """
190         Returns True if the route should be attached to this interface
191         (ie, it references a gateway in this interface's network segment)
192         """
193         if self.address and self.netprefix:
194             addr, prefix = self.address, self.netprefix
195             pointopoint = self.pointopoint
196             if not pointopoint:
197                 pointopoint = self.peer_iface.address
198             
199             if pointopoint:
200                 prefix = 32
201                 
202             dest, destprefix, nexthop, metric = route
203             
204             myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
205             gwIp = ipaddr.IPNetwork(nexthop)
206             
207             if pointopoint:
208                 peerIp = ipaddr.IPNetwork(pointopoint)
209                 
210                 if gwIp == peerIp:
211                     return True
212             else:
213                 if gwIp in myNet:
214                     return True
215         return False
216     
217     def add_address(self, address, netprefix, broadcast):
218         if (self.address or self.netprefix or self.netmask) is not None:
219             raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
220         if broadcast:
221             raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
222         
223         self.address = address
224         self.netprefix = netprefix
225         self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
226     
227     def validate(self):
228         if not self.node:
229             raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
230         if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
231             raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
232         if not self.address or not self.netprefix or not self.netmask:
233             raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
234         if self.filter_module and self.peer_proto not in ('udp','tcp',None):
235             raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
236         if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
237             raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
238     
239     def _impl_instance(self, home_path, listening):
240         impl = self._PROTO_MAP[self.peer_proto](
241             self, self.peer_iface, home_path, self.tun_key, listening)
242         impl.port = self.tun_port
243         return impl
244     
245     def recover(self):
246         if self.peer_proto:
247             self.peer_proto_impl = self._impl_instance(
248                 self._home_path,
249                 False) # no way to know, no need to know
250             self.peer_proto_impl.recover()
251         else:
252             self._delay_recover = True
253     
254     def prepare(self, home_path, listening):
255         if not self.peer_iface and (self.peer_proto and (listening or (self.peer_addr and self.peer_port))):
256             # Ad-hoc peer_iface
257             self.peer_iface = _CrossIface(
258                 self.peer_proto,
259                 self.peer_addr,
260                 self.peer_port,
261                 self.peer_cipher)
262         if self.peer_iface:
263             if not self.peer_proto_impl:
264                 self.peer_proto_impl = self._impl_instance(home_path, listening)
265             if self._delay_recover:
266                 self.peer_proto_impl.recover()
267             else:
268                 self.peer_proto_impl.prepare()
269     
270     def setup(self):
271         if self.peer_proto_impl:
272             self.peer_proto_impl.setup()
273     
274     def cleanup(self):
275         if self.peer_proto_impl:
276             self.peer_proto_impl.shutdown()
277
278     def destroy(self):
279         if self.peer_proto_impl:
280             self.peer_proto_impl.destroy()
281             self.peer_proto_impl = None
282
283     def async_launch_wait(self):
284         if self.peer_proto_impl:
285             self.peer_proto_impl.async_launch_wait()
286
287     def sync_trace(self, local_dir, whichtrace):
288         if self.peer_proto_impl:
289             return self.peer_proto_impl.sync_trace(local_dir, whichtrace)
290         else:
291             return None
292
293     def remote_trace_path(self, whichtrace):
294         if self.peer_proto_impl:
295             return self.peer_proto_impl.remote_trace_path(whichtrace)
296         else:
297             return None
298
299 class TapIface(TunIface):
300     _PROTO_MAP = tunproto.TAP_PROTO_MAP
301     _KIND = 'TAP'
302
303 # Yep, it does nothing - yet
304 class Internet(object):
305     def __init__(self, api=None):
306         if not api:
307             api = plcapi.PLCAPI()
308         self._api = api
309
310 class NetPipe(object):
311     def __init__(self, api=None):
312         if not api:
313             api = plcapi.PLCAPI()
314         self._api = api
315
316         # Attributes
317         self.mode = None
318         self.addrList = None
319         self.portList = None
320         
321         self.plrIn = None
322         self.bwIn = None
323         self.delayIn = None
324
325         self.plrOut = None
326         self.bwOut = None
327         self.delayOut = None
328         
329         # These get initialized when the pipe is connected to its node
330         self.node = None
331         self.configured = False
332     
333     def validate(self):
334         if not self.mode:
335             raise RuntimeError, "Undefined NetPipe mode"
336         if not self.portList:
337             raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
338         if not (self.plrIn or self.bwIn or self.delayIn):
339             raise RuntimeError, "Undefined NetPipe inbound characteristics"
340         if not (self.plrOut or self.bwOut or self.delayOut):
341             raise RuntimeError, "Undefined NetPipe outbound characteristics"
342         if not self.node:
343             raise RuntimeError, "Unconnected NetPipe"
344     
345     def _add_pipedef(self, bw, plr, delay, options):
346         if delay:
347             options.extend(("delay","%dms" % (delay,)))
348         if bw:
349             options.extend(("bw","%.8fMbit/s" % (bw,)))
350         if plr:
351             options.extend(("plr","%.8f" % (plr,)))
352     
353     def _get_ruledef(self):
354         scope = "%s%s%s" % (
355             self.portList,
356             "@" if self.addrList else "",
357             self.addrList or "",
358         )
359         
360         options = []
361         if self.bwIn or self.plrIn or self.delayIn:
362             options.append("IN")
363             self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
364         if self.bwOut or self.plrOut or self.delayOut:
365             options.append("OUT")
366             self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
367         options = ' '.join(options)
368         
369         return (scope,options)
370     
371     def recover(self):
372         # Rules are safe on their nodes
373         self.configured = True
374
375     def configure(self):
376         # set up rule
377         scope, options = self._get_ruledef()
378         command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
379         
380         (out,err),proc = server.popen_ssh_command(
381             command,
382             host = self.node.hostname,
383             port = None,
384             user = self.node.slicename,
385             agent = None,
386             ident_key = self.node.ident_path,
387             server_key = self.node.server_key
388             )
389     
390         if proc.wait():
391             raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
392         
393         # we have to clean up afterwards
394         self.configured = True
395     
396     def refresh(self):
397         if self.configured:
398             # refresh rule
399             scope, options = self._get_ruledef()
400             command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
401             
402             (out,err),proc = server.popen_ssh_command(
403                 command,
404                 host = self.node.hostname,
405                 port = None,
406                 user = self.node.slicename,
407                 agent = None,
408                 ident_key = self.node.ident_path,
409                 server_key = self.node.server_key
410                 )
411         
412             if proc.wait():
413                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
414     
415     def cleanup(self):
416         if self.configured:
417             # remove rule
418             scope, options = self._get_ruledef()
419             command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
420             
421             (out,err),proc = server.popen_ssh_command(
422                 command,
423                 host = self.node.hostname,
424                 port = None,
425                 user = self.node.slicename,
426                 agent = None,
427                 ident_key = self.node.ident_path,
428                 server_key = self.node.server_key
429                 )
430         
431             if proc.wait():
432                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
433             
434             self.configured = False
435     
436     def sync_trace(self, local_dir, whichtrace):
437         if whichtrace != 'netpipeStats':
438             raise ValueError, "Unsupported trace %s" % (whichtrace,)
439         
440         local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
441         
442         # create parent local folders
443         proc = subprocess.Popen(
444             ["mkdir", "-p", os.path.dirname(local_path)],
445             stdout = open("/dev/null","w"),
446             stdin = open("/dev/null","r"))
447
448         if proc.wait():
449             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
450         
451         (out,err),proc = server.popen_ssh_command(
452             "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
453             host = self.node.hostname,
454             port = None,
455             user = self.node.slicename,
456             agent = None,
457             ident_key = self.node.ident_path,
458             server_key = self.node.server_key
459             )
460         
461         if proc.wait():
462             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
463         
464         # dump results to file
465         f = open(local_path, "wb")
466         f.write(err or "")
467         f.write(out or "")
468         f.close()
469         
470         return local_path
471     
472 class TunFilter(object):
473     def __init__(self, api=None):
474         if not api:
475             api = plcapi.PLCAPI()
476         self._api = api
477         
478         # Attributes
479         self.module = None
480
481         # These get initialised when the filter is connected
482         self.peer_guid = None
483         self.peer_proto = None
484         self.iface_guid = None
485         self.peer = None
486         self.iface = None
487     
488     def _get(what, self):
489         wref = self.iface
490         if wref:
491             wref = wref()
492         if wref:
493             return getattr(wref, what)
494         else:
495             return None
496
497     def _set(what, self, val):
498         wref = self.iface
499         if wref:
500             wref = wref()
501         if wref:
502             setattr(wref, what, val)
503     
504     tun_proto = property(
505         functools.partial(_get, 'tun_proto'),
506         functools.partial(_set, 'tun_proto') )
507     tun_addr = property(
508         functools.partial(_get, 'tun_addr'),
509         functools.partial(_set, 'tun_addr') )
510     tun_port = property(
511         functools.partial(_get, 'tun_port'),
512         functools.partial(_set, 'tun_port') )
513     tun_key = property(
514         functools.partial(_get, 'tun_key'),
515         functools.partial(_set, 'tun_key') )
516     tun_cipher = property(
517         functools.partial(_get, 'tun_cipher'),
518         functools.partial(_set, 'tun_cipher') )
519     
520     del _get
521     del _set
522