5df36c4bbc522029e36b416361b11045b57e0e46
[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 from nepi.resources.linux.application import LinuxApplication
23 from nepi.resources.planetlab.node import PlanetlabNode
24 from nepi.util.timefuncs import tnow, tdiffsec
25
26 import os
27 import time
28
29 PYTHON_VSYS_VERSION = "1.0"
30
31 @clsinit_copy
32 class PlanetlabTap(LinuxApplication):
33     _rtype = "planetlab::Tap"
34     _help = "Creates a TAP device on a PlanetLab host"
35     _platform = "planetlab"
36
37     @classmethod
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",
42               flags = Flags.Design)
43
44         mac = Attribute("mac", "MAC Address",
45                 flags = Flags.Design)
46
47         prefix = Attribute("prefix", "IPv4 network prefix of the endpoint",
48                 flags = Flags.Design)
49
50         mtu = Attribute("mtu", "Maximum transmition unit for device",
51                 type = Types.Integer)
52
53         devname = Attribute("deviceName", 
54                 "Name of the network interface (e.g. eth0, wlan0, etc)",
55                 flags = Flags.NoWrite)
56
57         up = Attribute("up", "Link up", default = True, 
58                 type = Types.Bool)
59         
60         snat = Attribute("snat", "Set SNAT=1", 
61                 type = Types.Bool,
62                 flags = Flags.Design)
63         
64         pointopoint = Attribute("pointopoint", "Peer IP address", 
65                 flags = Flags.Design)
66
67         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
68                 flags = Flags.Design)
69
70         txqueuelen = Attribute("txqueuelen", "Length of transmission queue", 
71                 flags = Flags.Design)
72
73         gre_key = Attribute("greKey", 
74                 "GRE key to be used to configure GRE tunnel", 
75                 default = "1",
76                 flags = Flags.Design)
77
78         gre_remote = Attribute("greRemote", 
79                 "Public IP of remote endpoint for GRE tunnel", 
80                 flags = Flags.Design)
81
82         tear_down = Attribute("tearDown", 
83                 "Bash script to be executed before releasing the resource",
84                 flags = Flags.Design)
85
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)
98
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
103
104     @property
105     def node(self):
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"
109
110     @property
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
116
117         return self._gre_enabled
118
119     def upload_sources(self):
120         scripts = []
121
122         # vif-creation python script
123         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
124                 "pl-vif-create.py")
125
126         scripts.append(pl_vif_create)
127         
128         # vif-up python script
129         pl_vif_up = os.path.join(os.path.dirname(__file__), "scripts",
130                 "pl-vif-up.py")
131         
132         scripts.append(pl_vif_up)
133
134         # vif-down python script
135         pl_vif_down = os.path.join(os.path.dirname(__file__), "scripts",
136                 "pl-vif-down.py")
137         
138         scripts.append(pl_vif_down)
139
140         # udp-connect python script
141         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
142                 "pl-vif-udp-connect.py")
143         
144         scripts.append(pl_vif_connect)
145
146         # tunnel creation python script
147         tunchannel = os.path.join(os.path.dirname(__file__), "..", "linux",
148                 "scripts", "tunchannel.py")
149
150         scripts.append(tunchannel)
151
152         # Upload scripts
153         scripts = ";".join(scripts)
154
155         self.node.upload(scripts,
156                 os.path.join(self.node.src_dir),
157                 overwrite = False)
158
159         # upload stop.sh script
160         stop_command = self.replace_paths(self._stop_command)
161
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.
167                 overwrite = True)
168
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)
177
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  
183             # is created. 
184             self._run_in_background()
185             
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) 
191
192     def do_deploy(self):
193         if not self.node or self.node.state < ResourceState.PROVISIONED:
194             self.ec.schedule(self.reschedule_delay, self.deploy)
195         else:
196             if not self.get("command"):
197                 self.set("command", self._start_command)
198
199             if not self.get("depends"):
200                 self.set("depends", self._dependencies)
201
202             if not self.get("install"):
203                 self.set("install", self._install)
204
205             self.do_discover()
206             self.do_provision()
207
208             self.set_ready()
209
210     def do_start(self):
211         if self.state == ResourceState.READY:
212             command = self.get("command")
213             self.info("Starting command '%s'" % command)
214
215             self.set_started()
216         else:
217             msg = " Failed to execute command '%s'" % command
218             self.error(msg, out, err)
219             raise RuntimeError, msg
220
221     def do_stop(self):
222         command = self.get('command') or ''
223         
224         if self.state == ResourceState.STARTED:
225             self.info("Stopping command '%s'" % command)
226
227             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
228             (out, err), proc = self.execute_command(command,
229                     blocking = True)
230
231             if err:
232                 msg = " Failed to stop command '%s' " % command
233                 self.error(msg, out, err)
234
235             self.set_stopped()
236
237     @property
238     def state(self):
239         state_check_delay = 0.5
240         if self._state == ResourceState.STARTED and \
241                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
242
243             if self.get("deviceName"):
244                 (out, err), proc = self.node.execute("ifconfig")
245
246                 if out.strip().find(self.get("deviceName")) == -1: 
247                     # tap is not running is not running (socket not found)
248                     self.set_stopped()
249
250             self._last_state_check = tnow()
251
252         return self._state
253
254     def do_release(self):
255         # Node needs to wait until all associated RMs are released
256         # to be released
257         from nepi.resources.linux.tunnel import LinuxTunnel
258         rms = self.get_connected(LinuxTunnel.get_rtype())
259
260         for rm in rms:
261             if rm.state < ResourceState.STOPPED:
262                 self.ec.schedule(self.reschedule_delay, self.release)
263                 return 
264
265         super(PlanetlabTap, self).do_release()
266
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 """
270         vif_name = None
271         delay = 0.5
272
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
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(exec_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 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)
305
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,
309                 shfile = shfile,
310                 overwrite = False)
311
312         # invoke connect script
313         cmd = "bash %s" % shfile
314         (out, err), proc = self.node.run(cmd, connection_run_home) 
315              
316         # check if execution errors occurred
317         msg = " Failed to connect endpoints "
318         
319         if proc.poll() or err:
320             self.error(msg, out, err)
321             raise RuntimeError, msg
322     
323         # Wait for pid file to be generated
324         pid, ppid = self.node.wait_pid(connection_run_home)
325         
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
331             if err:
332                 msg = " Failed to start command '%s' " % command
333                 self.error(msg, out, err)
334                 raise RuntimeError, msg
335         
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) 
341
342         return True
343
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)
348         return port
349
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)
355
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,
359                 shfile = shfile,
360                 overwrite = False)
361
362         # invoke connect script
363         cmd = "bash %s" % shfile
364         (out, err), proc = self.node.run(cmd, self.run_home) 
365              
366         # check if execution errors occurred
367         msg = "Failed to connect endpoints "
368         
369         if proc.poll():
370             self.error(msg, out, err)
371             raise RuntimeError, msg
372     
373         # Wait for pid file to be generated
374         self._pid, self._ppid = self.node.wait_pid(self.run_home)
375         
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
381             if err:
382                 msg = " Failed to start command '%s' " % command
383                 self.error(msg, out, err)
384                 raise RuntimeError, msg
385
386         port = self.wait_local_port()
387
388         return port
389
390     def _udp_connect_command(self, remote_endpoint, connection_run_home, 
391             cipher, cipher_key, bwlimit, txqueuelen):
392
393         # Set the remote endpoint, (private) IP of the device
394         self.set("pointopoint", remote_endpoint.get("ip"))
395
396         # Public IP of the node
397         remote_ip = remote_endpoint.node.get("ip")
398
399         local_port_file = os.path.join(self.run_home, 
400                 "local_port")
401
402         remote_port_file = os.path.join(self.run_home, 
403                 "remote_port")
404
405         ret_file = os.path.join(self.run_home, 
406                 "ret_file")
407
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
411         
412         command = ["( "]
413         command.append(vif_up_command)
414
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)
426         if cipher:
427             command.append("-c %s " % cipher)
428         if cipher_key:
429             command.append("-k %s " % cipher_key)
430         if txqueuelen:
431             command.append("-q %s " % txqueuelen)
432         if bwlimit:
433             command.append("-b %s " % bwlimit)
434
435         command.append(")")
436
437         command = " ".join(command)
438         command = self.replace_paths(command)
439
440         return command
441
442     def establish_udp_connection(self, remote_endpoint, 
443             connection_app_home,
444             connection_run_home, 
445             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     def _gre_connect_command(self, remote_endpoint, connection_run_home): 
505         # Set the remote endpoint, (private) IP of the device
506         self.set("pointopoint", remote_endpoint.get("ip"))
507         # Public IP of the node
508         self.set("greRemote", remote_endpoint.node.get("ip"))
509
510         # Generate GRE connect command
511
512         # Use vif_down command to first kill existing TAP in GRE mode
513         vif_down_command = self._vif_down_command
514
515         # Use pl-vif-up.py script to configure TAP with peer info
516         vif_up_command = self._vif_up_command
517         
518         command = ["("]
519         command.append(vif_down_command)
520         command.append(") ; (")
521         command.append(vif_up_command)
522         command.append(")")
523
524         command = " ".join(command)
525         command = self.replace_paths(command)
526
527         return command
528
529     @property
530     def _start_command(self):
531         if self.gre_enabled:
532             command = []
533         else:
534             command = ["sudo -S python ${SRC}/pl-vif-create.py"]
535             
536             command.append("-t %s" % self.vif_type)
537             command.append("-a %s" % self.get("ip"))
538             command.append("-n %s" % self.get("prefix"))
539             command.append("-f %s " % self.vif_name_file)
540             command.append("-S %s " % self.sock_name)
541
542             if self.get("snat") == True:
543                 command.append("-s")
544
545             if self.get("pointopoint"):
546                 command.append("-p %s" % self.get("pointopoint"))
547             
548             if self.get("txqueuelen"):
549                 command.append("-q %s" % self.get("txqueuelen"))
550
551         return " ".join(command)
552
553     @property
554     def _stop_command(self):
555         if self.gre_enabled:
556             command = self._vif_down_command
557         else:
558             command = ["sudo -S "]
559             command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
560             command.append("python ${SRC}/pl-vif-down.py")
561             command.append("-S %s " % self.sock_name)
562             command = " ".join(command)
563
564         return command
565
566     @property
567     def _vif_up_command(self):
568         if self.gre_enabled:
569             device_name = "%s" % self.guid
570         else:
571             device_name = self.get("deviceName")
572
573         # Use pl-vif-up.py script to configure TAP
574         command = ["sudo -S "]
575         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
576         command.append("python ${SRC}/pl-vif-up.py")
577         command.append("-u %s" % self.node.get("username"))
578         command.append("-N %s" % device_name)
579         command.append("-t %s" % self.vif_type)
580         command.append("-a %s" % self.get("ip"))
581         command.append("-n %s" % self.get("prefix"))
582
583         if self.get("snat") == True:
584             command.append("-s")
585
586         if self.get("pointopoint"):
587             command.append("-p %s" % self.get("pointopoint"))
588         
589         if self.get("txqueuelen"):
590             command.append("-q %s" % self.get("txqueuelen"))
591
592         if self.gre_enabled:
593             command.append("-g %s" % self.get("greKey"))
594             command.append("-G %s" % self.get("greRemote"))
595         
596         command.append("-f %s " % self.vif_name_file)
597
598         return " ".join(command)
599
600     @property
601     def _vif_down_command(self):
602         if self.gre_enabled:
603             device_name = "%s" % self.guid
604         else:
605             device_name = self.get("deviceName")
606
607         command = ["sudo -S "]
608         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
609         command.append("python ${SRC}/pl-vif-down.py")
610         command.append("-N %s " % device_name)
611         
612         if self.gre_enabled:
613             command.append("-u %s" % self.node.get("username"))
614             command.append("-t %s" % self.vif_type)
615             command.append("-D")
616
617         return " ".join(command)
618
619     @property
620     def vif_type(self):
621         return "IFF_TAP"
622
623     @property
624     def vif_name_file(self):
625         return os.path.join(self.run_home, "vif_name")
626
627     @property
628     def sock_name(self):
629         return os.path.join(self.run_home, "tap.sock")
630
631     @property
632     def _dependencies(self):
633         return "mercurial make gcc"
634
635     @property
636     def _install(self):
637         # Install python-vsys and python-passfd
638         install_vsys = ( " ( "
639                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
640                     " ) "
641                     " || "
642                     " ( "
643                     "   cd ${SRC} ; "
644                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
645                     "   cd python-vsys ; "
646                     "   make all ; "
647                     "   sudo -S make install "
648                     " )" ) % ({
649                         "version": PYTHON_VSYS_VERSION
650                         })
651
652         install_passfd = ( " ( python -c 'import passfd' ) "
653                     " || "
654                     " ( "
655                     "   cd ${SRC} ; "
656                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
657                     "   cd python-passfd ; "
658                     "   make all ; "
659                     "   sudo -S make install "
660                     " )" )
661
662         return "%s ; %s" % ( install_vsys, install_passfd )
663
664     def valid_connection(self, guid):
665         # TODO: Validate!
666         return True
667