New file setup.py: builds a python package
[osm/RO.git] / vimconn_openvim.py
index ac02678..e86b54d 100644 (file)
@@ -323,11 +323,13 @@ get_processor_rankings_response_schema = {
 }
 
 class vimconnector(vimconn.vimconnector):
-    def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,log_level="DEBUG",config={}):
+    def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None,
+                 log_level="DEBUG", config={}, persistent_info={}):
         vimconn.vimconnector.__init__(self, uuid, name, tenant_id, tenant_name, url, url_admin, user, passwd, log_level, config)
         self.tenant = None
         self.headers_req = {'content-type': 'application/json'}
-        self.logger = logging.getLogger('mano.vim.openvim')
+        self.logger = logging.getLogger('openmano.vim.openvim')
+        self.persistent_info = persistent_info
         if tenant_id:
             self.tenant = tenant_id
 
@@ -377,7 +379,7 @@ class vimconnector(vimconn.vimconnector):
             js_v(client_data, schema)
             #print "Input data: ", str(client_data)
             return True, client_data
-        except js_e.ValidationError, exc:
+        except js_e.ValidationError as exc:
             print "validate_in error, jsonschema exception ", exc.message, "at", exc.path
             return False, ("validate_in error, jsonschema exception ", exc.message, "at", exc.path)
     
@@ -481,7 +483,7 @@ class vimconnector(vimconn.vimconnector):
         except requests.exceptions.RequestException as e:
             self._format_request_exception(e)
 
-    def new_network(self,net_name,net_type, shared=False, **vim_specific):
+    def new_network(self,net_name, net_type, ip_profile=None, shared=False, vlan=None): #, **vim_specific):
         '''Adds a tenant network to VIM'''
         '''Returns the network identifier'''
         try:
@@ -489,7 +491,9 @@ class vimconnector(vimconn.vimconnector):
             if net_type=="bridge":
                 net_type="bridge_data"
             payload_req = {"name": net_name, "type": net_type, "tenant_id": self.tenant, "shared": shared}
-            payload_req.update(vim_specific)
+            if vlan:
+                payload_req["provider:vlan"] = vlan
+            # payload_req.update(vim_specific)
             url = self.url+'/networks'
             self.logger.info("Adding a new network POST: %s  DATA: %s", url, str(payload_req))
             vim_response = requests.post(url, headers = self.headers_req, data=json.dumps({"network": payload_req}) )
@@ -591,8 +595,10 @@ class vimconnector(vimconn.vimconnector):
         '''Adds a tenant flavor to VIM'''
         '''Returns the flavor identifier'''
         try:
+            new_flavor_dict = flavor_data.copy()
+            new_flavor_dict["name"] = flavor_data["name"][:64]
             self._get_my_tenant()
-            payload_req = json.dumps({'flavor': flavor_data})
+            payload_req = json.dumps({'flavor': new_flavor_dict})
             url = self.url+'/'+self.tenant+'/flavors'
             self.logger.info("Adding a new VIM flavor POST %s", url)
             vim_response = requests.post(url, headers = self.headers_req, data=payload_req)
@@ -647,7 +653,7 @@ class vimconnector(vimconn.vimconnector):
         ''' Adds a tenant image to VIM, returns image_id'''
         try:
             self._get_my_tenant()
-            new_image_dict={'name': image_dict['name']}
+            new_image_dict={'name': image_dict['name'][:64]}
             if image_dict.get('description'):
                 new_image_dict['description'] = image_dict['description']
             if image_dict.get('metadata'):
@@ -688,7 +694,7 @@ class vimconnector(vimconn.vimconnector):
 
     
     def get_image_id_from_path(self, path):
-        '''Get the image id from image path in the VIM database'''
+        '''Get the image id from image path in the VIM database. Returns the image_id'''
         try:
             self._get_my_tenant()
             url=self.url + '/' + self.tenant + '/images?path='+quote(path)
@@ -710,6 +716,36 @@ class vimconnector(vimconn.vimconnector):
         except (requests.exceptions.RequestException, js_e.ValidationError) as e:
             self._format_request_exception(e)
 
+    def get_image_list(self, filter_dict={}):
+        '''Obtain tenant images from VIM
+        Filter_dict can be:
+            name: image name
+            id: image uuid
+            checksum: image checksum
+            location: image path
+        Returns the image list of dictionaries:
+            [{<the fields at Filter_dict plus some VIM specific>}, ...]
+            List can be empty
+        '''
+        try:
+            self._get_my_tenant()
+            filterquery=[]
+            filterquery_text=''
+            for k,v in filter_dict.iteritems():
+                filterquery.append(str(k)+'='+str(v))
+            if len(filterquery)>0:
+                filterquery_text='?'+ '&'.join(filterquery)
+            url = self.url+'/'+self.tenant+'/images'+filterquery_text
+            self.logger.info("Getting image list GET %s", url)
+            vim_response = requests.get(url, headers = self.headers_req)
+            self._check_http_request_response(vim_response)
+            self.logger.debug(vim_response.text)
+            #print json.dumps(vim_response.json(), indent=4)
+            response = vim_response.json()
+            return response['images']
+        except (requests.exceptions.RequestException, js_e.ValidationError) as e:
+            self._format_request_exception(e)
+
     def new_vminstancefromJSON(self, vm_data):
         '''Adds a VM instance to VIM'''
         '''Returns the instance identifier'''
@@ -721,7 +757,7 @@ class vimconnector(vimconn.vimconnector):
         payload_req = vm_data
         try:
             vim_response = requests.post(self.url+'/'+self.tenant+'/servers', headers = self.headers_req, data=payload_req)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             print "new_vminstancefromJSON Exception: ", e.args
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print vim_response
@@ -746,7 +782,7 @@ class vimconnector(vimconn.vimconnector):
             #print text
             return -vim_response.status_code,text
 
-    def new_vminstance(self,name,description,start,image_id,flavor_id,net_list, cloud_config=None):
+    def new_vminstance(self,name,description,start,image_id,flavor_id,net_list, cloud_config=None, disk_list=None):
         '''Adds a VM instance to VIM
         Params:
             start: indicates if VM must start or boot in pause mode. Ignored
@@ -763,6 +799,7 @@ class vimconnector(vimconn.vimconnector):
                 #TODO ip, security groups
         Returns the instance identifier
         '''
+        self.logger.debug("new_vminstance input: image='%s' flavor='%s' nics='%s'", image_id, flavor_id, str(net_list))
         try:
             self._get_my_tenant()
 #            net_list = []
@@ -781,7 +818,7 @@ class vimconnector(vimconn.vimconnector):
                 if net.get("model"):       net_dict["model"] = net["model"]
                 if net.get("mac_address"): net_dict["mac_address"] = net["mac_address"]
                 virtio_net_list.append(net_dict)
-            payload_dict={  "name":        name,
+            payload_dict={  "name":        name[:64],
                             "description": description,
                             "imageRef":    image_id,
                             "flavorRef":   flavor_id,
@@ -910,7 +947,7 @@ class vimconnector(vimconn.vimconnector):
                         interface={}
                         interface['vim_info']  = yaml.safe_dump(port)
                         interface["mac_address"] = port.get("mac_address")
-                        interface["vim_net_id"] = port["network_id"]
+                        interface["vim_net_id"] = port.get("network_id")
                         interface["vim_interface_id"] = port["id"]
                         interface["ip_address"] = port.get("ip_address")
                         if interface["ip_address"]:
@@ -1047,7 +1084,7 @@ class vimconnector(vimconn.vimconnector):
         url=self.url+'/hosts'
         try:
             vim_response = requests.get(url)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             print "get_hosts_info Exception: ", e.args
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print "vim get", url, "response:",  vim_response.status_code, vim_response.json()
@@ -1069,7 +1106,7 @@ class vimconnector(vimconn.vimconnector):
             url=self.url+'/hosts/'+host['id']
             try:
                 vim_response = requests.get(url)
-            except requests.exceptions.RequestException, e:
+            except requests.exceptions.RequestException as e:
                 print "get_hosts_info Exception: ", e.args
                 return -vimconn.HTTP_Not_Found, str(e.args[0])
             print "vim get", url, "response:",  vim_response.status_code, vim_response.json()
@@ -1091,7 +1128,7 @@ class vimconnector(vimconn.vimconnector):
         url=self.url+'/hosts'
         try:
             vim_response = requests.get(url)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             print "get_hosts Exception: ", e.args
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print "vim get", url, "response:",  vim_response.status_code, vim_response.json()
@@ -1112,7 +1149,7 @@ class vimconnector(vimconn.vimconnector):
             url=self.url+'/' + vim_tenant + '/servers?hostId='+host['id']
             try:
                 vim_response = requests.get(url)
-            except requests.exceptions.RequestException, e:
+            except requests.exceptions.RequestException as e:
                 print "get_hosts Exception: ", e.args
                 return -vimconn.HTTP_Not_Found, str(e.args[0])
             print "vim get", url, "response:",  vim_response.status_code, vim_response.json()
@@ -1132,7 +1169,7 @@ class vimconnector(vimconn.vimconnector):
         url=self.url+'/processor_ranking'
         try:
             vim_response = requests.get(url)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             print "get_processor_rankings Exception: ", e.args
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print "vim get", url, "response:", vim_response.status_code, vim_response.json()
@@ -1175,7 +1212,7 @@ class vimconnector(vimconn.vimconnector):
         payload_req = port_data
         try:
             vim_response = requests.post(self.url_admin+'/ports', headers = self.headers_req, data=payload_req)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             self.logger.error("new_external_port Exception: ", str(e))
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print vim_response
@@ -1209,7 +1246,7 @@ class vimconnector(vimconn.vimconnector):
         payload_req = '{"network":{"name": "' + net_name + '","shared":true,"type": "' + net_type + '"}}'
         try:
             vim_response = requests.post(self.url+'/networks', headers = self.headers_req, data=payload_req)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             self.logger.error( "new_external_network Exception: ", e.args)
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print vim_response
@@ -1249,7 +1286,7 @@ class vimconnector(vimconn.vimconnector):
             url= self.url
         try:
             vim_response = requests.put(url +'/ports/'+port_id, headers = self.headers_req, data=payload_req)
-        except requests.exceptions.RequestException, e:
+        except requests.exceptions.RequestException as e:
             print "connect_port_network Exception: ", e.args
             return -vimconn.HTTP_Not_Found, str(e.args[0])
         print vim_response