4df138bb89b288e3304fa3ff2f3f73d025d9e726
[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 time
29
30 PYTHON_VSYS_VERSION = "1.0"
31
32 @clsinit_copy
33 class PlanetlabTap(LinuxApplication):
34     _rtype = "PlanetlabTap"
35     _help = "Creates a TAP device on a PlanetLab host"
36     _backend = "planetlab"
37
38     @classmethod
39     def _register_attributes(cls):
40         endpoint_ip = Attribute("endpoint_ip", "IP of the endpoint. This is the attribute " 
41                                 "you should use to establish a tunnel or a remote "
42                                 "connection between endpoint",
43               flags = Flags.Design)
44
45         mac = Attribute("mac", "MAC Address",
46                 flags = Flags.Design)
47
48         endpoint_prefix = Attribute("endpoint_prefix", "IPv4 network prefix of the endpoint",
49                 type = Types.Integer,
50                 flags = Flags.Design)
51
52         mtu = Attribute("mtu", "Maximum transmition unit for device",
53                 type = Types.Integer)
54
55         devname = Attribute("deviceName", 
56                 "Name of the network interface (e.g. eth0, wlan0, etc)",
57                 flags = Flags.NoWrite)
58
59         up = Attribute("up", "Link up", 
60                 type = Types.Bool)
61         
62         snat = Attribute("snat", "Set SNAT=1", 
63                 type = Types.Bool,
64                 flags = Flags.Design)
65         
66         pointopoint = Attribute("pointopoint", "Peer IP address", 
67                 flags = Flags.Design)
68
69         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
70                 flags = Flags.Design)
71
72         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
73                 flags = Flags.Design)
74
75         gre_key = Attribute("greKey", 
76                 "GRE key to be used to configure GRE tunnel", 
77                 default = "1",
78                 flags = Flags.Design)
79
80         gre_remote = Attribute("greRemote", 
81                 "Public IP of remote endpoint for GRE tunnel", 
82                 flags = Flags.Design)
83
84         tear_down = Attribute("tearDown", 
85                 "Bash script to be executed before releasing the resource",
86                 flags = Flags.Design)
87
88         cls._register_attribute(endpoint_ip)
89         cls._register_attribute(mac)
90         cls._register_attribute(endpoint_prefix)
91         cls._register_attribute(mtu)
92         cls._register_attribute(devname)
93         cls._register_attribute(up)
94         cls._register_attribute(snat)
95         cls._register_attribute(pointopoint)
96         cls._register_attribute(txqueuelen)
97         cls._register_attribute(gre_key)
98         cls._register_attribute(gre_remote)
99         cls._register_attribute(tear_down)
100
101     def __init__(self, ec, guid):
102         super(PlanetlabTap, self).__init__(ec, guid)
103         self._home = "tap-%s" % self.guid
104         self._gre_enabled = False
105
106     @property
107     def node(self):
108         node = self.get_connected(PlanetlabNode.get_rtype())
109         if node: return node[0]
110         raise RuntimeError, "TAP/TUN devices must be connected to Node"
111
112     @property
113     def gre_enabled(self):
114         if not self._gre_enabled:
115             from nepi.resources.linux.gretunnel import LinuxGRETunnel
116             gre = self.get_connected(LinuxGRETunnel.get_rtype())
117             if gre: self._gre_enabled = True
118
119         return self._gre_enabled
120
121     def upload_sources(self):
122         scripts = []
123
124         # vif-creation python script
125         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
126                 "pl-vif-create.py")
127
128         scripts.append(pl_vif_create)
129         
130         # vif-up python script
131         pl_vif_up = os.path.join(os.path.dirname(__file__), "scripts",
132                 "pl-vif-up.py")
133         
134         scripts.append(pl_vif_up)
135
136         # vif-down python script
137         pl_vif_down = os.path.join(os.path.dirname(__file__), "scripts",
138                 "pl-vif-down.py")
139         
140         scripts.append(pl_vif_down)
141
142         # udp-connect python script
143         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
144                 "pl-vif-udp-connect.py")
145         
146         scripts.append(pl_vif_connect)
147
148         # tunnel creation python script
149         tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
150                 "scripts", "tunchannel.py")
151
152         scripts.append(tunchannel)
153
154         # Upload scripts
155         scripts = ";".join(scripts)
156
157         self.node.upload(scripts,
158                 os.path.join(self.node.src_dir),
159                 overwrite = False)
160
161         # upload stop.sh script
162         stop_command = self.replace_paths(self._stop_command)
163
164         self.node.upload_command(stop_command,
165                 shfile = os.path.join(self.app_home, "stop.sh"),
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, exec_run_home = None):
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         # The vif_name file will be created in the tap-home, while the
276         # current execution home might be elsewhere to check for errors
277         # (e.g. could be a tunnel-home)
278         if not exec_run_home:
279             exec_run_home = self.run_home
280
281         for i in xrange(20):
282             (out, err), proc = self.node.check_output(self.run_home, "vif_name")
283
284             if proc.poll() > 0:
285                 (out, err), proc = self.node.check_errors(exec_run_home)
286                 
287                 if err.strip():
288                     raise RuntimeError, err
289
290             if out:
291                 vif_name = out.strip()
292                 break
293             else:
294                 time.sleep(delay)
295                 delay = delay * 1.5
296         else:
297             msg = "Couldn't retrieve vif_name"
298             self.error(msg, out, err)
299             raise RuntimeError, msg
300
301         return vif_name
302
303     def gre_connect(self, remote_endpoint, connection_app_home,
304             connection_run_home):
305         gre_connect_command = self._gre_connect_command(
306                 remote_endpoint, connection_run_home)
307
308         # upload command to connect.sh script
309         shfile = os.path.join(connection_app_home, "gre-connect.sh")
310         self.node.upload_command(gre_connect_command,
311                 shfile = shfile,
312                 overwrite = False)
313
314         # invoke connect script
315         cmd = "bash %s" % shfile
316         (out, err), proc = self.node.run(cmd, connection_run_home) 
317              
318         # check if execution errors occurred
319         msg = " Failed to connect endpoints "
320         
321         if proc.poll() or err:
322             self.error(msg, out, err)
323             raise RuntimeError, msg
324     
325         # Wait for pid file to be generated
326         pid, ppid = self.node.wait_pid(connection_run_home)
327         
328         # If the process is not running, check for error information
329         # on the remote machine
330         if not pid or not ppid:
331             (out, err), proc = self.node.check_errors(connection_run_home)
332             # Out is what was written in the stderr file
333             if err:
334                 msg = " Failed to start command '%s' " % command
335                 self.error(msg, out, err)
336                 raise RuntimeError, msg
337         
338         # After creating the TAP, the pl-vif-create.py script
339         # will write the name of the TAP to a file. We wait until
340         # we can read the interface name from the file.
341         vif_name = self.wait_vif_name(exec_run_home = connection_run_home)
342         self.set("deviceName", vif_name) 
343
344         return True
345
346
347     def initiate_udp_connection(self, remote_endpoint, connection_app_home, 
348             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
349         port = self.udp_connect(remote_endpoint, connection_app_home, 
350             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
351         return port
352
353
354     def udp_connect(self, remote_endpoint, connection_app_home, 
355             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
356         udp_connect_command = self._udp_connect_command(
357                 remote_endpoint, connection_run_home,
358                 cipher, cipher_key, bwlimit, txqueuelen)
359
360         # upload command to connect.sh script
361         shfile = os.path.join(self.app_home, "udp-connect.sh")
362         self.node.upload_command(udp_connect_command,
363                 shfile = shfile,
364                 overwrite = False)
365
366         # invoke connect script
367         cmd = "bash %s" % shfile
368         (out, err), proc = self.node.run(cmd, self.run_home) 
369              
370         # check if execution errors occurred
371         msg = "Failed to connect endpoints "
372         
373         if proc.poll():
374             self.error(msg, out, err)
375             raise RuntimeError, msg
376     
377         # Wait for pid file to be generated
378         self._pid, self._ppid = self.node.wait_pid(self.run_home)
379         
380         # If the process is not running, check for error information
381         # on the remote machine
382         if not self._pid or not self._ppid:
383             (out, err), proc = self.node.check_errors(self.run_home)
384             # Out is what was written in the stderr file
385             if err:
386                 msg = " Failed to start command '%s' " % command
387                 self.error(msg, out, err)
388                 raise RuntimeError, msg
389
390         port = self.wait_local_port()
391
392         return port
393
394     def _udp_connect_command(self, remote_endpoint, connection_run_home, 
395             cipher, cipher_key, bwlimit, txqueuelen):
396
397         # Set the remote endpoint
398         self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
399
400         remote_ip = remote_endpoint.node.get("ip")
401
402         local_port_file = os.path.join(self.run_home, 
403                 "local_port")
404
405         remote_port_file = os.path.join(self.run_home, 
406                 "remote_port")
407
408         ret_file = os.path.join(self.run_home, 
409                 "ret_file")
410
411         # Generate UDP connect command
412         # Use pl-vif-up.py script to configure TAP with peer info
413         vif_up_command = self._vif_up_command
414         
415         command = ["( "]
416         command.append(vif_up_command)
417
418         # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
419         command.append(") & (")
420         command.append("sudo -S")
421         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
422         command.append("python ${SRC}/pl-vif-udp-connect.py")
423         command.append("-t %s" % self.vif_type)
424         command.append("-S %s " % self.sock_name)
425         command.append("-l %s " % local_port_file)
426         command.append("-r %s " % remote_port_file)
427         command.append("-H %s " % remote_ip)
428         command.append("-R %s " % ret_file)
429         if cipher:
430             command.append("-c %s " % cipher)
431         if cipher_key:
432             command.append("-k %s " % cipher_key)
433         if txqueuelen:
434             command.append("-q %s " % txqueuelen)
435         if bwlimit:
436             command.append("-b %s " % bwlimit)
437
438         command.append(")")
439
440         command = " ".join(command)
441         command = self.replace_paths(command)
442
443         return command
444
445     def establish_udp_connection(self, remote_endpoint, port):
446         # upload remote port number to file
447         rem_port = "%s\n" % port
448         self.node.upload(rem_port,
449                 os.path.join(self.run_home, "remote_port"),
450                 text = True, 
451                 overwrite = False)
452
453     def verify_connection(self):
454         self.wait_result()
455
456     def terminate_connection(self):
457         if  self._pid and self._ppid:
458             (out, err), proc = self.node.kill(self._pid, self._ppid, 
459                     sudo = True) 
460
461             # check if execution errors occurred
462             if proc.poll() and err:
463                 msg = " Failed to Kill the Tap"
464                 self.error(msg, out, err)
465                 raise RuntimeError, msg
466
467     def check_status(self):
468         return self.node.status(self._pid, self._ppid)
469
470     def wait_local_port(self):
471         """ Waits until the local_port file for the endpoint is generated, 
472         and returns the port number 
473         
474         """
475         return self.wait_file("local_port")
476
477     def wait_result(self):
478         """ Waits until the return code file for the endpoint is generated 
479         
480         """ 
481         return self.wait_file("ret_file")
482  
483     def wait_file(self, filename):
484         """ Waits until file on endpoint is generated """
485         result = None
486         delay = 1.0
487
488         for i in xrange(20):
489             (out, err), proc = self.node.check_output(
490                     self.run_home, filename)
491             if out:
492                 result = out.strip()
493                 break
494             else:
495                 time.sleep(delay)
496                 delay = delay * 1.5
497         else:
498             msg = "Couldn't retrieve %s" % filename
499             self.error(msg, out, err)
500             raise RuntimeError, msg
501
502         return result
503
504
505
506     def _gre_connect_command(self, remote_endpoint, connection_run_home): 
507         # Set the remote endpoint
508         self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
509         self.set("greRemote", remote_endpoint.node.get("ip"))
510
511         # Generate GRE connect command
512
513         # Use vif_down command to first kill existing TAP in GRE mode
514         vif_down_command = self._vif_down_command
515
516         # Use pl-vif-up.py script to configure TAP with peer info
517         vif_up_command = self._vif_up_command
518         
519         command = ["("]
520         command.append(vif_down_command)
521         command.append(") ; (")
522         command.append(vif_up_command)
523         command.append(")")
524
525         command = " ".join(command)
526         command = self.replace_paths(command)
527
528         return command
529
530
531     @property
532     def _start_command(self):
533         if self.gre_enabled:
534             command = []
535         else:
536             command = ["sudo -S python ${SRC}/pl-vif-create.py"]
537             
538             command.append("-t %s" % self.vif_type)
539             command.append("-a %s" % self.get("endpoint_ip"))
540             command.append("-n %d" % self.get("endpoint_prefix"))
541             command.append("-f %s " % self.vif_name_file)
542             command.append("-S %s " % self.sock_name)
543
544             if self.get("snat") == True:
545                 command.append("-s")
546
547             if self.get("pointopoint"):
548                 command.append("-p %s" % self.get("pointopoint"))
549             
550             if self.get("txqueuelen"):
551                 command.append("-q %s" % self.get("txqueuelen"))
552
553         return " ".join(command)
554
555     @property
556     def _stop_command(self):
557         if self.gre_enabled:
558             command = self._vif_down_command
559         else:
560             command = ["sudo -S "]
561             command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
562             command.append("python ${SRC}/pl-vif-down.py")
563             command.append("-S %s " % self.sock_name)
564             command = " ".join(command)
565
566         return command
567
568     @property
569     def _vif_up_command(self):
570         if self.gre_enabled:
571             device_name = "%s" % self.guid
572         else:
573             device_name = self.get("deviceName")
574
575         # Use pl-vif-up.py script to configure TAP
576         command = ["sudo -S "]
577         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
578         command.append("python ${SRC}/pl-vif-up.py")
579         command.append("-u %s" % self.node.get("username"))
580         command.append("-N %s" % device_name)
581         command.append("-t %s" % self.vif_type)
582         command.append("-a %s" % self.get("endpoint_ip"))
583         command.append("-n %d" % self.get("endpoint_prefix"))
584
585         if self.get("snat") == True:
586             command.append("-s")
587
588         if self.get("pointopoint"):
589             command.append("-p %s" % self.get("pointopoint"))
590         
591         if self.get("txqueuelen"):
592             command.append("-q %s" % self.get("txqueuelen"))
593
594         if self.gre_enabled:
595             command.append("-g %s" % self.get("greKey"))
596             command.append("-G %s" % self.get("greRemote"))
597         
598         command.append("-f %s " % self.vif_name_file)
599
600         return " ".join(command)
601
602     @property
603     def _vif_down_command(self):
604         if self.gre_enabled:
605             device_name = "%s" % self.guid
606         else:
607             device_name = self.get("deviceName")
608
609         command = ["sudo -S "]
610         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
611         command.append("python ${SRC}/pl-vif-down.py")
612         command.append("-N %s " % device_name)
613         
614         if self.gre_enabled:
615             command.append("-u %s" % self.node.get("username"))
616             command.append("-t %s" % self.vif_type)
617             command.append("-D")
618
619         return " ".join(command)
620
621     @property
622     def vif_type(self):
623         return "IFF_TAP"
624
625     @property
626     def vif_name_file(self):
627         return os.path.join(self.run_home, "vif_name")
628
629     @property
630     def sock_name(self):
631         return os.path.join(self.run_home, "tap.sock")
632
633     @property
634     def _dependencies(self):
635         return "mercurial make gcc"
636
637     @property
638     def _install(self):
639         # Install python-vsys and python-passfd
640         install_vsys = ( " ( "
641                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
642                     " ) "
643                     " || "
644                     " ( "
645                     "   cd ${SRC} ; "
646                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
647                     "   cd python-vsys ; "
648                     "   make all ; "
649                     "   sudo -S make install "
650                     " )" ) % ({
651                         "version": PYTHON_VSYS_VERSION
652                         })
653
654         install_passfd = ( " ( python -c 'import passfd' ) "
655                     " || "
656                     " ( "
657                     "   cd ${SRC} ; "
658                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
659                     "   cd python-passfd ; "
660                     "   make all ; "
661                     "   sudo -S make install "
662                     " )" )
663
664         return "%s ; %s" % ( install_vsys, install_passfd )
665
666     def valid_connection(self, guid):
667         # TODO: Validate!
668         return True
669