Allowing manual configuration of Public IP attribute for LinuxNode
[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         ip4 = Attribute("ip4", "IPv4 Address",
41               flags = Flags.Design)
42
43         mac = Attribute("mac", "MAC Address",
44                 flags = Flags.Design)
45
46         prefix4 = Attribute("prefix4", "IPv4 network prefix",
47                 type = Types.Integer,
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", 
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(ip4)
87         cls._register_attribute(mac)
88         cls._register_attribute(prefix4)
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(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(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 udp_connect(self, remote_endpoint, connection_app_home, 
345             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
346         udp_connect_command = self._udp_connect_command(
347                 remote_endpoint, connection_run_home,
348                 cipher, cipher_key, bwlimit, txqueuelen)
349
350         # upload command to connect.sh script
351         shfile = os.path.join(connection_app_home, "udp-connect.sh")
352         self.node.upload_command(udp_connect_command,
353                 shfile = shfile,
354                 overwrite = False)
355
356         # invoke connect script
357         cmd = "bash %s" % shfile
358         (out, err), proc = self.node.run(cmd, connection_run_home) 
359              
360         # check if execution errors occurred
361         msg = "Failed to connect endpoints "
362         
363         if proc.poll():
364             self.error(msg, out, err)
365             raise RuntimeError, msg
366     
367         # Wait for pid file to be generated
368         pid, ppid = self.node.wait_pid(connection_run_home)
369         
370         # If the process is not running, check for error information
371         # on the remote machine
372         if not pid or not ppid:
373             (out, err), proc = self.node.check_errors(connection_run_home)
374             # Out is what was written in the stderr file
375             if err:
376                 msg = " Failed to start command '%s' " % command
377                 self.error(msg, out, err)
378                 raise RuntimeError, msg
379
380         return pid, ppid
381
382     def _udp_connect_command(self, remote_endpoint, connection_run_home, 
383             cipher, cipher_key, bwlimit, txqueuelen):
384
385         # Set the remote endpoint
386         self.set("pointopoint", remote_endpoint.get("ip4"))
387
388         print "REMOTE IP", remote_ip
389         remote_ip = remote_endpoint.node.get("ip")
390
391         local_port_file = os.path.join(connection_run_home, 
392                 "local_port")
393
394         remote_port_file = os.path.join(connection_run_home, 
395                 "remote_port")
396
397         ret_file = os.path.join(connection_run_home, 
398                 "ret_file")
399
400         # Generate UDP connect command
401         # Use pl-vif-up.py script to configure TAP with peer info
402         vif_up_command = self._vif_up_command
403         
404         command = ["( "]
405         command.append(vif_up_command)
406
407         # Use pl-vid-udp-connect.py to stablish the tunnel between endpoints
408         command.append(") & (")
409         command.append("sudo -S")
410         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
411         command.append("python ${SRC}/pl-vif-udp-connect.py")
412         command.append("-t %s" % self.vif_type)
413         command.append("-S %s " % self.sock_name)
414         command.append("-l %s " % local_port_file)
415         command.append("-r %s " % remote_port_file)
416         command.append("-H %s " % remote_ip)
417         command.append("-R %s " % ret_file)
418         if cipher:
419             command.append("-c %s " % cipher)
420         if cipher_key:
421             command.append("-k %s " % cipher_key)
422         if txqueuelen:
423             command.append("-q %s " % txqueuelen)
424         if bwlimit:
425             command.append("-b %s " % bwlimit)
426
427         command.append(")")
428
429         command = " ".join(command)
430         command = self.replace_paths(command)
431
432         return command
433
434     def _gre_connect_command(self, remote_endpoint, connection_run_home): 
435         # Set the remote endpoint
436         self.set("pointopoint", remote_endpoint.get("ip4"))
437         self.set("greRemote", remote_endpoint.node.get("ip"))
438
439         # Generate GRE connect command
440
441         # Use vif_down command to first kill existing TAP in GRE mode
442         vif_down_command = self._vif_down_command
443
444         # Use pl-vif-up.py script to configure TAP with peer info
445         vif_up_command = self._vif_up_command
446         
447         command = ["("]
448         command.append(vif_down_command)
449         command.append(") ; (")
450         command.append(vif_up_command)
451         command.append(")")
452
453         command = " ".join(command)
454         command = self.replace_paths(command)
455
456         return command
457
458     @property
459     def _start_command(self):
460         if self.gre_enabled:
461             command = []
462         else:
463             command = ["sudo -S python ${SRC}/pl-vif-create.py"]
464             
465             command.append("-t %s" % self.vif_type)
466             command.append("-a %s" % self.get("ip4"))
467             command.append("-n %d" % self.get("prefix4"))
468             command.append("-f %s " % self.vif_name_file)
469             command.append("-S %s " % self.sock_name)
470
471             if self.get("snat") == True:
472                 command.append("-s")
473
474             if self.get("pointopoint"):
475                 command.append("-p %s" % self.get("pointopoint"))
476             
477             if self.get("txqueuelen"):
478                 command.append("-q %s" % self.get("txqueuelen"))
479
480         return " ".join(command)
481
482     @property
483     def _stop_command(self):
484         if self.gre_enabled:
485             command = self._vif_down_command
486         else:
487             command = ["sudo -S "]
488             command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
489             command.append("python ${SRC}/pl-vif-down.py")
490             command.append("-S %s " % self.sock_name)
491             command = " ".join(command)
492
493         return command
494
495     @property
496     def _vif_up_command(self):
497         if self.gre_enabled:
498             device_name = "%s" % self.guid
499         else:
500             device_name = self.get("deviceName")
501
502         # Use pl-vif-up.py script to configure TAP
503         command = ["sudo -S "]
504         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
505         command.append("python ${SRC}/pl-vif-up.py")
506         command.append("-u %s" % self.node.get("username"))
507         command.append("-N %s" % device_name)
508         command.append("-t %s" % self.vif_type)
509         command.append("-a %s" % self.get("ip4"))
510         command.append("-n %d" % self.get("prefix4"))
511
512         if self.get("snat") == True:
513             command.append("-s")
514
515         if self.get("pointopoint"):
516             command.append("-p %s" % self.get("pointopoint"))
517         
518         if self.get("txqueuelen"):
519             command.append("-q %s" % self.get("txqueuelen"))
520
521         if self.gre_enabled:
522             command.append("-g %s" % self.get("greKey"))
523             command.append("-G %s" % self.get("greRemote"))
524         
525         command.append("-f %s " % self.vif_name_file)
526
527         return " ".join(command)
528
529     @property
530     def _vif_down_command(self):
531         if self.gre_enabled:
532             device_name = "%s" % self.guid
533         else:
534             device_name = self.get("deviceName")
535
536         command = ["sudo -S "]
537         command.append("PYTHONPATH=$PYTHONPATH:${SRC}")
538         command.append("python ${SRC}/pl-vif-down.py")
539         command.append("-N %s " % device_name)
540         
541         if self.gre_enabled:
542             command.append("-u %s" % self.node.get("username"))
543             command.append("-t %s" % self.vif_type)
544             command.append("-D")
545
546         return " ".join(command)
547
548     @property
549     def vif_type(self):
550         return "IFF_TAP"
551
552     @property
553     def vif_name_file(self):
554         return os.path.join(self.run_home, "vif_name")
555
556     @property
557     def sock_name(self):
558         return os.path.join(self.run_home, "tap.sock")
559
560     @property
561     def _dependencies(self):
562         return "mercurial make gcc"
563
564     @property
565     def _install(self):
566         # Install python-vsys and python-passfd
567         install_vsys = ( " ( "
568                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
569                     " ) "
570                     " || "
571                     " ( "
572                     "   cd ${SRC} ; "
573                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
574                     "   cd python-vsys ; "
575                     "   make all ; "
576                     "   sudo -S make install "
577                     " )" ) % ({
578                         "version": PYTHON_VSYS_VERSION
579                         })
580
581         install_passfd = ( " ( python -c 'import passfd' ) "
582                     " || "
583                     " ( "
584                     "   cd ${SRC} ; "
585                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
586                     "   cd python-passfd ; "
587                     "   make all ; "
588                     "   sudo -S make install "
589                     " )" )
590
591         return "%s ; %s" % ( install_vsys, install_passfd )
592
593     def valid_connection(self, guid):
594         # TODO: Validate!
595         return True
596