Push openflow RMs
[nepi.git] / src / nepi / resources / planetlab / openvswitch / ovs.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@inria.fr>
20
21
22 from nepi.execution.resource import ResourceManager, clsinit_copy, ResourceState
23 from nepi.execution.attribute import Attribute, Flags
24 from nepi.resources.planetlab.node import PlanetlabNode        
25 from nepi.resources.linux.application import LinuxApplication
26 import os
27
28 reschedule_delay = "0.5s"
29
30 @clsinit_copy                    
31 class OVSWitch(LinuxApplication):
32     
33     _rtype = "OVSWitch"
34     _authorized_connections = ["PlanetlabNode", "OVSPort", "LinuxNode"]       
35
36     @classmethod
37     def _register_attributes(cls):
38         """ Register the attributes of OVSWitch RM 
39
40         """
41         bridge_name = Attribute("bridge_name", "Name of the switch/bridge",
42                 flags = Flags.ExecReadOnly)     
43         virtual_ip_pref = Attribute("virtual_ip_pref", "Virtual IP/PREFIX of the switch",
44                 flags = Flags.ExecReadOnly)       
45         controller_ip = Attribute("controller_ip", "IP of the controller",
46                 flags = Flags.ExecReadOnly)
47         controller_port = Attribute("controller_port", "Port of the controller",
48                 flags = Flags.ExecReadOnly)
49
50         cls._register_attribute(bridge_name)
51         cls._register_attribute(virtual_ip_pref)
52         cls._register_attribute(controller_ip)
53         cls._register_attribute(controller_port)
54
55     def __init__(self, ec, guid):
56         """
57         :param ec: The Experiment controller
58         :type ec: ExperimentController
59         :param guid: guid of the RM
60         :type guid: int
61         :param creds: Credentials to communicate with the rm 
62         :type creds: dict
63     
64         """
65         super(OVSWitch, self).__init__(ec, guid)
66         self._pid = None
67         self._ppid = None
68         self._home = "ovswitch-%s" % self.guid
69         self._checks = "ovsChecks-%s" % self.guid
70
71     @property
72     def node(self):
73         node = self.get_connected(PlanetlabNode.rtype())
74         if node: return node[0]
75         return None
76
77     @property
78     def ovs_home(self):
79         return os.path.join(self.node.exp_home, self._home)
80
81     @property
82     def ovs_checks(self):
83         return os.path.join(self.ovs_home, self._checks)
84
85     @property
86     def pid(self):
87         return self._pid
88
89     @property
90     def ppid(self):
91         return self._ppid
92
93 #    def valid_connection(self, guid):
94 #        """ Check if the connection with the guid in parameter is possible. Only meaningful connections are allowed.
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.rtype() in self._authorized_connections:
103 #            msg = "Connection between %s %s and %s %s accepted" % \
104 #                (self.rtype(), self._guid, rm.rtype(), guid)
105 #            self.debug(msg)
106 #            return True
107 #        msg = "Connection between %s %s and %s %s refused" % \
108 #             (self.rtype(), self._guid, rm.rtype(), guid)
109 #        self.debug(msg)
110 #        return False
111
112     def valid_connection(self, guid):
113         # TODO: Validate!
114         return True
115
116     def provision(self):
117         # create home dir for ovs
118         self.node.mkdir(self.ovs_home)
119         # create dir for ovs checks
120         self.node.mkdir(self.ovs_checks)
121
122     def check_sliver_ovs(self):  
123         """ Check if sliver-ovs exists. If it does not exist, we interrupt
124         the execution immediately. 
125         """
126         cmd = "compgen -c | grep sliver-ovs"                    
127         out = err = ""
128
129         (out,err), proc = self.node.run_and_wait(cmd, self.ovs_checks, 
130                     shfile = "check_cmd.sh",
131                 pidfile = "check_cmd_pidfile",
132                 ecodefile = "check_cmd_exitcode", 
133                 sudo = True, 
134                 stdout = "check_cmd_stdout", 
135                 stderr = "check_cmd_stderr")
136
137         (out, err), proc = self.node.check_output(self.ovs_checks, 'check_cmd_exitcode')
138         if out != "0\n":
139             msg = "Command sliver-ovs does not exist on the VM"          
140             self.debug(msg)
141             raise RuntimeError, msg
142         msg = "Command sliver-ovs exists" 
143         self.debug(msg)                                         
144
145     def deploy(self):
146         """ Wait until node is associated and deployed
147         """
148         node = self.node
149         if not node or node.state < ResourceState.READY:
150             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
151             self.ec.schedule(reschedule_delay, self.deploy)
152
153         else:
154             try:
155                 self.discover()
156                 self.provision()
157                 self.check_sliver_ovs()
158                 self.servers_on()
159                 self.create_bridge()
160                 self.assign_contr()
161                 self.ovs_status()
162             except:
163                 self._state = ResourceState.FAILED
164                 raise
165                 
166             self._state = ResourceState.READY
167
168     def servers_on(self):
169         """ Start the openvswitch servers and also checking 
170             if they started successfully 
171         """
172         self.info("Starting the OVSWitch servers")
173         command = ("sliver-ovs start") 
174                                 
175         out = err = ""                                                                  
176         (out, err), proc = self.node.run_and_wait(command, self.ovs_checks,   
177                 shfile = "start_srv.sh",
178                 pidfile = "start_srv_pidfile",
179                 ecodefile = "start_srv_exitcode", 
180                 sudo = True, 
181                 raise_on_error = True,
182                 stdout = "start_srv_stdout", 
183                 stderr = "start_srv_stderr")
184
185         (out, err), proc = self.node.check_output(self.ovs_checks, 'start_srv_exitcode')
186
187         if out != "0\n":
188             self.debug("Servers have not started")
189             raise RuntimeError, msg     
190                                 
191         cmd = "ps -A | grep ovsdb-server"
192         out = err = ""
193         (out, err), proc = self.node.run_and_wait(cmd, self.ovs_checks, 
194                 shfile = "status_srv.sh",
195                 pidfile = "status_srv_pidfile",
196                 ecodefile = "status_srv_exitcode", 
197                 sudo = True, 
198                 stdout = "status_srv_stdout", 
199                 stderr = "status_srv_stderr")
200
201         # Check if the servers are running or not
202         (out, err), proc = self.node.check_output(self.ovs_checks, 'status_srv_exitcode')
203         if out != "0\n":
204             self.debug("Servers are not running")
205             raise RuntimeError, msg
206         self.info("Servers started")  
207
208     def del_old_br(self):
209         # TODO: Delete old bridges that might exist maybe by adding atribute
210         """ With ovs-vsctl list-br
211         """
212         pass
213
214     def create_bridge(self):
215         """ Create the bridge/switch and we check if we have any 
216             error during the SSH connection         
217         """
218         # TODO: Add check for virtual_ip belonging to vsys_tag
219         self.del_old_br()
220         
221         if self.get("bridge_name") and self.get("virtual_ip_pref"):     
222             bridge_name = self.get("bridge_name")
223             virtual_ip_pref = self.get("virtual_ip_pref")
224             self.info(" Creating the bridge %s and assigning %s" %\
225                 (bridge_name, virtual_ip_pref) )
226             cmd = "sliver-ovs create-bridge '%s' '%s'" %\
227                 (bridge_name, virtual_ip_pref) 
228             out = err = ""
229             (out, err), proc = self.node.run_and_wait(cmd, self.ovs_checks,
230                     shfile = "create_br.sh",
231                     pidfile = "create_br_pidfile",
232                     ecodefile = "create_br_exitcode", 
233                     sudo = True, 
234                     stdout = "create_br_stdout", 
235                     stderr = "create_br_stderr") 
236             (out, err), proc = self.node.check_output(self.ovs_checks, 'create_br_exitcode')
237             if out != "0\n":
238                 msg = "No such pltap netdev\novs-appctl: ovs-vswitchd: server returned an error"
239                 self.debug("Check again the virtual IP")                        
240                 raise RuntimeError, msg
241             self.info("Bridge %s created" % bridge_name)
242           
243         else:   
244             msg = "No assignment in one or both attributes"
245             self.error(msg)
246             self.debug("Bridge name is %s and virtual_ip_pref is %s" %\
247                 (self.get("bridge_name"), self.get("virtual_ip_pref")) )
248             raise AttributeError, msg
249
250     def assign_contr(self):
251         """ Set the controller IP
252         """
253         if self.get("controller_ip") and self.get("controller_port"):
254             controller_ip = self.get("controller_ip")
255             controller_port = self.get("controller_port")
256             self.info("Assigning the controller to the %s" % self.get("bridge_name"))
257             cmd = "ovs-vsctl set-controller %s tcp:%s:%s" %\
258                 (self.get("bridge_name"), controller_ip, controller_port)
259             out = err = ""
260             (out, err), proc = self.node.run(cmd, self.ovs_checks,
261                     sudo = True, 
262                     stdout = "stdout", 
263                     stderr = "stderr")
264             if err != "":
265                 self.debug("SSH connection refusing in assign_contr")
266                 raise RuntimeError, msg
267             self.info("Controller assigned")
268             
269     def ovs_status(self):
270         """ Print the status of the created bridge                                      
271         """
272         cmd = "sliver-ovs show | tail -n +2"
273         out = err = ""
274         (out, err), proc = self.node.run_and_wait(cmd, self.ovs_home,
275                 sudo = True, 
276                 stdout = "show_stdout", 
277                 stderr = "show_stderr") 
278         (out, err), proc = self.node.check_output(self.ovs_home, 'show_stdout')
279         self.info(out)
280
281     def start(self):
282         """ Start the RM. It means nothing special for 
283             ovswitch for now.   
284         """
285         pass
286
287     def stop(self):
288         """ Stop the RM.It means nothing 
289             for ovswitch for now.
290         """
291         pass
292
293     def release(self):
294         """ Delete the bridge and 
295             close the servers
296         """
297         # Node needs to wait until all associated RMs are released
298         # to be released
299         from nepi.resources.planetlab.openvswitch.ovsport import OVSPort
300         rm = self.get_connected(OVSPort.rtype())
301
302         if rm[0].state < ResourceState.FINISHED:
303             self.ec.schedule(reschedule_delay, self.release)
304             return 
305             
306         msg = "Deleting the bridge %s" % self.get('bridge_name')
307         self.info(msg)
308         cmd = "sliver-ovs del-bridge %s" % self.get('bridge_name')
309         (out, err), proc = self.node.run(cmd, self.ovs_checks,
310                 sudo = True)
311         cmd = "sliver-ovs stop"
312         (out, err), proc = self.node.run(cmd, self.ovs_checks,
313                 sudo = True)
314         
315         if proc.poll():
316             self.fail()
317             self.error(msg, out, err)
318             raise RuntimeError, msg
319      
320         self._state = ResourceState.RELEASED
321