Adding tuncahnnel and pl-vif-tunnconnect scripts
[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 ResourceManager, 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 # TODO: - routes!!!
31
32 PYTHON_VSYS_VERSION = "1.0"
33
34 @clsinit_copy
35 class PlanetlabTap(LinuxApplication):
36     _rtype = "PlanetlabTap"
37
38     @classmethod
39     def _register_attributes(cls):
40         ip4 = Attribute("ip4", "IPv4 Address",
41               flags = Flags.ExecReadOnly)
42
43         mac = Attribute("mac", "MAC Address",
44                 flags = Flags.ExecReadOnly)
45
46         prefix4 = Attribute("prefix4", "IPv4 network prefix",
47                 type = Types.Integer,
48                 flags = Flags.ExecReadOnly)
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.ReadOnly)
56
57         up = Attribute("up", "Link up", type = Types.Bool)
58         
59         snat = Attribute("snat", "Set SNAT=1", type = Types.Bool,
60                 flags = Flags.ReadOnly)
61         
62         pointopoint = Attribute("pointopoint", "Peer IP address", 
63                 flags = Flags.ReadOnly)
64
65         tear_down = Attribute("tearDown", "Bash script to be executed before " + \
66                 "releasing the resource",
67                 flags = Flags.ExecReadOnly)
68
69         cls._register_attribute(ip4)
70         cls._register_attribute(mac)
71         cls._register_attribute(prefix4)
72         cls._register_attribute(mtu)
73         cls._register_attribute(devname)
74         cls._register_attribute(up)
75         cls._register_attribute(snat)
76         cls._register_attribute(pointopoint)
77         cls._register_attribute(tear_down)
78
79     def __init__(self, ec, guid):
80         super(PlanetlabTap, self).__init__(ec, guid)
81         self._home = "tap-%s" % self.guid
82
83     @property
84     def node(self):
85         node = self.get_connected(PlanetlabNode.rtype())
86         if node: return node[0]
87         return None
88
89     def upload_sources(self):
90         # upload vif-creation python script
91         pl_vif_create = os.path.join(os.path.dirname(__file__), "scripts",
92                 "pl-vif-create.py")
93
94         self.node.upload(pl_vif_create,
95                 os.path.join(self.app_home, "pl-vif-create.py"),
96                 overwrite = False)
97
98         # upload vif-stop python script
99         pl_vif_stop = os.path.join(os.path.dirname(__file__), "scripts",
100                 "pl-vif-stop.py")
101
102         self.node.upload(pl_vif_stop,
103                 os.path.join(self.app_home, "pl-vif-stop.py"),
104                 overwrite = False)
105
106         # upload vif-connect python script
107         pl_vif_connect = os.path.join(os.path.dirname(__file__), "scripts",
108                 "pl-vif-tunconnect.py")
109
110         self.node.upload(pl_vif_connect,
111                 os.path.join(self.app_home, "pl-vif-connect.py"),
112                 overwrite = False)
113
114         # upload tun-connect python script
115         tunchannel = os.path.join(os.path.dirname(__file__), "..", "all", "scripts",
116                 "tunchannel.py")
117
118         self.node.upload(tunchannel,
119                 os.path.join(self.app_home, "tunchannel.py"),
120                 overwrite = False)
121
122         # upload stop.sh script
123         stop_command = self.replace_paths(self._stop_command)
124         self.node.upload(stop_command,
125                 os.path.join(self.app_home, "stop.sh"),
126                 text = True, 
127                 overwrite = False)
128
129     def upload_start_command(self):
130         super(PlanetlabTap, self).upload_start_command()
131
132         # We want to make sure the device is up and running
133         # before the deploy finishes (so things will be ready
134         # before other stuff starts running).
135         # Run the command as a bash script in background,
136         # in the host ( but wait until the command has
137         # finished to continue )
138         self._run_in_background()
139         
140         # Retrive if_name
141         if_name = self.wait_if_name()
142         self.set("deviceName", if_name) 
143
144     def deploy(self):
145         if not self.node or self.node.state < ResourceState.PROVISIONED:
146             self.ec.schedule(reschedule_delay, self.deploy)
147         else:
148             if not self.get("command"):
149                 self.set("command", self._start_command)
150
151             if not self.get("depends"):
152                 self.set("depends", self._dependencies)
153
154             if not self.get("install"):
155                 self.set("install", self._install)
156
157             try:
158                 self.discover()
159                 self.provision()
160             except:
161                 self.fail()
162                 raise
163  
164             self.debug("----- READY ---- ")
165             self._ready_time = tnow()
166             self._state = ResourceState.READY
167
168     def start(self):
169         if self._state == ResourceState.READY:
170             command = self.get("command")
171             self.info("Starting command '%s'" % command)
172
173             self._start_time = tnow()
174             self._state = ResourceState.STARTED
175         else:
176             msg = " Failed to execute command '%s'" % command
177             self.error(msg, out, err)
178             self._state = ResourceState.FAILED
179             raise RuntimeError, msg
180
181     def stop(self):
182         command = self.get('command') or ''
183         state = self.state
184         
185         if state == ResourceState.STARTED:
186             self.info("Stopping command '%s'" % command)
187
188             command = "bash %s" % os.path.join(self.app_home, "stop.sh")
189             (out, err), proc = self.execute_command(command,
190                     blocking = True)
191
192             self._stop_time = tnow()
193             self._state = ResourceState.STOPPED
194
195     @property
196     def state(self):
197         # First check if the ccnd has failed
198         state_check_delay = 0.5
199         if self._state == ResourceState.STARTED and \
200                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
201
202             if self.get("deviceName"):
203                 (out, err), proc = self.node.execute("ifconfig")
204
205                 if out.strip().find(self.get("deviceName")) == -1: 
206                     # tap is not running is not running (socket not found)
207                     self._state = ResourceState.FINISHED
208
209             self._last_state_check = tnow()
210
211         return self._state
212
213     def wait_if_name(self):
214         """ Waits until the if_name file for the command is generated, 
215             and returns the if_name for the devide """
216         if_name = None
217         delay = 1.0
218
219         for i in xrange(4):
220             (out, err), proc = self.node.check_output(self.run_home, "if_name")
221
222             if out:
223                 if_name = out.strip()
224                 break
225             else:
226                 time.sleep(delay)
227                 delay = delay * 1.5
228         else:
229             msg = "Couldn't retrieve if_name"
230             self.error(msg, out, err)
231             self.fail()
232             raise RuntimeError, msg
233
234         return if_name
235
236     @property
237     def _start_command(self):
238         command = ["sudo -S python ${APP_HOME}/pl-vif-create.py"]
239         
240         command.append("-t %s" % self.vif_type)
241         command.append("-a %s" % self.get("ip4"))
242         command.append("-n %d" % self.get("prefix4"))
243         command.append("-f %s " % self.if_name_file)
244         command.append("-S %s " % self.sock_name)
245         if self.get("snat") == True:
246             command.append("-s")
247         if self.get("pointopoint"):
248             command.append("-p %s" % self.get("pointopoint"))
249
250         return " ".join(command)
251
252     @property
253     def _stop_command(self):
254         command = ["sudo -S python ${APP_HOME}/pl-vif-stop.py"]
255         
256         command.append("-S %s " % self.sock_name)
257         return " ".join(command)
258
259     @property
260     def vif_type(self):
261         return "IFF_TAP"
262
263     @property
264     def if_name_file(self):
265         return os.path.join(self.run_home, "if_name")
266
267     @property
268     def sock_name(self):
269         return os.path.join(self.run_home, "tap.sock")
270
271     @property
272     def _dependencies(self):
273         return "mercurial make gcc"
274
275     @property
276     def _install(self):
277         install_vsys = ( " ( "
278                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
279                     " ) "
280                     " || "
281                     " ( "
282                     "   cd ${SRC} ; "
283                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
284                     "   cd python-vsys ; "
285                     "   make all ; "
286                     "   sudo -S make install "
287                     " )" ) % ({
288                         "version": PYTHON_VSYS_VERSION
289                         })
290
291         install_passfd = ( " ( python -c 'import passfd' ) "
292                     " || "
293                     " ( "
294                     "   cd ${SRC} ; "
295                     "   hg clone http://nepi.inria.fr/code/python-passfd ; "
296                     "   cd python-passfd ; "
297                     "   make all ; "
298                     "   sudo -S make install "
299                     " )" )
300
301         return "%s ; %s" % ( install_vsys, install_passfd )
302
303     def valid_connection(self, guid):
304         # TODO: Validate!
305         return True
306