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