7d8cd3e20360506f425b726da9a1f69f26c6c3a2
[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 #       - Make base clase 'virtual device' and redefine vif_type
32 #       - write the name of the device (if_name) to a file and allow the 
33 #           RM to read it and set the 'deviceName' attribute
34 #       - Instead of doing an infinite loop, open a port for communication allowing
35 #           to pass the fd to another process
36
37 PYTHON_VSYS_VERSION = "1.0"
38
39 @clsinit_copy
40 class PlanetlabTap(LinuxApplication):
41     _rtype = "PlanetlabTap"
42
43     @classmethod
44     def _register_attributes(cls):
45         ip4 = Attribute("ip4", "IPv4 Address",
46               flags = Flags.ExecReadOnly)
47
48         mac = Attribute("mac", "MAC Address",
49                 flags = Flags.ExecReadOnly)
50
51         prefix4 = Attribute("prefix4", "IPv4 network prefix",
52                 flags = Flags.ExecReadOnly)
53
54         mtu = Attribute("mtu", "Maximum transmition unit for device",
55                 type = Types.Integer)
56
57         devname = Attribute("deviceName", 
58                 "Name of the network interface (e.g. eth0, wlan0, etc)",
59                 flags = Flags.ReadOnly)
60
61         up = Attribute("up", "Link up", type = Types.Bool)
62         
63         snat = Attribute("snat", "Set SNAT=1", type = Types.Bool,
64                 flags = Flags.ReadOnly)
65         
66         pointopoint = Attribute("pointopoint", "Peer IP address", 
67                 flags = Flags.ReadOnly)
68
69         tear_down = Attribute("tearDown", "Bash script to be executed before " + \
70                 "releasing the resource",
71                 flags = Flags.ExecReadOnly)
72
73         cls._register_attribute(ip4)
74         cls._register_attribute(mac)
75         cls._register_attribute(prefix4)
76         cls._register_attribute(mtu)
77         cls._register_attribute(devname)
78         cls._register_attribute(up)
79         cls._register_attribute(snat)
80         cls._register_attribute(pointopoint)
81         cls._register_attribute(tear_down)
82
83     def __init__(self, ec, guid):
84         super(PlanetlabTap, self).__init__(ec, guid)
85         self._home = "tap-%s" % self.guid
86
87     @property
88     def node(self):
89         node = self.get_connected(PlanetlabNode.rtype())
90         if node: return node[0]
91         return None
92
93     def upload_sources(self):
94         depends = "mercurial make gcc"
95         self.set("depends", depends)
96
97         install = ( " ( "
98                     "   python -c 'import vsys, os;  vsys.__version__ == \"%(version)s\" or os._exit(1)' "
99                     " ) "
100                     " ||"
101                     " ( "
102                     "   cd ${SRC} ; "
103                     "   hg clone http://nepi.inria.fr/code/python-vsys ; "
104                     "   cd python-vsys ; "
105                     "   make all ; "
106                     "   sudo -S make install "
107                     " )" ) % ({
108                         "version": PYTHON_VSYS_VERSION
109                         })
110
111         self.set("install", install)
112
113     def upload_start_command(self):
114         # upload tap-creation python script
115         start_script = self.replace_paths(self._start_script)
116         self.node.upload(start_script,
117                 os.path.join(self.app_home, "tap_create.py"),
118                 text = True, 
119                 overwrite = False)
120
121         # upload start.sh
122         start_command = self.replace_paths(self._start_command)
123
124         self.info("Uploading command '%s'" % start_command)
125         
126         self.set("command", start_command)
127         self.node.upload(start_command,
128                 os.path.join(self.app_home, "start.sh"),
129                 text = True, 
130                 overwrite = False)
131
132         # We want to make sure the device is up and running
133         # before the experiment starts.
134         # Run the command as a bash script in background,
135         # in the host ( but wait until the command has
136         # finished to continue )
137         self._run_in_background()
138         
139         # Retrive if_name
140         if_name = self.wait_if_name()
141         self.set("deviceName", if_name) 
142
143     def deploy(self):
144         if not self.node or self.node.state < ResourceState.PROVISIONED:
145             self.ec.schedule(reschedule_delay, self.deploy)
146         else:
147
148             try:
149                 self.discover()
150                 self.provision()
151             except:
152                 self.fail()
153                 raise
154  
155             self.debug("----- READY ---- ")
156             self._ready_time = tnow()
157             self._state = ResourceState.READY
158
159     def start(self):
160         if self._state == ResourceState.READY:
161             command = self.get("command")
162             self.info("Starting command '%s'" % command)
163
164             self._start_time = tnow()
165             self._state = ResourceState.STARTED
166         else:
167             msg = " Failed to execute command '%s'" % command
168             self.error(msg, out, err)
169             self._state = ResourceState.FAILED
170             raise RuntimeError, msg
171
172     def stop(self):
173         command = self.get('command') or ''
174         state = self.state
175         
176         if state == ResourceState.STARTED:
177             self.info("Stopping command '%s'" % command)
178
179             command = "rm %s" % os.path.join(self.run_home, "if_stop")
180             (out, err), proc = self.execute_command(command)
181
182             self._stop_time = tnow()
183             self._state = ResourceState.STOPPED
184
185     @property
186     def state(self):
187         # First check if the ccnd has failed
188         state_check_delay = 0.5
189         if self._state == ResourceState.STARTED and \
190                 tdiffsec(tnow(), self._last_state_check) > state_check_delay:
191
192             if self.get("deviceName"):
193                 (out, err), proc = self.node.execute("ifconfig")
194
195                 if out.strip().find(self.get("deviceName")) == -1: 
196                     # tap is not running is not running (socket not found)
197                     self._state = ResourceState.FINISHED
198
199             self._last_state_check = tnow()
200
201         return self._state
202
203     def wait_if_name(self):
204         """ Waits until the if_name file for the command is generated, 
205             and returns the if_name for the devide """
206         if_name = None
207         delay = 1.0
208
209         for i in xrange(4):
210             (out, err), proc = self.node.check_output(self.run_home, "if_name")
211
212             if out:
213                 if_name = out.strip()
214                 break
215             else:
216                 time.sleep(delay)
217                 delay = delay * 1.5
218         else:
219             msg = "Couldn't retrieve if_name"
220             self.error(msg, out, err)
221             self.fail()
222             raise RuntimeError, msg
223
224         return if_name
225
226     @property
227     def _start_command(self):
228         return "sudo -S python ${APP_HOME}/tap_create.py" 
229
230     @property
231     def _start_script(self):
232         return ( "import vsys, time, os \n"
233                  "(fd, if_name) = vsys.fd_tuntap(vsys.%(devtype)s)\n"
234                  "vsys.vif_up(if_name, '%(ip)s', %(prefix)s%(snat)s%(pointopoint)s)\n"
235                  "f = open('%(if_name_file)s', 'w')\n"
236                  "f.write(if_name)\n"
237                  "f.close()\n\n"
238                  "f = open('%(if_stop_file)s', 'w')\n"
239                  "f.close()\n\n"
240                  "while os.path.exists('%(if_stop_file)s'):\n"
241                  "    time.sleep(2)\n"
242                ) % ({
243                    "devtype": self._vif_type,
244                    "ip": self.get("ip4"),
245                    "prefix": self.get("prefix4"),
246                    "snat": ", snat=True" if self.get("snat") else "",
247                    "pointopoint": ", pointopoint=%s" % self.get("pointopoint") \
248                            if self.get("pointopoint") else "",
249                     "if_name_file": os.path.join(self.run_home, "if_name"),
250                     "if_stop_file": os.path.join(self.run_home, "if_stop"),
251                    })
252
253     @property
254     def _vif_type(self):
255         return "IFF_TAP"
256
257     def valid_connection(self, guid):
258         # TODO: Validate!
259         return True
260