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, \
23 from nepi.resources.linux.application import LinuxApplication
24 from nepi.resources.planetlab.node import PlanetlabNode
25 from nepi.util.timefuncs import tnow, tdiffsec
30 PYTHON_VSYS_VERSION = "1.0"
33 class PlanetlabTap(LinuxApplication):
34 _rtype = "PlanetlabTap"
35 _help = "Creates a TAP device on a PlanetLab host"
36 _backend = "planetlab"
39 def _register_attributes(cls):
40 ip4 = Attribute("ip4", "IPv4 Address",
43 mac = Attribute("mac", "MAC Address",
46 prefix4 = Attribute("prefix4", "IPv4 network prefix",
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(ip4)
87 cls._register_attribute(mac)
88 cls._register_attribute(prefix4)
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(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(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 udp_connect(self, remote_endpoint, connection_app_home,
345 connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
346 udp_connect_command = self._udp_connect_command(
347 remote_endpoint, connection_run_home,
348 cipher, cipher_key, bwlimit, txqueuelen)
350 # upload command to connect.sh script
351 shfile = os.path.join(connection_app_home, "udp-connect.sh")
352 self.node.upload_command(udp_connect_command,
356 # invoke connect script
357 cmd = "bash %s" % shfile
358 (out, err), proc = self.node.run(cmd, connection_run_home)
360 # check if execution errors occurred
361 msg = "Failed to connect endpoints "
364 self.error(msg, out, err)
365 raise RuntimeError, msg
367 # Wait for pid file to be generated
368 pid, ppid = self.node.wait_pid(connection_run_home)
370 # If the process is not running, check for error information
371 # on the remote machine
372 if not pid or not ppid:
373 (out, err), proc = self.node.check_errors(connection_run_home)
374 # Out is what was written in the stderr file
376 msg = " Failed to start command '%s' " % command
377 self.error(msg, out, err)
378 raise RuntimeError, msg
382 def _udp_connect_command(self, remote_endpoint, connection_run_home,
383 cipher, cipher_key, bwlimit, txqueuelen):
385 # Set the remote endpoint
386 self.set("pointopoint", remote_endpoint.get("ip4"))
388 print "REMOTE IP", remote_ip
389 remote_ip = remote_endpoint.node.get("ip")
391 local_port_file = os.path.join(connection_run_home,
394 remote_port_file = os.path.join(connection_run_home,
397 ret_file = os.path.join(connection_run_home,
400 # Generate UDP connect command
401 # Use pl-vif-up.py script to configure TAP with peer info
402 vif_up_command = self._vif_up_command
405 command.append(vif_up_command)
407 # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
408 command.append(") & (")
409 command.append("sudo -S")
410 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
411 command.append("python ${SRC}/pl-vif-udp-connect.py")
412 command.append("-t %s" % self.vif_type)
413 command.append("-S %s " % self.sock_name)
414 command.append("-l %s " % local_port_file)
415 command.append("-r %s " % remote_port_file)
416 command.append("-H %s " % remote_ip)
417 command.append("-R %s " % ret_file)
419 command.append("-c %s " % cipher)
421 command.append("-k %s " % cipher_key)
423 command.append("-q %s " % txqueuelen)
425 command.append("-b %s " % bwlimit)
429 command = " ".join(command)
430 command = self.replace_paths(command)
434 def _gre_connect_command(self, remote_endpoint, connection_run_home):
435 # Set the remote endpoint
436 self.set("pointopoint", remote_endpoint.get("ip4"))
437 self.set("greRemote", remote_endpoint.node.get("ip"))
439 # Generate GRE connect command
441 # Use vif_down command to first kill existing TAP in GRE mode
442 vif_down_command = self._vif_down_command
444 # Use pl-vif-up.py script to configure TAP with peer info
445 vif_up_command = self._vif_up_command
448 command.append(vif_down_command)
449 command.append(") ; (")
450 command.append(vif_up_command)
453 command = " ".join(command)
454 command = self.replace_paths(command)
459 def _start_command(self):
463 command = ["sudo -S python ${SRC}/pl-vif-create.py"]
465 command.append("-t %s" % self.vif_type)
466 command.append("-a %s" % self.get("ip4"))
467 command.append("-n %d" % self.get("prefix4"))
468 command.append("-f %s " % self.vif_name_file)
469 command.append("-S %s " % self.sock_name)
471 if self.get("snat") == True:
474 if self.get("pointopoint"):
475 command.append("-p %s" % self.get("pointopoint"))
477 if self.get("txqueuelen"):
478 command.append("-q %s" % self.get("txqueuelen"))
480 return " ".join(command)
483 def _stop_command(self):
485 command = self._vif_down_command
487 command = ["sudo -S "]
488 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
489 command.append("python ${SRC}/pl-vif-down.py")
490 command.append("-S %s " % self.sock_name)
491 command = " ".join(command)
496 def _vif_up_command(self):
498 device_name = "%s" % self.guid
500 device_name = self.get("deviceName")
502 # Use pl-vif-up.py script to configure TAP
503 command = ["sudo -S "]
504 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
505 command.append("python ${SRC}/pl-vif-up.py")
506 command.append("-u %s" % self.node.get("username"))
507 command.append("-N %s" % device_name)
508 command.append("-t %s" % self.vif_type)
509 command.append("-a %s" % self.get("ip4"))
510 command.append("-n %d" % self.get("prefix4"))
512 if self.get("snat") == True:
515 if self.get("pointopoint"):
516 command.append("-p %s" % self.get("pointopoint"))
518 if self.get("txqueuelen"):
519 command.append("-q %s" % self.get("txqueuelen"))
522 command.append("-g %s" % self.get("greKey"))
523 command.append("-G %s" % self.get("greRemote"))
525 command.append("-f %s " % self.vif_name_file)
527 return " ".join(command)
530 def _vif_down_command(self):
532 device_name = "%s" % self.guid
534 device_name = self.get("deviceName")
536 command = ["sudo -S "]
537 command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
538 command.append("python ${SRC}/pl-vif-down.py")
539 command.append("-N %s " % device_name)
542 command.append("-u %s" % self.node.get("username"))
543 command.append("-t %s" % self.vif_type)
546 return " ".join(command)
553 def vif_name_file(self):
554 return os.path.join(self.run_home, "vif_name")
558 return os.path.join(self.run_home, "tap.sock")
561 def _dependencies(self):
562 return "mercurial make gcc"
566 # Install python-vsys and python-passfd
567 install_vsys = ( " ( "
568 " python -c 'import vsys, os; vsys.__version__ == \"%(version)s\" or os._exit(1)' "
573 " hg clone http://nepi.inria.fr/code/python-vsys ; "
576 " sudo -S make install "
578 "version": PYTHON_VSYS_VERSION
581 install_passfd = ( " ( python -c 'import passfd' ) "
585 " hg clone http://nepi.inria.fr/code/python-passfd ; "
586 " cd python-passfd ; "
588 " sudo -S make install "
591 return "%s ; %s" % ( install_vsys, install_passfd )
593 def valid_connection(self, guid):