74a8baa0b512683de505d1b39cd08d21d52e7145
[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 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19 #             Alexandros Kouvakas <alexandros.kouvakas@gmail.com>
20
21 from nepi.execution.attribute import Attribute, Flags, Types
22 from nepi.execution.resource import ResourceManager, clsinit_copy, \
23         ResourceState
24 from nepi.resources.planetlab.openvswitch.ovs import OVSWitch        
25 from nepi.resources.planetlab.node import PlanetlabNode        
26 from nepi.resources.linux.application import LinuxApplication
27
28 reschedule_delay = "0.5s"
29
30 @clsinit_copy                 
31 class OVSPort(LinuxApplication):
32     """
33     .. class:: Class Args :
34       
35         :param ec: The Experiment controller
36         :type ec: ExperimentController
37         :param guid: guid of the RM
38         :type guid: int
39
40     """
41     
42     _rtype = "OVSPort"
43     _help = "Runs an OpenVSwitch on a PlanetLab host"
44     _backend = "planetlab"
45
46     _authorized_connections = ["OVSWitch", "Tunnel"]      
47
48     @classmethod
49     def _register_attributes(cls):
50         """ Register the attributes of OVSPort RM 
51
52         """
53         port_name = Attribute("port_name", "Name of the port",
54             flags = Flags.ExecReadOnly)                 
55
56         cls._register_attribute(port_name)
57
58     def __init__(self, ec, guid):
59         """
60         :param ec: The Experiment controller
61         :type ec: ExperimentController
62         :param guid: guid of the RM
63         :type guid: int
64     
65         """
66         super(OVSPort, self).__init__(ec, guid)
67         self._port_number = None
68         self.port_info = []          
69
70     @property
71     def node(self):
72         rm_list = self.get_connected(OVSWitch.get_rtype())
73         if rm_list:
74             for elt in rm_list:
75                 node = elt.get_connected(PlanetlabNode.get_rtype())
76                 if node: return node[0]
77         return node[0]
78
79     @property
80     def ovswitch(self):
81         ovswitch = self.get_connected(OVSWitch.get_rtype())
82         if ovswitch: return ovswitch[0]
83         return None
84         
85     @property
86     def port_number(self):
87         return self._port_number
88
89     def valid_connection(self, guid):
90         # TODO: Validate!
91         return True
92
93 #    def valid_connection(self, guid):
94 #        """ Check if the connection is available.
95
96 #        :param guid: Guid of the current RM
97 #        :type guid: int
98 #        :rtype:  Boolean
99
100 #        """
101 #        rm = self.ec.get_resource(guid)
102 #        if rm.get_rtype() in self._authorized_connections:
103 #            msg = "Connection between %s %s and %s %s accepted" % (self.get_rtype(), self._guid, rm.get_rtype(), guid)
104 #            self.debug(msg)
105 #            return True
106 #        msg = "Connection between %s %s and %s %s refused" % (self.get_rtype(), self._guid, rm.get_rtype(), guid)
107 #        self.debug(msg)
108
109     def get_ip(self):
110         """ Return the ip of the node. This data is necessary to
111         create the tunnel.
112         """
113
114         import socket
115         return socket.gethostbyname(self.node.get('hostname'))
116     
117     def create_port(self):
118         """ Create the desired port
119         """
120         msg = "Creating the port %s" % self.get('port_name')
121         self.debug(msg)
122
123         if not self.get('port_name'):
124             msg = "The port name is not assigned"
125             self.error(msg)
126             raise AttributeError, msg
127
128         if not self.ovswitch:
129             msg = "The OVSwitch RM is not running"
130             self.error(msg)
131             raise AttributeError, msg
132
133         cmd = "sliver-ovs create-port %s %s" % (self.ovswitch.get('bridge_name'),
134                                                 self.get('port_name'))   
135         self.node.run(cmd, self.ovswitch.ovs_checks, 
136                 stderr = "stdout-%s" % self.get('port_name'), 
137                 stdout = "stderr-%s" % self.get('port_name'),
138                 sudo = True)
139
140         self.info("Created the port %s on switch %s" % (self.get('port_name'),
141                                              self.ovswitch.get('bridge_name')))     
142             
143     def get_local_end(self):
144         """ Get the local_endpoint of the port
145         """
146
147         msg = "Discovering the number of the port %s" % self.get('port_name')
148         self.debug(msg)
149
150         command = "sliver-ovs get-local-endpoint %s" % self.get('port_name')
151         out = err = ""
152         (out, err), proc = self.node.run_and_wait(command, 
153                 self.ovswitch.ovs_checks,
154                 shfile = "port_number-%s.sh" % self.get('port_name'),
155                 pidfile = "port_number_pidfile-%s" % self.get('port_name'),
156                 ecodefile = "port_number_exitcode-%s" % self.get('port_name'), 
157                 sudo = True, 
158                 stdout = "stdout-%s" % self.get('port_name'),    
159                 stderr = "stderr-%s" % self.get('port_name'))
160
161         if err != "":
162             msg = "Error retrieving the local endpoint of the port"
163             self.error(msg)
164             raise AttributeError, msg
165
166         if out:
167             self._port_number = int(out)
168
169         self.info("The number of the %s is %s" % (self.get('port_name'), 
170            self.port_number))
171    
172     def set_port_info(self, ip):
173         info = []
174         info.append(self.node.get('hostname'))
175         info.append(ip)
176         info.append(self.get('port_name'))
177         info.append(self.ovswitch.get('virtual_ip_pref'))
178         info.append(self.port_number)
179         return info
180
181     def switch_connect_command(self, local_port_name, 
182             remote_ip, remote_port_num):
183         """ Script for switch links
184         """
185         command = ["sliver-ovs"]
186         command.append("set-remote-endpoint ")
187         command.append("%s " % local_port_name)
188         command.append("%s " % remote_ip)
189         command.append("%s " % remote_port_num)
190         command = " ".join(command)
191         command = self.replace_paths(command)
192         return command
193         
194     def do_deploy(self):
195         """ Wait until ovswitch is started
196         """
197
198         if not self.ovswitch or self.ovswitch.state < ResourceState.READY:       
199             self.debug("---- RESCHEDULING DEPLOY ---- OVSwitch state %s " % self.ovswitch.state )  
200             self.ec.schedule(reschedule_delay, self.deploy)
201             return
202
203         self.do_discover()
204         self.do_provision()
205         ip = self.get_ip()
206         self.create_port()
207         self.get_local_end()
208         self.ovswitch.ovs_status()
209
210         self.port_info = self.set_port_info(ip)
211
212         super(OVSPort, self).do_deploy()
213
214     def do_release(self):
215         """ Delete the port on the OVSwitch. It needs to wait for the tunnel
216         to be released.
217         """
218
219         from nepi.resources.planetlab.openvswitch.tunnel import OVSTunnel
220         rm = self.get_connected(OVSTunnel.get_rtype())
221
222         if rm and rm[0].state < ResourceState.RELEASED:
223             self.ec.schedule(reschedule_delay, self.release)
224             return 
225             
226         cmd = "sliver-ovs del_port %s" % self.get('port_name')
227         (out, err), proc = self.node.run(cmd, self.ovswitch.ovs_checks,
228                 sudo = True)
229
230         msg = "Deleting the port %s" % self.get('port_name')
231         self.info(msg)
232
233         if proc.poll():
234             self.error(msg, out, err)
235             raise RuntimeError, msg
236
237         super(OVSPort, self).do_release()
238