Refactor update-net task to ovim.py 90/1290/4
authormirabal <leonardo.mirabal@altran.com>
Mon, 13 Mar 2017 14:15:18 +0000 (15:15 +0100)
committermirabal <leonardo.mirabal@altran.com>
Wed, 15 Mar 2017 15:29:23 +0000 (16:29 +0100)
- Every update-net task is dispached to each ofc threard available to each net

Change-Id: Ic459a96ac6401fdc72f8aca2c0edf52a2aff2b29
Signed-off-by: mirabal <leonardo.mirabal@altran.com>
httpserver.py
ovim.py

index b15f7a1..e35daf0 100644 (file)
@@ -1619,14 +1619,18 @@ def http_post_server_id(tenant_id):
             r,c = config_dic['host_threads'][ server['host_id'] ].insert_task( 'restore-iface',*port )
             if r < 0:
                 print ' http_post_servers ERROR RESTORE IFACE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' +  c
-        #updata nets
-        for net in nets:
-            r,c = config_dic['of_thread'].insert_task("update-net", net)
-            if r < 0:
-                print ':http_post_servers ERROR UPDATING NETS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' +  c
-
-            
-        #look for dhcp ip address
+        # update nets
+        for net_id in nets:
+            try:
+                my.ovim.net_update_ofc_thread(net_id)
+            except ovim.ovimException as e:
+                raise ovim.ovimException("http_post_servers, Error updating network with id '{}', '{}'".
+                                         format(net_id, str(e)), HTTP_Internal_Server_Error)
+            except Exception as e:
+                raise ovim.ovimException("http_post_servers, Error updating network with id '{}', '{}'".
+                                         format(net_id, str(e)), HTTP_Internal_Server_Error)
+
+        # look for dhcp ip address
         r2, c2 = my.db.get_table(FROM="ports", SELECT=["mac", "ip_address", "net_id"], WHERE={"instance_id": new_instance})
         if r2 >0:
             for iface in c2:
@@ -1806,12 +1810,20 @@ def http_server_action(server_id, tenant_id, action):
             if r1 < 0:
                 print ' http_post_server_action error at server deletion ERROR resore-iface !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' +  c1
                 data={'result' : 'deleting in process, but ifaces cannot be restored!!!!!'}
-        for net in nets:
-            r1,c1 = config_dic['of_thread'].insert_task("update-net", net)
-            if r1 < 0:
-                print ' http_post_server_action error at server deletion ERROR UPDATING NETS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' +  c1
-                data={'result' : 'deleting in process, but openflow rules cannot be deleted!!!!!'}
-        #look for dhcp ip address 
+        for net_id in nets:
+            try:
+                my.ovim.net_update_ofc_thread(net_id)
+            except ovim.ovimException as e:
+                raise ovim.ovimException("http_post_servers, Error updating network with id '{}', '{}'".
+                                         format(net_id, str(e)), HTTP_Internal_Server_Error)
+            except Exception as e:
+                raise ovim.ovimException("http_post_server_action error at server deletion "
+                                         "ERROR UPDATING NET '{}', '{}'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!".
+                                         format(net_id, str(e)), HTTP_Internal_Server_Error)
+
+            data = {'result': 'deleting in process, but openflow rules cannot be deleted!!!!!'}
+
+        # look for dhcp ip address
         if r2 >0 and config_dic.get("dhcp_server"):
             for iface in c2:
                 if iface["net_id"] in config_dic["dhcp_nets"]:
@@ -1973,7 +1985,7 @@ def http_put_network_id(network_id):
         http_content = format_in(network_update_schema)
         change_keys_http2db(http_content['network'], http2db_network)
         network = http_content['network']
-        return my.ovim.edit_network(network_id, network)
+        return format_out(my.ovim.edit_network(network_id, network))
 
     except ovim.ovimException as e:
         my.logger.error(str(e), exc_info=True)
diff --git a/ovim.py b/ovim.py
index 9fef4f9..16b3f03 100644 (file)
--- a/ovim.py
+++ b/ovim.py
@@ -661,17 +661,24 @@ class ovim():
             # if result > 0 and nbports>0 and 'admin_state_up' in network
             #     and network['admin_state_up'] != network_old[0]['admin_state_up']:
             if result > 0:
-                r, c = self.config['of_thread'].insert_task("update-net", network_id)
-                if r < 0:
-                    raise ovimException("Error while launching openflow rules %s" % c, HTTP_Internal_Server_Error)
+
+                try:
+                    self.net_update_ofc_thread(network_id)
+                except ovimException as e:
+                    raise ovimException("Error while launching openflow rules in network '{}' {}"
+                                        .format(network_id, str(e)), HTTP_Internal_Server_Error)
+                except Exception as e:
+                    raise ovimException("Error while launching openflow rules in network '{}' {}"
+                                        .format(network_id, str(e)), HTTP_Internal_Server_Error)
+
                 if self.config.get("dhcp_server"):
                     if network_id in self.config["dhcp_nets"]:
                         self.config["dhcp_nets"].remove(network_id)
-                    if network.get("name", network_old["name"]) in self.config["dhcp_server"].get("nets", ()):
+                    if network.get("name", network_old[0]["name"]) in self.config["dhcp_server"].get("nets", ()):
                         self.config["dhcp_nets"].append(network_id)
                     else:
-                        net_bind = network.get("bind", network_old["bind"])
-                        if net_bind and net_bind[:7] == "bridge:" and net_bind[7:] in self.config["dhcp_server"].get(
+                        net_bind = network.get("bind_type", network_old[0]["bind_type"])
+                        if net_bind and net_bind and net_bind[:7] == "bridge:" and net_bind[7:] in self.config["dhcp_server"].get(
                                 "bridge_ifaces", ()):
                             self.config["dhcp_nets"].append(network_id)
             return network_id
@@ -744,9 +751,16 @@ class ovim():
             if net["type"] != "ptp" and net["type"] != "data":
                 result -= 1
                 continue
-            r, c = self.config['of_thread'].insert_task("update-net", net['uuid'])
-            if r < 0:
-                raise ovimException(str(c), -r)
+
+            try:
+                self.net_update_ofc_thread(net['uuid'])
+            except ovimException as e:
+                raise ovimException("Error updating network'{}' {}".format(net['uuid'], str(e)),
+                                    HTTP_Internal_Server_Error)
+            except Exception as e:
+                raise ovimException("Error updating network '{}' {}".format(net['uuid'], str(e)),
+                                    HTTP_Internal_Server_Error)
+
         return result
 
     def delete_openflow_rules(self):
@@ -789,10 +803,15 @@ class ovim():
         result, uuid = self.db.new_row('ports', port_data, True, True)
         if result > 0:
             if 'net_id' in port_data:
-                r, c = self.config['of_thread'].insert_task("update-net", port_data['net_id'])
-                if r < 0:
-                    self.logger.error("Cannot insert a task for updating network '$s' %s", port_data['net_id'], c)
-                    #TODO put network in error status
+                try:
+                    self.net_update_ofc_thread(port_data['net_id'])
+                except ovimException as e:
+                    raise ovimException("Cannot insert a task for updating network '{}' {}"
+                                        .format(port_data['net_id'], str(e)), HTTP_Internal_Server_Error)
+                except Exception as e:
+                    raise ovimException("Cannot insert a task for updating network '{}' {}"
+                                        .format(port_data['net_id'], str(e)), HTTP_Internal_Server_Error)
+
             return uuid
         else:
             raise ovimException(str(uuid), -result)
@@ -853,16 +872,59 @@ class ovim():
 
         result, uuid = self.db.new_row('ports', port_data, True, True)
         if result > 0:
-            if 'net_id' in port_data and port_data['ofc_id'] in self.config['ofcs_thread']:
-                r, c = self.config['ofcs_thread'][port_data['ofc_id']].insert_task("update-net", port_data['net_id'])
-                if r < 0:
-                    message = "Cannot insert a task for updating network '$s' %s", port_data['net_id'], c
-                    self.logger.error(message)
-                    raise ovimException(message, HTTP_Internal_Server_Error)
+            try:
+                self.net_update_ofc_thread(port_data['net_id'], port_data['ofc_id'])
+            except ovimException as e:
+                raise ovimException("Cannot insert a task for updating network '{}' {}".
+                                    format(port_data['net_id'], str(e)), HTTP_Internal_Server_Error)
+            except Exception as e:
+                raise ovimException("Cannot insert a task for updating network '{}' {}"
+                                    .format(port_data['net_id'], e), HTTP_Internal_Server_Error)
             return uuid
         else:
             raise ovimException(str(uuid), -result)
 
+    def net_update_ofc_thread(self, net_id, ofc_id=None):
+        """
+        Insert a update net task by net id or ofc_id for each ofc thread
+        :param net_id: network id
+        :param ofc_id: openflow controller id
+        :return:
+        """
+        if not net_id:
+            raise ovimException("No net_id received", HTTP_Internal_Server_Error)
+
+        switch_dpid = None
+        r = -1
+        c = 'No valid ofc_id or switch_dpid received'
+
+        if not ofc_id:
+            ports = self.get_ports(filter={"net_id": net_id})
+            for port in ports:
+                port_ofc_id = port.get('ofc_id', None)
+                if port_ofc_id:
+                    ofc_id = port['ofc_id']
+                    switch_dpid = port['switch_dpid']
+                    break
+
+        # If no ofc_id found it, default ofc_id is used.
+        if not ofc_id and not switch_dpid:
+            ofc_id = "Default"
+
+        if ofc_id and ofc_id in self.config['ofcs_thread']:
+            r, c = self.config['ofcs_thread'][ofc_id].insert_task("update-net", net_id)
+        elif switch_dpid:
+
+            ofcs_dpid_list = self.config['ofcs_thread_dpid']
+            for ofc_t in ofcs_dpid_list:
+                if switch_dpid in ofc_t:
+                    r, c = ofc_t[switch_dpid].insert_task("update-net", net_id)
+
+        if r < 0:
+            message = "Cannot insert a task for updating network '$s', %s", net_id, c
+            self.logger.error(message)
+            raise ovimException(message, HTTP_Internal_Server_Error)
+
     def delete_port(self, port_id):
         # Look for the previous port data
         result, ports = self.db.get_table(WHERE={'uuid': port_id, "type": "external"}, FROM='ports')
@@ -878,9 +940,16 @@ class ovim():
         network = ports[0].get('net_id', None)
         if network:
             # change of net.
-            r, c = self.config['of_thread'].insert_task("update-net", network)
-            if r < 0:
-                self.logger.error("Cannot insert a task for updating network '$s' %s", network, c)
+
+            try:
+                self.net_update_ofc_thread(network)
+            except ovimException as e:
+                raise ovimException("Cannot insert a task for delete network '{}' {}".format(network, str(e)),
+                                    HTTP_Internal_Server_Error)
+            except Exception as e:
+                raise ovimException("Cannot insert a task for delete network '{}' {}".format(network, str(e)),
+                                    HTTP_Internal_Server_Error)
+
         return content
 
     def edit_port(self, port_id, port_data, admin=True):
@@ -931,10 +1000,15 @@ class ovim():
         # Insert task to complete actions
         if result > 0:
             for net_id in nets:
-                r, v = self.config['of_thread'].insert_task("update-net", net_id)
-                if r < 0:
-                    self.logger.error("Error updating network '{}' {}".format(r,v))
-                    # TODO Do something if fails
+                try:
+                    self.net_update_ofc_thread(net_id)
+                except ovimException as e:
+                    raise ovimException("Error updating network'{}' {}".format(net_id, str(e)),
+                                        HTTP_Internal_Server_Error)
+                except Exception as e:
+                    raise ovimException("Error updating network '{}' {}".format(net_id, str(e)),
+                                        HTTP_Internal_Server_Error)
+
             if host_id:
                 r, v = self.config['host_threads'][host_id].insert_task("edit-iface", port_id, old_net, new_net)
                 if r < 0: