Replacing _backend for _platform class attribute in ResourceManager
[nepi.git] / src / nepi / resources / planetlab / openvswitch / ovsport.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 # Authors: Alina Quereilhac <alina.quereilhac@inria.fr>
19 #         Alexandros Kouvakas <alexandros.kouvakas@inria.fr>
20 #         Julien Tribino <julien.tribino@inria.fr>
21
22 from nepi.execution.attribute import Attribute, Flags, Types
23 from nepi.execution.resource import ResourceManager, clsinit_copy, \
24         ResourceState
25 from nepi.resources.planetlab.openvswitch.ovs import OVSSwitch        
26 from nepi.resources.planetlab.node import PlanetlabNode        
27 from nepi.resources.linux.application import LinuxApplication
28
29 import os
30
31 @clsinit_copy                 
32 class OVSPort(LinuxApplication):
33     """
34     .. class:: Class Args :
35       
36         :param ec: The Experiment controller
37         :type ec: ExperimentController
38         :param guid: guid of the RM
39         :type guid: int
40
41     """
42     
43     _rtype = "planetlab::OVSPort"
44     _help = "Runs an OpenVSwitch on a PlanetLab host"
45     _platform = "planetlab"
46
47     _authorized_connections = ["planetlab::OVSSwitch", "linux::UdpTunnel", "linux::Tunnel"]      
48
49     @classmethod
50     def _register_attributes(cls):
51         """ Register the attributes of OVSPort RM 
52
53         """
54         port_name = Attribute("port_name", "Name of the port",
55             flags = Flags.Design)                       
56         ip = Attribute("ip", "IP of the endpoint. This is the attribute " 
57                                 "you should use to establish a tunnel or a remote "
58                                 "connection between endpoint",
59             flags = Flags.Design)
60         network = Attribute("network", "Network used by the port",
61             flags = Flags.Design)       
62
63         cls._register_attribute(port_name)
64         cls._register_attribute(ip)
65         cls._register_attribute(network)
66
67     def __init__(self, ec, guid):
68         """
69         :param ec: The Experiment controller
70         :type ec: ExperimentController
71         :param guid: guid of the RM
72         :type guid: int
73     
74         """
75         super(OVSPort, self).__init__(ec, guid)
76
77
78         self._port_number = None
79         # in case of connection by tunnel        
80         self._remote_ip = None    
81
82     def log_message(self, msg):
83         return " guid %d - OVSPort - %s " % (self.guid, msg)
84
85     @property
86     def node(self):
87         """ Node that run the switch and the ports
88         """
89         rm_list = self.get_connected(OVSSwitch.get_rtype())
90         if rm_list:
91             for elt in rm_list:
92                 node = elt.get_connected(PlanetlabNode.get_rtype())
93                 if node: return node[0]
94         return node[0]
95
96     @property
97     def ovsswitch(self):
98         """ Switch where the port is created
99         """
100         ovsswitch = self.get_connected(OVSSwitch.get_rtype())
101         if ovsswitch: return ovsswitch[0]
102         return None
103         
104     @property
105     def remote_ip(self):
106         return self._remote_ip
107
108     @property
109     def port_number(self):
110         return self._port_number
111
112     def valid_connection(self, guid):
113         """ Check if the connection is available.
114
115         :param guid: Guid of the current RM
116         :type guid: int
117         :rtype:  Boolean
118
119         """
120         rm = self.ec.get_resource(guid)
121         if rm.get_rtype() in self._authorized_connections:
122             msg = "Connection between %s %s and %s %s accepted" % (self.get_rtype(), self._guid, rm.get_rtype(), guid)
123             self.debug(msg)
124             return True
125         msg = "Connection between %s %s and %s %s refused" % (self.get_rtype(), self._guid, rm.get_rtype(), guid)
126         self.debug(msg)
127
128     def create_port(self):
129         """ Create the desired port
130         """
131         msg = "Creating the port %s" % self.get('port_name')
132         self.debug(msg)
133
134         if not self.get('port_name'):
135             msg = "The port name is not assigned"
136             self.error(msg)
137             raise AttributeError, msg
138
139         if not self.ovsswitch:
140             msg = "The OVSwitch RM is not running"
141             self.error(msg)
142             raise AttributeError, msg
143
144         cmd = "sliver-ovs create-port %s %s" % (self.ovsswitch.get('bridge_name'),
145                                                 self.get('port_name'))   
146         self.node.run(cmd, self.ovsswitch.ovs_checks, 
147                 stderr = "stdout-%s" % self.get('port_name'), 
148                 stdout = "stderr-%s" % self.get('port_name'),
149                 sudo = True)
150
151         self.info("Created the port %s on switch %s" % (self.get('port_name'),
152                                              self.ovsswitch.get('bridge_name')))     
153             
154     def initiate_udp_connection(self, remote_endpoint, connection_app_home, 
155             connection_run_home, cipher, cipher_key, bwlimit, txqueuelen):
156         """ Get the local_endpoint of the port
157         """
158
159         self._remote_ip = remote_endpoint.node.get("ip")
160
161         msg = "Discovering the number of the port %s" % self.get('port_name')
162         self.info(msg)
163
164         command = "sliver-ovs get-local-endpoint %s" % self.get('port_name')
165         out = err = ""
166         (out, err), proc = self.node.run_and_wait(command, 
167                 self.ovsswitch.ovs_checks,
168                 shfile = "port_number-%s.sh" % self.get('port_name'),
169                 pidfile = "port_number_pidfile-%s" % self.get('port_name'),
170                 ecodefile = "port_number_exitcode-%s" % self.get('port_name'), 
171                 sudo = True, 
172                 stdout = "stdout-%s" % self.get('port_name'),    
173                 stderr = "stderr-%s" % self.get('port_name'))
174
175         if err != "":
176             msg = "Error retrieving the local endpoint of the port"
177             self.error(msg)
178             raise AttributeError, msg
179
180         if out:
181             self._port_number = int(out)
182
183         self.info("The number of the %s is %s" % (self.get('port_name'), 
184            self.port_number))
185
186         if remote_endpoint.is_rm_instance("planetlab::Tap"):
187             self._vroute = self.ec.register_resource("planetlab::Vroute")
188             self.ec.set(self._vroute, "action", "add")
189             self.ec.set(self._vroute, "network", self.get("network"))
190
191             print "Vroute Guid :" + str(self._vroute)
192
193             self.ec.register_connection(self._vroute, remote_endpoint.guid)
194             self.ec.deploy(guids=[self._vroute], group = self.deployment_group)
195
196             # For debugging
197             msg = "Route for the tap configured"
198             self.debug(msg)
199
200         return self.port_number
201
202
203     def establish_udp_connection(self,remote_endpoint, port):
204         establish_connection_command = self._establish_connection_command(port)
205
206         # upload command to connect.sh script
207         shfile = os.path.join(self.app_home, "sw-connect.sh")
208         self.node.upload_command(establish_connection_command,
209                 shfile = shfile,
210                 overwrite = False)
211
212         # invoke connect script
213         cmd = "bash %s" % shfile
214         (out, err), proc = self.node.run(cmd, self.run_home,
215                 sudo  = True,
216                 stdout = "sw_stdout",
217                 stderr = "sw_stderr") 
218              
219         # check if execution errors occurred
220         msg = "Failed to connect endpoints "
221         if proc.poll():
222             self.error(msg, out, err)
223             raise RuntimeError, msg
224     
225         # Wait for pid file to be generated
226         self._pid, self._ppid = self.node.wait_pid(self.run_home)
227         
228         # If the process is not running, check for error information
229         # on the remote machine
230         if not self._pid or not self._ppid:
231             (out, err), proc = self.node.check_errors(self.run_home)
232             # Out is what was written in the stderr file
233             if err:
234                 msg = " Failed to start command '%s' " % command
235                 self.error(msg, out, err)
236                 raise RuntimeError, msg
237
238         # For debugging
239         msg = "Connection on port configured"
240         self.debug(msg)
241
242
243     def _establish_connection_command(self, port):
244         """ Script to create the connection from a switch to a 
245              remote endpoint
246         """
247         local_port_name = self.get('port_name')
248
249         command = ["sliver-ovs"]
250         command.append("set-remote-endpoint ")
251         command.append("%s " % local_port_name)
252         command.append("%s " % self.remote_ip)
253         command.append("%s " % port)
254         command = " ".join(command)
255         command = self.replace_paths(command)
256         return command
257         
258     def verify_connection(self):
259         self.ovsswitch.ovs_status()
260
261     def terminate_connection(self):
262         return True
263
264     def check_status(self):
265         return self.node.status(self._pid, self._ppid)
266
267     def do_deploy(self):
268         """ Deploy the OVS port after the OVS Switch
269         """
270
271         if not self.ovsswitch or self.ovsswitch.state < ResourceState.READY:       
272             self.debug("---- RESCHEDULING DEPLOY ---- OVSwitch state %s " % self.ovsswitch.state )  
273             self.ec.schedule(self.reschedule_delay, self.deploy)
274             return
275
276         self.do_discover()
277         self.do_provision()
278
279         self.create_port()
280         end_ip = self.ovsswitch.get('virtual_ip_pref').split('/')
281         self.set("ip", end_ip[0])
282
283         #Check the status of the OVS Switch
284         self.ovsswitch.ovs_status()
285
286         super(OVSPort, self).do_deploy()
287
288     def do_release(self):
289         """ Delete the port on the OVSwitch. It needs to wait for the tunnel
290         to be released.
291         """
292         from nepi.resources.linux.udptunnel import LinuxUdpTunnel
293         rm = self.get_connected(LinuxUdpTunnel.get_rtype())
294
295         if rm and rm[0].state < ResourceState.STOPPED:
296             self.ec.schedule(self.reschedule_delay, self.release)
297             return 
298             
299         cmd = "sliver-ovs del_port %s" % self.get('port_name')
300         (out, err), proc = self.node.run(cmd, self.ovsswitch.ovs_checks,
301                 sudo = True)
302
303         msg = "Deleting the port %s" % self.get('port_name')
304         self.info(msg)
305
306         if proc.poll():
307             self.error(msg, out, err)
308             raise RuntimeError, msg
309
310         super(OVSPort, self).do_release()
311