blob: 59c2dca2604dcd202e1ae8915c68f52fb21750dc [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
tiernof97fd272016-07-11 14:32:37 +020039from db_base import db_base_Exception
tierno7edb6752016-03-21 17:37:52 +010040
41global global_config
42global vimconn_imported
43
tiernoae4a8d12016-07-08 12:30:39 +020044
tierno7edb6752016-03-21 17:37:52 +010045vimconn_imported={} #dictionary with VIM type as key, loaded module as value
tiernoae4a8d12016-07-08 12:30:39 +020046logger = logging.getLogger('mano.nfvo')
tierno7edb6752016-03-21 17:37:52 +010047
48class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020049 def __init__(self, message, http_code):
50 self.http_code = http_code
51 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010052
53
54def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
55 '''Obtain flavorList
56 return result, content:
57 <0, error_text upon error
58 nb_records, flavor_list on success
59 '''
60 WHERE_dict={}
61 WHERE_dict['vnf_id'] = vnf_id
62 if nfvo_tenant is not None:
63 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
64
65 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
66 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +020067 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
68 #print "get_flavor_list result:", result
69 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +010070 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +020071 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +010072 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +020073 return flavorList
tierno7edb6752016-03-21 17:37:52 +010074
75def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
76 '''Obtain imageList
77 return result, content:
78 <0, error_text upon error
79 nb_records, flavor_list on success
80 '''
81 WHERE_dict={}
82 WHERE_dict['vnf_id'] = vnf_id
83 if nfvo_tenant is not None:
84 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
85
86 #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 +020087 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 +010088 imageList=[]
tiernof97fd272016-07-11 14:32:37 +020089 for image in images:
tierno7edb6752016-03-21 17:37:52 +010090 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +020091 return imageList
tierno7edb6752016-03-21 17:37:52 +010092
93def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, vim_tenant=None):
94 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tiernobe41e222016-09-02 15:16:13 +020095 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +010096 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +020097 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +010098 '''
99 WHERE_dict={}
100 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
101 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
102 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
103 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
104 if nfvo_tenant or vim_tenant:
105 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'
106 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
107 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
108 'user','passwd')
109 else:
110 from_ = 'datacenters as d'
111 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200112 try:
113 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
114 vim_dict={}
115 for vim in vims:
116 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id')}
117 if vim["config"] != None:
118 extra.update(yaml.load(vim["config"]))
119 if vim["type"] not in vimconn_imported:
120 module_info=None
121 try:
122 module = "vimconn_" + vim["type"]
123 module_info = imp.find_module(module)
124 vim_conn = imp.load_module(vim["type"], *module_info)
125 vimconn_imported[vim["type"]] = vim_conn
126 except (IOError, ImportError) as e:
127 if module_info and module_info[0]:
128 file.close(module_info[0])
129 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
130 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
131
tierno7edb6752016-03-21 17:37:52 +0100132 try:
tiernof97fd272016-07-11 14:32:37 +0200133 #if not tenant:
134 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
135 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
136 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
137 tenant_id=vim.get('vim_tenant_id'), tenant_name=vim.get('vim_tenant_name'),
138 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
139 user=vim.get('user'), passwd=vim.get('passwd'),
140 config=extra
141 )
142 except Exception as e:
143 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
144 return vim_dict
145 except db_base_Exception as e:
146 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
147
tierno7edb6752016-03-21 17:37:52 +0100148def rollback(mydb, vims, rollback_list):
149 undeleted_items=[]
150 #delete things by reverse order
151 for i in range(len(rollback_list)-1, -1, -1):
152 item = rollback_list[i]
153 if item["where"]=="vim":
154 if item["vim_id"] not in vims:
155 continue
156 vim=vims[ item["vim_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200157 try:
158 if item["what"]=="image":
159 vim.delete_image(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200160 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200161 elif item["what"]=="flavor":
162 vim.delete_flavor(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200163 mydb.delete_row(FROM="datacenters_flavos", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200164 elif item["what"]=="network":
165 vim.delete_network(item["uuid"])
166 elif item["what"]=="vm":
167 vim.delete_vminstance(item["uuid"])
168 except vimconn.vimconnException as e:
169 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
170 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200171 except db_base_Exception as e:
172 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 +0200173
tierno7edb6752016-03-21 17:37:52 +0100174 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200175 try:
176 if item["what"]=="image":
177 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
178 elif item["what"]=="flavor":
179 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
180 except db_base_Exception as e:
181 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
182 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno7edb6752016-03-21 17:37:52 +0100183 if len(undeleted_items)==0:
184 return True," Rollback successful."
185 else:
186 return False," Rollback fails to delete: " + str(undeleted_items)
187
188def check_vnf_descriptor(vnf_descriptor):
189 global global_config
190 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
191 vnfc_interfaces={}
192 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
193 name_list = []
194 #dataplane interfaces
195 for numa in vnfc.get("numas",() ):
196 for interface in numa.get("interfaces",()):
197 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200198 raise NfvoException("Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC"\
199 .format(vnfc["name"], interface["name"]),
200 HTTP_Bad_Request)
201 name_list.append( interface["name"] )
tierno7edb6752016-03-21 17:37:52 +0100202 #bridge interfaces
203 for interface in vnfc.get("bridge-ifaces",() ):
204 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200205 raise NfvoException("Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC"\
206 .format(vnfc["name"], interface["name"]),
207 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100208 name_list.append( interface["name"] )
209 vnfc_interfaces[ vnfc["name"] ] = name_list
210
211 #check if the info in external_connections matches with the one in the vnfcs
212 name_list=[]
213 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
214 if external_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200215 raise NfvoException("Error at vnf:external-connections:name, value '{}' already used as an external-connection"\
216 .format(external_connection["name"]),
217 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100218 name_list.append(external_connection["name"])
219 if external_connection["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200220 raise NfvoException("Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC"\
221 .format(external_connection["name"], external_connection["VNFC"]),
222 HTTP_Bad_Request)
223
tierno7edb6752016-03-21 17:37:52 +0100224 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200225 raise NfvoException("Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC"\
226 .format(external_connection["name"], external_connection["local_iface_name"]),
227 HTTP_Bad_Request )
tierno7edb6752016-03-21 17:37:52 +0100228
229 #check if the info in internal_connections matches with the one in the vnfcs
230 name_list=[]
231 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
232 if internal_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200233 raise NfvoException("Error at vnf:internal-connections:name, value '%s' already used as an internal-connection"\
234 .format(internal_connection["name"]),
235 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100236 name_list.append(internal_connection["name"])
237 #We should check that internal-connections of type "ptp" have only 2 elements
238 if len(internal_connection["elements"])>2 and internal_connection["type"] == "ptp":
tiernof97fd272016-07-11 14:32:37 +0200239 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements, size must be 2 for a type:'ptp'"\
240 .format(internal_connection["name"]),
241 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100242 for port in internal_connection["elements"]:
243 if port["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200244 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC"\
245 .format(internal_connection["name"], port["VNFC"]),
246 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100247 if port["local_iface_name"] not in vnfc_interfaces[ port["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200248 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC"\
249 .format(internal_connection["name"], port["local_iface_name"]),
250 HTTP_Bad_Request)
251 return -HTTP_Bad_Request,
tierno7edb6752016-03-21 17:37:52 +0100252
253def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error = False):
254 #look if image exist
255 if only_create_at_vim:
256 image_mano_id = image_dict['uuid']
257 else:
tiernof97fd272016-07-11 14:32:37 +0200258 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
259 if len(images)>=1:
260 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100261 else:
262 #create image
263 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
264 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None)
265 }
tiernof97fd272016-07-11 14:32:37 +0200266 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
267 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100268 #create image at every vim
269 for vim_id,vim in vims.iteritems():
270 image_created="false"
271 #look at database
tiernof97fd272016-07-11 14:32:37 +0200272 image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100273 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200274 try:
275 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
276 except vimconn.vimconnNotFoundException as e:
tierno7edb6752016-03-21 17:37:52 +0100277 #Create the image in VIM
tiernoae4a8d12016-07-08 12:30:39 +0200278 try:
279 image_vim_id = vim.new_image(image_dict)
tierno7edb6752016-03-21 17:37:52 +0100280 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
281 image_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200282 except vimconn.vimconnException as e:
283 if return_on_error:
284 logger.error("Error creating image at VIM: %s", str(e))
tiernof97fd272016-07-11 14:32:37 +0200285 raise
tiernoae4a8d12016-07-08 12:30:39 +0200286 image_vim_id = str(e)
287 logger.warn("Error creating image at VIM: %s", str(e))
288 continue
289 except vimconn.vimconnException as e:
290 logger.warn("Error contacting VIM to know if the image exist at VIM: %s", str(e))
291 image_vim_id = str(e)
292 continue
tierno7edb6752016-03-21 17:37:52 +0100293 #if reach here the image has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200294 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100295 #add new vim_id at datacenters_images
296 mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created})
297 elif image_db[0]["vim_id"]!=image_vim_id:
298 #modify existing vim_id at datacenters_images
299 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
300
tiernof97fd272016-07-11 14:32:37 +0200301 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100302
303def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_vim=False, return_on_error = False):
304 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
305 'ram':flavor_dict.get('ram'),
306 'vcpus':flavor_dict.get('vcpus'),
307 }
308 if 'extended' in flavor_dict and flavor_dict['extended']==None:
309 del flavor_dict['extended']
310 if 'extended' in flavor_dict:
311 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
312
313 #look if flavor exist
314 if only_create_at_vim:
315 flavor_mano_id = flavor_dict['uuid']
316 else:
tiernof97fd272016-07-11 14:32:37 +0200317 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
318 if len(flavors)>=1:
319 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100320 else:
321 #create flavor
322 #create one by one the images of aditional disks
323 dev_image_list=[] #list of images
324 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
325 dev_nb=0
326 for device in flavor_dict['extended'].get('devices',[]):
327 if "image" not in device:
328 continue
329 image_dict={'location':device['image'], 'name':flavor_dict['name']+str(dev_nb)+"-img", 'description':flavor_dict.get('description')}
330 image_metadata_dict = device.get('image metadata', None)
331 image_metadata_str = None
332 if image_metadata_dict != None:
333 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
334 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200335 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
336 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100337 dev_image_list.append(image_id)
338 dev_nb += 1
339 temp_flavor_dict['name'] = flavor_dict['name']
340 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200341 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
342 flavor_mano_id= content
343 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100344 #create flavor at every vim
345 if 'uuid' in flavor_dict:
346 del flavor_dict['uuid']
347 flavor_vim_id=None
348 for vim_id,vim in vims.items():
349 flavor_created="false"
350 #look at database
tiernof97fd272016-07-11 14:32:37 +0200351 flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100352 #look at VIM if this flavor exist SKIPPED
353 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
354 #if res_vim < 0:
355 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
356 # continue
357 #elif res_vim==0:
358
359 #Create the flavor in VIM
360 #Translate images at devices from MANO id to VIM id
tierno7edb6752016-03-21 17:37:52 +0100361 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
362 #make a copy of original devices
363 devices_original=[]
364 for device in flavor_dict["extended"].get("devices",[]):
365 dev={}
366 dev.update(device)
367 devices_original.append(dev)
368 if 'image' in device:
369 del device['image']
370 if 'image metadata' in device:
371 del device['image metadata']
372 dev_nb=0
373 for index in range(0,len(devices_original)) :
374 device=devices_original[index]
375 if "image" not in device:
376 continue
377 image_dict={'location':device['image'], 'name':flavor_dict['name']+str(dev_nb)+"-img", 'description':flavor_dict.get('description')}
378 image_metadata_dict = device.get('image metadata', None)
379 image_metadata_str = None
380 if image_metadata_dict != None:
381 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
382 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200383 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 +0100384 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200385 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 +0100386 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
387 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200388 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100389 #check that this vim_id exist in VIM, if not create
390 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200391 try:
392 vim.get_flavor(flavor_vim_id)
393 continue #flavor exist
394 except vimconn.vimconnException:
395 pass
tierno7edb6752016-03-21 17:37:52 +0100396 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200397 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
398 try:
399 flavor_vim_id = vim.new_flavor(flavor_dict)
tierno7edb6752016-03-21 17:37:52 +0100400 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
401 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200402 except vimconn.vimconnException as e:
403 if return_on_error:
404 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200405 raise
tiernoae4a8d12016-07-08 12:30:39 +0200406 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
407 continue
tierno7edb6752016-03-21 17:37:52 +0100408 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200409 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100410 #add new vim_id at datacenters_flavors
411 mydb.new_row('datacenters_flavors', {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id, 'created':flavor_created})
412 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
413 #modify existing vim_id at datacenters_flavors
414 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
415
tiernof97fd272016-07-11 14:32:37 +0200416 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100417
418def new_vnf(mydb, tenant_id, vnf_descriptor):
419 global global_config
420
421 # Step 1. Check the VNF descriptor
tiernof97fd272016-07-11 14:32:37 +0200422 check_vnf_descriptor(vnf_descriptor)
tierno7edb6752016-03-21 17:37:52 +0100423 # Step 2. Check tenant exist
424 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200425 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100426 if "tenant_id" in vnf_descriptor["vnf"]:
427 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200428 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
429 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100430 else:
431 vnf_descriptor['vnf']['tenant_id'] = tenant_id
432 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200433 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100434 else:
435 vims={}
436
437 # Step 4. Review the descriptor and add missing fields
438 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +0200439 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +0100440 vnf_name = vnf_descriptor['vnf']['name']
441 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
442 if "physical" in vnf_descriptor['vnf']:
443 del vnf_descriptor['vnf']['physical']
444 #print vnf_descriptor
445 # Step 5. Check internal connections
446 # TODO: to be moved to step 1????
447 internal_connections=vnf_descriptor['vnf'].get('internal_connections',[])
448 for ic in internal_connections:
449 if len(ic['elements'])>2 and ic['type']=='ptp':
tiernof97fd272016-07-11 14:32:37 +0200450 raise NfvoException("Mismatch 'type':'ptp' with {} elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'data'".format(len(ic), ic['name']),
451 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100452 elif len(ic['elements'])==2 and ic['type']=='data':
tiernof97fd272016-07-11 14:32:37 +0200453 raise NfvoException("Mismatch 'type':'data' with 2 elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'ptp'".format(ic['name']),
454 HTTP_Bad_Request)
455
tierno7edb6752016-03-21 17:37:52 +0100456 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200457 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
458 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno7edb6752016-03-21 17:37:52 +0100459
460 #For each VNFC, we add it to the VNFCDict and we create a flavor.
461 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
462 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +0100463 try:
tiernof97fd272016-07-11 14:32:37 +0200464 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100465 for vnfc in vnf_descriptor['vnf']['VNFC']:
466 VNFCitem={}
467 VNFCitem["name"] = vnfc['name']
468 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
469
tiernof97fd272016-07-11 14:32:37 +0200470 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno7edb6752016-03-21 17:37:52 +0100471
472 myflavorDict = {}
473 myflavorDict["name"] = vnfc['name']+"-flv"
474 myflavorDict["description"] = VNFCitem["description"]
475 myflavorDict["ram"] = vnfc.get("ram", 0)
476 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
477 myflavorDict["disk"] = vnfc.get("disk", 1)
478 myflavorDict["extended"] = {}
479
480 devices = vnfc.get("devices")
481 if devices != None:
482 myflavorDict["extended"]["devices"] = devices
483
484 # TODO:
485 # 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
486 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
487
488 # Previous code has been commented
489 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
490 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
491 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
492 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
493 #else:
494 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
495 # if result2:
496 # print "Error creating flavor: unknown processor model. Rollback successful."
497 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
498 # else:
499 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
500 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
501
502 if 'numas' in vnfc and len(vnfc['numas'])>0:
503 myflavorDict['extended']['numas'] = vnfc['numas']
504
505 #print myflavorDict
506
507 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200508 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +0100509
tiernof97fd272016-07-11 14:32:37 +0200510 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100511 VNFCitem["flavor_id"] = flavor_id
512 VNFCDict[vnfc['name']] = VNFCitem
513
tiernof97fd272016-07-11 14:32:37 +0200514 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100515 # Step 6.3 New images are created in the VIM
516 #For each VNFC, we must create the appropriate image.
517 #This "for" loop might be integrated with the previous one
518 #In case this integration is made, the VNFCDict might become a VNFClist.
519 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +0200520 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
tierno7edb6752016-03-21 17:37:52 +0100521 image_dict={'location':vnfc['VNFC image'], 'name':vnfc['name']+"-img", 'description':VNFCDict[vnfc['name']]['description']}
522 image_metadata_dict = vnfc.get('image metadata', None)
523 image_metadata_str = None
524 if image_metadata_dict is not None:
525 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
526 image_dict['metadata']=image_metadata_str
527 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +0200528 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
529 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +0100530 VNFCDict[vnfc['name']]["image_id"] = image_id
531 VNFCDict[vnfc['name']]["image_path"] = vnfc['VNFC image']
532
tiernof97fd272016-07-11 14:32:37 +0200533
534 # Step 7. Storing the VNF descriptor in the repository
535 if "descriptor" not in vnf_descriptor["vnf"]:
536 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +0100537
tiernof97fd272016-07-11 14:32:37 +0200538 # Step 8. Adding the VNF to the NFVO DB
539 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
540 return vnf_id
541 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +0100542 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +0200543 if isinstance(e, db_base_Exception):
544 error_text = "Exception at database"
545 elif isinstance(e, KeyError):
546 error_text = "KeyError exception "
547 e.http_code = HTTP_Internal_Server_Error
548 else:
549 error_text = "Exception at VIM"
550 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
551 #logger.error("start_scenario %s", error_text)
552 raise NfvoException(error_text, e.http_code)
553
tierno7edb6752016-03-21 17:37:52 +0100554def get_vnf_id(mydb, tenant_id, vnf_id):
555 #check valid tenant_id
tiernof97fd272016-07-11 14:32:37 +0200556 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100557 #obtain data
558 where_or = {}
559 if tenant_id != "any":
560 where_or["tenant_id"] = tenant_id
561 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200562 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 +0100563
tiernof97fd272016-07-11 14:32:37 +0200564 vnf_id=vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100565 filter_keys = ('uuid','name','description','public', "tenant_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +0200566 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +0100567 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
568 data={'vnf' : filtered_content}
569 #GET VM
tiernof97fd272016-07-11 14:32:37 +0200570 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tierno7edb6752016-03-21 17:37:52 +0100571 SELECT=('vms.uuid as uuid','vms.name as name', 'vms.description as description'),
572 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200573 if len(content)==0:
574 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100575
576 data['vnf']['VNFC'] = content
577 #GET NET
tiernof97fd272016-07-11 14:32:37 +0200578 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +0100579 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
580 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200581 data['vnf']['nets'] = content
tierno7edb6752016-03-21 17:37:52 +0100582 #GET Interfaces
tiernof97fd272016-07-11 14:32:37 +0200583 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 +0100584 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
585 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
586 WHERE={'vnfs.uuid': vnf_id},
587 WHERE_NOT={'interfaces.external_name': None} )
588 #print content
tiernof97fd272016-07-11 14:32:37 +0200589 data['vnf']['external-connections'] = content
590 return data
tierno7edb6752016-03-21 17:37:52 +0100591
592
593def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
594 # Check tenant exist
595 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200596 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100597 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200598 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100599 else:
600 vims={}
601
602 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
603 where_or = {}
604 if tenant_id != "any":
605 where_or["tenant_id"] = tenant_id
606 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200607 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
608 vnf_id = vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100609
610 # "Getting the list of flavors and tenants of the VNF"
tiernof97fd272016-07-11 14:32:37 +0200611 flavorList = get_flavorlist(mydb, vnf_id)
612 if len(flavorList)==0:
613 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100614
tiernof97fd272016-07-11 14:32:37 +0200615 imageList = get_imagelist(mydb, vnf_id)
616 if len(imageList)==0:
617 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100618
tiernof97fd272016-07-11 14:32:37 +0200619 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
620 if deleted == 0:
621 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100622
623 undeletedItems = []
624 for flavor in flavorList:
625 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +0200626 try:
627 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
628 if len(c) > 0:
629 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
630 continue
631 #flavor not used, must be deleted
632 #delelte at VIM
633 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +0100634 for flavor_vim in c:
635 if flavor_vim["datacenter_id"] not in vims:
636 continue
637 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
638 continue
639 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200640 try:
641 myvim.delete_flavor(flavor_vim["vim_id"])
642 except vimconn.vimconnNotFoundException as e:
643 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
644 except vimconn.vimconnException as e:
645 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
646 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
647 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200648 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
649 mydb.delete_row_by_id('flavors', flavor)
650 except db_base_Exception as e:
651 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +0100652 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +0200653
tierno7edb6752016-03-21 17:37:52 +0100654
655 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +0200656 try:
657 #check if image is used by other vnf
658 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
659 if len(c) > 0:
660 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
661 continue
662 #image not used, must be deleted
663 #delelte at VIM
664 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +0100665 for image_vim in c:
666 if image_vim["datacenter_id"] not in vims:
667 continue
668 if image_vim['created']=='false': #skip this image because not created by openmano
669 continue
670 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200671 try:
672 myvim.delete_image(image_vim["vim_id"])
673 except vimconn.vimconnNotFoundException as e:
674 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
675 except vimconn.vimconnException as e:
676 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
677 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
678 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200679 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
680 mydb.delete_row_by_id('images', image)
681 except db_base_Exception as e:
682 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +0100683 undeletedItems.append("image %s" % image)
684
tiernof97fd272016-07-11 14:32:37 +0200685 return vnf_id + " " + vnf["name"]
686 #if undeletedItems:
687 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +0100688
689def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
690 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
691 if result < 0:
692 return result, vims
693 elif result == 0:
694 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
695 myvim = vims.values()[0]
696 result,servers = myvim.get_hosts_info()
697 if result < 0:
698 return result, servers
699 topology = {'name':myvim['name'] , 'servers': servers}
700 return result, topology
701
702def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +0200703 vims = get_vim(mydb, nfvo_tenant_id)
704 if len(vims) == 0:
705 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
706 elif len(vims)>1:
707 #print "nfvo.datacenter_action() error. Several datacenters found"
708 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +0100709 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +0200710 try:
711 hosts = myvim.get_hosts()
712 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +0100713
tiernof97fd272016-07-11 14:32:37 +0200714 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
715 for host in hosts:
716 server={'name':host['name'], 'vms':[]}
717 for vm in host['instances']:
718 #get internal name and model
719 try:
720 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
721 WHERE={'vim_vm_id':vm['id']} )
722 if len(c) == 0:
723 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
724 continue
725 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
726
727 except db_base_Exception as e:
728 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
729 datacenter['Datacenters'][0]['servers'].append(server)
730 #return -400, "en construccion"
tierno7edb6752016-03-21 17:37:52 +0100731
tiernof97fd272016-07-11 14:32:37 +0200732 #print 'datacenters '+ json.dumps(datacenter, indent=4)
733 return datacenter
734 except vimconn.vimconnException as e:
735 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +0100736
737def new_scenario(mydb, tenant_id, topo):
738
739# result, vims = get_vim(mydb, tenant_id)
740# if result < 0:
741# return result, vims
742#1: parse input
743 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200744 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100745 if "tenant_id" in topo:
746 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200747 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
748 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100749 else:
750 tenant_id=None
751
752#1.1: get VNFs and external_networks (other_nets).
753 vnfs={}
754 other_nets={} #external_networks, bridge_networks and data_networkds
755 nodes = topo['topology']['nodes']
756 for k in nodes.keys():
757 if nodes[k]['type'] == 'VNF':
758 vnfs[k] = nodes[k]
759 vnfs[k]['ifaces'] = {}
760 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
761 other_nets[k] = nodes[k]
762 other_nets[k]['external']=True
763 elif nodes[k]['type'] == 'network':
764 other_nets[k] = nodes[k]
765 other_nets[k]['external']=False
766
767
768#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
769 for name,vnf in vnfs.items():
tiernocea279c2016-07-18 12:36:49 +0200770 where={}
771 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +0100772 error_text = ""
773 error_pos = "'topology':'nodes':'" + name + "'"
774 if 'vnf_id' in vnf:
775 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +0200776 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +0100777 if 'VNF model' in vnf:
778 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +0200779 where['name'] = vnf['VNF model']
780 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +0200781 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
782
tiernocea279c2016-07-18 12:36:49 +0200783 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
784 FROM='vnfs',
785 WHERE=where,
786 WHERE_OR=where_or,
787 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +0200788 if len(vnf_db)==0:
789 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
790 elif len(vnf_db)>1:
791 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +0100792 vnf['uuid']=vnf_db[0]['uuid']
793 vnf['description']=vnf_db[0]['description']
794 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +0200795 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 +0100796 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
797 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +0100798 for ext_iface in ext_ifaces:
799 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
800
801#1.4 get list of connections
802 conections = topo['topology']['connections']
803 conections_list = []
804 for k in conections.keys():
805 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
806 ifaces_list = conections[k]['nodes'].items()
807 elif type(conections[k]['nodes'])==list: #list with dictionary
808 ifaces_list=[]
809 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
810 for k2 in conection_pair_list:
811 ifaces_list += k2
812
813 con_type = conections[k].get("type", "link")
814 if con_type != "link":
815 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +0200816 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100817 other_nets[k] = {'external': False}
818 if conections[k].get("graph"):
819 other_nets[k]["graph"] = conections[k]["graph"]
820 ifaces_list.append( (k, None) )
821
822
823 if con_type == "external_network":
824 other_nets[k]['external'] = True
825 if conections[k].get("model"):
826 other_nets[k]["model"] = conections[k]["model"]
827 else:
828 other_nets[k]["model"] = k
829 if con_type == "dataplane_net" or con_type == "bridge_net":
830 other_nets[k]["model"] = con_type
831
832
833 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)
834 #print set(ifaces_list)
835 #check valid VNF and iface names
836 for iface in ifaces_list:
837 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +0200838 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
839 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100840 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +0200841 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
842 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100843
844#1.5 unify connections from the pair list to a consolidated list
845 index=0
846 while index < len(conections_list):
847 index2 = index+1
848 while index2 < len(conections_list):
849 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
850 conections_list[index] |= conections_list[index2]
851 del conections_list[index2]
852 else:
853 index2 += 1
854 conections_list[index] = list(conections_list[index]) # from set to list again
855 index += 1
856 #for k in conections_list:
857 # print k
858
859
860
861#1.6 Delete non external nets
862# for k in other_nets.keys():
863# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
864# for con in conections_list:
865# delete_indexes=[]
866# for index in range(0,len(con)):
867# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
868# for index in delete_indexes:
869# del con[index]
870# del other_nets[k]
871#1.7: Check external_ports are present at database table datacenter_nets
872 for k,net in other_nets.items():
873 error_pos = "'topology':'nodes':'" + k + "'"
874 if net['external']==False:
875 if 'name' not in net:
876 net['name']=k
877 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +0200878 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100879 if net['model']=='bridge_net':
880 net['type']='bridge';
881 elif net['model']=='dataplane_net':
882 net['type']='data';
883 else:
tiernof97fd272016-07-11 14:32:37 +0200884 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100885 else: #external
886#IF we do not want to check that external network exist at datacenter
887 pass
888#ELSE
889# error_text = ""
890# WHERE_={}
891# if 'net_id' in net:
892# error_text += " 'net_id' " + net['net_id']
893# WHERE_['uuid'] = net['net_id']
894# if 'model' in net:
895# error_text += " 'model' " + net['model']
896# WHERE_['name'] = net['model']
897# if len(WHERE_) == 0:
898# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
899# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
900# FROM='datacenter_nets', WHERE=WHERE_ )
901# if r<0:
902# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
903# elif r==0:
904# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
905# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
906# elif r>1:
907# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
908# return -HTTP_Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
909# other_nets[k].update(net_db[0])
910#ENDIF
911 net_list={}
912 net_nb=0 #Number of nets
913 for con in conections_list:
914 #check if this is connected to a external net
915 other_net_index=-1
916 #print
917 #print "con", con
918 for index in range(0,len(con)):
919 #check if this is connected to a external net
920 for net_key in other_nets.keys():
921 if con[index][0]==net_key:
922 if other_net_index>=0:
923 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 +0200924 #print "nfvo.new_scenario " + error_text
925 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100926 else:
927 other_net_index = index
928 net_target = net_key
929 break
930 #print "other_net_index", other_net_index
931 try:
932 if other_net_index>=0:
933 del con[other_net_index]
934#IF we do not want to check that external network exist at datacenter
935 if other_nets[net_target]['external'] :
936 if "name" not in other_nets[net_target]:
937 other_nets[net_target]['name'] = other_nets[net_target]['model']
938 if other_nets[net_target]["type"] == "external_network":
939 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
940 other_nets[net_target]["type"] = "data"
941 else:
942 other_nets[net_target]["type"] = "bridge"
943#ELSE
944# if other_nets[net_target]['external'] :
945# 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
946# if type_=='data' and other_nets[net_target]['type']=="ptp":
947# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
948# print "nfvo.new_scenario " + error_text
949# return -HTTP_Bad_Request, error_text
950#ENDIF
951 for iface in con:
952 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
953 else:
954 #create a net
955 net_type_bridge=False
956 net_type_data=False
957 net_target = "__-__net"+str(net_nb)
958 net_list[net_target] = {'name': "net-"+str(net_nb), 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
959 'external':False}
960 for iface in con:
961 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
962 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
963 if iface_type=='mgmt' or iface_type=='bridge':
964 net_type_bridge = True
965 else:
966 net_type_data = True
967 if net_type_bridge and net_type_data:
968 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 +0200969 #print "nfvo.new_scenario " + error_text
970 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100971 elif net_type_bridge:
972 type_='bridge'
973 else:
974 type_='data' if len(con)>2 else 'ptp'
975 net_list[net_target]['type'] = type_
976 net_nb+=1
977 except Exception:
978 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +0200979 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +0100980 #raise e
tiernof97fd272016-07-11 14:32:37 +0200981 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100982
983#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
984 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +0200985 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +0100986 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
987 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +0200988 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +0100989 add_mgmt_net = False
990 for vnf in vnfs.values():
991 for iface in vnf['ifaces'].values():
992 if iface['type']=='mgmt' and 'net_key' not in iface:
993 #iface not connected
994 iface['net_key'] = 'mgmt'
995 add_mgmt_net = True
996 if add_mgmt_net and 'mgmt' not in net_list:
997 net_list['mgmt']=mgmt_net[0]
998 net_list['mgmt']['external']=True
999 net_list['mgmt']['graph']={'visible':False}
1000
1001 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001002 #print
1003 #print 'net_list', net_list
1004 #print
1005 #print 'vnfs', vnfs
1006 #print
tierno7edb6752016-03-21 17:37:52 +01001007
1008#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001009 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001010 'tenant_id':tenant_id, 'name':topo['name'],
1011 'description':topo.get('description',topo['name']),
1012 'public': topo.get('public', False)
1013 })
tierno7edb6752016-03-21 17:37:52 +01001014
tiernof97fd272016-07-11 14:32:37 +02001015 return c
tierno7edb6752016-03-21 17:37:52 +01001016
tierno392f2852016-05-13 12:28:55 +02001017def new_scenario_v02(mydb, tenant_id, scenario_dict):
1018 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001019 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001020 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001021 if "tenant_id" in scenario:
1022 if scenario["tenant_id"] != tenant_id:
1023 print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001024 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1025 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001026 else:
1027 tenant_id=None
1028
1029#1: Check that VNF are present at database table vnfs and update content into scenario dict
1030 for name,vnf in scenario["vnfs"].iteritems():
tiernocea279c2016-07-18 12:36:49 +02001031 where={}
1032 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001033 error_text = ""
1034 error_pos = "'topology':'nodes':'" + name + "'"
1035 if 'vnf_id' in vnf:
1036 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001037 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001038 if 'vnf_name' in vnf:
1039 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001040 where['name'] = vnf['vnf_name']
1041 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +02001042 raise NfvoException("Needed a 'vnf_id' or 'VNF model' at " + error_pos, HTTP_Bad_Request)
tiernocea279c2016-07-18 12:36:49 +02001043 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1044 FROM='vnfs',
1045 WHERE=where,
1046 WHERE_OR=where_or,
1047 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001048 if len(vnf_db)==0:
1049 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1050 elif len(vnf_db)>1:
1051 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001052 vnf['uuid']=vnf_db[0]['uuid']
1053 vnf['description']=vnf_db[0]['description']
1054 vnf['ifaces'] = {}
1055 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +02001056 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 +01001057 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1058 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001059 for ext_iface in ext_ifaces:
1060 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1061
1062#2: Insert net_key at every vnf interface
1063 for net_name,net in scenario["networks"].iteritems():
1064 net_type_bridge=False
1065 net_type_data=False
1066 for iface_dict in net["interfaces"]:
1067 for vnf,iface in iface_dict.iteritems():
1068 if vnf not in scenario["vnfs"]:
1069 error_text = "Error at 'networks':'%s':'interfaces' VNF '%s' not match any VNF at 'vnfs'" % (net_name, vnf)
tiernof97fd272016-07-11 14:32:37 +02001070 #print "nfvo.new_scenario_v02 " + error_text
1071 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001072 if iface not in scenario["vnfs"][vnf]['ifaces']:
1073 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface not match any VNF interface" % (net_name, iface)
tiernof97fd272016-07-11 14:32:37 +02001074 #print "nfvo.new_scenario_v02 " + error_text
1075 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001076 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
1077 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface already connected at network '%s'" \
1078 % (net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
tiernof97fd272016-07-11 14:32:37 +02001079 #print "nfvo.new_scenario_v02 " + error_text
1080 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001081 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
1082 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
1083 if iface_type=='mgmt' or iface_type=='bridge':
1084 net_type_bridge = True
1085 else:
1086 net_type_data = True
1087 if net_type_bridge and net_type_data:
1088 error_text = "Error connection interfaces of bridge type and data type at 'networks':'%s':'interfaces'" % (net_name)
tiernof97fd272016-07-11 14:32:37 +02001089 #print "nfvo.new_scenario " + error_text
1090 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001091 elif net_type_bridge:
1092 type_='bridge'
1093 else:
1094 type_='data' if len(net["interfaces"])>2 else 'ptp'
1095 net['type'] = type_
1096 net['name'] = net_name
1097 net['external'] = net.get('external', False)
1098
1099#3: insert at database
1100 scenario["nets"] = scenario["networks"]
1101 scenario['tenant_id'] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001102 scenario_id = mydb.new_scenario( scenario)
1103 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01001104
1105def edit_scenario(mydb, tenant_id, scenario_id, data):
1106 data["uuid"] = scenario_id
1107 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001108 c = mydb.edit_scenario( data )
1109 return c
tierno7edb6752016-03-21 17:37:52 +01001110
1111def 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 +02001112 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01001113 datacenter_id = None
1114 datacenter_name=None
1115 if datacenter != None:
tierno42fcc3b2016-07-06 17:20:40 +02001116 if utils.check_valid_uuid(datacenter):
tierno7edb6752016-03-21 17:37:52 +01001117 datacenter_id = datacenter
1118 else:
1119 datacenter_name = datacenter
tiernof97fd272016-07-11 14:32:37 +02001120 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, vim_tenant)
1121 if len(vims) == 0:
1122 raise NfvoException("datacenter '{}' not found".format(datacenter), HTTP_Not_Found)
1123 elif len(vims)>1:
1124 #logger.error("nfvo.datacenter_new_netmap() error. Several datacenters found")
1125 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001126 myvim = vims.values()[0]
tierno392f2852016-05-13 12:28:55 +02001127 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001128 datacenter_id = myvim['id']
1129 datacenter_name = myvim['name']
1130 datacenter_tenant_id = myvim['config']['datacenter_tenant_id']
1131 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001132 try:
1133 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tiernof97fd272016-07-11 14:32:37 +02001134 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id)
tiernoae4a8d12016-07-08 12:30:39 +02001135 scenarioDict['datacenter_tenant_id'] = datacenter_tenant_id
1136 scenarioDict['datacenter_id'] = datacenter_id
1137 #print '================scenarioDict======================='
1138 #print json.dumps(scenarioDict, indent=4)
1139 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno7edb6752016-03-21 17:37:52 +01001140
tiernoae4a8d12016-07-08 12:30:39 +02001141 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
1142 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001143
tiernoae4a8d12016-07-08 12:30:39 +02001144 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1145 auxNetDict['scenario'] = {}
1146
1147 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
1148 for sce_net in scenarioDict['nets']:
1149 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno7edb6752016-03-21 17:37:52 +01001150
tiernoae4a8d12016-07-08 12:30:39 +02001151 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01001152 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02001153 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01001154 myNetDict = {}
1155 myNetDict["name"] = myNetName
1156 myNetDict["type"] = myNetType
1157 myNetDict["tenant_id"] = myvim_tenant
tierno7edb6752016-03-21 17:37:52 +01001158 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02001159 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001160 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02001161 if not sce_net["external"]:
1162 network_id = myvim.new_network(myNetName, myNetType)
1163 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
1164 sce_net['vim_id'] = network_id
1165 auxNetDict['scenario'][sce_net['uuid']] = network_id
1166 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
1167 else:
1168 if sce_net['vim_id'] == None:
1169 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
1170 _, message = rollback(mydb, vims, rollbackList)
1171 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02001172 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02001173 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
1174 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno7edb6752016-03-21 17:37:52 +01001175
tiernoae4a8d12016-07-08 12:30:39 +02001176 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
1177 #For each vnf net, we create it and we add it to instanceNetlist.
1178 for sce_vnf in scenarioDict['vnfs']:
1179 for net in sce_vnf['nets']:
1180 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
1181
1182 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
1183 myNetName = myNetName[0:255] #limit length
1184 myNetType = net['type']
1185 myNetDict = {}
1186 myNetDict["name"] = myNetName
1187 myNetDict["type"] = myNetType
1188 myNetDict["tenant_id"] = myvim_tenant
1189 #print myNetDict
1190 #TODO:
1191 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001192 network_id = myvim.new_network(myNetName, myNetType)
tiernoae4a8d12016-07-08 12:30:39 +02001193 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
1194 net['vim_id'] = network_id
1195 if sce_vnf['uuid'] not in auxNetDict:
1196 auxNetDict[sce_vnf['uuid']] = {}
1197 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1198 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
1199
1200 #print "auxNetDict:"
1201 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
1202
1203 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
1204 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
1205 i = 0
1206 for sce_vnf in scenarioDict['vnfs']:
1207 for vm in sce_vnf['vms']:
1208 i += 1
1209 myVMDict = {}
1210 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
1211 myVMDict['name'] = "%s.%s.%d" % (instance_scenario_name,sce_vnf['name'],i)
1212 #myVMDict['description'] = vm['description']
1213 myVMDict['description'] = myVMDict['name'][0:99]
1214 if not startvms:
1215 myVMDict['start'] = "no"
1216 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1217 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
1218
1219 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001220 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
1221 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001222 vm['vim_image_id'] = image_id
1223
1224 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001225 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001226 if flavor_dict['extended']!=None:
1227 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tiernof97fd272016-07-11 14:32:37 +02001228 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001229 vm['vim_flavor_id'] = flavor_id
1230
1231
1232 myVMDict['imageRef'] = vm['vim_image_id']
1233 myVMDict['flavorRef'] = vm['vim_flavor_id']
1234 myVMDict['networks'] = []
1235 for iface in vm['interfaces']:
1236 netDict = {}
1237 if iface['type']=="data":
1238 netDict['type'] = iface['model']
1239 elif "model" in iface and iface["model"]!=None:
1240 netDict['model']=iface['model']
1241 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1242 #discover type of interface looking at flavor
1243 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1244 for flavor_iface in numa.get('interfaces',[]):
1245 if flavor_iface.get('name') == iface['internal_name']:
1246 if flavor_iface['dedicated'] == 'yes':
1247 netDict['type']="PF" #passthrough
1248 elif flavor_iface['dedicated'] == 'no':
1249 netDict['type']="VF" #siov
1250 elif flavor_iface['dedicated'] == 'yes:sriov':
1251 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1252 netDict["mac_address"] = flavor_iface.get("mac_address")
1253 break;
1254 netDict["use"]=iface['type']
1255 if netDict["use"]=="data" and not netDict.get("type"):
1256 #print "netDict", netDict
1257 #print "iface", iface
1258 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'])
1259 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02001260 raise NfvoException(e_text + "After database migration some information is not available. \
1261 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02001262 else:
tiernof97fd272016-07-11 14:32:37 +02001263 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02001264 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1265 netDict["type"]="virtual"
1266 if "vpci" in iface and iface["vpci"] is not None:
1267 netDict['vpci'] = iface['vpci']
1268 if "mac" in iface and iface["mac"] is not None:
1269 netDict['mac_address'] = iface['mac']
1270 netDict['name'] = iface['internal_name']
1271 if iface['net_id'] is None:
1272 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001273 #print iface
1274 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02001275 if vnf_iface['interface_id']==iface['uuid']:
1276 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
1277 break
1278 else:
1279 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1280 #skip bridge ifaces not connected to any net
1281 #if 'net_id' not in netDict or netDict['net_id']==None:
1282 # continue
1283 myVMDict['networks'].append(netDict)
1284 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1285 #print myVMDict['name']
1286 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1287 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1288 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1289 vm_id = myvim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
1290 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'])
1291 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
1292 vm['vim_id'] = vm_id
1293 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1294 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1295 for net in myVMDict['networks']:
1296 if "vim_id" in net:
1297 for iface in vm['interfaces']:
1298 if net["name"]==iface["internal_name"]:
1299 iface["vim_id"]=net["vim_id"]
1300 break
1301
1302 logger.debug("start scenario Deployment done")
1303 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
1304 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001305 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
1306 return mydb.get_instance_scenario(instance_id)
1307
1308 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001309 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001310 if isinstance(e, db_base_Exception):
1311 error_text = "Exception at database"
1312 else:
1313 error_text = "Exception at VIM"
1314 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1315 #logger.error("start_scenario %s", error_text)
1316 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001317
tiernoa4e1a6e2016-08-31 14:19:40 +02001318
1319def unify_cloud_config(cloud_config):
1320 index_to_delete = []
1321 users = cloud_config.get("users", [])
1322 for index0 in range(0,len(users)):
1323 if index0 in index_to_delete:
1324 continue
1325 for index1 in range(index0+1,len(users)):
1326 if index1 in index_to_delete:
1327 continue
1328 if users[index0]["name"] == users[index1]["name"]:
1329 index_to_delete.append(index1)
1330 for key in users[index1].get("key-pairs",()):
1331 if "key-pairs" not in users[index0]:
1332 users[index0]["key-pairs"] = [key]
1333 elif key not in users[index0]["key-pairs"]:
1334 users[index0]["key-pairs"].append(key)
1335 index_to_delete.sort(reverse=True)
1336 for index in index_to_delete:
1337 del users[index]
1338
tiernobe41e222016-09-02 15:16:13 +02001339def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None):
1340 datacenter_id = None
1341 datacenter_name = None
1342 if datacenter_id_name:
1343 if utils.check_valid_uuid(datacenter_id_name):
1344 datacenter_id = datacenter_id_name
1345 else:
1346 datacenter_name = datacenter_id_name
1347 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, vim_tenant=None)
1348 if len(vims) == 0:
1349 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1350 elif len(vims)>1:
1351 #print "nfvo.datacenter_action() error. Several datacenters found"
1352 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1353 return vims.keys()[0], vims.values()[0]
1354
tierno7edb6752016-03-21 17:37:52 +01001355def create_instance(mydb, tenant_id, instance_dict):
tiernoae4a8d12016-07-08 12:30:39 +02001356 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
garciadeblas0c317ee2016-08-29 12:33:06 +02001357 logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01001358 scenario = instance_dict["scenario"]
tiernobe41e222016-09-02 15:16:13 +02001359
1360 #find main datacenter
1361 myvims = {}
tierno7edb6752016-03-21 17:37:52 +01001362 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02001363 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
1364 myvims[default_datacenter_id] = vim
tierno392f2852016-05-13 12:28:55 +02001365 #myvim_tenant = myvim['tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001366# default_datacenter_name = vim['name']
1367 default_datacenter_tenant_id = vim['config']['datacenter_tenant_id'] #TODO revisar
tierno7edb6752016-03-21 17:37:52 +01001368 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001369
1370 #print "Checking that the scenario exists and getting the scenario dictionary"
tiernobe41e222016-09-02 15:16:13 +02001371 scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id)
1372 scenarioDict['datacenter_tenant_id'] = default_datacenter_tenant_id
1373 scenarioDict['datacenter_id'] = default_datacenter_id
tiernof97fd272016-07-11 14:32:37 +02001374
tierno7edb6752016-03-21 17:37:52 +01001375 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1376 auxNetDict['scenario'] = {}
1377
tiernobe41e222016-09-02 15:16:13 +02001378 print "scenario dict: ",yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False) #TODO quitar
tierno7edb6752016-03-21 17:37:52 +01001379 instance_name = instance_dict["name"]
1380 instance_description = instance_dict.get("description")
1381 try:
1382 #0 check correct parameters
tiernobe41e222016-09-02 15:16:13 +02001383 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001384 found=False
1385 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001386 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01001387 found = True
1388 break
1389 if not found:
tiernobe41e222016-09-02 15:16:13 +02001390 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request)
1391 if "sites" not in net_instance_desc:
1392 net_instance_desc["sites"] = [ {} ]
1393 site_without_datacenter_field = False
1394 for site in net_instance_desc["sites"]:
1395 if site.get("datacenter"):
1396 if site["datacenter"] not in myvims:
1397 #Add this datacenter to myvims
1398 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
1399 myvims[d] = v
1400 site["datacenter"] = d #change name to id
1401 else:
1402 if site_without_datacenter_field:
1403 raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
1404 site_without_datacenter_field = True
1405 site["datacenter"] = default_datacenter_id #change name to id
1406
1407 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001408 found=False
1409 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001410 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01001411 found = True
1412 break
1413 if not found:
tiernobe41e222016-09-02 15:16:13 +02001414 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
1415 if "datacenter" in vnf_instance_desc:
1416 #Add this datacenter to myvims
1417 if vnf_instance_desc["datacenter"] not in myvims:
1418 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
1419 myvims[d] = v
1420 scenario_vnf["datacenter"] = d #change name to id
tiernoa4e1a6e2016-08-31 14:19:40 +02001421 #0.1 parse cloud-config parameters
1422 cloud_config = scenarioDict.get("cloud-config", {})
1423 if instance_dict.get("cloud-config"):
1424 cloud_config.update( instance_dict["cloud-config"])
1425 if not cloud_config:
1426 cloud_config = None
1427 else:
1428 scenarioDict["cloud-config"] = cloud_config
1429 unify_cloud_config(cloud_config)
tierno7edb6752016-03-21 17:37:52 +01001430
1431 #1. Creating new nets (sce_nets) in the VIM"
1432 for sce_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001433 sce_net["vim_id_sites"]={}
tierno7edb6752016-03-21 17:37:52 +01001434 descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{})
tiernobe41e222016-09-02 15:16:13 +02001435 net_name = descriptor_net.get("vim-network-name")
1436 auxNetDict['scenario'][sce_net['uuid']] = {}
1437
1438 sites = descriptor_net.get("sites", [ {} ])
1439 for site in sites:
1440 if site.get("datacenter"):
1441 vim = myvims[ site["datacenter"] ]
1442 datacenter_id = site["datacenter"]
tierno7edb6752016-03-21 17:37:52 +01001443 else:
tiernobe41e222016-09-02 15:16:13 +02001444 vim = myvims[ default_datacenter_id ]
1445 datacenter_id = default_datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001446
tiernobe41e222016-09-02 15:16:13 +02001447 net_type = sce_net['type']
1448 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True
1449 if sce_net["external"]:
1450 if not net_name:
1451 net_name = sce_net["name"]
1452 if "netmap-use" in site or "netmap-create" in site:
1453 create_network = False
1454 lookfor_network = False
1455 if "netmap-use" in site:
1456 lookfor_network = True
1457 if utils.check_valid_uuid(site["netmap-use"]):
1458 filter_text = "scenario id '%s'" % site["netmap-use"]
1459 lookfor_filter["id"] = site["netmap-use"]
1460 else:
1461 filter_text = "scenario name '%s'" % site["netmap-use"]
1462 lookfor_filter["name"] = site["netmap-use"]
1463 if "netmap-create" in site:
1464 create_network = True
1465 net_vim_name = net_name
1466 if site["netmap-create"]:
1467 net_vim_name = site["netmap-create"]
1468
1469 elif sce_net['vim_id'] != None:
1470 #there is a netmap at datacenter_nets database #TODO REVISE!!!!
1471 create_network = False
1472 lookfor_network = True
1473 lookfor_filter["id"] = sce_net['vim_id']
1474 filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"])
1475 #look for network at datacenter and return error
1476 else:
1477 #There is not a netmap, look at datacenter for a net with this name and create if not found
1478 create_network = True
1479 lookfor_network = True
1480 lookfor_filter["name"] = sce_net["name"]
1481 net_vim_name = sce_net["name"]
1482 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01001483 else:
tiernobe41e222016-09-02 15:16:13 +02001484 if not net_name:
1485 net_name = "%s.%s" %(instance_name, sce_net["name"])
1486 net_name = net_name[:255] #limit length
1487 net_vim_name = net_name
1488 create_network = True
1489 lookfor_network = False
1490
1491 if lookfor_network:
1492 vim_nets = vim.get_network_list(filter_dict=lookfor_filter)
1493 if len(vim_nets) > 1:
1494 raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1495 elif len(vim_nets) == 0:
1496 if not create_network:
1497 raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1498 else:
1499 sce_net["vim_id_sites"][datacenter_id] = vim_nets[0]['id']
1500
1501 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id']
1502 create_network = False
1503 if create_network:
1504 #if network is not external
1505 network_id = vim.new_network(net_vim_name, net_type)
1506 sce_net["vim_id_sites"][datacenter_id] = network_id
1507 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = network_id
1508 rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':network_id})
tierno7edb6752016-03-21 17:37:52 +01001509
1510 #2. Creating new nets (vnf internal nets) in the VIM"
1511 #For each vnf net, we create it and we add it to instanceNetlist.
1512 for sce_vnf in scenarioDict['vnfs']:
1513 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02001514 if sce_vnf.get("datacenter"):
1515 vim = myvims[ sce_vnf["datacenter"] ]
1516 datacenter_id = sce_vnf["datacenter"]
1517 else:
1518 vim = myvims[ default_datacenter_id ]
1519 datacenter_id = default_datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001520 descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{})
1521 net_name = descriptor_net.get("name")
1522 if not net_name:
1523 net_name = "%s.%s" %(instance_name, net["name"])
1524 net_name = net_name[:255] #limit length
1525 net_type = net['type']
tiernobe41e222016-09-02 15:16:13 +02001526 network_id = vim.new_network(net_name, net_type)
tierno7edb6752016-03-21 17:37:52 +01001527 net['vim_id'] = network_id
1528 if sce_vnf['uuid'] not in auxNetDict:
1529 auxNetDict[sce_vnf['uuid']] = {}
1530 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1531 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
1532
tiernoae4a8d12016-07-08 12:30:39 +02001533 #print "auxNetDict:"
1534 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001535
1536 #3. Creating new vm instances in the VIM
tiernoae4a8d12016-07-08 12:30:39 +02001537 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
tierno7edb6752016-03-21 17:37:52 +01001538 for sce_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001539 if sce_vnf.get("datacenter"):
1540 vim = myvims[ sce_vnf["datacenter"] ]
1541 datacenter_id = sce_vnf["datacenter"]
1542 else:
1543 vim = myvims[ default_datacenter_id ]
1544 datacenter_id = default_datacenter_id
1545 sce_vnf["datacenter_id"] = datacenter_id
1546 sce_vnf["datacenter_tenant_id"] = vim['config']['datacenter_tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001547 i = 0
1548 for vm in sce_vnf['vms']:
1549 i += 1
1550 myVMDict = {}
1551 myVMDict['name'] = "%s.%s.%d" % (instance_name,sce_vnf['name'],i)
1552 myVMDict['description'] = myVMDict['name'][0:99]
1553# if not startvms:
1554# myVMDict['start'] = "no"
1555 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1556 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001557 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tiernobe41e222016-09-02 15:16:13 +02001558 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01001559 vm['vim_image_id'] = image_id
1560
1561 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001562 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01001563 if flavor_dict['extended']!=None:
1564 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tiernobe41e222016-09-02 15:16:13 +02001565 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
tierno7edb6752016-03-21 17:37:52 +01001566 vm['vim_flavor_id'] = flavor_id
1567
1568 myVMDict['imageRef'] = vm['vim_image_id']
1569 myVMDict['flavorRef'] = vm['vim_flavor_id']
1570 myVMDict['networks'] = []
1571#TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
1572 for iface in vm['interfaces']:
1573 netDict = {}
1574 if iface['type']=="data":
1575 netDict['type'] = iface['model']
1576 elif "model" in iface and iface["model"]!=None:
1577 netDict['model']=iface['model']
1578 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1579 #discover type of interface looking at flavor
1580 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1581 for flavor_iface in numa.get('interfaces',[]):
1582 if flavor_iface.get('name') == iface['internal_name']:
1583 if flavor_iface['dedicated'] == 'yes':
1584 netDict['type']="PF" #passthrough
1585 elif flavor_iface['dedicated'] == 'no':
1586 netDict['type']="VF" #siov
1587 elif flavor_iface['dedicated'] == 'yes:sriov':
1588 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1589 netDict["mac_address"] = flavor_iface.get("mac_address")
1590 break;
1591 netDict["use"]=iface['type']
1592 if netDict["use"]=="data" and not netDict.get("type"):
1593 #print "netDict", netDict
1594 #print "iface", iface
1595 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'])
1596 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02001597 raise NfvoException(e_text + "After database migration some information is not available. \
1598 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001599 else:
tiernoae4a8d12016-07-08 12:30:39 +02001600 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01001601 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1602 netDict["type"]="virtual"
1603 if "vpci" in iface and iface["vpci"] is not None:
1604 netDict['vpci'] = iface['vpci']
1605 if "mac" in iface and iface["mac"] is not None:
1606 netDict['mac_address'] = iface['mac']
1607 netDict['name'] = iface['internal_name']
1608 if iface['net_id'] is None:
1609 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001610 #print iface
1611 #print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01001612 if vnf_iface['interface_id']==iface['uuid']:
tiernobe41e222016-09-02 15:16:13 +02001613 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01001614 break
1615 else:
1616 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1617 #skip bridge ifaces not connected to any net
1618 #if 'net_id' not in netDict or netDict['net_id']==None:
1619 # continue
1620 myVMDict['networks'].append(netDict)
tiernoae4a8d12016-07-08 12:30:39 +02001621 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1622 #print myVMDict['name']
1623 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1624 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1625 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tiernobe41e222016-09-02 15:16:13 +02001626 vm_id = vim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
tiernoa4e1a6e2016-08-31 14:19:40 +02001627 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'], cloud_config = cloud_config)
tierno7edb6752016-03-21 17:37:52 +01001628 vm['vim_id'] = vm_id
1629 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1630 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1631 for net in myVMDict['networks']:
1632 if "vim_id" in net:
1633 for iface in vm['interfaces']:
1634 if net["name"]==iface["internal_name"]:
1635 iface["vim_id"]=net["vim_id"]
1636 break
tiernoae4a8d12016-07-08 12:30:39 +02001637 logger.debug("create_instance Deployment done")
tiernobe41e222016-09-02 15:16:13 +02001638 print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001639 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001640 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_name, instance_description, scenarioDict)
1641 return mydb.get_instance_scenario(instance_id)
1642 except (NfvoException, vimconn.vimconnException,db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02001643 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001644 if isinstance(e, db_base_Exception):
1645 error_text = "database Exception"
1646 elif isinstance(e, vimconn.vimconnException):
1647 error_text = "VIM Exception"
1648 else:
1649 error_text = "Exception"
1650 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1651 #logger.error("create_instance: %s", error_text)
1652 raise NfvoException(error_text, e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02001653
tierno7edb6752016-03-21 17:37:52 +01001654def delete_instance(mydb, tenant_id, instance_id):
tiernoae4a8d12016-07-08 12:30:39 +02001655 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02001656 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +02001657 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001658 tenant_id = instanceDict["tenant_id"]
tiernoae4a8d12016-07-08 12:30:39 +02001659 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02001660 try:
1661 vims = get_vim(mydb, tenant_id, instanceDict['datacenter_id'])
1662 if len(vims) == 0:
1663 logger.error("!!!!!! nfvo.delete_instance() datacenter not found!!!!")
1664 myvim = None
1665 else:
1666 myvim = vims.values()[0]
1667 except NfvoException as e:
1668 logger.error("!!!!!! nfvo.delete_instance() datacenter Exception!!!! " + str(e))
tierno7edb6752016-03-21 17:37:52 +01001669 myvim = None
tierno7edb6752016-03-21 17:37:52 +01001670
1671
1672 #1. Delete from Database
1673
tiernof97fd272016-07-11 14:32:37 +02001674 #result,c = mydb.delete_row_by_id('instance_scenarios', instance_id, nfvo_tenant)
1675 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001676
1677 #2. delete from VIM
1678 if not myvim:
1679 error_msg = "Not possible to delete VIM VMs and networks. Datacenter not found at database!!!"
1680 else:
1681 error_msg = ""
1682
1683 #2.1 deleting VMs
1684 #vm_fail_list=[]
1685 for sce_vnf in instanceDict['vnfs']:
1686 if not myvim:
1687 continue
1688 for vm in sce_vnf['vms']:
tiernoae4a8d12016-07-08 12:30:39 +02001689 try:
1690 myvim.delete_vminstance(vm['vim_vm_id'])
1691 except vimconn.vimconnNotFoundException as e:
1692 error_msg+="\n VM id={} not found at VIM".format(vm['vim_vm_id'])
1693 logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found",
1694 vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'])
1695 except vimconn.vimconnException as e:
1696 error_msg+="\n Error: " + e.http_code + " VM id=" + vm['vim_vm_id']
1697 logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s': %s",
1698 e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e))
tierno7edb6752016-03-21 17:37:52 +01001699
1700 #2.2 deleting NETS
1701 #net_fail_list=[]
1702 for net in instanceDict['nets']:
1703 if net['external']:
1704 continue #skip not created nets
1705 if not myvim:
1706 continue
tiernoae4a8d12016-07-08 12:30:39 +02001707 try:
1708 myvim.delete_network(net['vim_net_id'])
1709 except vimconn.vimconnNotFoundException as e:
1710 error_msg+="\n NET id={} not found at VIM".format(net['vim_net_id'])
1711 logger.warn("NET '%s', VIM id '%s', from VNF_id '%s' not found",
tiernobe41e222016-09-02 15:16:13 +02001712 net['uuid'], net['vim_net_id'], sce_vnf['vnf_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001713 except vimconn.vimconnException as e:
1714 error_msg+="\n Error: " + e.http_code + " Net id=" + net['vim_vm_id']
1715 logger.error("Error %d deleting NET '%s', VIM id '%s', from VNF_id '%s': %s",
1716 e.http_code, net['uuid'], net['vim_net_id'], sce_vnf['vnf_id'], str(e))
tierno7edb6752016-03-21 17:37:52 +01001717 if len(error_msg)>0:
tiernof97fd272016-07-11 14:32:37 +02001718 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 +01001719 else:
tiernof97fd272016-07-11 14:32:37 +02001720 return 'instance ' + message + ' deleted'
tierno7edb6752016-03-21 17:37:52 +01001721
1722def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
1723 '''Refreshes a scenario instance. It modifies instanceDict'''
1724 '''Returns:
1725 - 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
1726 - error_msg
1727 '''
1728 # Assumption: nfvo_tenant and instance_id were checked before entering into this function
tiernoae4a8d12016-07-08 12:30:39 +02001729 #print "nfvo.refresh_instance begins"
tierno7edb6752016-03-21 17:37:52 +01001730 #print json.dumps(instanceDict, indent=4)
1731
tiernoae4a8d12016-07-08 12:30:39 +02001732 #print "Getting the VIM URL and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02001733 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
1734 if len(vims) == 0:
1735 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001736 myvim = vims.values()[0]
1737
tiernoae4a8d12016-07-08 12:30:39 +02001738 # 1. Getting VIM vm and net list
tierno7edb6752016-03-21 17:37:52 +01001739 vms_updated = [] #List of VM instance uuids in openmano that were updated
1740 vms_notupdated=[]
tiernoae4a8d12016-07-08 12:30:39 +02001741 vm_list = []
tierno7edb6752016-03-21 17:37:52 +01001742 for sce_vnf in instanceDict['vnfs']:
1743 for vm in sce_vnf['vms']:
tiernoae4a8d12016-07-08 12:30:39 +02001744 vm_list.append(vm['vim_vm_id'])
1745 vms_notupdated.append(vm["uuid"])
1746
1747 nets_updated = [] #List of VM instance uuids in openmano that were updated
tierno7edb6752016-03-21 17:37:52 +01001748 nets_notupdated=[]
tiernoae4a8d12016-07-08 12:30:39 +02001749 net_list=[]
tierno7edb6752016-03-21 17:37:52 +01001750 for net in instanceDict['nets']:
tiernoae4a8d12016-07-08 12:30:39 +02001751 net_list.append(net['vim_net_id'])
1752 nets_notupdated.append(net["uuid"])
1753
1754 try:
1755 # 1. Getting the status of all VMs
1756 vm_dict = myvim.refresh_vms_status(vm_list)
1757
1758 # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
1759 for sce_vnf in instanceDict['vnfs']:
1760 for vm in sce_vnf['vms']:
1761 vm_id = vm['vim_vm_id']
1762 interfaces = vm_dict[vm_id].pop('interfaces', [])
1763 #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
1764 has_mgmt_iface = False
1765 for iface in vm["interfaces"]:
1766 if iface["type"]=="mgmt":
1767 has_mgmt_iface = True
1768 if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
1769 vm_dict[vm_id]['status'] = "ACTIVE"
1770 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'):
1771 vm['status'] = vm_dict[vm_id]['status']
1772 vm['error_msg'] = vm_dict[vm_id].get('error_msg')
1773 vm['vim_info'] = vm_dict[vm_id].get('vim_info')
1774 # 2.1. Update in openmano DB the VMs whose status changed
tiernof97fd272016-07-11 14:32:37 +02001775 try:
1776 updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +02001777 vms_notupdated.remove(vm["uuid"])
tiernof97fd272016-07-11 14:32:37 +02001778 if updates>0:
tiernoae4a8d12016-07-08 12:30:39 +02001779 vms_updated.append(vm["uuid"])
tiernof97fd272016-07-11 14:32:37 +02001780 except db_base_Exception as e:
1781 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tiernoae4a8d12016-07-08 12:30:39 +02001782 # 2.2. Update in openmano DB the interface VMs
1783 for interface in interfaces:
1784 #translate from vim_net_id to instance_net_id
1785 network_id=None
1786 for net in instanceDict['nets']:
1787 if net["vim_net_id"] == interface["vim_net_id"]:
1788 network_id = net["uuid"]
1789 break
1790 if not network_id:
1791 continue
1792 del interface["vim_net_id"]
tiernof97fd272016-07-11 14:32:37 +02001793 try:
1794 mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
1795 except db_base_Exception as e:
tiernoae4a8d12016-07-08 12:30:39 +02001796 logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
1797
1798 # 3. Getting the status of all nets
1799 net_dict = myvim.refresh_nets_status(net_list)
1800
1801 # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
1802 # TODO: update nets inside a vnf
1803 for net in instanceDict['nets']:
1804 net_id = net['vim_net_id']
1805 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'):
1806 net['status'] = net_dict[net_id]['status']
1807 net['error_msg'] = net_dict[net_id].get('error_msg')
1808 net['vim_info'] = net_dict[net_id].get('vim_info')
1809 # 5.1. Update in openmano DB the nets whose status changed
tiernof97fd272016-07-11 14:32:37 +02001810 try:
1811 updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +02001812 nets_notupdated.remove(net["uuid"])
tiernof97fd272016-07-11 14:32:37 +02001813 if updated>0:
tiernoae4a8d12016-07-08 12:30:39 +02001814 nets_updated.append(net["uuid"])
tiernof97fd272016-07-11 14:32:37 +02001815 except db_base_Exception as e:
1816 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tiernoae4a8d12016-07-08 12:30:39 +02001817 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02001818 #logger.error("VIM exception %s %s", type(e).__name__, str(e))
1819 raise NfvoException(str(e), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001820
1821 # Returns appropriate output
tiernoae4a8d12016-07-08 12:30:39 +02001822 #print "nfvo.refresh_instance finishes"
1823 logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
1824 str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01001825 instance_id = instanceDict['uuid']
tierno7edb6752016-03-21 17:37:52 +01001826 if len(vms_notupdated)+len(nets_notupdated)>0:
tiernoae4a8d12016-07-08 12:30:39 +02001827 error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
tierno7edb6752016-03-21 17:37:52 +01001828 return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
1829
tiernoae4a8d12016-07-08 12:30:39 +02001830 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01001831
1832def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02001833 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02001834 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01001835 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
1836
tiernoae4a8d12016-07-08 12:30:39 +02001837 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02001838 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
1839 if len(vims) == 0:
1840 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001841 myvim = vims.values()[0]
1842
1843
1844 input_vnfs = action_dict.pop("vnfs", [])
1845 input_vms = action_dict.pop("vms", [])
1846 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
1847 vm_result = {}
1848 vm_error = 0
1849 vm_ok = 0
1850 for sce_vnf in instanceDict['vnfs']:
1851 for vm in sce_vnf['vms']:
1852 if not action_over_all:
1853 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
1854 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
1855 continue
tiernoae4a8d12016-07-08 12:30:39 +02001856 try:
1857 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
tierno7edb6752016-03-21 17:37:52 +01001858 if "console" in action_dict:
tierno20fc2a22016-08-19 17:02:35 +02001859 if not global_config["http_console_proxy"]:
1860 vm_result[ vm['uuid'] ] = {"vim_result": 200,
1861 "description": "{protocol}//{ip}:{port}/{suffix}".format(
1862 protocol=data["protocol"],
1863 ip = data["server"],
1864 port = data["port"],
1865 suffix = data["suffix"]),
1866 "name":vm['name']
1867 }
1868 vm_ok +=1
1869 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
tierno7edb6752016-03-21 17:37:52 +01001870 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
1871 "description": "this console is only reachable by local interface",
1872 "name":vm['name']
1873 }
1874 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02001875 else:
tierno7edb6752016-03-21 17:37:52 +01001876 #print "console data", data
tierno20fc2a22016-08-19 17:02:35 +02001877 try:
1878 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
1879 vm_result[ vm['uuid'] ] = {"vim_result": 200,
1880 "description": "{protocol}//{ip}:{port}/{suffix}".format(
1881 protocol=data["protocol"],
1882 ip = global_config["http_console_host"],
1883 port = console_thread.port,
1884 suffix = data["suffix"]),
1885 "name":vm['name']
1886 }
1887 vm_ok +=1
1888 except NfvoException as e:
1889 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
1890 vm_error+=1
1891
tierno7edb6752016-03-21 17:37:52 +01001892 else:
tiernof97fd272016-07-11 14:32:37 +02001893 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
tierno7edb6752016-03-21 17:37:52 +01001894 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02001895 except vimconn.vimconnException as e:
1896 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
1897 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01001898
1899 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02001900 return vm_result
tierno7edb6752016-03-21 17:37:52 +01001901 else:
tierno351863c2016-07-23 01:46:03 +02001902 return vm_result
tierno7edb6752016-03-21 17:37:52 +01001903
1904def create_or_use_console_proxy_thread(console_server, console_port):
1905 #look for a non-used port
1906 console_thread_key = console_server + ":" + str(console_port)
1907 if console_thread_key in global_config["console_thread"]:
1908 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02001909 return global_config["console_thread"][console_thread_key]
tierno7edb6752016-03-21 17:37:52 +01001910
1911 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02001912 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01001913 if port in global_config["console_ports"]:
1914 continue
1915 try:
1916 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
1917 clithread.start()
1918 global_config["console_thread"][console_thread_key] = clithread
1919 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02001920 return clithread
tierno7edb6752016-03-21 17:37:52 +01001921 except cli.ConsoleProxyExceptionPortUsed as e:
1922 #port used, try with onoher
1923 continue
1924 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02001925 raise NfvoException(str(e), HTTP_Bad_Request)
1926 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001927
1928def check_tenant(mydb, tenant_id):
1929 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02001930 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
1931 if not tenant:
1932 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
1933 return
tierno7edb6752016-03-21 17:37:52 +01001934
1935def new_tenant(mydb, tenant_dict):
tiernof97fd272016-07-11 14:32:37 +02001936 tenant_id = mydb.new_row("nfvo_tenants", tenant_dict, add_uuid=True)
1937 return tenant_id
tierno7edb6752016-03-21 17:37:52 +01001938
1939def delete_tenant(mydb, tenant):
1940 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02001941
1942 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
1943 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
1944 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01001945
1946def new_datacenter(mydb, datacenter_descriptor):
1947 if "config" in datacenter_descriptor:
1948 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tiernof97fd272016-07-11 14:32:37 +02001949 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
1950 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001951
1952def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
1953 #obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02001954 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno7edb6752016-03-21 17:37:52 +01001955 #edit data
tiernof97fd272016-07-11 14:32:37 +02001956 datacenter_id = datacenter['uuid']
1957 where={'uuid': datacenter['uuid']}
tierno7edb6752016-03-21 17:37:52 +01001958 if "config" in datacenter_descriptor:
1959 if datacenter_descriptor['config']!=None:
1960 try:
1961 new_config_dict = datacenter_descriptor["config"]
1962 #delete null fields
1963 to_delete=[]
1964 for k in new_config_dict:
1965 if new_config_dict[k]==None:
1966 to_delete.append(k)
1967
tiernof97fd272016-07-11 14:32:37 +02001968 config_dict = yaml.load(datacenter["config"])
tierno7edb6752016-03-21 17:37:52 +01001969 config_dict.update(new_config_dict)
1970 #delete null fields
1971 for k in to_delete:
1972 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02001973 except Exception as e:
1974 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001975 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 +02001976 mydb.update_rows('datacenters', datacenter_descriptor, where)
1977 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001978
1979def delete_datacenter(mydb, datacenter):
1980 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02001981 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
1982 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
1983 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01001984
1985def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None):
1986 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02001987 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02001988 vims = get_vim(mydb, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01001989 else:
tiernof97fd272016-07-11 14:32:37 +02001990 vims = get_vim(mydb, datacenter_name=datacenter)
1991 if len(vims) == 0:
1992 raise NfvoException("datacenter '{}' not found".format(str(datacenter)), HTTP_Not_Found)
1993 elif len(vims)>1:
1994 #print "nfvo.datacenter_action() error. Several datacenters found"
1995 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1996
tierno7edb6752016-03-21 17:37:52 +01001997 datacenter_id=vims.keys()[0]
1998 myvim=vims[datacenter_id]
1999 datacenter_name=myvim["name"]
2000
2001 create_vim_tenant=True if vim_tenant_id==None and vim_tenant_name==None else False
2002
2003 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002004 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002005 if vim_tenant_name==None:
2006 vim_tenant_name=tenant_dict['name']
2007
2008 #check that this association does not exist before
2009 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernof97fd272016-07-11 14:32:37 +02002010 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2011 if len(tenants_datacenters)>0:
2012 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002013
2014 vim_tenant_id_exist_atdb=False
2015 if not create_vim_tenant:
2016 where_={"datacenter_id": datacenter_id}
2017 if vim_tenant_id!=None:
2018 where_["vim_tenant_id"] = vim_tenant_id
2019 if vim_tenant_name!=None:
2020 where_["vim_tenant_name"] = vim_tenant_name
2021 #check if vim_tenant_id is already at database
tiernof97fd272016-07-11 14:32:37 +02002022 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
2023 if len(datacenter_tenants_dict)>=1:
tierno7edb6752016-03-21 17:37:52 +01002024 datacenter_tenants_dict = datacenter_tenants_dict[0]
2025 vim_tenant_id_exist_atdb=True
2026 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
2027 else: #result=0
2028 datacenter_tenants_dict = {}
2029 #insert at table datacenter_tenants
2030 else: #if vim_tenant_id==None:
2031 #create tenant at VIM if not provided
tiernoae4a8d12016-07-08 12:30:39 +02002032 try:
2033 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
2034 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002035 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 +01002036 datacenter_tenants_dict = {}
2037 datacenter_tenants_dict["created"]="true"
2038
2039 #fill datacenter_tenants table
2040 if not vim_tenant_id_exist_atdb:
2041 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
2042 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
2043 datacenter_tenants_dict["user"] = vim_username
2044 datacenter_tenants_dict["passwd"] = vim_password
2045 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernof97fd272016-07-11 14:32:37 +02002046 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002047 datacenter_tenants_dict["uuid"] = id_
2048
2049 #fill tenants_datacenters table
2050 tenants_datacenter_dict["datacenter_tenant_id"]=datacenter_tenants_dict["uuid"]
tiernof97fd272016-07-11 14:32:37 +02002051 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
2052 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002053
2054def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
2055 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02002056 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002057 vims = get_vim(mydb, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002058 else:
tiernof97fd272016-07-11 14:32:37 +02002059 vims = get_vim(mydb, datacenter_name=datacenter)
2060 if len(vims) == 0:
2061 raise NfvoException("datacenter '{}' not found".format(str(datacenter)), HTTP_Not_Found)
2062 elif len(vims)>1:
2063 #print "nfvo.datacenter_action() error. Several datacenters found"
2064 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002065 datacenter_id=vims.keys()[0]
2066 myvim=vims[datacenter_id]
2067
2068 #get nfvo_tenant info
2069 if not tenant_id or tenant_id=="any":
2070 tenant_uuid = None
2071 else:
tiernof97fd272016-07-11 14:32:37 +02002072 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002073 tenant_uuid = tenant_dict['uuid']
2074
2075 #check that this association exist before
2076 tenants_datacenter_dict={"datacenter_id":datacenter_id }
2077 if tenant_uuid:
2078 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02002079 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2080 if len(tenant_datacenter_list)==0 and tenant_uuid:
2081 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002082
2083 #delete this association
tiernof97fd272016-07-11 14:32:37 +02002084 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01002085
2086 #get vim_tenant info and deletes
2087 warning=''
2088 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02002089 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2090 #try to delete vim:tenant
2091 try:
2092 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2093 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01002094 #delete tenant at VIM if created by NFVO
tiernoae4a8d12016-07-08 12:30:39 +02002095 try:
2096 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
2097 except vimconn.vimconnException as e:
2098 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
2099 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02002100 except db_base_Exception as e:
2101 logger.error("Cannot delete datacenter_tenants " + str(e))
2102 pass #the error will be caused because dependencies, vim_tenant can not be deleted
tierno7edb6752016-03-21 17:37:52 +01002103
tiernof97fd272016-07-11 14:32:37 +02002104 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01002105
2106def datacenter_action(mydb, tenant_id, datacenter, action_dict):
2107 #DEPRECATED
2108 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02002109 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002110 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002111 else:
tiernof97fd272016-07-11 14:32:37 +02002112 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2113 if len(vims) == 0:
2114 raise NfvoException("datacenter '{}' not found".format(str(datacenter)), HTTP_Not_Found)
2115 elif len(vims)>1:
2116 #print "nfvo.datacenter_action() error. Several datacenters found"
2117 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002118 datacenter_id=vims.keys()[0]
2119 myvim=vims[datacenter_id]
2120
2121 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02002122 try:
tiernof97fd272016-07-11 14:32:37 +02002123 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02002124 #print content
2125 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002126 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
2127 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002128 #update nets Change from VIM format to NFVO format
2129 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002130 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01002131 net_nfvo={'datacenter_id': datacenter_id}
2132 net_nfvo['name'] = net['name']
2133 #net_nfvo['description']= net['name']
2134 net_nfvo['vim_net_id'] = net['id']
2135 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2136 net_nfvo['shared'] = net['shared']
2137 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
2138 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002139 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
2140 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
2141 return inserted
tierno7edb6752016-03-21 17:37:52 +01002142 elif 'net-edit' in action_dict:
2143 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02002144 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002145 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01002146 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002147 return result
tierno7edb6752016-03-21 17:37:52 +01002148 elif 'net-delete' in action_dict:
2149 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02002150 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002151 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01002152 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002153 return result
tierno7edb6752016-03-21 17:37:52 +01002154
2155 else:
tiernof97fd272016-07-11 14:32:37 +02002156 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002157
2158def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
2159 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02002160 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002161 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002162 else:
tiernof97fd272016-07-11 14:32:37 +02002163 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2164 if len(vims) == 0:
2165 raise NfvoException("datacenter '{}' not found".format(str(datacenter)), HTTP_Not_Found)
2166 elif len(vims)>1:
2167 #print "nfvo.datacenter_action() error. Several datacenters found"
2168 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002169 datacenter_id=vims.keys()[0]
2170
tierno42fcc3b2016-07-06 17:20:40 +02002171 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002172 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01002173 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02002174 return result
tierno7edb6752016-03-21 17:37:52 +01002175
2176def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
2177 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02002178 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002179 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002180 else:
tiernof97fd272016-07-11 14:32:37 +02002181 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2182 if len(vims) == 0:
2183 raise NfvoException("datacenter '{}' not found".format(datacenter), HTTP_Not_Found)
2184 elif len(vims)>1:
2185 #logger.error("nfvo.datacenter_new_netmap() error. Several datacenters found")
2186 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002187 datacenter_id=vims.keys()[0]
2188 myvim=vims[datacenter_id]
2189 filter_dict={}
2190 if action_dict:
2191 action_dict = action_dict["netmap"]
2192 if 'vim_id' in action_dict:
2193 filter_dict["id"] = action_dict['vim_id']
2194 if 'vim_name' in action_dict:
2195 filter_dict["name"] = action_dict['vim_name']
2196 else:
2197 filter_dict["shared"] = True
2198
tiernoae4a8d12016-07-08 12:30:39 +02002199 try:
tiernof97fd272016-07-11 14:32:37 +02002200 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02002201 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002202 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
2203 raise NfvoException(str(e), HTTP_Internal_Server_Error)
2204 if len(vim_nets)>1 and action_dict:
2205 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
2206 elif len(vim_nets)==0: # and action_dict:
2207 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002208 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002209 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01002210 net_nfvo={'datacenter_id': datacenter_id}
2211 if action_dict and "name" in action_dict:
2212 net_nfvo['name'] = action_dict['name']
2213 else:
2214 net_nfvo['name'] = net['name']
2215 #net_nfvo['description']= net['name']
2216 net_nfvo['vim_net_id'] = net['id']
2217 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2218 net_nfvo['shared'] = net['shared']
2219 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02002220 try:
2221 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002222 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02002223 net_nfvo["uuid"] = net_id
2224 except db_base_Exception as e:
2225 if action_dict:
2226 raise
2227 else:
2228 net_nfvo["status"] = "FAIL: " + str(e)
tierno7edb6752016-03-21 17:37:52 +01002229 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002230 return net_list
tierno7edb6752016-03-21 17:37:52 +01002231
2232def vim_action_get(mydb, tenant_id, datacenter, item, name):
2233 #get datacenter info
tierno42fcc3b2016-07-06 17:20:40 +02002234 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002235 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002236 else:
tiernof97fd272016-07-11 14:32:37 +02002237 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2238 if len(vims) == 0:
2239 raise NfvoException("datacenter '{}' not found".format(datacenter), HTTP_Not_Found)
2240 elif len(vims)>1:
2241 #logger.error("nfvo.datacenter_new_netmap() error. Several datacenters found")
2242 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002243 datacenter_id=vims.keys()[0]
2244 myvim=vims[datacenter_id]
2245 filter_dict={}
2246 if name:
tierno42fcc3b2016-07-06 17:20:40 +02002247 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01002248 filter_dict["id"] = name
2249 else:
2250 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02002251 try:
2252 if item=="networks":
2253 #filter_dict['tenant_id'] = myvim['tenant_id']
2254 content = myvim.get_network_list(filter_dict=filter_dict)
2255 elif item=="tenants":
2256 content = myvim.get_tenant_list(filter_dict=filter_dict)
2257 else:
tiernof97fd272016-07-11 14:32:37 +02002258 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02002259 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02002260 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02002261 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02002262 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02002263 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 +02002264 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02002265 else:
tiernof97fd272016-07-11 14:32:37 +02002266 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02002267 except vimconn.vimconnException as e:
2268 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02002269 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002270
2271def vim_action_delete(mydb, tenant_id, datacenter, item, name):
2272 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02002273 if tenant_id == "any":
2274 tenant_id=None
2275
tierno66aa0372016-07-06 17:31:12 +02002276 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002277 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002278 else:
tiernof97fd272016-07-11 14:32:37 +02002279 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2280 if len(vims) == 0:
2281 raise NfvoException("datacenter '{}' not found".format(datacenter), HTTP_Not_Found)
2282 elif len(vims)>1:
2283 #logger.error("nfvo.datacenter_new_netmap() error. Several datacenters found")
2284 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002285 datacenter_id=vims.keys()[0]
2286 myvim=vims[datacenter_id]
tierno392f2852016-05-13 12:28:55 +02002287 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02002288 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
2289 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02002290 items = content.values()[0]
2291 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02002292 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002293 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02002294 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002295 else: # it is a dict
2296 item_id = items["id"]
2297 item_name = str(items.get("name"))
tierno7edb6752016-03-21 17:37:52 +01002298
tiernoae4a8d12016-07-08 12:30:39 +02002299 try:
2300 if item=="networks":
2301 content = myvim.delete_network(item_id)
2302 elif item=="tenants":
2303 content = myvim.delete_tenant(item_id)
2304 else:
tiernof97fd272016-07-11 14:32:37 +02002305 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002306 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002307 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
2308 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002309
tiernof97fd272016-07-11 14:32:37 +02002310 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno7edb6752016-03-21 17:37:52 +01002311
2312def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
2313 #get datacenter info
2314 print "vim_action_create descriptor", descriptor
tierno392f2852016-05-13 12:28:55 +02002315 if tenant_id == "any":
2316 tenant_id=None
2317
tierno42fcc3b2016-07-06 17:20:40 +02002318 if utils.check_valid_uuid(datacenter):
tiernof97fd272016-07-11 14:32:37 +02002319 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_id=datacenter)
tierno7edb6752016-03-21 17:37:52 +01002320 else:
tiernof97fd272016-07-11 14:32:37 +02002321 vims = get_vim(mydb, nfvo_tenant=tenant_id, datacenter_name=datacenter)
2322 if len(vims) == 0:
2323 raise NfvoException("datacenter '{}' not found".format(datacenter), HTTP_Not_Found)
2324 elif len(vims)>1:
2325 #logger.error("nfvo.datacenter_new_netmap() error. Several datacenters found")
2326 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002327 datacenter_id=vims.keys()[0]
2328 myvim=vims[datacenter_id]
2329
tiernoae4a8d12016-07-08 12:30:39 +02002330 try:
2331 if item=="networks":
2332 net = descriptor["network"]
2333 net_name = net.pop("name")
2334 net_type = net.pop("type", "bridge")
2335 net_public=net.pop("shared", False)
2336 content = myvim.new_network(net_name, net_type, net_public, **net)
2337 elif item=="tenants":
2338 tenant = descriptor["tenant"]
2339 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
2340 else:
tiernof97fd272016-07-11 14:32:37 +02002341 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002342 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002343 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002344
tierno7edb6752016-03-21 17:37:52 +01002345 return vim_action_get(mydb, tenant_id, datacenter, item, content)
2346
tierno66aa0372016-07-06 17:31:12 +02002347