Added TCP-handshake for TunChannel and tun_connect.py
[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         self.multicast = False
132         self.bwlimit = None
133         
134         # Enabled traces
135         self.capture = False
136
137         # These get initialized when the iface is connected to its node
138         self.node = None
139         
140         # These get initialized when the iface is connected to any filter
141         self.filter_module = None
142         
143         # These get initialized when the iface is configured
144         self.external_iface = None
145         
146         # These get initialized when the iface is configured
147         # They're part of the TUN standard attribute set
148         self.tun_port = None
149         self.tun_addr = None
150         self.tun_cipher = "AES"
151         
152         # These get initialized when the iface is connected to its peer
153         self.peer_iface = None
154         self.peer_proto = None
155         self.peer_addr = None
156         self.peer_port = None
157         self.peer_proto_impl = None
158         self._delay_recover = False
159
160         # same as peer proto, but for execute-time standard attribute lookups
161         self.tun_proto = None 
162         
163         
164         # Generate an initial random cryptographic key to use for tunnelling
165         # Upon connection, both endpoints will agree on a common one based on
166         # this one.
167         self.tun_key = ( ''.join(map(chr, [ 
168                     r.getrandbits(8) 
169                     for i in xrange(32) 
170                     for r in (random.SystemRandom(),) ])
171                 ).encode("base64").strip() )        
172         
173
174     def __str__(self):
175         return "%s<ip:%s/%s %s%s%s>" % (
176             self.__class__.__name__,
177             self.address, self.netprefix,
178             " up" if self.up else " down",
179             " snat" if self.snat else "",
180             (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
181         )
182     
183     __repr__ = __str__
184     
185     @property
186     def if_name(self):
187         if self.peer_proto_impl:
188             return self.peer_proto_impl.if_name
189
190     def routes_here(self, route):
191         """
192         Returns True if the route should be attached to this interface
193         (ie, it references a gateway in this interface's network segment)
194         """
195         if self.address and self.netprefix:
196             addr, prefix = self.address, self.netprefix
197             pointopoint = self.pointopoint
198             if not pointopoint:
199                 pointopoint = self.peer_iface.address
200             
201             if pointopoint:
202                 prefix = 32
203                 
204             dest, destprefix, nexthop, metric = route
205             
206             myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
207             gwIp = ipaddr.IPNetwork(nexthop)
208             
209             if pointopoint:
210                 peerIp = ipaddr.IPNetwork(pointopoint)
211                 
212                 if gwIp == peerIp:
213                     return True
214             else:
215                 if gwIp in myNet:
216                     return True
217         return False
218     
219     def add_address(self, address, netprefix, broadcast):
220         if (self.address or self.netprefix or self.netmask) is not None:
221             raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
222         if broadcast:
223             raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
224         
225         self.address = address
226         self.netprefix = netprefix
227         self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
228     
229     def validate(self):
230         if not self.node:
231             raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
232         if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
233             raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
234         if not self.address or not self.netprefix or not self.netmask:
235             raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
236         if self.filter_module and self.peer_proto not in ('udp','tcp',None):
237             raise RuntimeError, "Miscofnigured TUN: %s - filtered tunnels only work with udp or tcp links" % (self,)
238         if self.tun_cipher != 'PLAIN' and self.peer_proto not in ('udp','tcp',None):
239             raise RuntimeError, "Miscofnigured TUN: %s - ciphered tunnels only work with udp or tcp links" % (self,)
240     
241     def _impl_instance(self, home_path):
242         impl = self._PROTO_MAP[self.peer_proto](
243             self, self.peer_iface, home_path, self.tun_key)
244         impl.port = self.tun_port
245         return impl
246     
247     def recover(self):
248         if self.peer_proto:
249             self.peer_proto_impl = self._impl_instance(
250                 self._home_path,
251                 False) # no way to know, no need to know
252             self.peer_proto_impl.recover()
253         else:
254             self._delay_recover = True
255     
256     def prepare(self, home_path):
257         if not self.peer_iface and (self.peer_proto and self.peer_addr and self.peer_port):
258             # Ad-hoc peer_iface
259             self.peer_iface = _CrossIface(
260                 self.peer_proto,
261                 self.peer_addr,
262                 self.peer_port,
263                 self.peer_cipher)
264         if self.peer_iface:
265             if not self.peer_proto_impl:
266                 self.peer_proto_impl = self._impl_instance(home_path)
267             if self._delay_recover:
268                 self.peer_proto_impl.recover()
269     
270     def launch(self):
271         if self.peer_proto_impl:
272             self.peer_proto_impl.launch()
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 wait(self):
284         if self.peer_proto_impl:
285             self.peer_proto_impl.wait()
286
287     def sync_trace(self, local_dir, whichtrace, tracemap = None):
288         if self.peer_proto_impl:
289             return self.peer_proto_impl.sync_trace(local_dir, whichtrace,
290                     tracemap)
291         else:
292             return None
293
294     def remote_trace_path(self, whichtrace, tracemap = None):
295         if self.peer_proto_impl:
296             return self.peer_proto_impl.remote_trace_path(whichtrace, tracemap)
297         else:
298             return None
299
300     def remote_trace_name(self, whichtrace):
301         return whichtrace
302
303 class TapIface(TunIface):
304     _PROTO_MAP = tunproto.TAP_PROTO_MAP
305     _KIND = 'TAP'
306
307 # Yep, it does nothing - yet
308 class Internet(object):
309     def __init__(self, api=None):
310         if not api:
311             api = plcapi.PLCAPI()
312         self._api = api
313
314 class NetPipe(object):
315     def __init__(self, api=None):
316         if not api:
317             api = plcapi.PLCAPI()
318         self._api = api
319
320         # Attributes
321         self.mode = None
322         self.addrList = None
323         self.portList = None
324         
325         self.plrIn = None
326         self.bwIn = None
327         self.delayIn = None
328
329         self.plrOut = None
330         self.bwOut = None
331         self.delayOut = None
332         
333         # These get initialized when the pipe is connected to its node
334         self.node = None
335         self.configured = False
336     
337     def validate(self):
338         if not self.mode:
339             raise RuntimeError, "Undefined NetPipe mode"
340         if not self.portList:
341             raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
342         if not (self.plrIn or self.bwIn or self.delayIn):
343             raise RuntimeError, "Undefined NetPipe inbound characteristics"
344         if not (self.plrOut or self.bwOut or self.delayOut):
345             raise RuntimeError, "Undefined NetPipe outbound characteristics"
346         if not self.node:
347             raise RuntimeError, "Unconnected NetPipe"
348     
349     def _add_pipedef(self, bw, plr, delay, options):
350         if delay:
351             options.extend(("delay","%dms" % (delay,)))
352         if bw:
353             options.extend(("bw","%.8fMbit/s" % (bw,)))
354         if plr:
355             options.extend(("plr","%.8f" % (plr,)))
356     
357     def _get_ruledef(self):
358         scope = "%s%s%s" % (
359             self.portList,
360             "@" if self.addrList else "",
361             self.addrList or "",
362         )
363         
364         options = []
365         if self.bwIn or self.plrIn or self.delayIn:
366             options.append("IN")
367             self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
368         if self.bwOut or self.plrOut or self.delayOut:
369             options.append("OUT")
370             self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
371         options = ' '.join(options)
372         
373         return (scope,options)
374     
375     def recover(self):
376         # Rules are safe on their nodes
377         self.configured = True
378
379     def configure(self):
380         # set up rule
381         scope, options = self._get_ruledef()
382         command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
383         
384         (out,err),proc = server.popen_ssh_command(
385             command,
386             host = self.node.hostname,
387             port = None,
388             user = self.node.slicename,
389             agent = None,
390             ident_key = self.node.ident_path,
391             server_key = self.node.server_key
392             )
393     
394         if proc.wait():
395             raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
396         
397         # we have to clean up afterwards
398         self.configured = True
399     
400     def refresh(self):
401         if self.configured:
402             # refresh rule
403             scope, options = self._get_ruledef()
404             command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
405             
406             (out,err),proc = server.popen_ssh_command(
407                 command,
408                 host = self.node.hostname,
409                 port = None,
410                 user = self.node.slicename,
411                 agent = None,
412                 ident_key = self.node.ident_path,
413                 server_key = self.node.server_key
414                 )
415         
416             if proc.wait():
417                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
418     
419     def cleanup(self):
420         if self.configured:
421             # remove rule
422             scope, options = self._get_ruledef()
423             command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
424             
425             (out,err),proc = server.popen_ssh_command(
426                 command,
427                 host = self.node.hostname,
428                 port = None,
429                 user = self.node.slicename,
430                 agent = None,
431                 ident_key = self.node.ident_path,
432                 server_key = self.node.server_key
433                 )
434         
435             if proc.wait():
436                 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
437             
438             self.configured = False
439     
440     def sync_trace(self, local_dir, whichtrace):
441         if whichtrace != 'netpipeStats':
442             raise ValueError, "Unsupported trace %s" % (whichtrace,)
443         
444         local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
445         
446         # create parent local folders
447         proc = subprocess.Popen(
448             ["mkdir", "-p", os.path.dirname(local_path)],
449             stdout = open("/dev/null","w"),
450             stdin = open("/dev/null","r"))
451
452         if proc.wait():
453             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
454         
455         (out,err),proc = server.popen_ssh_command(
456             "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
457             host = self.node.hostname,
458             port = None,
459             user = self.node.slicename,
460             agent = None,
461             ident_key = self.node.ident_path,
462             server_key = self.node.server_key
463             )
464         
465         if proc.wait():
466             raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
467         
468         # dump results to file
469         f = open(local_path, "wb")
470         f.write(err or "")
471         f.write(out or "")
472         f.close()
473         
474         return local_path
475     
476 class TunFilter(object):
477     _TRACEMAP = {
478         # tracename : (remotename, localname)
479     }
480     
481     def __init__(self, api=None):
482         if not api:
483             api = plcapi.PLCAPI()
484         self._api = api
485         
486         # Attributes
487         self.module = None
488         self.args = None
489
490         # These get initialised when the filter is connected
491         self.peer_guid = None
492         self.peer_proto = None
493         self.iface_guid = None
494         self.peer = None
495         self.iface = None
496     
497     def _get(what, self):
498         wref = self.iface
499         if wref:
500             wref = wref()
501         if wref:
502             return getattr(wref, what)
503         else:
504             return None
505
506     def _set(what, self, val):
507         wref = self.iface
508         if wref:
509             wref = wref()
510         if wref:
511             setattr(wref, what, val)
512     
513     tun_proto = property(
514         functools.partial(_get, 'tun_proto'),
515         functools.partial(_set, 'tun_proto') )
516     tun_addr = property(
517         functools.partial(_get, 'tun_addr'),
518         functools.partial(_set, 'tun_addr') )
519     tun_port = property(
520         functools.partial(_get, 'tun_port'),
521         functools.partial(_set, 'tun_port') )
522     tun_key = property(
523         functools.partial(_get, 'tun_key'),
524         functools.partial(_set, 'tun_key') )
525     tun_cipher = property(
526         functools.partial(_get, 'tun_cipher'),
527         functools.partial(_set, 'tun_cipher') )
528     
529     del _get
530     del _set
531
532     def remote_trace_path(self, whichtrace):
533         iface = self.iface()
534         if iface is not None:
535             return iface.remote_trace_path(whichtrace, self._TRACEMAP)
536         return None
537
538     def remote_trace_name(self, whichtrace):
539         iface = self.iface()
540         if iface is not None:
541             return iface.remote_trace_name(whichtrace, self._TRACEMAP)
542         return None
543
544     def sync_trace(self, local_dir, whichtrace):
545         iface = self.iface()
546         if iface is not None:
547             return iface.sync_trace(local_dir, whichtrace, self._TRACEMAP)
548         return None
549
550 class ClassQueueFilter(TunFilter):
551     _TRACEMAP = {
552         # tracename : (remotename, localname)
553         'dropped_stats' : ('dropped_stats', 'dropped_stats')
554     }
555     
556     def __init__(self, api=None):
557         super(ClassQueueFilter, self).__init__(api)
558         # Attributes
559         self.module = "classqueue.py"
560
561 class ToSQueueFilter(TunFilter):
562     def __init__(self, api=None):
563         super(ToSQueueFilter, self).__init__(api)
564         # Attributes
565         self.module = "tosqueue.py"
566