2 # -*- coding: utf-8 -*-
4 from constants import TESTBED_ID
5 import nepi.util.ipaddr2 as ipaddr2
6 import nepi.util.server as server
16 class NodeIface(object):
17 def __init__(self, api=None):
25 # These get initialized at configuration time
31 self._interface_id = None
33 # These get initialized when the iface is connected to its node
36 # These get initialized when the iface is connected to the internet
37 self.has_internet = False
40 return "%s<ip:%s/%s up mac:%s>" % (
41 self.__class__.__name__,
42 self.address, self.netmask,
48 def add_address(self, address, netprefix, broadcast):
49 raise RuntimeError, "Cannot add explicit addresses to public interface"
51 def pick_iface(self, siblings):
53 Picks an interface using the PLCAPI to query information about the node.
55 Needs an assigned node.
58 siblings: other NodeIface elements attached to the same node
61 if self.node is None or self.node._node_id is None:
62 raise RuntimeError, "Cannot pick interface without an assigned node"
64 avail = self._api.GetInterfaces(
65 node_id=self.node._node_id,
66 is_primary=self.primary,
67 fields=('interface_id','mac','netmask','ip') )
69 used = set([sibling._interface_id for sibling in siblings
70 if sibling._interface_id is not None])
72 for candidate in avail:
73 candidate_id = candidate['interface_id']
74 if candidate_id not in used:
76 self._interface_id = candidate_id
77 self.address = candidate['ip']
78 self.lladdr = candidate['mac']
79 self.netprefix = candidate['netmask']
80 self.netmask = ipaddr2.ipv4_dot2mask(self.netprefix) if self.netprefix else None
83 raise RuntimeError, "Cannot configure interface: cannot find suitable interface in PlanetLab node"
86 if not self.has_internet:
87 raise RuntimeError, "All external interface devices must be connected to the Internet"
90 class _CrossIface(object):
91 def __init__(self, proto, addr, port):
92 self.tun_proto = proto
96 # Cannot access cross peers
97 self.peer_proto_impl = None
101 self.__class__.__name__,
109 class TunIface(object):
110 _PROTO_MAP = tunproto.TUN_PROTO_MAP
113 def __init__(self, api=None):
115 api = plcapi.PLCAPI()
120 self.netprefix = None
124 self.device_name = None
127 self.txqueuelen = None
128 self.pointopoint = None
133 # These get initialized when the iface is connected to its node
136 # These get initialized when the iface is configured
137 self.external_iface = None
139 # These get initialized when the iface is configured
140 # They're part of the TUN standard attribute set
144 # These get initialized when the iface is connected to its peer
145 self.peer_iface = None
146 self.peer_proto = None
147 self.peer_addr = None
148 self.peer_port = None
149 self.peer_proto_impl = None
151 # same as peer proto, but for execute-time standard attribute lookups
152 self.tun_proto = None
155 # Generate an initial random cryptographic key to use for tunnelling
156 # Upon connection, both endpoints will agree on a common one based on
158 self.tun_key = ( ''.join(map(chr, [
161 for r in (random.SystemRandom(),) ])
162 ).encode("base64").strip() )
166 return "%s<ip:%s/%s %s%s%s>" % (
167 self.__class__.__name__,
168 self.address, self.netprefix,
169 " up" if self.up else " down",
170 " snat" if self.snat else "",
171 (" p2p %s" % (self.pointopoint,)) if self.pointopoint else "",
178 if self.peer_proto_impl:
179 return self.peer_proto_impl.if_name
181 def routes_here(self, route):
183 Returns True if the route should be attached to this interface
184 (ie, it references a gateway in this interface's network segment)
186 if self.address and self.netprefix:
187 addr, prefix = self.address, self.netprefix
188 pointopoint = self.pointopoint
190 pointopoint = self.peer_iface.address
195 dest, destprefix, nexthop, metric = route
197 myNet = ipaddr.IPNetwork("%s/%d" % (addr, prefix))
198 gwIp = ipaddr.IPNetwork(nexthop)
201 peerIp = ipaddr.IPNetwork(pointopoint)
210 def add_address(self, address, netprefix, broadcast):
211 if (self.address or self.netprefix or self.netmask) is not None:
212 raise RuntimeError, "Cannot add more than one address to %s interfaces" % (self._KIND,)
214 raise ValueError, "%s interfaces cannot broadcast in PlanetLab (%s)" % (self._KIND,broadcast)
216 self.address = address
217 self.netprefix = netprefix
218 self.netmask = ipaddr2.ipv4_mask2dot(netprefix)
222 raise RuntimeError, "Unconnected %s iface - missing node" % (self._KIND,)
223 if self.peer_iface and self.peer_proto not in self._PROTO_MAP:
224 raise RuntimeError, "Unsupported tunnelling protocol: %s" % (self.peer_proto,)
225 if not self.address or not self.netprefix or not self.netmask:
226 raise RuntimeError, "Misconfigured %s iface - missing address" % (self._KIND,)
228 def _impl_instance(self, home_path, listening):
229 impl = self._PROTO_MAP[self.peer_proto](
230 self, self.peer_iface, home_path, self.tun_key, listening)
231 impl.port = self.tun_port
234 def prepare(self, home_path, listening):
235 if not self.peer_iface and (self.peer_proto and (listening or (self.peer_addr and self.peer_port))):
237 self.peer_iface = _CrossIface(
242 if not self.peer_proto_impl:
243 self.peer_proto_impl = self._impl_instance(home_path, listening)
244 self.peer_proto_impl.prepare()
247 if self.peer_proto_impl:
248 self.peer_proto_impl.setup()
251 if self.peer_proto_impl:
252 self.peer_proto_impl.shutdown()
255 if self.peer_proto_impl:
256 self.peer_proto_impl.destroy()
257 self.peer_proto_impl = None
259 def async_launch_wait(self):
260 if self.peer_proto_impl:
261 self.peer_proto_impl.async_launch_wait()
263 def sync_trace(self, local_dir, whichtrace):
264 if self.peer_proto_impl:
265 return self.peer_proto_impl.sync_trace(local_dir, whichtrace)
269 def remote_trace_path(self, whichtrace):
270 if self.peer_proto_impl:
271 return self.peer_proto_impl.remote_trace_path(whichtrace)
275 class TapIface(TunIface):
276 _PROTO_MAP = tunproto.TAP_PROTO_MAP
279 # Yep, it does nothing - yet
280 class Internet(object):
281 def __init__(self, api=None):
283 api = plcapi.PLCAPI()
286 class NetPipe(object):
287 def __init__(self, api=None):
289 api = plcapi.PLCAPI()
305 # These get initialized when the pipe is connected to its node
307 self.configured = False
311 raise RuntimeError, "Undefined NetPipe mode"
312 if not self.portList:
313 raise RuntimeError, "Undefined NetPipe port list - must always define the scope"
314 if not (self.plrIn or self.bwIn or self.delayIn):
315 raise RuntimeError, "Undefined NetPipe inbound characteristics"
316 if not (self.plrOut or self.bwOut or self.delayOut):
317 raise RuntimeError, "Undefined NetPipe outbound characteristics"
319 raise RuntimeError, "Unconnected NetPipe"
321 def _add_pipedef(self, bw, plr, delay, options):
323 options.extend(("delay","%dms" % (delay,)))
325 options.extend(("bw","%.8fMbit/s" % (bw,)))
327 options.extend(("plr","%.8f" % (plr,)))
329 def _get_ruledef(self):
332 "@" if self.addrList else "",
337 if self.bwIn or self.plrIn or self.delayIn:
339 self._add_pipedef(self.bwIn, self.plrIn, self.delayIn, options)
340 if self.bwOut or self.plrOut or self.delayOut:
341 options.append("OUT")
342 self._add_pipedef(self.bwOut, self.plrOut, self.delayOut, options)
343 options = ' '.join(options)
345 return (scope,options)
349 scope, options = self._get_ruledef()
350 command = "sudo -S netconfig config %s %s %s" % (self.mode, scope, options)
352 (out,err),proc = server.popen_ssh_command(
354 host = self.node.hostname,
356 user = self.node.slicename,
358 ident_key = self.node.ident_path,
359 server_key = self.node.server_key
363 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
365 # we have to clean up afterwards
366 self.configured = True
371 scope, options = self._get_ruledef()
372 command = "sudo -S netconfig refresh %s %s %s" % (self.mode, scope, options)
374 (out,err),proc = server.popen_ssh_command(
376 host = self.node.hostname,
378 user = self.node.slicename,
380 ident_key = self.node.ident_path,
381 server_key = self.node.server_key
385 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
390 scope, options = self._get_ruledef()
391 command = "sudo -S netconfig delete %s %s" % (self.mode, scope)
393 (out,err),proc = server.popen_ssh_command(
395 host = self.node.hostname,
397 user = self.node.slicename,
399 ident_key = self.node.ident_path,
400 server_key = self.node.server_key
404 raise RuntimeError, "Failed instal build sources: %s %s" % (out,err,)
406 self.configured = False
408 def sync_trace(self, local_dir, whichtrace):
409 if whichtrace != 'netpipeStats':
410 raise ValueError, "Unsupported trace %s" % (whichtrace,)
412 local_path = os.path.join(local_dir, "netpipe_stats_%s" % (self.mode,))
414 # create parent local folders
415 proc = subprocess.Popen(
416 ["mkdir", "-p", os.path.dirname(local_path)],
417 stdout = open("/dev/null","w"),
418 stdin = open("/dev/null","r"))
421 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
423 (out,err),proc = server.popen_ssh_command(
424 "echo 'Rules:' ; sudo -S netconfig show rules ; echo 'Pipes:' ; sudo -S netconfig show pipes",
425 host = self.node.hostname,
427 user = self.node.slicename,
429 ident_key = self.node.ident_path,
430 server_key = self.node.server_key
434 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
436 # dump results to file
437 f = open(local_path, "wb")