fix a race condition using database connection db_of at ovim.start without using...
[osm/openvim.git] / ovim.py
diff --git a/ovim.py b/ovim.py
index 02114a1..9fef4f9 100644 (file)
--- a/ovim.py
+++ b/ovim.py
@@ -180,7 +180,7 @@ class ovim():
         # check if this bridge is already used (present at database) for a network)
         used_bridge_nets = []
         for brnet in self.config['bridge_nets']:
-            r, nets = self.db_of.get_table(SELECT=('uuid',), FROM='nets', WHERE={'provider': "bridge:" + brnet[0]})
+            r, nets = self.db.get_table(SELECT=('uuid',), FROM='nets', WHERE={'provider': "bridge:" + brnet[0]})
             if r > 0:
                 brnet[3] = nets[0]['uuid']
                 used_bridge_nets.append(brnet[0])
@@ -192,7 +192,7 @@ class ovim():
         # get nets used by dhcp
         if self.config.get("dhcp_server"):
             for net in self.config["dhcp_server"].get("nets", ()):
-                r, nets = self.db_of.get_table(SELECT=('uuid',), FROM='nets', WHERE={'name': net})
+                r, nets = self.db.get_table(SELECT=('uuid',), FROM='nets', WHERE={'name': net})
                 if r > 0:
                     self.config['dhcp_nets'].append(nets[0]['uuid'])
 
@@ -217,7 +217,7 @@ class ovim():
         host_develop_bridge_iface = self.config.get('development_bridge', None)
 
         # get host list from data base before starting threads
-        r, hosts = self.db_of.get_table(SELECT=('name', 'ip_name', 'user', 'uuid'), FROM='hosts', WHERE={'status': 'ok'})
+        r, hosts = self.db.get_table(SELECT=('name', 'ip_name', 'user', 'uuid'), FROM='hosts', WHERE={'status': 'ok'})
         if r < 0:
             raise ovimException("Cannot get hosts from database {}".format(hosts))
 
@@ -797,6 +797,72 @@ class ovim():
         else:
             raise ovimException(str(uuid), -result)
 
+    def new_external_port(self, port_data):
+        """
+        Create new external port and check port mapping correspondence
+        :param port_data: port_data = {
+            'region': 'datacenter region',
+            'compute_node': 'compute node id',
+            'pci': 'pci port address',
+            'vlan': 'net vlan',
+            'net_id': 'net id',
+            'tenant_id': 'tenant id',
+            'mac': 'switch mac',
+            'name': 'port name'
+            'ip_address': 'ip address - optional'}
+        :return:
+        """
+
+        port_data['type'] = 'external'
+
+        if port_data.get('net_id'):
+            # check that new net has the correct type
+            result, new_net = self.db.check_target_net(port_data['net_id'], None, 'external')
+            if result < 0:
+                raise ovimException(str(new_net), -result)
+        # insert in data base
+        db_filter = {}
+
+        if port_data.get('region'):
+            db_filter['region'] = port_data['region']
+        if port_data.get('pci'):
+            db_filter['pci'] = port_data['pci']
+        if port_data.get('compute_node'):
+            db_filter['compute_node'] = port_data['compute_node']
+
+        columns = ['ofc_id', 'switch_dpid', 'switch_port', 'switch_mac', 'pci']
+        port_mapping_data = self.get_of_port_mappings(columns, db_filter)
+
+        if not len(port_mapping_data):
+            raise ovimException("No port mapping founded for region='{}', compute id='{}' and pci='{}'".
+                                format(db_filter['region'], db_filter['compute_node'], db_filter['pci']),
+                                HTTP_Not_Found)
+        elif len(port_mapping_data) > 1:
+            raise ovimException("Wrong port data was given, please check pci, region & compute id data",
+                                HTTP_Conflict)
+
+        port_data['ofc_id'] = port_mapping_data[0]['ofc_id']
+        port_data['switch_dpid'] = port_mapping_data[0]['switch_dpid']
+        port_data['switch_port'] = port_mapping_data[0]['switch_port']
+        port_data['switch_mac'] = port_mapping_data[0]['switch_mac']
+
+        # remove from compute_node, region and pci of_port_data to adapt to 'ports' structure
+        del port_data['compute_node']
+        del port_data['region']
+        del port_data['pci']
+
+        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)
+            return uuid
+        else:
+            raise ovimException(str(uuid), -result)
+
     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')
@@ -1073,6 +1139,63 @@ class ovim():
         else:
             raise ovimException(str(content), -result)
 
+    def set_of_port_mapping(self, of_maps, ofc_id=None, switch_dpid=None, region=None):
+        """
+        Create new port mapping entry
+        :param of_maps: List with port mapping information
+        # maps =[{"ofc_id": <ofc_id>,"region": datacenter region,"compute_node": compute uuid,"pci": pci adress,
+                "switch_dpid": swith dpid,"switch_port": port name,"switch_mac": mac}]
+        :param ofc_id: ofc id
+        :param switch_dpid: switch  dpid
+        :param region: datacenter region id
+        :return:
+        """
+
+        for map in of_maps:
+            if ofc_id:
+                map['ofc_id'] = ofc_id
+            if switch_dpid:
+                map['switch_dpid'] = switch_dpid
+            if region:
+                map['region'] = region
+
+        for of_map in of_maps:
+            result, uuid = self.db.new_row('of_port_mappings', of_map, True)
+            if result > 0:
+                of_map["uuid"] = uuid
+            else:
+                raise ovimException(str(uuid), -result)
+        return of_maps
+
+    def clear_of_port_mapping(self, db_filter={}):
+        """
+        Clear port mapping filtering using db_filter dict
+        :param db_filter: Parameter to filter during remove process
+        :return:
+        """
+        result, content = self.db.delete_row_by_dict(FROM='of_port_mappings', WHERE=db_filter)
+        # delete_row_by_key
+        if result >= 0:
+            return content
+        else:
+            raise ovimException("Error deleting of_port_mappings with filter='{}'".format(str(db_filter)),
+                                HTTP_Internal_Server_Error)
+
+    def get_of_port_mappings(self, column=None, db_filter=None, db_limit=None):
+        """
+        Retrive port mapping from DB
+        :param column:
+        :param db_filter:
+        :return:
+        """
+        result, content = self.db.get_table(SELECT=column, WHERE=db_filter, FROM='of_port_mappings', LIMIT=db_limit)
+
+        if result < 0:
+            self.logger.error("get_of_port_mappings Error %d %s", result, content)
+            raise ovimException(str(content), -result)
+        else:
+            return content
+
     def get_dhcp_controller(self):
         """
         Create an host_thread object for manage openvim controller and not create a thread for itself
@@ -1090,8 +1213,8 @@ class ovim():
         host_develop_mode = True if self.config['mode'] == 'development' else False
 
         dhcp_host = ht.host_thread(name='openvim_controller', user=ovs_controller_user, host=controller_ip,
-                                   db=self.config['db'],
-                                   db_lock=self.config['db_lock'], test=host_test_mode,
+                                   db=self.db_of,
+                                   db_lock=self.db_lock, test=host_test_mode,
                                    image_path=self.config['image_path'], version=self.config['version'],
                                    host_id='openvim_controller', develop_mode=host_develop_mode,
                                    develop_bridge_iface=bridge_ifaces)