blob: 1d95425724517342c3c53a6a5f06b3046948dd41 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5# This file is part of openmano
6# All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License. You may obtain
10# a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
21# contact with: nfvlabs@tid.es
22##
23
24'''
25NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
26'''
27__author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28__date__ ="$16-sep-2014 22:05:01$"
29
30import imp
31#import json
32import yaml
tierno42fcc3b2016-07-06 17:20:40 +020033import utils
tiernof97fd272016-07-11 14:32:37 +020034from db_base import HTTP_Unauthorized, HTTP_Bad_Request, HTTP_Internal_Server_Error, HTTP_Not_Found,\
tierno7edb6752016-03-21 17:37:52 +010035 HTTP_Conflict, HTTP_Method_Not_Allowed
36import console_proxy_thread as cli
tiernoae4a8d12016-07-08 12:30:39 +020037import vimconn
38import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020039import collections
tiernof97fd272016-07-11 14:32:37 +020040from db_base import db_base_Exception
tierno7edb6752016-03-21 17:37:52 +010041
42global global_config
43global vimconn_imported
tierno73ad9e42016-09-12 18:11:11 +020044global logger
tierno7edb6752016-03-21 17:37:52 +010045
tiernoae4a8d12016-07-08 12:30:39 +020046
tierno7edb6752016-03-21 17:37:52 +010047vimconn_imported={} #dictionary with VIM type as key, loaded module as value
tierno73ad9e42016-09-12 18:11:11 +020048logger = logging.getLogger('openmano.nfvo')
tierno7edb6752016-03-21 17:37:52 +010049
50class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020051 def __init__(self, message, http_code):
52 self.http_code = http_code
53 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010054
55
56def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
57 '''Obtain flavorList
58 return result, content:
59 <0, error_text upon error
60 nb_records, flavor_list on success
61 '''
62 WHERE_dict={}
63 WHERE_dict['vnf_id'] = vnf_id
64 if nfvo_tenant is not None:
65 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
66
67 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
68 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +020069 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
70 #print "get_flavor_list result:", result
71 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +010072 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +020073 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +010074 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +020075 return flavorList
tierno7edb6752016-03-21 17:37:52 +010076
77def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
78 '''Obtain imageList
79 return result, content:
80 <0, error_text upon error
81 nb_records, flavor_list on success
82 '''
83 WHERE_dict={}
84 WHERE_dict['vnf_id'] = vnf_id
85 if nfvo_tenant is not None:
86 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
87
88 #result, content = mydb.get_table(FROM='vms join vnfs on vms-vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +020089 images = mydb.get_rows(FROM='vms join images on vms.image_id=images.uuid',SELECT=('image_id',),WHERE=WHERE_dict )
tierno7edb6752016-03-21 17:37:52 +010090 imageList=[]
tiernof97fd272016-07-11 14:32:37 +020091 for image in images:
tierno7edb6752016-03-21 17:37:52 +010092 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +020093 return imageList
tierno7edb6752016-03-21 17:37:52 +010094
tiernoa2793912016-10-04 08:15:08 +000095def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
96 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None):
tierno7edb6752016-03-21 17:37:52 +010097 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tiernobe41e222016-09-02 15:16:13 +020098 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +010099 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200100 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100101 '''
102 WHERE_dict={}
103 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
104 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000105 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100106 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
107 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000108 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
109 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100110 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
111 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
112 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
113 'user','passwd')
114 else:
115 from_ = 'datacenters as d'
116 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200117 try:
118 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
119 vim_dict={}
120 for vim in vims:
121 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id')}
122 if vim["config"] != None:
123 extra.update(yaml.load(vim["config"]))
124 if vim["type"] not in vimconn_imported:
125 module_info=None
126 try:
127 module = "vimconn_" + vim["type"]
128 module_info = imp.find_module(module)
129 vim_conn = imp.load_module(vim["type"], *module_info)
130 vimconn_imported[vim["type"]] = vim_conn
131 except (IOError, ImportError) as e:
132 if module_info and module_info[0]:
133 file.close(module_info[0])
134 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
135 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
136
tierno7edb6752016-03-21 17:37:52 +0100137 try:
tiernof97fd272016-07-11 14:32:37 +0200138 #if not tenant:
139 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
140 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
141 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tierno3ae39742016-09-07 12:17:51 +0200142 tenant_id=vim.get('vim_tenant_id',vim_tenant), tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tiernof97fd272016-07-11 14:32:37 +0200143 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200144 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernof97fd272016-07-11 14:32:37 +0200145 config=extra
146 )
147 except Exception as e:
148 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
149 return vim_dict
150 except db_base_Exception as e:
151 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
152
tierno7edb6752016-03-21 17:37:52 +0100153def rollback(mydb, vims, rollback_list):
154 undeleted_items=[]
155 #delete things by reverse order
156 for i in range(len(rollback_list)-1, -1, -1):
157 item = rollback_list[i]
158 if item["where"]=="vim":
159 if item["vim_id"] not in vims:
160 continue
161 vim=vims[ item["vim_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200162 try:
163 if item["what"]=="image":
164 vim.delete_image(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200165 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200166 elif item["what"]=="flavor":
167 vim.delete_flavor(item["uuid"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200168 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200169 elif item["what"]=="network":
170 vim.delete_network(item["uuid"])
171 elif item["what"]=="vm":
172 vim.delete_vminstance(item["uuid"])
173 except vimconn.vimconnException as e:
174 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
175 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200176 except db_base_Exception as e:
177 logger.error("Error in rollback. Not possible to delete %s '%s' from DB.datacenters Message: %s", item['what'], item["uuid"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200178
tierno7edb6752016-03-21 17:37:52 +0100179 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200180 try:
181 if item["what"]=="image":
182 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
183 elif item["what"]=="flavor":
184 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
185 except db_base_Exception as e:
186 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
187 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno7edb6752016-03-21 17:37:52 +0100188 if len(undeleted_items)==0:
189 return True," Rollback successful."
190 else:
191 return False," Rollback fails to delete: " + str(undeleted_items)
192
193def check_vnf_descriptor(vnf_descriptor):
194 global global_config
195 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
196 vnfc_interfaces={}
197 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
198 name_list = []
199 #dataplane interfaces
200 for numa in vnfc.get("numas",() ):
201 for interface in numa.get("interfaces",()):
202 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200203 raise NfvoException("Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC"\
204 .format(vnfc["name"], interface["name"]),
205 HTTP_Bad_Request)
206 name_list.append( interface["name"] )
tierno7edb6752016-03-21 17:37:52 +0100207 #bridge interfaces
208 for interface in vnfc.get("bridge-ifaces",() ):
209 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200210 raise NfvoException("Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC"\
211 .format(vnfc["name"], interface["name"]),
212 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100213 name_list.append( interface["name"] )
214 vnfc_interfaces[ vnfc["name"] ] = name_list
215
216 #check if the info in external_connections matches with the one in the vnfcs
217 name_list=[]
218 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
219 if external_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200220 raise NfvoException("Error at vnf:external-connections:name, value '{}' already used as an external-connection"\
221 .format(external_connection["name"]),
222 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100223 name_list.append(external_connection["name"])
224 if external_connection["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200225 raise NfvoException("Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC"\
226 .format(external_connection["name"], external_connection["VNFC"]),
227 HTTP_Bad_Request)
228
tierno7edb6752016-03-21 17:37:52 +0100229 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200230 raise NfvoException("Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC"\
231 .format(external_connection["name"], external_connection["local_iface_name"]),
232 HTTP_Bad_Request )
tierno7edb6752016-03-21 17:37:52 +0100233
234 #check if the info in internal_connections matches with the one in the vnfcs
235 name_list=[]
236 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
237 if internal_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200238 raise NfvoException("Error at vnf:internal-connections:name, value '%s' already used as an internal-connection"\
239 .format(internal_connection["name"]),
240 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100241 name_list.append(internal_connection["name"])
242 #We should check that internal-connections of type "ptp" have only 2 elements
243 if len(internal_connection["elements"])>2 and internal_connection["type"] == "ptp":
tiernof97fd272016-07-11 14:32:37 +0200244 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements, size must be 2 for a type:'ptp'"\
245 .format(internal_connection["name"]),
246 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100247 for port in internal_connection["elements"]:
248 if port["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200249 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC"\
250 .format(internal_connection["name"], port["VNFC"]),
251 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100252 if port["local_iface_name"] not in vnfc_interfaces[ port["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200253 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC"\
254 .format(internal_connection["name"], port["local_iface_name"]),
255 HTTP_Bad_Request)
256 return -HTTP_Bad_Request,
tierno7edb6752016-03-21 17:37:52 +0100257
tierno5e91eb82016-10-04 09:39:07 +0000258def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
tierno7edb6752016-03-21 17:37:52 +0100259 #look if image exist
260 if only_create_at_vim:
261 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000262 if return_on_error == None:
263 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100264 else:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200265 if image_dict['location'] is not None:
266 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
267 else:
268 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200269 if len(images)>=1:
270 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100271 else:
272 #create image
273 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200274 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
275 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100276 }
tiernof97fd272016-07-11 14:32:37 +0200277 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
278 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100279 #create image at every vim
280 for vim_id,vim in vims.iteritems():
281 image_created="false"
282 #look at database
tiernof97fd272016-07-11 14:32:37 +0200283 image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100284 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200285 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200286 if image_dict['location'] is not None:
287 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
288 else:
289 filter_dict={}
290 filter_dict['name']=image_dict['universal_name']
291 filter_dict['checksum']=image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000292 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200293 vim_images = vim.get_image_list(filter_dict)
294 if len(vim_images) > 1:
295 raise NfvoException("More than one candidate VIM image found for filter: " + str(filter_dict), HTTP_Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000296 elif len(vim_images) == 0:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200297 raise NfvoException("Image not found at VIM with filter: '%s'", str(filter_dict))
298 else:
299 image_vim_id = vim_images[0].id
300
tiernoae4a8d12016-07-08 12:30:39 +0200301 except vimconn.vimconnNotFoundException as e:
tierno7edb6752016-03-21 17:37:52 +0100302 #Create the image in VIM
tiernoae4a8d12016-07-08 12:30:39 +0200303 try:
304 image_vim_id = vim.new_image(image_dict)
tierno7edb6752016-03-21 17:37:52 +0100305 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
306 image_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200307 except vimconn.vimconnException as e:
308 if return_on_error:
309 logger.error("Error creating image at VIM: %s", str(e))
tiernof97fd272016-07-11 14:32:37 +0200310 raise
tierno5e91eb82016-10-04 09:39:07 +0000311 image_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200312 logger.warn("Error creating image at VIM: %s", str(e))
313 continue
314 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000315 if return_on_error:
316 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
317 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200318 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000319 image_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200320 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200321 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200322 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100323 #add new vim_id at datacenters_images
324 mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created})
325 elif image_db[0]["vim_id"]!=image_vim_id:
326 #modify existing vim_id at datacenters_images
327 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
328
tiernof97fd272016-07-11 14:32:37 +0200329 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100330
tierno5e91eb82016-10-04 09:39:07 +0000331def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
tierno7edb6752016-03-21 17:37:52 +0100332 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
333 'ram':flavor_dict.get('ram'),
334 'vcpus':flavor_dict.get('vcpus'),
335 }
336 if 'extended' in flavor_dict and flavor_dict['extended']==None:
337 del flavor_dict['extended']
338 if 'extended' in flavor_dict:
339 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
340
341 #look if flavor exist
342 if only_create_at_vim:
343 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000344 if return_on_error == None:
345 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100346 else:
tiernof97fd272016-07-11 14:32:37 +0200347 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
348 if len(flavors)>=1:
349 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100350 else:
351 #create flavor
352 #create one by one the images of aditional disks
353 dev_image_list=[] #list of images
354 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
355 dev_nb=0
356 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200357 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100358 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200359 image_dict={}
360 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
361 image_dict['universal_name']=device.get('image name')
362 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
363 image_dict['location']=device.get('image')
364 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100365 image_metadata_dict = device.get('image metadata', None)
366 image_metadata_str = None
367 if image_metadata_dict != None:
368 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
369 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200370 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
371 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100372 dev_image_list.append(image_id)
373 dev_nb += 1
374 temp_flavor_dict['name'] = flavor_dict['name']
375 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200376 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
377 flavor_mano_id= content
378 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100379 #create flavor at every vim
380 if 'uuid' in flavor_dict:
381 del flavor_dict['uuid']
382 flavor_vim_id=None
383 for vim_id,vim in vims.items():
384 flavor_created="false"
385 #look at database
tiernof97fd272016-07-11 14:32:37 +0200386 flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100387 #look at VIM if this flavor exist SKIPPED
388 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
389 #if res_vim < 0:
390 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
391 # continue
392 #elif res_vim==0:
393
394 #Create the flavor in VIM
395 #Translate images at devices from MANO id to VIM id
tierno7edb6752016-03-21 17:37:52 +0100396 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
397 #make a copy of original devices
398 devices_original=[]
399 for device in flavor_dict["extended"].get("devices",[]):
400 dev={}
401 dev.update(device)
402 devices_original.append(dev)
403 if 'image' in device:
404 del device['image']
405 if 'image metadata' in device:
406 del device['image metadata']
407 dev_nb=0
408 for index in range(0,len(devices_original)) :
409 device=devices_original[index]
garciadeblasb69fa9f2016-09-28 12:04:10 +0200410 if "image" not in device or "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100411 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200412 image_dict={}
413 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
414 image_dict['universal_name']=device.get('image name')
415 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
416 image_dict['location']=device.get('image')
417 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100418 image_metadata_dict = device.get('image metadata', None)
419 image_metadata_str = None
420 if image_metadata_dict != None:
421 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
422 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200423 image_mano_id=create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error=return_on_error )
tierno7edb6752016-03-21 17:37:52 +0100424 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200425 image_vim_id=create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=True, return_on_error=return_on_error)
tierno7edb6752016-03-21 17:37:52 +0100426 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
427 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200428 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100429 #check that this vim_id exist in VIM, if not create
430 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200431 try:
432 vim.get_flavor(flavor_vim_id)
433 continue #flavor exist
434 except vimconn.vimconnException:
435 pass
tierno7edb6752016-03-21 17:37:52 +0100436 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200437 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
438 try:
439 flavor_vim_id = vim.new_flavor(flavor_dict)
tierno7edb6752016-03-21 17:37:52 +0100440 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
441 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200442 except vimconn.vimconnException as e:
443 if return_on_error:
444 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200445 raise
tiernoae4a8d12016-07-08 12:30:39 +0200446 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000447 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200448 continue
tierno7edb6752016-03-21 17:37:52 +0100449 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200450 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100451 #add new vim_id at datacenters_flavors
452 mydb.new_row('datacenters_flavors', {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id, 'created':flavor_created})
453 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
454 #modify existing vim_id at datacenters_flavors
455 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
456
tiernof97fd272016-07-11 14:32:37 +0200457 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100458
459def new_vnf(mydb, tenant_id, vnf_descriptor):
460 global global_config
461
462 # Step 1. Check the VNF descriptor
tiernof97fd272016-07-11 14:32:37 +0200463 check_vnf_descriptor(vnf_descriptor)
tierno7edb6752016-03-21 17:37:52 +0100464 # Step 2. Check tenant exist
465 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200466 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100467 if "tenant_id" in vnf_descriptor["vnf"]:
468 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200469 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
470 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100471 else:
472 vnf_descriptor['vnf']['tenant_id'] = tenant_id
473 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200474 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100475 else:
476 vims={}
477
478 # Step 4. Review the descriptor and add missing fields
479 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +0200480 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +0100481 vnf_name = vnf_descriptor['vnf']['name']
482 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
483 if "physical" in vnf_descriptor['vnf']:
484 del vnf_descriptor['vnf']['physical']
485 #print vnf_descriptor
486 # Step 5. Check internal connections
487 # TODO: to be moved to step 1????
488 internal_connections=vnf_descriptor['vnf'].get('internal_connections',[])
489 for ic in internal_connections:
490 if len(ic['elements'])>2 and ic['type']=='ptp':
tiernof97fd272016-07-11 14:32:37 +0200491 raise NfvoException("Mismatch 'type':'ptp' with {} elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'data'".format(len(ic), ic['name']),
492 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100493 elif len(ic['elements'])==2 and ic['type']=='data':
tiernof97fd272016-07-11 14:32:37 +0200494 raise NfvoException("Mismatch 'type':'data' with 2 elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'ptp'".format(ic['name']),
495 HTTP_Bad_Request)
496
tierno7edb6752016-03-21 17:37:52 +0100497 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200498 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
499 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno7edb6752016-03-21 17:37:52 +0100500
501 #For each VNFC, we add it to the VNFCDict and we create a flavor.
502 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
503 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +0100504 try:
tiernof97fd272016-07-11 14:32:37 +0200505 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100506 for vnfc in vnf_descriptor['vnf']['VNFC']:
507 VNFCitem={}
508 VNFCitem["name"] = vnfc['name']
509 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
510
tiernof97fd272016-07-11 14:32:37 +0200511 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno7edb6752016-03-21 17:37:52 +0100512
513 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200514 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
tierno7edb6752016-03-21 17:37:52 +0100515 myflavorDict["description"] = VNFCitem["description"]
516 myflavorDict["ram"] = vnfc.get("ram", 0)
517 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
518 myflavorDict["disk"] = vnfc.get("disk", 1)
519 myflavorDict["extended"] = {}
520
521 devices = vnfc.get("devices")
522 if devices != None:
523 myflavorDict["extended"]["devices"] = devices
524
525 # TODO:
526 # Mapping from processor models to rankings should be available somehow in the NFVO. They could be taken from VIM or directly from a new database table
527 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
528
529 # Previous code has been commented
530 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
531 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
532 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
533 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
534 #else:
535 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
536 # if result2:
537 # print "Error creating flavor: unknown processor model. Rollback successful."
538 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
539 # else:
540 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
541 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
542
543 if 'numas' in vnfc and len(vnfc['numas'])>0:
544 myflavorDict['extended']['numas'] = vnfc['numas']
545
546 #print myflavorDict
547
548 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200549 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +0100550
tiernof97fd272016-07-11 14:32:37 +0200551 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100552 VNFCitem["flavor_id"] = flavor_id
553 VNFCDict[vnfc['name']] = VNFCitem
554
tiernof97fd272016-07-11 14:32:37 +0200555 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100556 # Step 6.3 New images are created in the VIM
557 #For each VNFC, we must create the appropriate image.
558 #This "for" loop might be integrated with the previous one
559 #In case this integration is made, the VNFCDict might become a VNFClist.
560 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +0200561 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200562 image_dict={}
563 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
564 image_dict['universal_name']=vnfc.get('image name')
565 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
566 image_dict['location']=vnfc.get('VNFC image')
567 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100568 image_metadata_dict = vnfc.get('image metadata', None)
569 image_metadata_str = None
570 if image_metadata_dict is not None:
571 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
572 image_dict['metadata']=image_metadata_str
573 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +0200574 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
575 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +0100576 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200577 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno7edb6752016-03-21 17:37:52 +0100578
tiernof97fd272016-07-11 14:32:37 +0200579
580 # Step 7. Storing the VNF descriptor in the repository
581 if "descriptor" not in vnf_descriptor["vnf"]:
582 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +0100583
tiernof97fd272016-07-11 14:32:37 +0200584 # Step 8. Adding the VNF to the NFVO DB
585 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
586 return vnf_id
587 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +0100588 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +0200589 if isinstance(e, db_base_Exception):
590 error_text = "Exception at database"
591 elif isinstance(e, KeyError):
592 error_text = "KeyError exception "
593 e.http_code = HTTP_Internal_Server_Error
594 else:
595 error_text = "Exception at VIM"
596 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
597 #logger.error("start_scenario %s", error_text)
598 raise NfvoException(error_text, e.http_code)
599
garciadeblas9f8456e2016-09-05 05:02:59 +0200600def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
601 global global_config
602
603 # Step 1. Check the VNF descriptor
604 check_vnf_descriptor(vnf_descriptor)
605 # Step 2. Check tenant exist
606 if tenant_id != "any":
607 check_tenant(mydb, tenant_id)
608 if "tenant_id" in vnf_descriptor["vnf"]:
609 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
610 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
611 HTTP_Unauthorized)
612 else:
613 vnf_descriptor['vnf']['tenant_id'] = tenant_id
614 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
615 vims = get_vim(mydb, tenant_id)
616 else:
617 vims={}
618
619 # Step 4. Review the descriptor and add missing fields
620 #print vnf_descriptor
621 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
622 vnf_name = vnf_descriptor['vnf']['name']
623 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
624 if "physical" in vnf_descriptor['vnf']:
625 del vnf_descriptor['vnf']['physical']
626 #print vnf_descriptor
627 # Step 5. Check internal connections
628 # TODO: to be moved to step 1????
629 internal_connections=vnf_descriptor['vnf'].get('internal_connections',[])
630 for ic in internal_connections:
631 if len(ic['elements'])>2 and ic['type']=='e-line':
632 raise NfvoException("Mismatch 'type':'e-line' with {} elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'e-lan'".format(len(ic), ic['name']),
633 HTTP_Bad_Request)
634
635 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
636 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
637 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
638
639 #For each VNFC, we add it to the VNFCDict and we create a flavor.
640 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
641 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
642 try:
643 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
644 for vnfc in vnf_descriptor['vnf']['VNFC']:
645 VNFCitem={}
646 VNFCitem["name"] = vnfc['name']
647 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
648
649 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
650
651 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200652 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
garciadeblas9f8456e2016-09-05 05:02:59 +0200653 myflavorDict["description"] = VNFCitem["description"]
654 myflavorDict["ram"] = vnfc.get("ram", 0)
655 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
656 myflavorDict["disk"] = vnfc.get("disk", 1)
657 myflavorDict["extended"] = {}
658
659 devices = vnfc.get("devices")
660 if devices != None:
661 myflavorDict["extended"]["devices"] = devices
662
663 # TODO:
664 # Mapping from processor models to rankings should be available somehow in the NFVO. They could be taken from VIM or directly from a new database table
665 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
666
667 # Previous code has been commented
668 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
669 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
670 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
671 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
672 #else:
673 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
674 # if result2:
675 # print "Error creating flavor: unknown processor model. Rollback successful."
676 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
677 # else:
678 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
679 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
680
681 if 'numas' in vnfc and len(vnfc['numas'])>0:
682 myflavorDict['extended']['numas'] = vnfc['numas']
683
684 #print myflavorDict
685
686 # Step 6.2 New flavors are created in the VIM
687 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
688
689 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
690 VNFCitem["flavor_id"] = flavor_id
691 VNFCDict[vnfc['name']] = VNFCitem
692
693 logger.debug("Creating new images in the VIM for each VNFC")
694 # Step 6.3 New images are created in the VIM
695 #For each VNFC, we must create the appropriate image.
696 #This "for" loop might be integrated with the previous one
697 #In case this integration is made, the VNFCDict might become a VNFClist.
698 for vnfc in vnf_descriptor['vnf']['VNFC']:
699 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200700 image_dict={}
701 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
702 image_dict['universal_name']=vnfc.get('image name')
703 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
704 image_dict['location']=vnfc.get('VNFC image')
705 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +0200706 image_metadata_dict = vnfc.get('image metadata', None)
707 image_metadata_str = None
708 if image_metadata_dict is not None:
709 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
710 image_dict['metadata']=image_metadata_str
711 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
712 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
713 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
714 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200715 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
garciadeblas9f8456e2016-09-05 05:02:59 +0200716
717
718 # Step 7. Storing the VNF descriptor in the repository
719 if "descriptor" not in vnf_descriptor["vnf"]:
720 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
721
722 # Step 8. Adding the VNF to the NFVO DB
723 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
724 return vnf_id
725 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
726 _, message = rollback(mydb, vims, rollback_list)
727 if isinstance(e, db_base_Exception):
728 error_text = "Exception at database"
729 elif isinstance(e, KeyError):
730 error_text = "KeyError exception "
731 e.http_code = HTTP_Internal_Server_Error
732 else:
733 error_text = "Exception at VIM"
734 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
735 #logger.error("start_scenario %s", error_text)
736 raise NfvoException(error_text, e.http_code)
737
tierno7edb6752016-03-21 17:37:52 +0100738def get_vnf_id(mydb, tenant_id, vnf_id):
739 #check valid tenant_id
tiernof97fd272016-07-11 14:32:37 +0200740 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100741 #obtain data
742 where_or = {}
743 if tenant_id != "any":
744 where_or["tenant_id"] = tenant_id
745 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200746 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
tierno7edb6752016-03-21 17:37:52 +0100747
tiernof97fd272016-07-11 14:32:37 +0200748 vnf_id=vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100749 filter_keys = ('uuid','name','description','public', "tenant_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +0200750 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +0100751 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
752 data={'vnf' : filtered_content}
753 #GET VM
tiernof97fd272016-07-11 14:32:37 +0200754 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tierno7edb6752016-03-21 17:37:52 +0100755 SELECT=('vms.uuid as uuid','vms.name as name', 'vms.description as description'),
756 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200757 if len(content)==0:
758 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100759
760 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200761 #TODO: GET all the information from a VNFC and include it in the output.
762
tierno7edb6752016-03-21 17:37:52 +0100763 #GET NET
tiernof97fd272016-07-11 14:32:37 +0200764 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +0100765 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
766 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200767 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200768
769 #GET ip-profile for each net
770 for net in data['vnf']['nets']:
771 ipprofiles = mydb.get_rows(FROM='ip_profiles',
772 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
773 WHERE={'net_id': net["uuid"]} )
774 if len(ipprofiles)==1:
775 net["ip_profile"] = ipprofiles[0]
776 elif len(ipprofiles)>1:
777 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net['uuid']), HTTP_Bad_Request)
778
779
780 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
781
782 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +0200783 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces on vms.uuid=interfaces.vm_id',\
tierno7edb6752016-03-21 17:37:52 +0100784 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
785 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
786 WHERE={'vnfs.uuid': vnf_id},
787 WHERE_NOT={'interfaces.external_name': None} )
788 #print content
tiernof97fd272016-07-11 14:32:37 +0200789 data['vnf']['external-connections'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200790
tiernof97fd272016-07-11 14:32:37 +0200791 return data
tierno7edb6752016-03-21 17:37:52 +0100792
793
794def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
795 # Check tenant exist
796 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200797 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100798 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200799 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100800 else:
801 vims={}
802
803 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
804 where_or = {}
805 if tenant_id != "any":
806 where_or["tenant_id"] = tenant_id
807 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200808 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
809 vnf_id = vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100810
811 # "Getting the list of flavors and tenants of the VNF"
tiernof97fd272016-07-11 14:32:37 +0200812 flavorList = get_flavorlist(mydb, vnf_id)
813 if len(flavorList)==0:
814 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100815
tiernof97fd272016-07-11 14:32:37 +0200816 imageList = get_imagelist(mydb, vnf_id)
817 if len(imageList)==0:
818 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100819
tiernof97fd272016-07-11 14:32:37 +0200820 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
821 if deleted == 0:
822 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100823
824 undeletedItems = []
825 for flavor in flavorList:
826 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +0200827 try:
828 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
829 if len(c) > 0:
830 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
831 continue
832 #flavor not used, must be deleted
833 #delelte at VIM
834 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +0100835 for flavor_vim in c:
836 if flavor_vim["datacenter_id"] not in vims:
837 continue
838 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
839 continue
840 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200841 try:
842 myvim.delete_flavor(flavor_vim["vim_id"])
843 except vimconn.vimconnNotFoundException as e:
844 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
845 except vimconn.vimconnException as e:
846 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
847 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
848 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200849 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
850 mydb.delete_row_by_id('flavors', flavor)
851 except db_base_Exception as e:
852 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +0100853 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +0200854
tierno7edb6752016-03-21 17:37:52 +0100855
856 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +0200857 try:
858 #check if image is used by other vnf
859 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
860 if len(c) > 0:
861 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
862 continue
863 #image not used, must be deleted
864 #delelte at VIM
865 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +0100866 for image_vim in c:
867 if image_vim["datacenter_id"] not in vims:
868 continue
869 if image_vim['created']=='false': #skip this image because not created by openmano
870 continue
871 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200872 try:
873 myvim.delete_image(image_vim["vim_id"])
874 except vimconn.vimconnNotFoundException as e:
875 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
876 except vimconn.vimconnException as e:
877 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
878 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
879 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200880 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
881 mydb.delete_row_by_id('images', image)
882 except db_base_Exception as e:
883 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +0100884 undeletedItems.append("image %s" % image)
885
tiernof97fd272016-07-11 14:32:37 +0200886 return vnf_id + " " + vnf["name"]
887 #if undeletedItems:
888 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +0100889
890def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
891 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
892 if result < 0:
893 return result, vims
894 elif result == 0:
895 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
896 myvim = vims.values()[0]
897 result,servers = myvim.get_hosts_info()
898 if result < 0:
899 return result, servers
900 topology = {'name':myvim['name'] , 'servers': servers}
901 return result, topology
902
903def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +0200904 vims = get_vim(mydb, nfvo_tenant_id)
905 if len(vims) == 0:
906 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
907 elif len(vims)>1:
908 #print "nfvo.datacenter_action() error. Several datacenters found"
909 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +0100910 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +0200911 try:
912 hosts = myvim.get_hosts()
913 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +0100914
tiernof97fd272016-07-11 14:32:37 +0200915 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
916 for host in hosts:
917 server={'name':host['name'], 'vms':[]}
918 for vm in host['instances']:
919 #get internal name and model
920 try:
921 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
922 WHERE={'vim_vm_id':vm['id']} )
923 if len(c) == 0:
924 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
925 continue
926 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
927
928 except db_base_Exception as e:
929 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
930 datacenter['Datacenters'][0]['servers'].append(server)
931 #return -400, "en construccion"
tierno7edb6752016-03-21 17:37:52 +0100932
tiernof97fd272016-07-11 14:32:37 +0200933 #print 'datacenters '+ json.dumps(datacenter, indent=4)
934 return datacenter
935 except vimconn.vimconnException as e:
936 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +0100937
938def new_scenario(mydb, tenant_id, topo):
939
940# result, vims = get_vim(mydb, tenant_id)
941# if result < 0:
942# return result, vims
943#1: parse input
944 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200945 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100946 if "tenant_id" in topo:
947 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200948 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
949 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100950 else:
951 tenant_id=None
952
953#1.1: get VNFs and external_networks (other_nets).
954 vnfs={}
955 other_nets={} #external_networks, bridge_networks and data_networkds
956 nodes = topo['topology']['nodes']
957 for k in nodes.keys():
958 if nodes[k]['type'] == 'VNF':
959 vnfs[k] = nodes[k]
960 vnfs[k]['ifaces'] = {}
961 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
962 other_nets[k] = nodes[k]
963 other_nets[k]['external']=True
964 elif nodes[k]['type'] == 'network':
965 other_nets[k] = nodes[k]
966 other_nets[k]['external']=False
967
968
969#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
970 for name,vnf in vnfs.items():
tiernocea279c2016-07-18 12:36:49 +0200971 where={}
972 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +0100973 error_text = ""
974 error_pos = "'topology':'nodes':'" + name + "'"
975 if 'vnf_id' in vnf:
976 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +0200977 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +0100978 if 'VNF model' in vnf:
979 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +0200980 where['name'] = vnf['VNF model']
981 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +0200982 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
983
tiernocea279c2016-07-18 12:36:49 +0200984 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
985 FROM='vnfs',
986 WHERE=where,
987 WHERE_OR=where_or,
988 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +0200989 if len(vnf_db)==0:
990 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
991 elif len(vnf_db)>1:
992 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +0100993 vnf['uuid']=vnf_db[0]['uuid']
994 vnf['description']=vnf_db[0]['description']
995 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +0200996 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
tierno7edb6752016-03-21 17:37:52 +0100997 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
998 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +0100999 for ext_iface in ext_ifaces:
1000 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1001
1002#1.4 get list of connections
1003 conections = topo['topology']['connections']
1004 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001005 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001006 for k in conections.keys():
1007 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1008 ifaces_list = conections[k]['nodes'].items()
1009 elif type(conections[k]['nodes'])==list: #list with dictionary
1010 ifaces_list=[]
1011 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1012 for k2 in conection_pair_list:
1013 ifaces_list += k2
1014
1015 con_type = conections[k].get("type", "link")
1016 if con_type != "link":
1017 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001018 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001019 other_nets[k] = {'external': False}
1020 if conections[k].get("graph"):
1021 other_nets[k]["graph"] = conections[k]["graph"]
1022 ifaces_list.append( (k, None) )
1023
1024
1025 if con_type == "external_network":
1026 other_nets[k]['external'] = True
1027 if conections[k].get("model"):
1028 other_nets[k]["model"] = conections[k]["model"]
1029 else:
1030 other_nets[k]["model"] = k
1031 if con_type == "dataplane_net" or con_type == "bridge_net":
1032 other_nets[k]["model"] = con_type
1033
tiernoefd80c92016-09-16 14:17:46 +02001034 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001035 conections_list.append(set(ifaces_list)) #from list to set to operate as a set (this conversion removes elements that are repeated in a list)
1036 #print set(ifaces_list)
1037 #check valid VNF and iface names
1038 for iface in ifaces_list:
1039 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001040 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1041 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001042 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001043 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1044 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001045
1046#1.5 unify connections from the pair list to a consolidated list
1047 index=0
1048 while index < len(conections_list):
1049 index2 = index+1
1050 while index2 < len(conections_list):
1051 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1052 conections_list[index] |= conections_list[index2]
1053 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001054 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001055 else:
1056 index2 += 1
1057 conections_list[index] = list(conections_list[index]) # from set to list again
1058 index += 1
1059 #for k in conections_list:
1060 # print k
1061
1062
1063
1064#1.6 Delete non external nets
1065# for k in other_nets.keys():
1066# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1067# for con in conections_list:
1068# delete_indexes=[]
1069# for index in range(0,len(con)):
1070# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1071# for index in delete_indexes:
1072# del con[index]
1073# del other_nets[k]
1074#1.7: Check external_ports are present at database table datacenter_nets
1075 for k,net in other_nets.items():
1076 error_pos = "'topology':'nodes':'" + k + "'"
1077 if net['external']==False:
1078 if 'name' not in net:
1079 net['name']=k
1080 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001081 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001082 if net['model']=='bridge_net':
1083 net['type']='bridge';
1084 elif net['model']=='dataplane_net':
1085 net['type']='data';
1086 else:
tiernof97fd272016-07-11 14:32:37 +02001087 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001088 else: #external
1089#IF we do not want to check that external network exist at datacenter
1090 pass
1091#ELSE
1092# error_text = ""
1093# WHERE_={}
1094# if 'net_id' in net:
1095# error_text += " 'net_id' " + net['net_id']
1096# WHERE_['uuid'] = net['net_id']
1097# if 'model' in net:
1098# error_text += " 'model' " + net['model']
1099# WHERE_['name'] = net['model']
1100# if len(WHERE_) == 0:
1101# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1102# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1103# FROM='datacenter_nets', WHERE=WHERE_ )
1104# if r<0:
1105# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1106# elif r==0:
1107# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1108# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1109# elif r>1:
1110# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1111# return -HTTP_Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
1112# other_nets[k].update(net_db[0])
1113#ENDIF
1114 net_list={}
1115 net_nb=0 #Number of nets
1116 for con in conections_list:
1117 #check if this is connected to a external net
1118 other_net_index=-1
1119 #print
1120 #print "con", con
1121 for index in range(0,len(con)):
1122 #check if this is connected to a external net
1123 for net_key in other_nets.keys():
1124 if con[index][0]==net_key:
1125 if other_net_index>=0:
1126 error_text="There is some interface connected both to net '%s' and net '%s'" % (con[other_net_index][0], net_key)
tiernof97fd272016-07-11 14:32:37 +02001127 #print "nfvo.new_scenario " + error_text
1128 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001129 else:
1130 other_net_index = index
1131 net_target = net_key
1132 break
1133 #print "other_net_index", other_net_index
1134 try:
1135 if other_net_index>=0:
1136 del con[other_net_index]
1137#IF we do not want to check that external network exist at datacenter
1138 if other_nets[net_target]['external'] :
1139 if "name" not in other_nets[net_target]:
1140 other_nets[net_target]['name'] = other_nets[net_target]['model']
1141 if other_nets[net_target]["type"] == "external_network":
1142 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1143 other_nets[net_target]["type"] = "data"
1144 else:
1145 other_nets[net_target]["type"] = "bridge"
1146#ELSE
1147# if other_nets[net_target]['external'] :
1148# type_='data' if len(con)>1 else 'ptp' #an external net is connected to a external port, so it is ptp if only one connection is done to this net
1149# if type_=='data' and other_nets[net_target]['type']=="ptp":
1150# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1151# print "nfvo.new_scenario " + error_text
1152# return -HTTP_Bad_Request, error_text
1153#ENDIF
1154 for iface in con:
1155 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1156 else:
1157 #create a net
1158 net_type_bridge=False
1159 net_type_data=False
1160 net_target = "__-__net"+str(net_nb)
tiernoefd80c92016-09-16 14:17:46 +02001161 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
1162 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno7edb6752016-03-21 17:37:52 +01001163 'external':False}
1164 for iface in con:
1165 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1166 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1167 if iface_type=='mgmt' or iface_type=='bridge':
1168 net_type_bridge = True
1169 else:
1170 net_type_data = True
1171 if net_type_bridge and net_type_data:
1172 error_text = "Error connection interfaces of bridge type with data type. Firs node %s, iface %s" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001173 #print "nfvo.new_scenario " + error_text
1174 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001175 elif net_type_bridge:
1176 type_='bridge'
1177 else:
1178 type_='data' if len(con)>2 else 'ptp'
1179 net_list[net_target]['type'] = type_
1180 net_nb+=1
1181 except Exception:
1182 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001183 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01001184 #raise e
tiernof97fd272016-07-11 14:32:37 +02001185 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001186
1187#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
1188 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02001189 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01001190 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
1191 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02001192 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01001193 add_mgmt_net = False
1194 for vnf in vnfs.values():
1195 for iface in vnf['ifaces'].values():
1196 if iface['type']=='mgmt' and 'net_key' not in iface:
1197 #iface not connected
1198 iface['net_key'] = 'mgmt'
1199 add_mgmt_net = True
1200 if add_mgmt_net and 'mgmt' not in net_list:
1201 net_list['mgmt']=mgmt_net[0]
1202 net_list['mgmt']['external']=True
1203 net_list['mgmt']['graph']={'visible':False}
1204
1205 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001206 #print
1207 #print 'net_list', net_list
1208 #print
1209 #print 'vnfs', vnfs
1210 #print
tierno7edb6752016-03-21 17:37:52 +01001211
1212#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001213 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001214 'tenant_id':tenant_id, 'name':topo['name'],
1215 'description':topo.get('description',topo['name']),
1216 'public': topo.get('public', False)
1217 })
tierno7edb6752016-03-21 17:37:52 +01001218
tiernof97fd272016-07-11 14:32:37 +02001219 return c
tierno7edb6752016-03-21 17:37:52 +01001220
tierno392f2852016-05-13 12:28:55 +02001221def new_scenario_v02(mydb, tenant_id, scenario_dict):
1222 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001223 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001224 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001225 if "tenant_id" in scenario:
1226 if scenario["tenant_id"] != tenant_id:
1227 print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001228 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1229 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001230 else:
1231 tenant_id=None
1232
1233#1: Check that VNF are present at database table vnfs and update content into scenario dict
1234 for name,vnf in scenario["vnfs"].iteritems():
tiernocea279c2016-07-18 12:36:49 +02001235 where={}
1236 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001237 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001238 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01001239 if 'vnf_id' in vnf:
1240 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001241 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001242 if 'vnf_name' in vnf:
1243 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001244 where['name'] = vnf['vnf_name']
1245 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001246 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tiernocea279c2016-07-18 12:36:49 +02001247 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1248 FROM='vnfs',
1249 WHERE=where,
1250 WHERE_OR=where_or,
1251 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001252 if len(vnf_db)==0:
1253 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1254 elif len(vnf_db)>1:
1255 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001256 vnf['uuid']=vnf_db[0]['uuid']
1257 vnf['description']=vnf_db[0]['description']
1258 vnf['ifaces'] = {}
1259 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +02001260 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
tierno7edb6752016-03-21 17:37:52 +01001261 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1262 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001263 for ext_iface in ext_ifaces:
1264 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1265
1266#2: Insert net_key at every vnf interface
1267 for net_name,net in scenario["networks"].iteritems():
1268 net_type_bridge=False
1269 net_type_data=False
1270 for iface_dict in net["interfaces"]:
1271 for vnf,iface in iface_dict.iteritems():
1272 if vnf not in scenario["vnfs"]:
1273 error_text = "Error at 'networks':'%s':'interfaces' VNF '%s' not match any VNF at 'vnfs'" % (net_name, vnf)
tiernof97fd272016-07-11 14:32:37 +02001274 #print "nfvo.new_scenario_v02 " + error_text
1275 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001276 if iface not in scenario["vnfs"][vnf]['ifaces']:
1277 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface not match any VNF interface" % (net_name, iface)
tiernof97fd272016-07-11 14:32:37 +02001278 #print "nfvo.new_scenario_v02 " + error_text
1279 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001280 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
1281 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface already connected at network '%s'" \
1282 % (net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
tiernof97fd272016-07-11 14:32:37 +02001283 #print "nfvo.new_scenario_v02 " + error_text
1284 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001285 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
1286 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
1287 if iface_type=='mgmt' or iface_type=='bridge':
1288 net_type_bridge = True
1289 else:
1290 net_type_data = True
1291 if net_type_bridge and net_type_data:
1292 error_text = "Error connection interfaces of bridge type and data type at 'networks':'%s':'interfaces'" % (net_name)
tiernof97fd272016-07-11 14:32:37 +02001293 #print "nfvo.new_scenario " + error_text
1294 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001295 elif net_type_bridge:
1296 type_='bridge'
1297 else:
1298 type_='data' if len(net["interfaces"])>2 else 'ptp'
1299 net['type'] = type_
1300 net['name'] = net_name
1301 net['external'] = net.get('external', False)
1302
1303#3: insert at database
1304 scenario["nets"] = scenario["networks"]
1305 scenario['tenant_id'] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001306 scenario_id = mydb.new_scenario( scenario)
1307 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01001308
1309def edit_scenario(mydb, tenant_id, scenario_id, data):
1310 data["uuid"] = scenario_id
1311 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001312 c = mydb.edit_scenario( data )
1313 return c
tierno7edb6752016-03-21 17:37:52 +01001314
1315def start_scenario(mydb, tenant_id, scenario_id, instance_scenario_name, instance_scenario_description, datacenter=None,vim_tenant=None, startvms=True):
tiernoae4a8d12016-07-08 12:30:39 +02001316 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00001317 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
1318 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02001319 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001320 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00001321
tierno7edb6752016-03-21 17:37:52 +01001322 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001323 try:
1324 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tiernof97fd272016-07-11 14:32:37 +02001325 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00001326 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02001327 scenarioDict['datacenter_id'] = datacenter_id
1328 #print '================scenarioDict======================='
1329 #print json.dumps(scenarioDict, indent=4)
1330 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno7edb6752016-03-21 17:37:52 +01001331
tiernoae4a8d12016-07-08 12:30:39 +02001332 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
1333 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001334
tiernoae4a8d12016-07-08 12:30:39 +02001335 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1336 auxNetDict['scenario'] = {}
1337
1338 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
1339 for sce_net in scenarioDict['nets']:
1340 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno7edb6752016-03-21 17:37:52 +01001341
tiernoae4a8d12016-07-08 12:30:39 +02001342 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01001343 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02001344 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01001345 myNetDict = {}
1346 myNetDict["name"] = myNetName
1347 myNetDict["type"] = myNetType
1348 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001349 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01001350 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02001351 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001352 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02001353 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02001354 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001355 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
1356 sce_net['vim_id'] = network_id
1357 auxNetDict['scenario'][sce_net['uuid']] = network_id
1358 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001359 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001360 else:
1361 if sce_net['vim_id'] == None:
1362 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
1363 _, message = rollback(mydb, vims, rollbackList)
1364 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02001365 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02001366 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
1367 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno7edb6752016-03-21 17:37:52 +01001368
tiernoae4a8d12016-07-08 12:30:39 +02001369 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
1370 #For each vnf net, we create it and we add it to instanceNetlist.
1371 for sce_vnf in scenarioDict['vnfs']:
1372 for net in sce_vnf['nets']:
1373 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
1374
1375 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
1376 myNetName = myNetName[0:255] #limit length
1377 myNetType = net['type']
1378 myNetDict = {}
1379 myNetDict["name"] = myNetName
1380 myNetDict["type"] = myNetType
1381 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001382 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02001383 #print myNetDict
1384 #TODO:
1385 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02001386 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001387 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
1388 net['vim_id'] = network_id
1389 if sce_vnf['uuid'] not in auxNetDict:
1390 auxNetDict[sce_vnf['uuid']] = {}
1391 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1392 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001393 net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001394
1395 #print "auxNetDict:"
1396 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
1397
1398 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
1399 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
1400 i = 0
1401 for sce_vnf in scenarioDict['vnfs']:
1402 for vm in sce_vnf['vms']:
1403 i += 1
1404 myVMDict = {}
1405 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
1406 myVMDict['name'] = "%s.%s.%d" % (instance_scenario_name,sce_vnf['name'],i)
1407 #myVMDict['description'] = vm['description']
1408 myVMDict['description'] = myVMDict['name'][0:99]
1409 if not startvms:
1410 myVMDict['start'] = "no"
1411 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1412 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
1413
1414 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001415 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
1416 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001417 vm['vim_image_id'] = image_id
1418
1419 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001420 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001421 if flavor_dict['extended']!=None:
1422 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tiernof97fd272016-07-11 14:32:37 +02001423 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001424 vm['vim_flavor_id'] = flavor_id
1425
1426
1427 myVMDict['imageRef'] = vm['vim_image_id']
1428 myVMDict['flavorRef'] = vm['vim_flavor_id']
1429 myVMDict['networks'] = []
1430 for iface in vm['interfaces']:
1431 netDict = {}
1432 if iface['type']=="data":
1433 netDict['type'] = iface['model']
1434 elif "model" in iface and iface["model"]!=None:
1435 netDict['model']=iface['model']
1436 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1437 #discover type of interface looking at flavor
1438 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1439 for flavor_iface in numa.get('interfaces',[]):
1440 if flavor_iface.get('name') == iface['internal_name']:
1441 if flavor_iface['dedicated'] == 'yes':
1442 netDict['type']="PF" #passthrough
1443 elif flavor_iface['dedicated'] == 'no':
1444 netDict['type']="VF" #siov
1445 elif flavor_iface['dedicated'] == 'yes:sriov':
1446 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1447 netDict["mac_address"] = flavor_iface.get("mac_address")
1448 break;
1449 netDict["use"]=iface['type']
1450 if netDict["use"]=="data" and not netDict.get("type"):
1451 #print "netDict", netDict
1452 #print "iface", iface
1453 e_text = "Cannot determine the interface type PF or VF of VNF '%s' VM '%s' iface '%s'" %(sce_vnf['name'], vm['name'], iface['internal_name'])
1454 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02001455 raise NfvoException(e_text + "After database migration some information is not available. \
1456 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02001457 else:
tiernof97fd272016-07-11 14:32:37 +02001458 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02001459 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1460 netDict["type"]="virtual"
1461 if "vpci" in iface and iface["vpci"] is not None:
1462 netDict['vpci'] = iface['vpci']
1463 if "mac" in iface and iface["mac"] is not None:
1464 netDict['mac_address'] = iface['mac']
1465 netDict['name'] = iface['internal_name']
1466 if iface['net_id'] is None:
1467 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001468 #print iface
1469 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02001470 if vnf_iface['interface_id']==iface['uuid']:
1471 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
1472 break
1473 else:
1474 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1475 #skip bridge ifaces not connected to any net
1476 #if 'net_id' not in netDict or netDict['net_id']==None:
1477 # continue
1478 myVMDict['networks'].append(netDict)
1479 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1480 #print myVMDict['name']
1481 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1482 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1483 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1484 vm_id = myvim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
1485 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'])
1486 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
1487 vm['vim_id'] = vm_id
1488 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1489 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1490 for net in myVMDict['networks']:
1491 if "vim_id" in net:
1492 for iface in vm['interfaces']:
1493 if net["name"]==iface["internal_name"]:
1494 iface["vim_id"]=net["vim_id"]
1495 break
1496
1497 logger.debug("start scenario Deployment done")
1498 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
1499 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001500 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
1501 return mydb.get_instance_scenario(instance_id)
1502
1503 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001504 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001505 if isinstance(e, db_base_Exception):
1506 error_text = "Exception at database"
1507 else:
1508 error_text = "Exception at VIM"
1509 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1510 #logger.error("start_scenario %s", error_text)
1511 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001512
tiernoa4e1a6e2016-08-31 14:19:40 +02001513def unify_cloud_config(cloud_config):
1514 index_to_delete = []
1515 users = cloud_config.get("users", [])
1516 for index0 in range(0,len(users)):
1517 if index0 in index_to_delete:
1518 continue
1519 for index1 in range(index0+1,len(users)):
1520 if index1 in index_to_delete:
1521 continue
1522 if users[index0]["name"] == users[index1]["name"]:
1523 index_to_delete.append(index1)
1524 for key in users[index1].get("key-pairs",()):
1525 if "key-pairs" not in users[index0]:
1526 users[index0]["key-pairs"] = [key]
1527 elif key not in users[index0]["key-pairs"]:
1528 users[index0]["key-pairs"].append(key)
1529 index_to_delete.sort(reverse=True)
1530 for index in index_to_delete:
1531 del users[index]
1532
tiernoa2793912016-10-04 08:15:08 +00001533def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02001534 datacenter_id = None
1535 datacenter_name = None
1536 if datacenter_id_name:
1537 if utils.check_valid_uuid(datacenter_id_name):
1538 datacenter_id = datacenter_id_name
1539 else:
1540 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00001541 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02001542 if len(vims) == 0:
1543 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1544 elif len(vims)>1:
1545 #print "nfvo.datacenter_action() error. Several datacenters found"
1546 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1547 return vims.keys()[0], vims.values()[0]
1548
garciadeblas9f8456e2016-09-05 05:02:59 +02001549def new_scenario_v03(mydb, tenant_id, scenario_dict):
1550 scenario = scenario_dict["scenario"]
1551 if tenant_id != "any":
1552 check_tenant(mydb, tenant_id)
1553 if "tenant_id" in scenario:
1554 if scenario["tenant_id"] != tenant_id:
1555 logger("Tenant '%s' not found", tenant_id)
1556 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1557 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
1558 else:
1559 tenant_id=None
1560
1561#1: Check that VNF are present at database table vnfs and update content into scenario dict
1562 for name,vnf in scenario["vnfs"].iteritems():
1563 where={}
1564 where_or={"tenant_id": tenant_id, 'public': "true"}
1565 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001566 error_pos = "'scenario':'vnfs':'" + name + "'"
garciadeblas9f8456e2016-09-05 05:02:59 +02001567 if 'vnf_id' in vnf:
1568 error_text += " 'vnf_id' " + vnf['vnf_id']
1569 where['uuid'] = vnf['vnf_id']
1570 if 'vnf_name' in vnf:
1571 error_text += " 'vnf_name' " + vnf['vnf_name']
1572 where['name'] = vnf['vnf_name']
1573 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001574 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
garciadeblas9f8456e2016-09-05 05:02:59 +02001575 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1576 FROM='vnfs',
1577 WHERE=where,
1578 WHERE_OR=where_or,
1579 WHERE_AND_OR="AND")
1580 if len(vnf_db)==0:
1581 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1582 elif len(vnf_db)>1:
1583 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
1584 vnf['uuid']=vnf_db[0]['uuid']
1585 vnf['description']=vnf_db[0]['description']
1586 vnf['ifaces'] = {}
1587 # get external interfaces
1588 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1589 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1590 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
1591 for ext_iface in ext_ifaces:
1592 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1593
1594 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
1595
1596#2: Insert net_key and ip_address at every vnf interface
1597 for net_name,net in scenario["networks"].iteritems():
1598 net_type_bridge=False
1599 net_type_data=False
1600 for iface_dict in net["interfaces"]:
1601 logger.debug("Iface_dict %s", iface_dict)
1602 vnf = iface_dict["vnf"]
1603 iface = iface_dict["vnf_interface"]
1604 if vnf not in scenario["vnfs"]:
1605 error_text = "Error at 'networks':'%s':'interfaces' VNF '%s' not match any VNF at 'vnfs'" % (net_name, vnf)
1606 #logger.debug(error_text)
1607 raise NfvoException(error_text, HTTP_Not_Found)
1608 if iface not in scenario["vnfs"][vnf]['ifaces']:
1609 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface not match any VNF interface" % (net_name, iface)
1610 #logger.debug(error_text)
1611 raise NfvoException(error_text, HTTP_Bad_Request)
1612 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
1613 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface already connected at network '%s'" \
1614 % (net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
1615 #logger.debug(error_text)
1616 raise NfvoException(error_text, HTTP_Bad_Request)
1617 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
1618 scenario["vnfs"][vnf]['ifaces'][ iface ]['ip_address'] = iface_dict.get('ip_address',None)
1619 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
1620 if iface_type=='mgmt' or iface_type=='bridge':
1621 net_type_bridge = True
1622 else:
1623 net_type_data = True
1624 if net_type_bridge and net_type_data:
1625 error_text = "Error connection interfaces of bridge type and data type at 'networks':'%s':'interfaces'" % (net_name)
1626 #logger.debug(error_text)
1627 raise NfvoException(error_text, HTTP_Bad_Request)
1628 elif net_type_bridge:
1629 type_='bridge'
1630 else:
1631 type_='data' if len(net["interfaces"])>2 else 'ptp'
1632
1633 if ("implementation" in net):
1634 if (type_ == "bridge" and net["implementation"] == "underlay"):
1635 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at 'network':'%s'" % (net_name)
1636 #logger.debug(error_text)
1637 raise NfvoException(error_text, HTTP_Bad_Request)
1638 elif (type_ <> "bridge" and net["implementation"] == "overlay"):
1639 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at 'network':'%s'" % (net_name)
1640 #logger.debug(error_text)
1641 raise NfvoException(error_text, HTTP_Bad_Request)
1642 net.pop("implementation")
1643 if ("type" in net):
1644 if (type_ == "data" and net["type"] == "e-line"):
1645 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type 'e-line' at 'network':'%s'" % (net_name)
1646 #logger.debug(error_text)
1647 raise NfvoException(error_text, HTTP_Bad_Request)
1648 elif (type_ == "ptp" and net["type"] == "e-lan"):
1649 type_ = "data"
1650
1651 net['type'] = type_
1652 net['name'] = net_name
1653 net['external'] = net.get('external', False)
1654
1655#3: insert at database
1656 scenario["nets"] = scenario["networks"]
1657 scenario['tenant_id'] = tenant_id
1658 scenario_id = mydb.new_scenario2(scenario)
1659 return scenario_id
1660
1661def update(d, u):
1662 '''Takes dict d and updates it with the values in dict u.'''
1663 '''It merges all depth levels'''
1664 for k, v in u.iteritems():
1665 if isinstance(v, collections.Mapping):
1666 r = update(d.get(k, {}), v)
1667 d[k] = r
1668 else:
1669 d[k] = u[k]
1670 return d
1671
tierno7edb6752016-03-21 17:37:52 +01001672def create_instance(mydb, tenant_id, instance_dict):
tiernoae4a8d12016-07-08 12:30:39 +02001673 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno4319dad2016-09-05 12:11:11 +02001674 #logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01001675 scenario = instance_dict["scenario"]
tiernobe41e222016-09-02 15:16:13 +02001676
1677 #find main datacenter
1678 myvims = {}
tiernoa2793912016-10-04 08:15:08 +00001679 datacenter2tenant = {}
tierno7edb6752016-03-21 17:37:52 +01001680 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02001681 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
1682 myvims[default_datacenter_id] = vim
tiernoa2793912016-10-04 08:15:08 +00001683 datacenter2tenant[default_datacenter_id] = vim['config']['datacenter_tenant_id']
tierno392f2852016-05-13 12:28:55 +02001684 #myvim_tenant = myvim['tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001685# default_datacenter_name = vim['name']
tierno7edb6752016-03-21 17:37:52 +01001686 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001687
1688 #print "Checking that the scenario exists and getting the scenario dictionary"
tiernobe41e222016-09-02 15:16:13 +02001689 scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001690
garciadeblasbb6a1ed2016-09-30 14:02:09 +00001691 #logger.debug(">>>>>>> Dictionaries before merging")
1692 #logger.debug(">>>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
1693 #logger.debug(">>>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
garciadeblas9f8456e2016-09-05 05:02:59 +02001694
tiernobe41e222016-09-02 15:16:13 +02001695 scenarioDict['datacenter_id'] = default_datacenter_id
garciadeblas9f8456e2016-09-05 05:02:59 +02001696
tierno7edb6752016-03-21 17:37:52 +01001697 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1698 auxNetDict['scenario'] = {}
1699
tierno4319dad2016-09-05 12:11:11 +02001700 logger.debug("Creating instance from scenario-dict:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001701 instance_name = instance_dict["name"]
1702 instance_description = instance_dict.get("description")
1703 try:
1704 #0 check correct parameters
tiernobe41e222016-09-02 15:16:13 +02001705 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001706 found=False
1707 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001708 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01001709 found = True
1710 break
1711 if not found:
tiernobe41e222016-09-02 15:16:13 +02001712 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request)
1713 if "sites" not in net_instance_desc:
1714 net_instance_desc["sites"] = [ {} ]
1715 site_without_datacenter_field = False
1716 for site in net_instance_desc["sites"]:
1717 if site.get("datacenter"):
1718 if site["datacenter"] not in myvims:
1719 #Add this datacenter to myvims
1720 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
1721 myvims[d] = v
tiernoa2793912016-10-04 08:15:08 +00001722 datacenter2tenant[d] = v['config']['datacenter_tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001723 site["datacenter"] = d #change name to id
1724 else:
1725 if site_without_datacenter_field:
1726 raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
1727 site_without_datacenter_field = True
1728 site["datacenter"] = default_datacenter_id #change name to id
1729
1730 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001731 found=False
1732 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001733 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01001734 found = True
1735 break
1736 if not found:
tiernobe41e222016-09-02 15:16:13 +02001737 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
1738 if "datacenter" in vnf_instance_desc:
1739 #Add this datacenter to myvims
1740 if vnf_instance_desc["datacenter"] not in myvims:
1741 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
1742 myvims[d] = v
tiernoa2793912016-10-04 08:15:08 +00001743 datacenter2tenant[d] = v['config']['datacenter_tenant_id']
1744 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
tiernoa4e1a6e2016-08-31 14:19:40 +02001745 #0.1 parse cloud-config parameters
1746 cloud_config = scenarioDict.get("cloud-config", {})
1747 if instance_dict.get("cloud-config"):
1748 cloud_config.update( instance_dict["cloud-config"])
1749 if not cloud_config:
1750 cloud_config = None
1751 else:
1752 scenarioDict["cloud-config"] = cloud_config
1753 unify_cloud_config(cloud_config)
garciadeblas9f8456e2016-09-05 05:02:59 +02001754
1755 #0.2 merge instance information into scenario
1756 #Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
1757 #However, this is not possible yet.
1758 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
1759 for scenario_net in scenarioDict['nets']:
1760 if net_name == scenario_net["name"]:
1761 if 'ip-profile' in net_instance_desc:
1762 ipprofile = net_instance_desc['ip-profile']
1763 ipprofile['subnet_address'] = ipprofile.pop('subnet-address',None)
1764 ipprofile['ip_version'] = ipprofile.pop('ip-version','IPv4')
1765 ipprofile['gateway_address'] = ipprofile.pop('gateway-address',None)
1766 ipprofile['dns_address'] = ipprofile.pop('dns-address',None)
1767 if 'dhcp' in ipprofile:
1768 ipprofile['dhcp_start_address'] = ipprofile['dhcp'].get('start-address',None)
1769 ipprofile['dhcp_enabled'] = ipprofile['dhcp'].get('enabled',True)
1770 ipprofile['dhcp_count'] = ipprofile['dhcp'].get('count',None)
1771 del ipprofile['dhcp']
garciadeblasedca7b32016-09-29 14:01:52 +00001772 if 'ip_profile' not in scenario_net:
1773 scenario_net['ip_profile'] = ipprofile
1774 else:
1775 update(scenario_net['ip_profile'],ipprofile)
tiernoe6c58ce2016-09-14 16:02:49 +02001776 for interface in net_instance_desc.get('interfaces', () ):
garciadeblas9f8456e2016-09-05 05:02:59 +02001777 if 'ip_address' in interface:
1778 for vnf in scenarioDict['vnfs']:
1779 if interface['vnf'] == vnf['name']:
1780 for vnf_interface in vnf['interfaces']:
1781 if interface['vnf_interface'] == vnf_interface['external_name']:
1782 vnf_interface['ip_address']=interface['ip_address']
1783
garciadeblasbb6a1ed2016-09-30 14:02:09 +00001784 #logger.debug(">>>>>>>> Merged dictionary")
tierno4319dad2016-09-05 12:11:11 +02001785 logger.debug("Creating instance scenario-dict MERGED:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02001786
tierno7edb6752016-03-21 17:37:52 +01001787
1788 #1. Creating new nets (sce_nets) in the VIM"
1789 for sce_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001790 sce_net["vim_id_sites"]={}
tierno7edb6752016-03-21 17:37:52 +01001791 descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{})
tiernobe41e222016-09-02 15:16:13 +02001792 net_name = descriptor_net.get("vim-network-name")
1793 auxNetDict['scenario'][sce_net['uuid']] = {}
1794
1795 sites = descriptor_net.get("sites", [ {} ])
1796 for site in sites:
1797 if site.get("datacenter"):
1798 vim = myvims[ site["datacenter"] ]
1799 datacenter_id = site["datacenter"]
tierno7edb6752016-03-21 17:37:52 +01001800 else:
tiernobe41e222016-09-02 15:16:13 +02001801 vim = myvims[ default_datacenter_id ]
1802 datacenter_id = default_datacenter_id
tiernobe41e222016-09-02 15:16:13 +02001803 net_type = sce_net['type']
1804 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True
1805 if sce_net["external"]:
1806 if not net_name:
1807 net_name = sce_net["name"]
1808 if "netmap-use" in site or "netmap-create" in site:
1809 create_network = False
1810 lookfor_network = False
1811 if "netmap-use" in site:
1812 lookfor_network = True
1813 if utils.check_valid_uuid(site["netmap-use"]):
1814 filter_text = "scenario id '%s'" % site["netmap-use"]
1815 lookfor_filter["id"] = site["netmap-use"]
1816 else:
1817 filter_text = "scenario name '%s'" % site["netmap-use"]
1818 lookfor_filter["name"] = site["netmap-use"]
1819 if "netmap-create" in site:
1820 create_network = True
1821 net_vim_name = net_name
1822 if site["netmap-create"]:
1823 net_vim_name = site["netmap-create"]
1824
1825 elif sce_net['vim_id'] != None:
1826 #there is a netmap at datacenter_nets database #TODO REVISE!!!!
1827 create_network = False
1828 lookfor_network = True
1829 lookfor_filter["id"] = sce_net['vim_id']
1830 filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"])
1831 #look for network at datacenter and return error
1832 else:
1833 #There is not a netmap, look at datacenter for a net with this name and create if not found
1834 create_network = True
1835 lookfor_network = True
1836 lookfor_filter["name"] = sce_net["name"]
1837 net_vim_name = sce_net["name"]
1838 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01001839 else:
tiernobe41e222016-09-02 15:16:13 +02001840 if not net_name:
1841 net_name = "%s.%s" %(instance_name, sce_net["name"])
1842 net_name = net_name[:255] #limit length
1843 net_vim_name = net_name
1844 create_network = True
1845 lookfor_network = False
1846
1847 if lookfor_network:
1848 vim_nets = vim.get_network_list(filter_dict=lookfor_filter)
1849 if len(vim_nets) > 1:
1850 raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1851 elif len(vim_nets) == 0:
1852 if not create_network:
1853 raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1854 else:
1855 sce_net["vim_id_sites"][datacenter_id] = vim_nets[0]['id']
tiernobe41e222016-09-02 15:16:13 +02001856 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id']
1857 create_network = False
1858 if create_network:
1859 #if network is not external
garciadeblas9f8456e2016-09-05 05:02:59 +02001860 network_id = vim.new_network(net_vim_name, net_type, sce_net.get('ip_profile',None))
tiernobe41e222016-09-02 15:16:13 +02001861 sce_net["vim_id_sites"][datacenter_id] = network_id
1862 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = network_id
1863 rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001864 sce_net["created"] = True
tierno7edb6752016-03-21 17:37:52 +01001865
1866 #2. Creating new nets (vnf internal nets) in the VIM"
1867 #For each vnf net, we create it and we add it to instanceNetlist.
1868 for sce_vnf in scenarioDict['vnfs']:
1869 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02001870 if sce_vnf.get("datacenter"):
1871 vim = myvims[ sce_vnf["datacenter"] ]
1872 datacenter_id = sce_vnf["datacenter"]
1873 else:
1874 vim = myvims[ default_datacenter_id ]
1875 datacenter_id = default_datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001876 descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{})
1877 net_name = descriptor_net.get("name")
1878 if not net_name:
1879 net_name = "%s.%s" %(instance_name, net["name"])
1880 net_name = net_name[:255] #limit length
1881 net_type = net['type']
garciadeblas9f8456e2016-09-05 05:02:59 +02001882 network_id = vim.new_network(net_name, net_type, net.get('ip_profile',None))
tierno7edb6752016-03-21 17:37:52 +01001883 net['vim_id'] = network_id
1884 if sce_vnf['uuid'] not in auxNetDict:
1885 auxNetDict[sce_vnf['uuid']] = {}
1886 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1887 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001888 net["created"] = True
1889
tierno7edb6752016-03-21 17:37:52 +01001890
tiernoae4a8d12016-07-08 12:30:39 +02001891 #print "auxNetDict:"
1892 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001893
1894 #3. Creating new vm instances in the VIM
tiernoae4a8d12016-07-08 12:30:39 +02001895 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
tierno7edb6752016-03-21 17:37:52 +01001896 for sce_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001897 if sce_vnf.get("datacenter"):
1898 vim = myvims[ sce_vnf["datacenter"] ]
1899 datacenter_id = sce_vnf["datacenter"]
1900 else:
1901 vim = myvims[ default_datacenter_id ]
1902 datacenter_id = default_datacenter_id
1903 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001904 i = 0
1905 for vm in sce_vnf['vms']:
1906 i += 1
1907 myVMDict = {}
1908 myVMDict['name'] = "%s.%s.%d" % (instance_name,sce_vnf['name'],i)
1909 myVMDict['description'] = myVMDict['name'][0:99]
1910# if not startvms:
1911# myVMDict['start'] = "no"
1912 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1913 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001914 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00001915 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01001916 vm['vim_image_id'] = image_id
1917
1918 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001919 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01001920 if flavor_dict['extended']!=None:
1921 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tiernobe41e222016-09-02 15:16:13 +02001922 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
tierno7edb6752016-03-21 17:37:52 +01001923 vm['vim_flavor_id'] = flavor_id
1924
1925 myVMDict['imageRef'] = vm['vim_image_id']
1926 myVMDict['flavorRef'] = vm['vim_flavor_id']
1927 myVMDict['networks'] = []
tiernoa2793912016-10-04 08:15:08 +00001928 #TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno7edb6752016-03-21 17:37:52 +01001929 for iface in vm['interfaces']:
1930 netDict = {}
1931 if iface['type']=="data":
1932 netDict['type'] = iface['model']
1933 elif "model" in iface and iface["model"]!=None:
1934 netDict['model']=iface['model']
1935 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1936 #discover type of interface looking at flavor
1937 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1938 for flavor_iface in numa.get('interfaces',[]):
1939 if flavor_iface.get('name') == iface['internal_name']:
1940 if flavor_iface['dedicated'] == 'yes':
1941 netDict['type']="PF" #passthrough
1942 elif flavor_iface['dedicated'] == 'no':
1943 netDict['type']="VF" #siov
1944 elif flavor_iface['dedicated'] == 'yes:sriov':
1945 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1946 netDict["mac_address"] = flavor_iface.get("mac_address")
1947 break;
1948 netDict["use"]=iface['type']
1949 if netDict["use"]=="data" and not netDict.get("type"):
1950 #print "netDict", netDict
1951 #print "iface", iface
1952 e_text = "Cannot determine the interface type PF or VF of VNF '%s' VM '%s' iface '%s'" %(sce_vnf['name'], vm['name'], iface['internal_name'])
1953 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02001954 raise NfvoException(e_text + "After database migration some information is not available. \
1955 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001956 else:
tiernoae4a8d12016-07-08 12:30:39 +02001957 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01001958 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1959 netDict["type"]="virtual"
1960 if "vpci" in iface and iface["vpci"] is not None:
1961 netDict['vpci'] = iface['vpci']
1962 if "mac" in iface and iface["mac"] is not None:
1963 netDict['mac_address'] = iface['mac']
1964 netDict['name'] = iface['internal_name']
1965 if iface['net_id'] is None:
1966 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001967 #print iface
1968 #print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01001969 if vnf_iface['interface_id']==iface['uuid']:
tiernobe41e222016-09-02 15:16:13 +02001970 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01001971 break
1972 else:
1973 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1974 #skip bridge ifaces not connected to any net
1975 #if 'net_id' not in netDict or netDict['net_id']==None:
1976 # continue
1977 myVMDict['networks'].append(netDict)
tiernoae4a8d12016-07-08 12:30:39 +02001978 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1979 #print myVMDict['name']
1980 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1981 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1982 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tiernobe41e222016-09-02 15:16:13 +02001983 vm_id = vim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
tiernoa4e1a6e2016-08-31 14:19:40 +02001984 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'], cloud_config = cloud_config)
tierno7edb6752016-03-21 17:37:52 +01001985 vm['vim_id'] = vm_id
1986 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1987 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1988 for net in myVMDict['networks']:
1989 if "vim_id" in net:
1990 for iface in vm['interfaces']:
1991 if net["name"]==iface["internal_name"]:
1992 iface["vim_id"]=net["vim_id"]
1993 break
tiernoa2793912016-10-04 08:15:08 +00001994 scenarioDict["datacenter2tenant"] = datacenter2tenant
1995 logger.debug("create_instance Deployment done scenarioDict: %s",
1996 yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False) )
tiernof97fd272016-07-11 14:32:37 +02001997 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_name, instance_description, scenarioDict)
1998 return mydb.get_instance_scenario(instance_id)
1999 except (NfvoException, vimconn.vimconnException,db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02002000 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002001 if isinstance(e, db_base_Exception):
2002 error_text = "database Exception"
2003 elif isinstance(e, vimconn.vimconnException):
2004 error_text = "VIM Exception"
2005 else:
2006 error_text = "Exception"
2007 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2008 #logger.error("create_instance: %s", error_text)
2009 raise NfvoException(error_text, e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002010
tierno7edb6752016-03-21 17:37:52 +01002011def delete_instance(mydb, tenant_id, instance_id):
tiernoae4a8d12016-07-08 12:30:39 +02002012 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002013 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +02002014 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01002015 tenant_id = instanceDict["tenant_id"]
tiernoae4a8d12016-07-08 12:30:39 +02002016 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01002017
tiernoa2793912016-10-04 08:15:08 +00002018 #1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02002019 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002020
2021 #2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00002022 error_msg = ""
2023 myvims={}
tierno7edb6752016-03-21 17:37:52 +01002024
2025 #2.1 deleting VMs
2026 #vm_fail_list=[]
2027 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002028 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2029 if datacenter_key not in myvims:
2030 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
2031 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2032 if len(vims) == 0:
2033 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
2034 sce_vnf["datacenter_tenant_id"]))
2035 myvims[datacenter_key] = None
2036 else:
2037 myvims[datacenter_key] = vims.values()[0]
2038 myvim = myvims[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01002039 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002040 if not myvim:
2041 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
2042 continue
tiernoae4a8d12016-07-08 12:30:39 +02002043 try:
2044 myvim.delete_vminstance(vm['vim_vm_id'])
2045 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002046 error_msg+="\n VM VIM_id={} not found at datacenter={}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
tiernoae4a8d12016-07-08 12:30:39 +02002047 logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found",
2048 vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'])
2049 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002050 error_msg+="\n VM VIM_id={} at datacenter={} Error: {} {}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"], e.http_code, str(e))
2051 logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM_id '%s', from VNF_id '%s': %s",
tiernoae4a8d12016-07-08 12:30:39 +02002052 e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e))
tierno7edb6752016-03-21 17:37:52 +01002053
2054 #2.2 deleting NETS
2055 #net_fail_list=[]
2056 for net in instanceDict['nets']:
tierno66345bc2016-09-26 11:37:55 +02002057 if not net['created']:
tierno7edb6752016-03-21 17:37:52 +01002058 continue #skip not created nets
tiernoa2793912016-10-04 08:15:08 +00002059 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2060 if datacenter_key not in myvims:
2061 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
2062 datacenter_tenant_id=net["datacenter_tenant_id"])
2063 if len(vims) == 0:
2064 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2065 myvims[datacenter_key] = None
2066 else:
2067 myvims[datacenter_key] = vims.values()[0]
2068 myvim = myvims[datacenter_key]
2069
tierno7edb6752016-03-21 17:37:52 +01002070 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00002071 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
tierno7edb6752016-03-21 17:37:52 +01002072 continue
tiernoae4a8d12016-07-08 12:30:39 +02002073 try:
2074 myvim.delete_network(net['vim_net_id'])
2075 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002076 error_msg+="\n NET VIM_id={} not found at datacenter={}".format(net['vim_net_id'], net["datacenter_id"])
2077 logger.warn("NET '%s', VIM_id '%s', from VNF_net_id '%s' not found",
2078 net['uuid'], net['vim_net_id'], str(net['vnf_net_id']))
tiernoae4a8d12016-07-08 12:30:39 +02002079 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002080 error_msg+="\n NET VIM_id={} at datacenter={} Error: {} {}".format(net['vim_net_id'], net["datacenter_id"], e.http_code, str(e))
2081 logger.error("Error %d deleting NET '%s', VIM_id '%s', from VNF_net_id '%s': %s",
2082 e.http_code, net['uuid'], net['vim_net_id'], str(net['vnf_net_id']), str(e))
tierno7edb6752016-03-21 17:37:52 +01002083 if len(error_msg)>0:
tiernof97fd272016-07-11 14:32:37 +02002084 return 'instance ' + message + ' deleted but some elements could not be deleted, or already deleted (error: 404) from VIM: ' + error_msg
tierno7edb6752016-03-21 17:37:52 +01002085 else:
tiernof97fd272016-07-11 14:32:37 +02002086 return 'instance ' + message + ' deleted'
tierno7edb6752016-03-21 17:37:52 +01002087
2088def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
2089 '''Refreshes a scenario instance. It modifies instanceDict'''
2090 '''Returns:
2091 - result: <0 if there is any unexpected error, n>=0 if no errors where n is the number of vms and nets that couldn't be updated in the database
2092 - error_msg
2093 '''
2094 # Assumption: nfvo_tenant and instance_id were checked before entering into this function
tiernoae4a8d12016-07-08 12:30:39 +02002095 #print "nfvo.refresh_instance begins"
tierno7edb6752016-03-21 17:37:52 +01002096 #print json.dumps(instanceDict, indent=4)
2097
tiernoae4a8d12016-07-08 12:30:39 +02002098 #print "Getting the VIM URL and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002099 myvims={}
2100
tiernoae4a8d12016-07-08 12:30:39 +02002101 # 1. Getting VIM vm and net list
tierno7edb6752016-03-21 17:37:52 +01002102 vms_updated = [] #List of VM instance uuids in openmano that were updated
2103 vms_notupdated=[]
tiernoa2793912016-10-04 08:15:08 +00002104 vm_list = {}
tierno7edb6752016-03-21 17:37:52 +01002105 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002106 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2107 if datacenter_key not in vm_list:
2108 vm_list[datacenter_key] = []
2109 if datacenter_key not in myvims:
2110 vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
2111 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2112 if len(vims) == 0:
2113 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
2114 myvims[datacenter_key] = None
2115 else:
2116 myvims[datacenter_key] = vims.values()[0]
tierno7edb6752016-03-21 17:37:52 +01002117 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002118 vm_list[datacenter_key].append(vm['vim_vm_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002119 vms_notupdated.append(vm["uuid"])
2120
2121 nets_updated = [] #List of VM instance uuids in openmano that were updated
tierno7edb6752016-03-21 17:37:52 +01002122 nets_notupdated=[]
tiernoa2793912016-10-04 08:15:08 +00002123 net_list = {}
tierno7edb6752016-03-21 17:37:52 +01002124 for net in instanceDict['nets']:
tiernoa2793912016-10-04 08:15:08 +00002125 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2126 if datacenter_key not in net_list:
2127 net_list[datacenter_key] = []
2128 if datacenter_key not in myvims:
2129 vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
2130 datacenter_tenant_id=net["datacenter_tenant_id"])
2131 if len(vims) == 0:
2132 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2133 myvims[datacenter_key] = None
2134 else:
2135 myvims[datacenter_key] = vims.values()[0]
2136
2137 net_list[datacenter_key].append(net['vim_net_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002138 nets_notupdated.append(net["uuid"])
2139
tiernoa2793912016-10-04 08:15:08 +00002140 # 1. Getting the status of all VMs
2141 vm_dict={}
2142 for datacenter_key in myvims:
2143 if not vm_list.get(datacenter_key):
2144 continue
2145 failed = True
2146 failed_message=""
2147 if not myvims[datacenter_key]:
2148 failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2149 else:
2150 try:
2151 vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
2152 failed = False
2153 except vimconn.vimconnException as e:
2154 logger.error("VIM exception %s %s", type(e).__name__, str(e))
2155 failed_message = str(e)
2156 if failed:
2157 for vm in vm_list[datacenter_key]:
2158 vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
tiernoae4a8d12016-07-08 12:30:39 +02002159
tiernoa2793912016-10-04 08:15:08 +00002160 # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
2161 for sce_vnf in instanceDict['vnfs']:
2162 for vm in sce_vnf['vms']:
2163 vm_id = vm['vim_vm_id']
2164 interfaces = vm_dict[vm_id].pop('interfaces', [])
2165 #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
2166 has_mgmt_iface = False
2167 for iface in vm["interfaces"]:
2168 if iface["type"]=="mgmt":
2169 has_mgmt_iface = True
2170 if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
2171 vm_dict[vm_id]['status'] = "ACTIVE"
tiernoa3d49e62016-10-05 15:20:26 +00002172 if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
2173 vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
tiernoa2793912016-10-04 08:15:08 +00002174 if vm['status'] != vm_dict[vm_id]['status'] or vm.get('error_msg')!=vm_dict[vm_id].get('error_msg') or vm.get('vim_info')!=vm_dict[vm_id].get('vim_info'):
2175 vm['status'] = vm_dict[vm_id]['status']
2176 vm['error_msg'] = vm_dict[vm_id].get('error_msg')
2177 vm['vim_info'] = vm_dict[vm_id].get('vim_info')
2178 # 2.1. Update in openmano DB the VMs whose status changed
tiernof97fd272016-07-11 14:32:37 +02002179 try:
tiernoa2793912016-10-04 08:15:08 +00002180 updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
2181 vms_notupdated.remove(vm["uuid"])
2182 if updates>0:
2183 vms_updated.append(vm["uuid"])
tiernof97fd272016-07-11 14:32:37 +02002184 except db_base_Exception as e:
2185 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tiernoa2793912016-10-04 08:15:08 +00002186 # 2.2. Update in openmano DB the interface VMs
2187 for interface in interfaces:
2188 #translate from vim_net_id to instance_net_id
2189 network_id_list=[]
2190 for net in instanceDict['nets']:
2191 if net["vim_net_id"] == interface["vim_net_id"]:
2192 network_id_list.append(net["uuid"])
2193 if not network_id_list:
2194 continue
2195 del interface["vim_net_id"]
2196 try:
2197 for network_id in network_id_list:
2198 mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
2199 except db_base_Exception as e:
2200 logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
2201
2202 # 3. Getting the status of all nets
2203 net_dict = {}
2204 for datacenter_key in myvims:
2205 if not net_list.get(datacenter_key):
2206 continue
2207 failed = True
2208 failed_message = ""
2209 if not myvims[datacenter_key]:
2210 failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2211 else:
2212 try:
2213 net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
2214 failed = False
2215 except vimconn.vimconnException as e:
2216 logger.error("VIM exception %s %s", type(e).__name__, str(e))
2217 failed_message = str(e)
2218 if failed:
2219 for net in net_list[datacenter_key]:
2220 net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2221
2222 # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
2223 # TODO: update nets inside a vnf
2224 for net in instanceDict['nets']:
2225 net_id = net['vim_net_id']
tiernoa3d49e62016-10-05 15:20:26 +00002226 if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
2227 net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
tiernoa2793912016-10-04 08:15:08 +00002228 if net['status'] != net_dict[net_id]['status'] or net.get('error_msg')!=net_dict[net_id].get('error_msg') or net.get('vim_info')!=net_dict[net_id].get('vim_info'):
2229 net['status'] = net_dict[net_id]['status']
2230 net['error_msg'] = net_dict[net_id].get('error_msg')
2231 net['vim_info'] = net_dict[net_id].get('vim_info')
2232 # 5.1. Update in openmano DB the nets whose status changed
2233 try:
2234 updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
2235 nets_notupdated.remove(net["uuid"])
2236 if updated>0:
2237 nets_updated.append(net["uuid"])
2238 except db_base_Exception as e:
2239 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tierno7edb6752016-03-21 17:37:52 +01002240
2241 # Returns appropriate output
tiernoae4a8d12016-07-08 12:30:39 +02002242 #print "nfvo.refresh_instance finishes"
2243 logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
2244 str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01002245 instance_id = instanceDict['uuid']
tierno7edb6752016-03-21 17:37:52 +01002246 if len(vms_notupdated)+len(nets_notupdated)>0:
tiernoae4a8d12016-07-08 12:30:39 +02002247 error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
tierno7edb6752016-03-21 17:37:52 +01002248 return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
2249
tiernoae4a8d12016-07-08 12:30:39 +02002250 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01002251
2252def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02002253 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002254 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002255 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
2256
tiernoae4a8d12016-07-08 12:30:39 +02002257 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02002258 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
2259 if len(vims) == 0:
2260 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002261 myvim = vims.values()[0]
2262
2263
2264 input_vnfs = action_dict.pop("vnfs", [])
2265 input_vms = action_dict.pop("vms", [])
2266 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
2267 vm_result = {}
2268 vm_error = 0
2269 vm_ok = 0
2270 for sce_vnf in instanceDict['vnfs']:
2271 for vm in sce_vnf['vms']:
2272 if not action_over_all:
2273 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
2274 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
2275 continue
tiernoae4a8d12016-07-08 12:30:39 +02002276 try:
2277 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
tierno7edb6752016-03-21 17:37:52 +01002278 if "console" in action_dict:
tierno20fc2a22016-08-19 17:02:35 +02002279 if not global_config["http_console_proxy"]:
2280 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2281 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2282 protocol=data["protocol"],
2283 ip = data["server"],
2284 port = data["port"],
2285 suffix = data["suffix"]),
2286 "name":vm['name']
2287 }
2288 vm_ok +=1
2289 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
tierno7edb6752016-03-21 17:37:52 +01002290 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
2291 "description": "this console is only reachable by local interface",
2292 "name":vm['name']
2293 }
2294 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02002295 else:
tierno7edb6752016-03-21 17:37:52 +01002296 #print "console data", data
tierno20fc2a22016-08-19 17:02:35 +02002297 try:
2298 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
2299 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2300 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2301 protocol=data["protocol"],
2302 ip = global_config["http_console_host"],
2303 port = console_thread.port,
2304 suffix = data["suffix"]),
2305 "name":vm['name']
2306 }
2307 vm_ok +=1
2308 except NfvoException as e:
2309 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2310 vm_error+=1
2311
tierno7edb6752016-03-21 17:37:52 +01002312 else:
tiernof97fd272016-07-11 14:32:37 +02002313 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
tierno7edb6752016-03-21 17:37:52 +01002314 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02002315 except vimconn.vimconnException as e:
2316 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2317 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01002318
2319 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02002320 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002321 else:
tierno351863c2016-07-23 01:46:03 +02002322 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002323
2324def create_or_use_console_proxy_thread(console_server, console_port):
2325 #look for a non-used port
2326 console_thread_key = console_server + ":" + str(console_port)
2327 if console_thread_key in global_config["console_thread"]:
2328 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02002329 return global_config["console_thread"][console_thread_key]
tierno7edb6752016-03-21 17:37:52 +01002330
2331 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02002332 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01002333 if port in global_config["console_ports"]:
2334 continue
2335 try:
2336 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
2337 clithread.start()
2338 global_config["console_thread"][console_thread_key] = clithread
2339 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02002340 return clithread
tierno7edb6752016-03-21 17:37:52 +01002341 except cli.ConsoleProxyExceptionPortUsed as e:
2342 #port used, try with onoher
2343 continue
2344 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02002345 raise NfvoException(str(e), HTTP_Bad_Request)
2346 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002347
2348def check_tenant(mydb, tenant_id):
2349 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02002350 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
2351 if not tenant:
2352 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
2353 return
tierno7edb6752016-03-21 17:37:52 +01002354
2355def new_tenant(mydb, tenant_dict):
tiernof97fd272016-07-11 14:32:37 +02002356 tenant_id = mydb.new_row("nfvo_tenants", tenant_dict, add_uuid=True)
2357 return tenant_id
tierno7edb6752016-03-21 17:37:52 +01002358
2359def delete_tenant(mydb, tenant):
2360 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002361
2362 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
2363 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
2364 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01002365
2366def new_datacenter(mydb, datacenter_descriptor):
2367 if "config" in datacenter_descriptor:
2368 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02002369 #Check that datacenter-type is correct
2370 datacenter_type = datacenter_descriptor.get("type", "openvim");
2371 module_info = None
2372 try:
2373 module = "vimconn_" + datacenter_type
2374 module_info = imp.find_module(module)
2375 except (IOError, ImportError):
2376 if module_info and module_info[0]:
2377 file.close(module_info[0])
2378 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
2379
tiernof97fd272016-07-11 14:32:37 +02002380 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
2381 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002382
2383def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
2384 #obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02002385 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno7edb6752016-03-21 17:37:52 +01002386 #edit data
tiernof97fd272016-07-11 14:32:37 +02002387 datacenter_id = datacenter['uuid']
2388 where={'uuid': datacenter['uuid']}
tierno7edb6752016-03-21 17:37:52 +01002389 if "config" in datacenter_descriptor:
2390 if datacenter_descriptor['config']!=None:
2391 try:
2392 new_config_dict = datacenter_descriptor["config"]
2393 #delete null fields
2394 to_delete=[]
2395 for k in new_config_dict:
2396 if new_config_dict[k]==None:
2397 to_delete.append(k)
2398
tiernof97fd272016-07-11 14:32:37 +02002399 config_dict = yaml.load(datacenter["config"])
tierno7edb6752016-03-21 17:37:52 +01002400 config_dict.update(new_config_dict)
2401 #delete null fields
2402 for k in to_delete:
2403 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02002404 except Exception as e:
2405 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002406 datacenter_descriptor["config"]= yaml.safe_dump(config_dict,default_flow_style=True,width=256) if len(config_dict)>0 else None
tiernof97fd272016-07-11 14:32:37 +02002407 mydb.update_rows('datacenters', datacenter_descriptor, where)
2408 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002409
2410def delete_datacenter(mydb, datacenter):
2411 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002412 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
2413 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
2414 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01002415
2416def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None):
2417 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002418 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002419 datacenter_name=myvim["name"]
2420
2421 create_vim_tenant=True if vim_tenant_id==None and vim_tenant_name==None else False
2422
2423 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002424 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002425 if vim_tenant_name==None:
2426 vim_tenant_name=tenant_dict['name']
2427
2428 #check that this association does not exist before
2429 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernof97fd272016-07-11 14:32:37 +02002430 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2431 if len(tenants_datacenters)>0:
2432 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002433
2434 vim_tenant_id_exist_atdb=False
2435 if not create_vim_tenant:
2436 where_={"datacenter_id": datacenter_id}
2437 if vim_tenant_id!=None:
2438 where_["vim_tenant_id"] = vim_tenant_id
2439 if vim_tenant_name!=None:
2440 where_["vim_tenant_name"] = vim_tenant_name
2441 #check if vim_tenant_id is already at database
tiernof97fd272016-07-11 14:32:37 +02002442 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
2443 if len(datacenter_tenants_dict)>=1:
tierno7edb6752016-03-21 17:37:52 +01002444 datacenter_tenants_dict = datacenter_tenants_dict[0]
2445 vim_tenant_id_exist_atdb=True
2446 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
2447 else: #result=0
2448 datacenter_tenants_dict = {}
2449 #insert at table datacenter_tenants
2450 else: #if vim_tenant_id==None:
2451 #create tenant at VIM if not provided
tiernoae4a8d12016-07-08 12:30:39 +02002452 try:
2453 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
2454 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002455 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id, str(e)), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002456 datacenter_tenants_dict = {}
2457 datacenter_tenants_dict["created"]="true"
2458
2459 #fill datacenter_tenants table
2460 if not vim_tenant_id_exist_atdb:
2461 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
2462 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
2463 datacenter_tenants_dict["user"] = vim_username
2464 datacenter_tenants_dict["passwd"] = vim_password
2465 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernof97fd272016-07-11 14:32:37 +02002466 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002467 datacenter_tenants_dict["uuid"] = id_
2468
2469 #fill tenants_datacenters table
2470 tenants_datacenter_dict["datacenter_tenant_id"]=datacenter_tenants_dict["uuid"]
tiernof97fd272016-07-11 14:32:37 +02002471 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
2472 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002473
2474def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
2475 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002476 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002477
2478 #get nfvo_tenant info
2479 if not tenant_id or tenant_id=="any":
2480 tenant_uuid = None
2481 else:
tiernof97fd272016-07-11 14:32:37 +02002482 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002483 tenant_uuid = tenant_dict['uuid']
2484
2485 #check that this association exist before
2486 tenants_datacenter_dict={"datacenter_id":datacenter_id }
2487 if tenant_uuid:
2488 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02002489 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2490 if len(tenant_datacenter_list)==0 and tenant_uuid:
2491 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002492
2493 #delete this association
tiernof97fd272016-07-11 14:32:37 +02002494 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01002495
2496 #get vim_tenant info and deletes
2497 warning=''
2498 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02002499 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2500 #try to delete vim:tenant
2501 try:
2502 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2503 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01002504 #delete tenant at VIM if created by NFVO
tiernoae4a8d12016-07-08 12:30:39 +02002505 try:
2506 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
2507 except vimconn.vimconnException as e:
2508 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
2509 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02002510 except db_base_Exception as e:
2511 logger.error("Cannot delete datacenter_tenants " + str(e))
2512 pass #the error will be caused because dependencies, vim_tenant can not be deleted
tierno7edb6752016-03-21 17:37:52 +01002513
tiernof97fd272016-07-11 14:32:37 +02002514 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01002515
2516def datacenter_action(mydb, tenant_id, datacenter, action_dict):
2517 #DEPRECATED
2518 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002519 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002520
2521 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02002522 try:
tiernof97fd272016-07-11 14:32:37 +02002523 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02002524 #print content
2525 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002526 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
2527 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002528 #update nets Change from VIM format to NFVO format
2529 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002530 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01002531 net_nfvo={'datacenter_id': datacenter_id}
2532 net_nfvo['name'] = net['name']
2533 #net_nfvo['description']= net['name']
2534 net_nfvo['vim_net_id'] = net['id']
2535 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2536 net_nfvo['shared'] = net['shared']
2537 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
2538 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002539 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
2540 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
2541 return inserted
tierno7edb6752016-03-21 17:37:52 +01002542 elif 'net-edit' in action_dict:
2543 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02002544 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002545 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01002546 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002547 return result
tierno7edb6752016-03-21 17:37:52 +01002548 elif 'net-delete' in action_dict:
2549 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02002550 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002551 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01002552 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002553 return result
tierno7edb6752016-03-21 17:37:52 +01002554
2555 else:
tiernof97fd272016-07-11 14:32:37 +02002556 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002557
2558def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
2559 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002560 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002561
tierno42fcc3b2016-07-06 17:20:40 +02002562 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002563 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01002564 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02002565 return result
tierno7edb6752016-03-21 17:37:52 +01002566
2567def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
2568 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002569 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002570 filter_dict={}
2571 if action_dict:
2572 action_dict = action_dict["netmap"]
2573 if 'vim_id' in action_dict:
2574 filter_dict["id"] = action_dict['vim_id']
2575 if 'vim_name' in action_dict:
2576 filter_dict["name"] = action_dict['vim_name']
2577 else:
2578 filter_dict["shared"] = True
2579
tiernoae4a8d12016-07-08 12:30:39 +02002580 try:
tiernof97fd272016-07-11 14:32:37 +02002581 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02002582 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002583 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
2584 raise NfvoException(str(e), HTTP_Internal_Server_Error)
2585 if len(vim_nets)>1 and action_dict:
2586 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
2587 elif len(vim_nets)==0: # and action_dict:
2588 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002589 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002590 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01002591 net_nfvo={'datacenter_id': datacenter_id}
2592 if action_dict and "name" in action_dict:
2593 net_nfvo['name'] = action_dict['name']
2594 else:
2595 net_nfvo['name'] = net['name']
2596 #net_nfvo['description']= net['name']
2597 net_nfvo['vim_net_id'] = net['id']
2598 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2599 net_nfvo['shared'] = net['shared']
2600 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02002601 try:
2602 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002603 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02002604 net_nfvo["uuid"] = net_id
2605 except db_base_Exception as e:
2606 if action_dict:
2607 raise
2608 else:
2609 net_nfvo["status"] = "FAIL: " + str(e)
tierno7edb6752016-03-21 17:37:52 +01002610 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002611 return net_list
tierno7edb6752016-03-21 17:37:52 +01002612
2613def vim_action_get(mydb, tenant_id, datacenter, item, name):
2614 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002615 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002616 filter_dict={}
2617 if name:
tierno42fcc3b2016-07-06 17:20:40 +02002618 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01002619 filter_dict["id"] = name
2620 else:
2621 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02002622 try:
2623 if item=="networks":
2624 #filter_dict['tenant_id'] = myvim['tenant_id']
2625 content = myvim.get_network_list(filter_dict=filter_dict)
2626 elif item=="tenants":
2627 content = myvim.get_tenant_list(filter_dict=filter_dict)
2628 else:
tiernof97fd272016-07-11 14:32:37 +02002629 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02002630 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02002631 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02002632 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02002633 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02002634 raise NfvoException("No {} found with ".format(item[:-1]) + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), filter_dict.iteritems())),
tiernobe41e222016-09-02 15:16:13 +02002635 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02002636 else:
tiernof97fd272016-07-11 14:32:37 +02002637 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02002638 except vimconn.vimconnException as e:
2639 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02002640 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002641
2642def vim_action_delete(mydb, tenant_id, datacenter, item, name):
2643 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02002644 if tenant_id == "any":
2645 tenant_id=None
2646
tiernoa2793912016-10-04 08:15:08 +00002647 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02002648 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02002649 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
2650 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02002651 items = content.values()[0]
2652 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02002653 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002654 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02002655 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002656 else: # it is a dict
2657 item_id = items["id"]
2658 item_name = str(items.get("name"))
tierno7edb6752016-03-21 17:37:52 +01002659
tiernoae4a8d12016-07-08 12:30:39 +02002660 try:
2661 if item=="networks":
2662 content = myvim.delete_network(item_id)
2663 elif item=="tenants":
2664 content = myvim.delete_tenant(item_id)
2665 else:
tiernof97fd272016-07-11 14:32:37 +02002666 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002667 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002668 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
2669 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002670
tiernof97fd272016-07-11 14:32:37 +02002671 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno7edb6752016-03-21 17:37:52 +01002672
2673def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
2674 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002675 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02002676 if tenant_id == "any":
2677 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00002678 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02002679 try:
2680 if item=="networks":
2681 net = descriptor["network"]
2682 net_name = net.pop("name")
2683 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02002684 net_public = net.pop("shared", False)
2685 net_ipprofile = net.pop("ip_profile", None)
2686 content = myvim.new_network(net_name, net_type, net_ipprofile, shared=net_public, **net)
tiernoae4a8d12016-07-08 12:30:39 +02002687 elif item=="tenants":
2688 tenant = descriptor["tenant"]
2689 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
2690 else:
tiernof97fd272016-07-11 14:32:37 +02002691 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002692 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002693 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002694
tierno7edb6752016-03-21 17:37:52 +01002695 return vim_action_get(mydb, tenant_id, datacenter, item, content)
2696
tierno66aa0372016-07-06 17:31:12 +02002697