6947080525a514697cd8fe336b39096989202a27
[nepi.git] / src / nepi / resources / planetlab / tap.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
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.
9 #
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.
14 #
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/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 from nepi.execution.attribute import Attribute, Flags, Types
21 from nepi.execution.resource import clsinit_copy, ResourceState, \
22         reschedule_delay
23 from nepi.resources.linux.application import LinuxApplication
24 from nepi.resources.planetlab.node import PlanetlabNode
25 from nepi.util.timefuncs import tnow, tdiffsec
26
27 import os
28 import socket
29 import time
30
31 # TODO:
32 #       - CREATE GRE - PlanetlabGRE - it only needs to set the gre and remote
33 #               properties when configuring the vif_up
34
35 PYTHON_VSYS_VERSION = "1.0"
36
37 @clsinit_copy
38 class PlanetlabTap(LinuxApplication):
39     _rtype = "PlanetlabTap"
40     _help = "Creates a TAP device on a PlanetLab host"
41     _backend = "planetlab"
42
43     @classmethod
44     def _register_attributes(cls):
45         ip4 = Attribute("ip4", "IPv4 Address",
46               flags = Flags.Design)
47
48         mac = Attribute("mac", "MAC Address",
49                 flags = Flags.Design)
50
51         prefix4 = Attribute("prefix4", "IPv4 network prefix",
52                 type = Types.Integer,
53                 flags = Flags.Design)
54
55         mtu = Attribute("mtu", "Maximum transmition unit for device",
56                 type = Types.Integer)
57
58         devname = Attribute("deviceName", 
59                 "Name of the network interface (e.g. eth0, wlan0, etc)",
60                 flags = Flags.NoWrite)
61
62         up = Attribute("up", "Link up", 
63                 type = Types.Bool)
64         
65         snat = Attribute("snat", "Set SNAT=1", 
66                 type = Types.Bool,
67                 flags = Flags.Design)
68         
69         pointopoint = Attribute("pointopoint", "Peer IP address", 
70                 flags = Flags.Design)
71
72         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
73                 flags = Flags.Design)
74
75         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
76                 flags = Flags.Design)
77
78         gre_key = Attribute("greKey", 
79                 "GRE key to be used to configure GRE tunnel", 
80                 default = "1",
81                 flags = Flags.Design)
82
83         gre_remote = Attribute("greRemote", 
84                 "Public IP of remote endpoint for GRE tunnel", 
85                 flags = Flags.Design)
86
87         tear_down = Attribute("tearDown", 
88                 "Bash script to be executed before releasing the resource",
89                 flags = Flags.Design)
90
91         cls._register_attribute(ip4)
92         cls._register_attribute(mac)
93         cls._register_attribute(prefix4)
94         cls._register_attribute(mtu)
95         cls._register_attribute(devname)
96         cls._register_attribute(up)
97         cls._register_attribute(snat)
98         cls._register_attribute(pointopoint)
99         cls._register_attribute(txqueuelen)
100         cls._register_attribute(gre_key)
101         cls._register_attribute(gre_remote)
102         cls._register_attribute(tear_down)
103
104     def __init__(self, ec, guid):
105         super(PlanetlabTap, self).__init__(ec, guid)
106         self._home = "tap-%s" % self.guid
107         self._gre_enabled = False
108
109     @property
110     def node(self):
111         node = self.get_connected(PlanetlabNode.get_rtype())
112         if node: return node[0]
113         return None
114
115     @property
116     def gre_enabled(self):
117         if not self._gre_enabled:
118             from nepi.resources.linux.gretunnel import LinuxGRETunnel
119             gre = self.get_connected(LinuxGRETunnel.get_rtype())
120             if gre: self._gre_enabled = True
121
122         return self._gre_enabled
123
124     def upload_sources(self):
125         scripts = []
126
127         # vif-creation python script
128         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
129                 "pl-vif-create.py")
130
131         scripts.append(pl_vif_create)
132         
133         # vif-up python script
134         pl_vif_up = os.path.join(os.path.dirname(__file__), "scripts",
135                 "pl-vif-up.py")
136         
137         scripts.append(pl_vif_up)
138
139         # vif-down python script
140         pl_vif_down = os.path.join(os.path.dirname(__file__), "scripts",
141                 "pl-vif-down.py")
142         
143         scripts.append(pl_vif_down)
144
145         # udp-connect python script
146         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
147                 "pl-vif-udp-connect.py")
148         
149         scripts.append(pl_vif_connect)
150
151         # tunnel creation python script
152         tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
153                 "scripts", "tunchannel.py")
154
155         scripts.append(tunchannel)
156
157         # Upload scripts
158         scripts = ";".join(scripts)
159
160         self.node.upload(scripts,
161                 os.path.join(self.node.src_dir),
162                 overwrite = False)
163
164         # upload stop.sh script
165         stop_command = self.replace_paths(self._stop_command)
166
167         self.node.upload(stop_command,
168                 os.path.join(self.app_home, "stop.sh"),
169                 text = True,
170                 # Overwrite file every time. 
171                 # The stop.sh has the path to the socket, which should change
172                 # on every experiment run.
173                 overwrite = True)
174
175     def upload_start_command(self):
176         # If GRE mode is enabled, TAP creation is delayed until the
177         # tunnel is established
178         if not self.gre_enabled:
179             # Overwrite file every time. 
180             # The start.sh has the path to the socket, wich should change
181             # on every experiment run.
182             super(PlanetlabTap, self).upload_start_command(overwrite = True)
183
184             # We want to make sure the device is up and running
185             # before the deploy finishes, so we execute now the 
186             # start script. We run it in background, because the 
187             # TAP will live for as long as the process that 
188             # created it is running, and wait until the TAP  
189             # is created. 
190             self._run_in_background()
191             
192             # After creating the TAP, the pl-vif-create.py script
193             # will write the name of the TAP to a file. We wait until
194             # we can read the interface name from the file.
195             vif_name = self.wait_vif_name()
196             self.set("deviceName", vif_name) 
197
198     def do_deploy(self):
199         if not self.node or self.node.state < ResourceState.PROVISIONED:
200             self.ec.schedule(reschedule_delay, self.deploy)
201         else:
202             if not self.get("command"):
203                 self.set("command", self._start_command)
204
205             if not self.get("depends"):
206                 self.set("depends", self._dependencies)
207
208             if not self.get("install"):
209                 self.set("install", self._install)
210
211             self.do_discover()
212             self.do_provision()
213
214             self.set_ready()
215
216     def do_start(self):
217         if self.state == ResourceState.READY:
218             command = self.get("command")
219             self.info("Starting command '%s'" % command)
220
221             self.set_started()
222         else:
223             msg = " Failed to execute command '%s'" % command
224             self.error(msg, out, err)
225             raise RuntimeError, msg
226
227     def do_stop(self):
228         command = self.get('command') or ''
229         
230         if self.state == ResourceState.STARTED:
231             self.info("Stopping command '%s'" % command)
232
233             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
234             (out, err), proc = self.execute_command(command,
235                     blocking = True)
236
237             if err:
238                 msg = " Failed to stop command '%s' " % command
239                 self.error(msg, out, err)
240
241             self.set_stopped()
242
243     @property
244     def state(self):
245         state_check_delay = 0.5
246         if self._state == ResourceState.STARTED and \
247                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
248
249             if self.get("deviceName"):
250                 (out, err), proc = self.node.execute("ifconfig")
251
252                 if out.strip().find(self.get("deviceName")) == -1: 
253                     # tap is not running is not running (socket not found)
254                     self.set_stopped()
255
256             self._last_state_check = tnow()
257
258         return self._state
259
260     def do_release(self):
261         # Node needs to wait until all associated RMs are released
262         # to be released
263         from nepi.resources.linux.tunnel import LinuxTunnel
264         rms = self.get_connected(LinuxTunnel.get_rtype())
265
266         for rm in rms:
267             if rm.state < ResourceState.STOPPED:
268                 self.ec.schedule(reschedule_delay, self.release)
269                 return 
270
271         super(PlanetlabTap, self).do_release()
272
273     def wait_vif_name(self):
274         """ Waits until the vif_name file for the command is generated, 
275             and returns the vif_name for the device """
276         vif_name = None
277         delay = 0.5
278
279         for i in xrange(20):
280             (out, err), proc = self.node.check_output(self.run_home, "vif_name")
281
282             if proc.poll() > 0:
283                 (out, err), proc = self.node.check_errors(self.run_home)
284                 
285                 if err.strip():
286                     raise RuntimeError, err
287
288             if out:
289                 vif_name = out.strip()
290                 break
291             else:
292                 time.sleep(delay)
293                 delay = delay * 1.5
294         else:
295             msg = "Couldn't retrieve vif_name"
296             self.error(msg, out, err)
297             raise RuntimeError, msg
298
299         return vif_name
300
301     def udp_connect_command(self, remote_endpoint, connection_run_home, 
302             cipher, cipher_key, bwlimit, txqueuelen):
303
304         # Set the remote endpoint
305         self.set("pointopoint", remote_endpoint.get("ip4"))
306
307         remote_ip = socket.gethostbyname(
308                 remote_endpoint.node.get("hostname"))
309
310         local_port_file = os.path.join(connection_run_home, 
311                 "local_port")
312
313         remote_port_file = os.path.join(connection_run_home, 
314                 "remote_port")
315
316         ret_file = os.path.join(connection_run_home, 
317                 "ret_file")
318
319         # Generate UDP connect command
320         # Use pl-vif-up.py script to configure TAP with peer info
321         vif_up_command = self._vif_up_command
322         
323         command = ["( "]
324         command.append(vif_up_command)
325
326         # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
327         command.append(") & (")
328         command.append("sudo -S")
329         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
330         command.append("python ${SRC}/pl-vif-udp-connect.py")
331         command.append("-t %s" % self.vif_type)
332         command.append("-S %s " % self.sock_name)
333         command.append("-l %s " % local_port_file)
334         command.append("-r %s " % remote_port_file)
335         command.append("-H %s " % remote_ip)
336         command.append("-R %s " % ret_file)
337         if cipher:
338             command.append("-c %s " % cipher)
339         if cipher_key:
340             command.append("-k %s " % cipher_key)
341         if txqueuelen:
342             command.append("-q %s " % txqueuelen)
343         if bwlimit:
344             command.append("-b %s " % bwlimit)
345
346         command.append(")")
347
348         command = " ".join(command)
349         command = self.replace_paths(command)
350
351         return command
352
353     def gre_connect_command(self, remote_endpoint, connection_run_home): 
354         # Set the remote endpoint
355         self.set("pointopoint", remote_endpoint.get("ip4"))
356         self.set("gre_remote", socket.gethostbyname(
357             remote_endpoint.node.get("hostname")))
358
359         # Generate GRE connect command
360
361         # Use vif_down command to first kill existing TAP in GRE mode
362         vif_down_command = self._vif_command_command
363
364         # Use pl-vif-up.py script to configure TAP with peer info
365         vif_up_command = self._vif_up_command
366         
367         command = ["("]
368         command.append(vif_down_command)
369         command.append(") ; (")
370         command.append(vif_up_command)
371         command.append(")")
372
373         command = " ".join(command)
374         command = self.replace_paths(command)
375
376         return command
377
378     @property
379     def _start_command(self):
380         if self.gre_enabled:
381             command = []
382         else:
383             command = ["sudo -S python ${SRC}/pl-vif-create.py"]
384             
385             command.append("-t %s" % self.vif_type)
386             command.append("-a %s" % self.get("ip4"))
387             command.append("-n %d" % self.get("prefix4"))
388             command.append("-f %s " % self.vif_name_file)
389             command.append("-S %s " % self.sock_name)
390
391             if self.get("snat") == True:
392                 command.append("-s")
393
394             if self.get("pointopoint"):
395                 command.append("-p %s" % self.get("pointopoint"))
396             
397             if self.get("txqueuelen"):
398                 command.append("-q %s" % self.get("txqueuelen"))
399
400         return " ".join(command)
401
402     @property
403     def _stop_command(self):
404         if self.gre_enabled:
405             command = self._vif_down_command()
406         else:
407             command = ["sudo -S "]
408             command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
409             command.append("python ${SRC}/pl-vif-down.py")
410             command.append("-S %s " % self.sock_name)
411             command = " ".join(command)
412
413         return command
414
415     @property
416     def _vif_up_command(self):
417         if self.gre_enabled:
418             device_name = "%s" % self.guid
419         else:
420             device_name = self.get("deviceName")
421
422         # Use pl-vif-up.py script to configure TAP
423         command = ["sudo -S "]
424         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
425         command.append("python ${SRC}/pl-vif-up.py")
426         command.append("-N %s" % self.get("deviceName"))
427         command.append("-t %s" % self.vif_type)
428         command.append("-a %s" % self.get("ip4"))
429         command.append("-n %d" % self.get("prefix4"))
430
431         if self.get("snat") == True:
432             command.append("-s")
433
434         if self.get("pointopoint"):
435             command.append("-p %s" % self.get("pointopoint"))
436         
437         if self.get("txqueuelen"):
438             command.append("-q %s" % self.get("txqueuelen"))
439
440         if self.gre_enabled:
441             command.append("-g %s" % self.gre("greKey"))
442             command.append("-G %s" % self.gre("greRemote"))
443         
444         command.append("-f %s " % self.vif_name_file)
445
446         return " ".join(command)
447
448     @property
449     def _vif_down_command(self):
450         command = ["sudo -S "]
451         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
452         command.append("python ${SRC}/pl-vif-down.py")
453         command.append("-D")
454         command.append("-N %s " % self.get("deviceName"))
455
456         return " ".join(command)
457
458     @property
459     def vif_type(self):
460         return "IFF_TAP"
461
462     @property
463     def vif_name_file(self):
464         return os.path.join(self.run_home, "vif_name")
465
466     @property
467     def sock_name(self):
468         return os.path.join(self.run_home, "tap.sock")
469
470     @property
471     def _dependencies(self):
472         return "mercurial make gcc"
473
474     @property
475     def _install(self):
476         # Install python-vsys and python-passfd
477         install_vsys = ( " ( "
478                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
479                     " ) "
480                     " || "
481                     " ( "
482                     "   cd ${SRC} ; "
483                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
484                     "   cd python-vsys ; "
485                     "   make all ; "
486                     "   sudo -S make install "
487                     " )" ) % ({
488                         "version": PYTHON_VSYS_VERSION
489                         })
490
491         install_passfd = ( " ( python -c 'import passfd' ) "
492                     " || "
493                     " ( "
494                     "   cd ${SRC} ; "
495                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
496                     "   cd python-passfd ; "
497                     "   make all ; "
498                     "   sudo -S make install "
499                     " )" )
500
501         return "%s ; %s" % ( install_vsys, install_passfd )
502
503     def valid_connection(self, guid):
504         # TODO: Validate!
505         return True
506