2 # -*- coding: utf-8 -*-
14 from nepi.util import server
16 class TunProtoBase(object):
17 def __init__(self, local, peer, home_path, key):
18 # Weak references, since ifaces do have a reference to the
19 # tunneling protocol implementation - we don't want strong
20 # circular references.
21 self.peer = weakref.ref(peer)
22 self.local = weakref.ref(local)
28 self.home_path = home_path
39 raise RuntimeError, "Lost reference to peering interfaces before launching"
41 raise RuntimeError, "Unconnected TUN - missing node"
43 # Make sure all the paths are created where
44 # they have to be created for deployment
45 cmd = "mkdir -p %s" % (server.shell_escape(self.home_path),)
46 (out,err),proc = server.popen_ssh_command(
48 host = local.node.hostname,
50 user = local.node.slicename,
52 ident_key = local.node.ident_path,
53 server_key = local.node.server_key
57 raise RuntimeError, "Failed to set up TUN forwarder: %s %s" % (out,err,)
60 def _install_scripts(self):
64 raise RuntimeError, "Lost reference to peering interfaces before launching"
66 raise RuntimeError, "Unconnected TUN - missing node"
68 # Install the tun_connect script and tunalloc utility
69 from nepi.util import tunchannel
71 os.path.join(os.path.dirname(__file__), 'scripts', 'tun_connect.py'),
72 os.path.join(os.path.dirname(__file__), 'scripts', 'tunalloc.c'),
73 re.sub(r"([.]py)[co]$", r'\1', tunchannel.__file__, 1), # pyc/o files are version-specific
76 local.node.slicename, local.node.hostname,
77 os.path.join(self.home_path,'.'),)
78 (out,err),proc = server.popen_scp(
81 ident_key = local.node.ident_path,
82 server_key = local.node.server_key
86 raise RuntimeError, "Failed upload TUN connect script %r: %s %s" % (sources, out,err,)
88 # Make sure all dependencies are satisfied
89 local.node.wait_dependencies()
92 "cd %(home)s && gcc -fPIC -shared tunalloc.c -o tunalloc.so"
94 "wget -q -c -O python-passfd-src.tar.gz %(passfd_url)s && "
95 "mkdir -p python-passfd && "
96 "cd python-passfd && "
97 "tar xzf ../python-passfd-src.tar.gz --strip-components=1 && "
98 "python setup.py build && "
99 "python setup.py install --install-lib .. "
101 if local.tun_proto == "fd" else ""
104 'home' : server.shell_escape(self.home_path),
105 'passfd_url' : "http://yans.pl.sophia.inria.fr/code/hgwebdir.cgi/python-passfd/archive/2a6472c64c87.tar.gz",
107 (out,err),proc = server.popen_ssh_command(
109 host = local.node.hostname,
111 user = local.node.slicename,
113 ident_key = local.node.ident_path,
114 server_key = local.node.server_key
118 raise RuntimeError, "Failed to set up TUN forwarder: %s %s" % (out,err,)
120 def launch(self, check_proto, listen, extra_args=[]):
124 if not peer or not local:
125 raise RuntimeError, "Lost reference to peering interfaces before launching"
127 peer_port = peer.tun_port
128 peer_addr = peer.tun_addr
129 peer_proto= peer.tun_proto
131 local_port = self.port
132 local_cap = local.capture
133 local_addr = local.address
134 local_mask = local.netprefix
135 local_snat = local.snat
136 local_txq = local.txqueuelen
138 if check_proto != peer_proto:
139 raise RuntimeError, "Peering protocol mismatch: %s != %s" % (check_proto, peer_proto)
141 if not listen and ((peer_proto != 'fd' and not peer_port) or not peer_addr):
142 raise RuntimeError, "Misconfigured peer: %s" % (peer,)
144 if listen and ((peer_proto != 'fd' and not local_port) or not local_addr or not local_mask):
145 raise RuntimeError, "Misconfigured TUN: %s" % (local,)
147 args = ["python", "tun_connect.py",
148 "-m", str(self.mode),
149 "-A", str(local_addr),
150 "-M", str(local_mask)]
152 if check_proto == 'fd':
153 passfd_arg = str(peer_addr)
154 if passfd_arg.startswith('\x00'):
155 # cannot shell_encode null characters :(
156 passfd_arg = "base64:"+base64.b64encode(passfd_arg)
158 passfd_arg = '$HOME/'+server.shell_escape(passfd_arg)
160 "--pass-fd", passfd_arg
164 "-p", str(local_port if listen else peer_port),
171 args.extend(("-Q",str(local_txq)))
173 args.extend(map(str,extra_args))
174 if not listen and check_proto != 'fd':
175 args.append(str(peer_addr))
178 self._install_scripts()
180 # Start process in a "daemonized" way, using nohup and heavy
181 # stdin/out redirection to avoid connection issues
182 (out,err),proc = rspawn.remote_spawn(
186 home = self.home_path,
188 stdout = 'capture' if local_cap else '/dev/null',
189 stderr = rspawn.STDOUT,
192 host = local.node.hostname,
194 user = local.node.slicename,
196 ident_key = local.node.ident_path,
197 server_key = local.node.server_key
201 raise RuntimeError, "Failed to set up TUN: %s %s" % (out,err,)
205 def _launch_and_wait(self, *p, **kw):
208 self.launch(*p, **kw)
210 # Wait for the process to be started
211 while self.status() == rspawn.NOT_STARTED:
214 # Wait for the connection to be established
216 for spin in xrange(30):
217 if self.status() != rspawn.RUNNING:
220 (out,err),proc = server.popen_ssh_command(
221 "cd %(home)s ; grep -c Connected capture" % dict(
222 home = server.shell_escape(self.home_path)),
223 host = local.node.hostname,
225 user = local.node.slicename,
227 ident_key = local.node.ident_path,
228 server_key = local.node.server_key
234 if out.strip() != '0':
239 def async_launch(self, check_proto, listen, extra_args=[]):
240 if not self._launcher:
241 self._launcher = threading.Thread(
242 target = self._launch_and_wait,
243 args = (check_proto, listen, extra_args))
244 self._launcher.start()
246 def async_launch_wait(self):
248 self._launcher.join()
249 if not self._started:
250 raise RuntimeError, "Failed to launch TUN forwarder"
251 elif not self._started:
258 raise RuntimeError, "Lost reference to local interface"
261 # NOTE: wait a bit for the pidfile to be created
262 if self._started and not self._pid or not self._ppid:
263 pidtuple = rspawn.remote_check_pid(
264 os.path.join(self.home_path,'pid'),
265 host = local.node.hostname,
267 user = local.node.slicename,
269 ident_key = local.node.ident_path,
270 server_key = local.node.server_key
274 self._pid, self._ppid = pidtuple
280 raise RuntimeError, "Lost reference to local interface"
283 if not self._started:
284 return rspawn.NOT_STARTED
285 elif not self._pid or not self._ppid:
286 return rspawn.NOT_STARTED
288 status = rspawn.remote_status(
289 self._pid, self._ppid,
290 host = local.node.hostname,
292 user = local.node.slicename,
294 ident_key = local.node.ident_path
302 raise RuntimeError, "Lost reference to local interface"
304 status = self.status()
305 if status == rspawn.RUNNING:
306 # kill by ppid+pid - SIGTERM first, then try SIGKILL
308 self._pid, self._ppid,
309 host = local.node.hostname,
311 user = local.node.slicename,
313 ident_key = local.node.ident_path,
314 server_key = local.node.server_key,
318 def sync_trace(self, local_dir, whichtrace):
319 if whichtrace != 'packets':
327 local_path = os.path.join(local_dir, 'capture')
329 # create parent local folders
330 proc = subprocess.Popen(
331 ["mkdir", "-p", os.path.dirname(local_path)],
332 stdout = open("/dev/null","w"),
333 stdin = open("/dev/null","r"))
336 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
339 (out,err),proc = server.popen_scp(
340 '%s@%s:%s' % (local.node.slicename, local.node.hostname,
341 os.path.join(self.home_path, 'capture')),
345 ident_key = local.node.ident_path,
346 server_key = local.node.server_key
350 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
359 eg: set up listening ports
361 raise NotImplementedError
369 raise NotImplementedError
375 raise NotImplementedError
378 class TunProtoUDP(TunProtoBase):
379 def __init__(self, local, peer, home_path, key, listening):
380 super(TunProtoUDP, self).__init__(local, peer, home_path, key)
381 self.listening = listening
387 self.async_launch('udp', False, ("-u",str(self.port)))
392 class TunProtoFD(TunProtoBase):
393 def __init__(self, local, peer, home_path, key, listening):
394 super(TunProtoFD, self).__init__(local, peer, home_path, key)
395 self.listening = listening
401 self.async_launch('fd', False)
406 class TunProtoTCP(TunProtoBase):
407 def __init__(self, local, peer, home_path, key, listening):
408 super(TunProtoTCP, self).__init__(local, peer, home_path, key)
409 self.listening = listening
413 self.async_launch('tcp', True)
416 if not self.listening:
417 # make sure our peer is ready
419 if peer and peer.peer_proto_impl:
420 peer.peer_proto_impl.async_launch_wait()
422 if not self._started:
423 self.launch('tcp', False)
425 # make sure WE are ready
426 self.async_launch_wait()
433 class TapProtoUDP(TunProtoUDP):
434 def __init__(self, local, peer, home_path, key, listening):
435 super(TapProtoUDP, self).__init__(local, peer, home_path, key, listening)
438 class TapProtoTCP(TunProtoTCP):
439 def __init__(self, local, peer, home_path, key, listening):
440 super(TapProtoTCP, self).__init__(local, peer, home_path, key, listening)
443 class TapProtoFD(TunProtoFD):
444 def __init__(self, local, peer, home_path, key, listening):
445 super(TapProtoFD, self).__init__(local, peer, home_path, key, listening)