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