2 # NEPI, a framework to manage network experiments
3 # Copyright (C) 2013 INRIA
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
20 from nepi.execution.attribute import Attribute, Flags, Types
21 from nepi.execution.resource import clsinit_copy, ResourceState
22 from nepi.resources.linux.application import LinuxApplication
23 from nepi.resources.linux.node import LinuxNode
24 from nepi.util.timefuncs import tnow, tdiffsec
29 PYTHON_VSYS_VERSION = "1.0"
32 class LinuxTap(LinuxApplication):
34 _help = "Creates a TAP device on a Linux host"
38 def _register_attributes(cls):
39 endpoint_ip = Attribute("endpoint_ip", "IPv4 Address",
42 mac = Attribute("mac", "MAC Address",
45 endpoint_prefix = Attribute("endpoint_prefix", "IPv4 network prefix",
49 mtu = Attribute("mtu", "Maximum transmition unit for device",
52 devname = Attribute("deviceName",
53 "Name of the network interface (e.g. eth0, wlan0, etc)",
54 flags = Flags.NoWrite)
56 up = Attribute("up", "Link up",
59 pointopoint = Attribute("pointopoint", "Peer IP address",
62 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
65 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
68 gre_key = Attribute("greKey",
69 "GRE key to be used to configure GRE tunnel",
73 gre_remote = Attribute("greRemote",
74 "Public IP of remote endpoint for GRE tunnel",
77 pi = Attribute("pi", "Add PI (protocol information) header",
81 tear_down = Attribute("tearDown",
82 "Bash script to be executed before releasing the resource",
85 cls._register_attribute(endpoint_ip)
86 cls._register_attribute(mac)
87 cls._register_attribute(endpoint_prefix)
88 cls._register_attribute(mtu)
89 cls._register_attribute(devname)
90 cls._register_attribute(up)
91 cls._register_attribute(pointopoint)
92 cls._register_attribute(txqueuelen)
93 cls._register_attribute(gre_key)
94 cls._register_attribute(gre_remote)
95 cls._register_attribute(pi)
96 cls._register_attribute(tear_down)
98 def __init__(self, ec, guid):
99 super(LinuxTap, self).__init__(ec, guid)
100 self._home = "tap-%s" % self.guid
101 self._gre_enabled = False
102 self._tunnel_mode = False
106 node = self.get_connected(LinuxNode.get_rtype())
107 if node: return node[0]
108 raise RuntimeError, "TAP/TUN devices must be connected to Node"
111 def gre_enabled(self):
112 if not self._gre_enabled:
113 from nepi.resources.linux.gretunnel import LinuxGRETunnel
114 gre = self.get_connected(LinuxGRETunnel.get_rtype())
115 if gre: self._gre_enabled = True
117 return self._gre_enabled
120 def tunnel_mode(self):
121 if not self._tunnel_mode:
122 from nepi.resources.linux.tunnel import LinuxTunnel
123 tunnel = self.get_connected(LinuxTunnel.get_rtype())
124 if tunnel: self._tunnel_mode = True
126 return self._tunnel_mode
128 def upload_sources(self):
131 # udp-connect python script
132 udp_connect = os.path.join(os.path.dirname(__file__), "scripts",
133 "linux-udp-connect.py")
135 scripts.append(udp_connect)
137 # tunnel creation python script
138 tunchannel = os.path.join(os.path.dirname(__file__), "scripts",
141 scripts.append(tunchannel)
144 scripts = ";".join(scripts)
146 self.node.upload(scripts,
147 os.path.join(self.node.src_dir),
150 # upload stop.sh script
151 stop_command = self.replace_paths(self._stop_command)
153 self.node.upload(stop_command,
154 os.path.join(self.app_home, "stop.sh"),
156 # Overwrite file every time.
157 # The stop.sh has the path to the socket, which should change
158 # on every experiment run.
161 def upload_start_command(self):
162 # If GRE mode is enabled, TAP creation is delayed until the
163 # tunnel is established
164 if not self.tunnel_mode:
165 # We want to make sure the device is up and running
166 # before the deploy is over, so we execute the
167 # start script now and wait until it finishes.
168 command = self.get("command")
169 command = self.replace_paths(command)
171 shfile = os.path.join(self.app_home, "start.sh")
172 self.node.run_and_wait(command, self.run_home,
177 if not self.node or self.node.state < ResourceState.PROVISIONED:
178 self.ec.schedule(self.reschedule_delay, self.deploy)
180 if not self.get("deviceName"):
181 self.set("deviceName", "%s%d" % (self.vif_prefix, self.guid))
183 if not self.get("command"):
184 self.set("command", self._start_command)
192 if self.state == ResourceState.READY:
193 command = self.get("command")
194 self.info("Starting command '%s'" % command)
198 msg = " Failed to execute command '%s'" % command
199 self.error(msg, out, err)
200 raise RuntimeError, msg
203 command = self.get('command') or ''
205 if self.state == ResourceState.STARTED:
206 self.info("Stopping command '%s'" % command)
208 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
209 (out, err), proc = self.execute_command(command,
213 msg = " Failed to stop command '%s' " % command
214 self.error(msg, out, err)
220 state_check_delay = 0.5
221 if self._state == ResourceState.STARTED and \
222 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
224 if self.get("deviceName"):
225 (out, err), proc = self.node.execute("ifconfig")
227 if out.strip().find(self.get("deviceName")) == -1:
228 # tap is not running is not running (socket not found)
231 self._last_state_check = tnow()
235 def do_release(self):
236 # Node needs to wait until all associated RMs are released
238 from nepi.resources.linux.tunnel import LinuxTunnel
239 rms = self.get_connected(LinuxTunnel.get_rtype())
242 if rm.state < ResourceState.STOPPED:
243 self.ec.schedule(self.reschedule_delay, self.release)
246 super(LinuxTap, self).do_release()
248 def gre_connect(self, remote_endpoint, connection_app_home,
249 connection_run_home):
250 gre_connect_command = self._gre_connect_command(
251 remote_endpoint, connection_run_home)
253 # upload command to connect.sh script
254 shfile = os.path.join(connection_app_home, "gre-connect.sh")
255 self.node.upload_command(gre_connect_command,
259 # invoke connect script
260 cmd = "bash %s" % shfile
261 (out, err), proc = self.node.run(cmd, connection_run_home)
263 # check if execution errors occurred
264 msg = " Failed to connect endpoints "
266 if proc.poll() or err:
267 self.error(msg, out, err)
268 raise RuntimeError, msg
270 # Wait for pid file to be generated
271 pid, ppid = self.node.wait_pid(connection_run_home)
273 # If the process is not running, check for error information
274 # on the remote machine
275 if not pid or not ppid:
276 (out, err), proc = self.node.check_errors(connection_run_home)
277 # Out is what was written in the stderr file
279 msg = " Failed to start command '%s' " % command
280 self.error(msg, out, err)
281 raise RuntimeError, msg
285 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
286 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
287 port = self.udp_connect(remote_endpoint, connection_app_home,
288 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
291 def udp_connect(self, remote_endpoint, connection_app_home,
292 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
293 udp_connect_command = self._udp_connect_command(
294 remote_endpoint, connection_run_home,
295 cipher, cipher_key, bwlimit, txqueuelen)
297 # upload command to connect.sh script
298 shfile = os.path.join(self.app_home, "udp-connect.sh")
299 self.node.upload_command(udp_connect_command,
303 # invoke connect script
304 cmd = "bash %s" % shfile
305 (out, err), proc = self.node.run(cmd, self.run_home)
307 # check if execution errors occurred
308 msg = "Failed to connect endpoints "
311 self.error(msg, out, err)
312 raise RuntimeError, msg
314 # Wait for pid file to be generated
315 self._pid, self._ppid = self.node.wait_pid(self.run_home)
317 # If the process is not running, check for error information
318 # on the remote machine
319 if not self._pid or not self._ppid:
320 (out, err), proc = self.node.check_errors(self.run_home)
321 # Out is what was written in the stderr file
323 msg = " Failed to start command '%s' " % command
324 self.error(msg, out, err)
325 raise RuntimeError, msg
327 port = self.wait_local_port()
331 def _udp_connect_command(self, remote_endpoint, connection_run_home,
332 cipher, cipher_key, bwlimit, txqueuelen):
334 # Set the remote endpoint
335 self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
337 # Planetlab TAPs always use PI headers
338 from nepi.resources.planetlab.tap import PlanetlabTap
339 if self.is_rm_instance(PlanetlabTap.get_rtype()):
342 remote_ip = remote_endpoint.node.get("ip")
344 local_port_file = os.path.join(self.run_home,
347 remote_port_file = os.path.join(self.run_home,
350 ret_file = os.path.join(self.run_home,
353 # Generate UDP connect command
354 # Use the start command to configure TAP with peer info
355 start_command = self._start_command
358 command.append(start_command)
360 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
361 command.append(") & (")
362 command.append("sudo -S")
363 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
364 command.append("python ${SRC}/linux-udp-connect.py")
365 command.append("-N %s" % self.get("deviceName"))
366 command.append("-t %s" % self.vif_type)
369 command.append("-l %s " % local_port_file)
370 command.append("-r %s " % remote_port_file)
371 command.append("-H %s " % remote_ip)
372 command.append("-R %s " % ret_file)
374 command.append("-c %s " % cipher)
376 command.append("-k %s " % cipher_key)
378 command.append("-q %s " % txqueuelen)
380 command.append("-b %s " % bwlimit)
384 command = " ".join(command)
385 command = self.replace_paths(command)
389 def _gre_connect_command(self, remote_endpoint, connection_run_home):
390 # Set the remote endpoint
391 self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
392 self.set("greRemote", remote_endpoint.node.get("ip"))
394 # Generate GRE connect command
396 command.append(self._stop_command)
397 command.append(") ; (")
398 command.append(self._start_gre_command)
401 command = " ".join(command)
402 command = self.replace_paths(command)
406 def establish_udp_connection(self, remote_endpoint, port):
407 # upload remote port number to file
408 rem_port = "%s\n" % port
409 self.node.upload(rem_port,
410 os.path.join(self.run_home, "remote_port"),
414 def verify_connection(self):
417 def terminate_connection(self):
418 if self._pid and self._ppid:
419 (out, err), proc = self.node.kill(self._pid, self._ppid,
422 # check if execution errors occurred
423 if proc.poll() and err:
424 msg = " Failed to Kill the Tap"
425 self.error(msg, out, err)
426 raise RuntimeError, msg
428 def check_status(self):
429 return self.node.status(self._pid, self._ppid)
431 def wait_local_port(self):
432 """ Waits until the local_port file for the endpoint is generated,
433 and returns the port number
436 return self.wait_file("local_port")
438 def wait_result(self):
439 """ Waits until the return code file for the endpoint is generated
442 return self.wait_file("ret_file")
444 def wait_file(self, filename):
445 """ Waits until file on endpoint is generated """
450 (out, err), proc = self.node.check_output(
451 self.run_home, filename)
459 msg = "Couldn't retrieve %s" % filename
460 self.error(msg, out, err)
461 raise RuntimeError, msg
466 def _start_command(self):
468 if not self.gre_enabled:
469 # Make sure to clean TAP if it existed
470 stop_command = self._stop_command
473 start_command.append("sudo -S ip tuntap add %s mode %s %s" % (
474 self.get("deviceName"),
476 "pi" if self.get("pi") else ""))
477 start_command.append("sudo -S ip link set %s up" % self.get("deviceName"))
478 start_command.append("sudo -S ip addr add %s/%d dev %s" % (
479 self.get("endpoint_ip"),
480 self.get("endpoint_prefix"),
481 self.get("deviceName"),
484 start_command = ";".join(start_command)
487 command.append(stop_command)
488 command.append(") ; (")
489 command.append(start_command)
492 return " ".join(command)
495 def _stop_command(self):
497 command.append("sudo -S ip link set %s down" % self.get("deviceName"))
498 command.append("sudo -S ip link del %s" % self.get("deviceName"))
500 return ";".join(command)
503 def _start_gre_command(self):
505 command.append("sudo -S modprobe ip_gre")
506 command.append("sudo -S ip link add %s type gre remote %s local %s ttl 64 csum key %s" % (
507 self.get("deviceName"),
508 self.get("greRemote"),
512 command.append("sudo -S ip addr add %s/%d peer %s/%d dev %s" % (
513 self.get("endpoint_ip"),
514 self.get("endpoint_prefix"),
515 self.get("pointopoint"),
516 self.get("endpoint_prefix"),
517 self.get("deviceName"),
519 command.append("sudo -S ip link set %s up " % self.get("deviceName"))
521 return ";".join(command)
528 def vif_prefix(self):
532 return os.path.join(self.run_home, "tap.sock")
534 def valid_connection(self, guid):