Changing reschedule_delay internals
[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 = "PlanetlabTap"
34     _help = "Creates a TAP device on a PlanetLab host"
35     _backend = "planetlab"
36
37     @classmethod
38     def _register_attributes(cls):
39         endpoint_ip = Attribute("endpoint_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         endpoint_prefix = Attribute("endpoint_prefix", "IPv4 network prefix of the endpoint",
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(endpoint_ip)
88         cls._register_attribute(mac)
89         cls._register_attribute(endpoint_prefix)
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         raise RuntimeError, "TAP/TUN devices must be connected to Node"
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_command(stop_command,
164                 shfile = os.path.join(self.app_home, "stop.sh"),
165                 # Overwrite file every time. 
166                 # The stop.sh has the path to the socket, which should change
167                 # on every experiment run.
168                 overwrite = True)
169
170     def upload_start_command(self):
171         # If GRE mode is enabled, TAP creation is delayed until the
172         # tunnel is established
173         if not self.gre_enabled:
174             # Overwrite file every time. 
175             # The start.sh has the path to the socket, wich should change
176             # on every experiment run.
177             super(PlanetlabTap, self).upload_start_command(overwrite = True)
178
179             # We want to make sure the device is up and running
180             # before the deploy finishes, so we execute now the 
181             # start script. We run it in background, because the 
182             # TAP will live for as long as the process that 
183             # created it is running, and wait until the TAP  
184             # is created. 
185             self._run_in_background()
186             
187             # After creating the TAP, the pl-vif-create.py script
188             # will write the name of the TAP to a file. We wait until
189             # we can read the interface name from the file.
190             vif_name = self.wait_vif_name()
191             self.set("deviceName", vif_name) 
192
193     def do_deploy(self):
194         if not self.node or self.node.state < ResourceState.PROVISIONED:
195             self.ec.schedule(self.reschedule_delay, self.deploy)
196         else:
197             if not self.get("command"):
198                 self.set("command", self._start_command)
199
200             if not self.get("depends"):
201                 self.set("depends", self._dependencies)
202
203             if not self.get("install"):
204                 self.set("install", self._install)
205
206             self.do_discover()
207             self.do_provision()
208
209             self.set_ready()
210
211     def do_start(self):
212         if self.state == ResourceState.READY:
213             command = self.get("command")
214             self.info("Starting command '%s'" % command)
215
216             self.set_started()
217         else:
218             msg = " Failed to execute command '%s'" % command
219             self.error(msg, out, err)
220             raise RuntimeError, msg
221
222     def do_stop(self):
223         command = self.get('command') or ''
224         
225         if self.state == ResourceState.STARTED:
226             self.info("Stopping command '%s'" % command)
227
228             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
229             (out, err), proc = self.execute_command(command,
230                     blocking = True)
231
232             if err:
233                 msg = " Failed to stop command '%s' " % command
234                 self.error(msg, out, err)
235
236             self.set_stopped()
237
238     @property
239     def state(self):
240         state_check_delay = 0.5
241         if self._state == ResourceState.STARTED and \
242                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
243
244             if self.get("deviceName"):
245                 (out, err), proc = self.node.execute("ifconfig")
246
247                 if out.strip().find(self.get("deviceName")) == -1: 
248                     # tap is not running is not running (socket not found)
249                     self.set_stopped()
250
251             self._last_state_check = tnow()
252
253         return self._state
254
255     def do_release(self):
256         # Node needs to wait until all associated RMs are released
257         # to be released
258         from nepi.resources.linux.tunnel import LinuxTunnel
259         rms = self.get_connected(LinuxTunnel.get_rtype())
260
261         for rm in rms:
262             if rm.state < ResourceState.STOPPED:
263                 self.ec.schedule(self.reschedule_delay, self.release)
264                 return 
265
266         super(PlanetlabTap, self).do_release()
267
268     def wait_vif_name(self, exec_run_home = None):
269         """ Waits until the vif_name file for the command is generated, 
270             and returns the vif_name for the device """
271         vif_name = None
272         delay = 0.5
273
274         # The vif_name file will be created in the tap-home, while the
275         # current execution home might be elsewhere to check for errors
276         # (e.g. could be a tunnel-home)
277         if not exec_run_home:
278             exec_run_home = self.run_home
279
280         for i in xrange(20):
281             (out, err), proc = self.node.check_output(self.run_home, "vif_name")
282
283             if proc.poll() > 0:
284                 (out, err), proc = self.node.check_errors(exec_run_home)
285                 
286                 if err.strip():
287                     raise RuntimeError, err
288
289             if out:
290                 vif_name = out.strip()
291                 break
292             else:
293                 time.sleep(delay)
294                 delay = delay * 1.5
295         else:
296             msg = "Couldn't retrieve vif_name"
297             self.error(msg, out, err)
298             raise RuntimeError, msg
299
300         return vif_name
301
302     def gre_connect(self, remote_endpoint, connection_app_home,
303             connection_run_home):
304         gre_connect_command = self._gre_connect_command(
305                 remote_endpoint, connection_run_home)
306
307         # upload command to connect.sh script
308         shfile = os.path.join(connection_app_home, "gre-connect.sh")
309         self.node.upload_command(gre_connect_command,
310                 shfile = shfile,
311                 overwrite = False)
312
313         # invoke connect script
314         cmd = "bash %s" % shfile
315         (out, err), proc = self.node.run(cmd, connection_run_home) 
316              
317         # check if execution errors occurred
318         msg = " Failed to connect endpoints "
319         
320         if proc.poll() or err:
321             self.error(msg, out, err)
322             raise RuntimeError, msg
323     
324         # Wait for pid file to be generated
325         pid, ppid = self.node.wait_pid(connection_run_home)
326         
327         # If the process is not running, check for error information
328         # on the remote machine
329         if not pid or not ppid:
330             (out, err), proc = self.node.check_errors(connection_run_home)
331             # Out is what was written in the stderr file
332             if err:
333                 msg = " Failed to start command '%s' " % command
334                 self.error(msg, out, err)
335                 raise RuntimeError, msg
336         
337         # After creating the TAP, the pl-vif-create.py script
338         # will write the name of the TAP to a file. We wait until
339         # we can read the interface name from the file.
340         vif_name = self.wait_vif_name(exec_run_home = connection_run_home)
341         self.set("deviceName", vif_name) 
342
343         return True
344
345
346     def initiate_udp_connection(self, remote_endpoint, connection_app_home, 
347             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
348         port = self.udp_connect(remote_endpoint, connection_app_home, 
349             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen)
350         return port
351
352
353     def udp_connect(self, remote_endpoint, connection_app_home, 
354             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
355         udp_connect_command = self._udp_connect_command(
356                 remote_endpoint, connection_run_home,
357                 cipher, cipher_key, bwlimit, txqueuelen)
358
359         # upload command to connect.sh script
360         shfile = os.path.join(self.app_home, "udp-connect.sh")
361         self.node.upload_command(udp_connect_command,
362                 shfile = shfile,
363                 overwrite = False)
364
365         # invoke connect script
366         cmd = "bash %s" % shfile
367         (out, err), proc = self.node.run(cmd, self.run_home) 
368              
369         # check if execution errors occurred
370         msg = "Failed to connect endpoints "
371         
372         if proc.poll():
373             self.error(msg, out, err)
374             raise RuntimeError, msg
375     
376         # Wait for pid file to be generated
377         self._pid, self._ppid = self.node.wait_pid(self.run_home)
378         
379         # If the process is not running, check for error information
380         # on the remote machine
381         if not self._pid or not self._ppid:
382             (out, err), proc = self.node.check_errors(self.run_home)
383             # Out is what was written in the stderr file
384             if err:
385                 msg = " Failed to start command '%s' " % command
386                 self.error(msg, out, err)
387                 raise RuntimeError, msg
388
389         port = self.wait_local_port()
390
391         return port
392
393     def _udp_connect_command(self, remote_endpoint, connection_run_home, 
394             cipher, cipher_key, bwlimit, txqueuelen):
395
396         # Set the remote endpoint
397         self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
398
399         remote_ip = remote_endpoint.node.get("ip")
400
401         local_port_file = os.path.join(self.run_home, 
402                 "local_port")
403
404         remote_port_file = os.path.join(self.run_home, 
405                 "remote_port")
406
407         ret_file = os.path.join(self.run_home, 
408                 "ret_file")
409
410         # Generate UDP connect command
411         # Use pl-vif-up.py script to configure TAP with peer info
412         vif_up_command = self._vif_up_command
413         
414         command = ["( "]
415         command.append(vif_up_command)
416
417         # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
418         command.append(") & (")
419         command.append("sudo -S")
420         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
421         command.append("python ${SRC}/pl-vif-udp-connect.py")
422         command.append("-t %s" % self.vif_type)
423         command.append("-S %s " % self.sock_name)
424         command.append("-l %s " % local_port_file)
425         command.append("-r %s " % remote_port_file)
426         command.append("-H %s " % remote_ip)
427         command.append("-R %s " % ret_file)
428         if cipher:
429             command.append("-c %s " % cipher)
430         if cipher_key:
431             command.append("-k %s " % cipher_key)
432         if txqueuelen:
433             command.append("-q %s " % txqueuelen)
434         if bwlimit:
435             command.append("-b %s " % bwlimit)
436
437         command.append(")")
438
439         command = " ".join(command)
440         command = self.replace_paths(command)
441
442         return command
443
444     def establish_udp_connection(self, remote_endpoint, port):
445         # upload remote port number to file
446         rem_port = "%s\n" % port
447         self.node.upload(rem_port,
448                 os.path.join(self.run_home, "remote_port"),
449                 text = True, 
450                 overwrite = False)
451
452     def verify_connection(self):
453         self.wait_result()
454
455     def terminate_connection(self):
456         if  self._pid and self._ppid:
457             (out, err), proc = self.node.kill(self._pid, self._ppid, 
458                     sudo = True) 
459
460             # check if execution errors occurred
461             if proc.poll() and err:
462                 msg = " Failed to Kill the Tap"
463                 self.error(msg, out, err)
464                 raise RuntimeError, msg
465
466     def check_status(self):
467         return self.node.status(self._pid, self._ppid)
468
469     def wait_local_port(self):
470         """ Waits until the local_port file for the endpoint is generated, 
471         and returns the port number 
472         
473         """
474         return self.wait_file("local_port")
475
476     def wait_result(self):
477         """ Waits until the return code file for the endpoint is generated 
478         
479         """ 
480         return self.wait_file("ret_file")
481  
482     def wait_file(self, filename):
483         """ Waits until file on endpoint is generated """
484         result = None
485         delay = 1.0
486
487         for i in xrange(20):
488             (out, err), proc = self.node.check_output(
489                     self.run_home, filename)
490             if out:
491                 result = out.strip()
492                 break
493             else:
494                 time.sleep(delay)
495                 delay = delay * 1.5
496         else:
497             msg = "Couldn't retrieve %s" % filename
498             self.error(msg, out, err)
499             raise RuntimeError, msg
500
501         return result
502
503
504
505     def _gre_connect_command(self, remote_endpoint, connection_run_home): 
506         # Set the remote endpoint
507         self.set("pointopoint", remote_endpoint.get("endpoint_ip"))
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
530     @property
531     def _start_command(self):
532         if self.gre_enabled:
533             command = []
534         else:
535             command = ["sudo -S python ${SRC}/pl-vif-create.py"]
536             
537             command.append("-t %s" % self.vif_type)
538             command.append("-a %s" % self.get("endpoint_ip"))
539             command.append("-n %d" % self.get("endpoint_prefix"))
540             command.append("-f %s " % self.vif_name_file)
541             command.append("-S %s " % self.sock_name)
542
543             if self.get("snat") == True:
544                 command.append("-s")
545
546             if self.get("pointopoint"):
547                 command.append("-p %s" % self.get("pointopoint"))
548             
549             if self.get("txqueuelen"):
550                 command.append("-q %s" % self.get("txqueuelen"))
551
552         return " ".join(command)
553
554     @property
555     def _stop_command(self):
556         if self.gre_enabled:
557             command = self._vif_down_command
558         else:
559             command = ["sudo -S "]
560             command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
561             command.append("python ${SRC}/pl-vif-down.py")
562             command.append("-S %s " % self.sock_name)
563             command = " ".join(command)
564
565         return command
566
567     @property
568     def _vif_up_command(self):
569         if self.gre_enabled:
570             device_name = "%s" % self.guid
571         else:
572             device_name = self.get("deviceName")
573
574         # Use pl-vif-up.py script to configure TAP
575         command = ["sudo -S "]
576         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
577         command.append("python ${SRC}/pl-vif-up.py")
578         command.append("-u %s" % self.node.get("username"))
579         command.append("-N %s" % device_name)
580         command.append("-t %s" % self.vif_type)
581         command.append("-a %s" % self.get("endpoint_ip"))
582         command.append("-n %d" % self.get("endpoint_prefix"))
583
584         if self.get("snat") == True:
585             command.append("-s")
586
587         if self.get("pointopoint"):
588             command.append("-p %s" % self.get("pointopoint"))
589         
590         if self.get("txqueuelen"):
591             command.append("-q %s" % self.get("txqueuelen"))
592
593         if self.gre_enabled:
594             command.append("-g %s" % self.get("greKey"))
595             command.append("-G %s" % self.get("greRemote"))
596         
597         command.append("-f %s " % self.vif_name_file)
598
599         return " ".join(command)
600
601     @property
602     def _vif_down_command(self):
603         if self.gre_enabled:
604             device_name = "%s" % self.guid
605         else:
606             device_name = self.get("deviceName")
607
608         command = ["sudo -S "]
609         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
610         command.append("python ${SRC}/pl-vif-down.py")
611         command.append("-N %s " % device_name)
612         
613         if self.gre_enabled:
614             command.append("-u %s" % self.node.get("username"))
615             command.append("-t %s" % self.vif_type)
616             command.append("-D")
617
618         return " ".join(command)
619
620     @property
621     def vif_type(self):
622         return "IFF_TAP"
623
624     @property
625     def vif_name_file(self):
626         return os.path.join(self.run_home, "vif_name")
627
628     @property
629     def sock_name(self):
630         return os.path.join(self.run_home, "tap.sock")
631
632     @property
633     def _dependencies(self):
634         return "mercurial make gcc"
635
636     @property
637     def _install(self):
638         # Install python-vsys and python-passfd
639         install_vsys = ( " ( "
640                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
641                     " ) "
642                     " || "
643                     " ( "
644                     "   cd ${SRC} ; "
645                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
646                     "   cd python-vsys ; "
647                     "   make all ; "
648                     "   sudo -S make install "
649                     " )" ) % ({
650                         "version": PYTHON_VSYS_VERSION
651                         })
652
653         install_passfd = ( " ( python -c 'import passfd' ) "
654                     " || "
655                     " ( "
656                     "   cd ${SRC} ; "
657                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
658                     "   cd python-passfd ; "
659                     "   make all ; "
660                     "   sudo -S make install "
661                     " )" )
662
663         return "%s ; %s" % ( install_vsys, install_passfd )
664
665     def valid_connection(self, guid):
666         # TODO: Validate!
667         return True
668