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