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.planetlab.node import PlanetlabNode
24 from nepi.util.timefuncs import tnow, tdiffsec
29 PYTHON_VSYS_VERSION = "1.0"
32 class PlanetlabTap(LinuxApplication):
33 _rtype = "planetlab::Tap"
34 _help = "Creates a TAP device on a PlanetLab host"
35 _backend = "planetlab"
38 def _register_attributes(cls):
39 ip = Attribute("ip", "IP of the endpoint. This is the attribute "
40 "you should use to establish a tunnel or a remote "
41 "connection between endpoint",
44 mac = Attribute("mac", "MAC Address",
47 prefix = Attribute("prefix", "IPv4 network prefix of the endpoint",
50 mtu = Attribute("mtu", "Maximum transmition unit for device",
53 devname = Attribute("deviceName",
54 "Name of the network interface (e.g. eth0, wlan0, etc)",
55 flags = Flags.NoWrite)
57 up = Attribute("up", "Link up",
60 snat = Attribute("snat", "Set SNAT=1",
64 pointopoint = Attribute("pointopoint", "Peer IP address",
67 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
70 txqueuelen = Attribute("txqueuelen", "Length of transmission queue",
73 gre_key = Attribute("greKey",
74 "GRE key to be used to configure GRE tunnel",
78 gre_remote = Attribute("greRemote",
79 "Public IP of remote endpoint for GRE tunnel",
82 tear_down = Attribute("tearDown",
83 "Bash script to be executed before releasing the resource",
86 cls._register_attribute(ip)
87 cls._register_attribute(mac)
88 cls._register_attribute(prefix)
89 cls._register_attribute(mtu)
90 cls._register_attribute(devname)
91 cls._register_attribute(up)
92 cls._register_attribute(snat)
93 cls._register_attribute(pointopoint)
94 cls._register_attribute(txqueuelen)
95 cls._register_attribute(gre_key)
96 cls._register_attribute(gre_remote)
97 cls._register_attribute(tear_down)
99 def __init__(self, ec, guid):
100 super(PlanetlabTap, self).__init__(ec, guid)
101 self._home = "tap-%s" % self.guid
102 self._gre_enabled = False
106 node = self.get_connected(PlanetlabNode.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
119 def upload_sources(self):
122 # vif-creation python script
123 pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
126 scripts.append(pl_vif_create)
128 # vif-up python script
129 pl_vif_up = os.path.join(os.path.dirname(__file__), "scripts",
132 scripts.append(pl_vif_up)
134 # vif-down python script
135 pl_vif_down = os.path.join(os.path.dirname(__file__), "scripts",
138 scripts.append(pl_vif_down)
140 # udp-connect python script
141 pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
142 "pl-vif-udp-connect.py")
144 scripts.append(pl_vif_connect)
146 # tunnel creation python script
147 tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
148 "scripts", "tunchannel.py")
150 scripts.append(tunchannel)
153 scripts = ";".join(scripts)
155 self.node.upload(scripts,
156 os.path.join(self.node.src_dir),
159 # upload stop.sh script
160 stop_command = self.replace_paths(self._stop_command)
162 self.node.upload_command(stop_command,
163 shfile = os.path.join(self.app_home, "stop.sh"),
164 # Overwrite file every time.
165 # The stop.sh has the path to the socket, which should change
166 # on every experiment run.
169 def upload_start_command(self):
170 # If GRE mode is enabled, TAP creation is delayed until the
171 # tunnel is established
172 if not self.gre_enabled:
173 # Overwrite file every time.
174 # The start.sh has the path to the socket, wich should change
175 # on every experiment run.
176 super(PlanetlabTap, self).upload_start_command(overwrite = True)
178 # We want to make sure the device is up and running
179 # before the deploy finishes, so we execute now the
180 # start script. We run it in background, because the
181 # TAP will live for as long as the process that
182 # created it is running, and wait until the TAP
184 self._run_in_background()
186 # After creating the TAP, the pl-vif-create.py script
187 # will write the name of the TAP to a file. We wait until
188 # we can read the interface name from the file.
189 vif_name = self.wait_vif_name()
190 self.set("deviceName", vif_name)
193 if not self.node or self.node.state < ResourceState.PROVISIONED:
194 self.ec.schedule(self.reschedule_delay, self.deploy)
196 if not self.get("command"):
197 self.set("command", self._start_command)
199 if not self.get("depends"):
200 self.set("depends", self._dependencies)
202 if not self.get("install"):
203 self.set("install", self._install)
211 if self.state == ResourceState.READY:
212 command = self.get("command")
213 self.info("Starting command '%s'" % command)
217 msg = " Failed to execute command '%s'" % command
218 self.error(msg, out, err)
219 raise RuntimeError, msg
222 command = self.get('command') or ''
224 if self.state == ResourceState.STARTED:
225 self.info("Stopping command '%s'" % command)
227 command = "bash %s" % os.path.join(self.app_home, "stop.sh")
228 (out, err), proc = self.execute_command(command,
232 msg = " Failed to stop command '%s' " % command
233 self.error(msg, out, err)
239 state_check_delay = 0.5
240 if self._state == ResourceState.STARTED and \
241 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
243 if self.get("deviceName"):
244 (out, err), proc = self.node.execute("ifconfig")
246 if out.strip().find(self.get("deviceName")) == -1:
247 # tap is not running is not running (socket not found)
250 self._last_state_check = tnow()
254 def do_release(self):
255 # Node needs to wait until all associated RMs are released
257 from nepi.resources.linux.tunnel import LinuxTunnel
258 rms = self.get_connected(LinuxTunnel.get_rtype())
261 if rm.state < ResourceState.STOPPED:
262 self.ec.schedule(self.reschedule_delay, self.release)
265 super(PlanetlabTap, self).do_release()
267 def wait_vif_name(self, exec_run_home = None):
268 """ Waits until the vif_name file for the command is generated,
269 and returns the vif_name for the device """
273 # The vif_name file will be created in the tap-home, while the
274 # current execution home might be elsewhere to check for errors
275 # (e.g. could be a tunnel-home)
276 if not exec_run_home:
277 exec_run_home = self.run_home
280 (out, err), proc = self.node.check_output(self.run_home, "vif_name")
283 (out, err), proc = self.node.check_errors(exec_run_home)
286 raise RuntimeError, err
289 vif_name = out.strip()
295 msg = "Couldn't retrieve vif_name"
296 self.error(msg, out, err)
297 raise RuntimeError, msg
301 def gre_connect(self, remote_endpoint, connection_app_home,
302 connection_run_home):
303 gre_connect_command = self._gre_connect_command(
304 remote_endpoint, connection_run_home)
306 # upload command to connect.sh script
307 shfile = os.path.join(connection_app_home, "gre-connect.sh")
308 self.node.upload_command(gre_connect_command,
312 # invoke connect script
313 cmd = "bash %s" % shfile
314 (out, err), proc = self.node.run(cmd, connection_run_home)
316 # check if execution errors occurred
317 msg = " Failed to connect endpoints "
319 if proc.poll() or err:
320 self.error(msg, out, err)
321 raise RuntimeError, msg
323 # Wait for pid file to be generated
324 pid, ppid = self.node.wait_pid(connection_run_home)
326 # If the process is not running, check for error information
327 # on the remote machine
328 if not pid or not ppid:
329 (out, err), proc = self.node.check_errors(connection_run_home)
330 # Out is what was written in the stderr file
332 msg = " Failed to start command '%s' " % command
333 self.error(msg, out, err)
334 raise RuntimeError, msg
336 # After creating the TAP, the pl-vif-create.py script
337 # will write the name of the TAP to a file. We wait until
338 # we can read the interface name from the file.
339 vif_name = self.wait_vif_name(exec_run_home = connection_run_home)
340 self.set("deviceName", vif_name)
344 def initiate_udp_connection(self, remote_endpoint, connection_app_home,
345 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
346 port = self.udp_connect(remote_endpoint, connection_app_home,
347 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
350 def udp_connect(self, remote_endpoint, connection_app_home,
351 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
352 udp_connect_command = self._udp_connect_command(
353 remote_endpoint, connection_run_home,
354 cipher, cipher_key, bwlimit, txqueuelen)
356 # upload command to connect.sh script
357 shfile = os.path.join(self.app_home, "udp-connect.sh")
358 self.node.upload_command(udp_connect_command,
362 # invoke connect script
363 cmd = "bash %s" % shfile
364 (out, err), proc = self.node.run(cmd, self.run_home)
366 # check if execution errors occurred
367 msg = "Failed to connect endpoints "
370 self.error(msg, out, err)
371 raise RuntimeError, msg
373 # Wait for pid file to be generated
374 self._pid, self._ppid = self.node.wait_pid(self.run_home)
376 # If the process is not running, check for error information
377 # on the remote machine
378 if not self._pid or not self._ppid:
379 (out, err), proc = self.node.check_errors(self.run_home)
380 # Out is what was written in the stderr file
382 msg = " Failed to start command '%s' " % command
383 self.error(msg, out, err)
384 raise RuntimeError, msg
386 port = self.wait_local_port()
390 def _udp_connect_command(self, remote_endpoint, connection_run_home,
391 cipher, cipher_key, bwlimit, txqueuelen):
393 # Set the remote endpoint, (private) IP of the device
394 self.set("pointopoint", remote_endpoint.get("ip"))
396 # Public IP of the node
397 remote_ip = remote_endpoint.node.get("ip")
399 local_port_file = os.path.join(self.run_home,
402 remote_port_file = os.path.join(self.run_home,
405 ret_file = os.path.join(self.run_home,
408 # Generate UDP connect command
409 # Use pl-vif-up.py script to configure TAP with peer info
410 vif_up_command = self._vif_up_command
413 command.append(vif_up_command)
415 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
416 command.append(") & (")
417 command.append("sudo -S")
418 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
419 command.append("python ${SRC}/pl-vif-udp-connect.py")
420 command.append("-t %s" % self.vif_type)
421 command.append("-S %s " % self.sock_name)
422 command.append("-l %s " % local_port_file)
423 command.append("-r %s " % remote_port_file)
424 command.append("-H %s " % remote_ip)
425 command.append("-R %s " % ret_file)
427 command.append("-c %s " % cipher)
429 command.append("-k %s " % cipher_key)
431 command.append("-q %s " % txqueuelen)
433 command.append("-b %s " % bwlimit)
437 command = " ".join(command)
438 command = self.replace_paths(command)
442 def establish_udp_connection(self, remote_endpoint, port):
443 # upload remote port number to file
444 rem_port = "%s\n" % port
445 self.node.upload(rem_port,
446 os.path.join(self.run_home, "remote_port"),
450 def verify_connection(self):
453 def terminate_connection(self):
454 if self._pid and self._ppid:
455 (out, err), proc = self.node.kill(self._pid, self._ppid,
458 # check if execution errors occurred
459 if proc.poll() and err:
460 msg = " Failed to Kill the Tap"
461 self.error(msg, out, err)
462 raise RuntimeError, msg
464 def check_status(self):
465 return self.node.status(self._pid, self._ppid)
467 def wait_local_port(self):
468 """ Waits until the local_port file for the endpoint is generated,
469 and returns the port number
472 return self.wait_file("local_port")
474 def wait_result(self):
475 """ Waits until the return code file for the endpoint is generated
478 return self.wait_file("ret_file")
480 def wait_file(self, filename):
481 """ Waits until file on endpoint is generated """
486 (out, err), proc = self.node.check_output(
487 self.run_home, filename)
495 msg = "Couldn't retrieve %s" % filename
496 self.error(msg, out, err)
497 raise RuntimeError, msg
501 def _gre_connect_command(self, remote_endpoint, connection_run_home):
502 # Set the remote endpoint, (private) IP of the device
503 self.set("pointopoint", remote_endpoint.get("ip"))
504 # Public IP of the node
505 self.set("greRemote", remote_endpoint.node.get("ip"))
507 # Generate GRE connect command
509 # Use vif_down command to first kill existing TAP in GRE mode
510 vif_down_command = self._vif_down_command
512 # Use pl-vif-up.py script to configure TAP with peer info
513 vif_up_command = self._vif_up_command
516 command.append(vif_down_command)
517 command.append(") ; (")
518 command.append(vif_up_command)
521 command = " ".join(command)
522 command = self.replace_paths(command)
527 def _start_command(self):
531 command = ["sudo -S python ${SRC}/pl-vif-create.py"]
533 command.append("-t %s" % self.vif_type)
534 command.append("-a %s" % self.get("ip"))
535 command.append("-n %s" % self.get("prefix"))
536 command.append("-f %s " % self.vif_name_file)
537 command.append("-S %s " % self.sock_name)
539 if self.get("snat") == True:
542 if self.get("pointopoint"):
543 command.append("-p %s" % self.get("pointopoint"))
545 if self.get("txqueuelen"):
546 command.append("-q %s" % self.get("txqueuelen"))
548 return " ".join(command)
551 def _stop_command(self):
553 command = self._vif_down_command
555 command = ["sudo -S "]
556 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
557 command.append("python ${SRC}/pl-vif-down.py")
558 command.append("-S %s " % self.sock_name)
559 command = " ".join(command)
564 def _vif_up_command(self):
566 device_name = "%s" % self.guid
568 device_name = self.get("deviceName")
570 # Use pl-vif-up.py script to configure TAP
571 command = ["sudo -S "]
572 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
573 command.append("python ${SRC}/pl-vif-up.py")
574 command.append("-u %s" % self.node.get("username"))
575 command.append("-N %s" % device_name)
576 command.append("-t %s" % self.vif_type)
577 command.append("-a %s" % self.get("ip"))
578 command.append("-n %s" % self.get("prefix"))
580 if self.get("snat") == True:
583 if self.get("pointopoint"):
584 command.append("-p %s" % self.get("pointopoint"))
586 if self.get("txqueuelen"):
587 command.append("-q %s" % self.get("txqueuelen"))
590 command.append("-g %s" % self.get("greKey"))
591 command.append("-G %s" % self.get("greRemote"))
593 command.append("-f %s " % self.vif_name_file)
595 return " ".join(command)
598 def _vif_down_command(self):
600 device_name = "%s" % self.guid
602 device_name = self.get("deviceName")
604 command = ["sudo -S "]
605 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
606 command.append("python ${SRC}/pl-vif-down.py")
607 command.append("-N %s " % device_name)
610 command.append("-u %s" % self.node.get("username"))
611 command.append("-t %s" % self.vif_type)
614 return " ".join(command)
621 def vif_name_file(self):
622 return os.path.join(self.run_home, "vif_name")
626 return os.path.join(self.run_home, "tap.sock")
629 def _dependencies(self):
630 return "mercurial make gcc"
634 # Install python-vsys and python-passfd
635 install_vsys = ( " ( "
636 " python -c 'import vsys, os; vsys.__version__ == \"%(version)s\" or os._exit(1)' "
641 " hg clone http://nepi.inria.fr/code/python-vsys ; "
644 " sudo -S make install "
646 "version": PYTHON_VSYS_VERSION
649 install_passfd = ( " ( python -c 'import passfd' ) "
653 " hg clone http://nepi.inria.fr/code/python-passfd ; "
654 " cd python-passfd ; "
656 " sudo -S make install "
659 return "%s ; %s" % ( install_vsys, install_passfd )
661 def valid_connection(self, guid):