blob: 21e57195a40510a15339c32eb5868950b57f44d7 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5# This file is part of openmano
6# All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License. You may obtain
10# a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
21# contact with: nfvlabs@tid.es
22##
23
24'''
25NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
26'''
27__author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28__date__ ="$16-sep-2014 22:05:01$"
29
30import imp
31#import json
32import yaml
tierno42fcc3b2016-07-06 17:20:40 +020033import utils
tiernof97fd272016-07-11 14:32:37 +020034from db_base import HTTP_Unauthorized, HTTP_Bad_Request, HTTP_Internal_Server_Error, HTTP_Not_Found,\
tierno7edb6752016-03-21 17:37:52 +010035 HTTP_Conflict, HTTP_Method_Not_Allowed
36import console_proxy_thread as cli
tiernoae4a8d12016-07-08 12:30:39 +020037import vimconn
38import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020039import collections
tiernof97fd272016-07-11 14:32:37 +020040from db_base import db_base_Exception
tierno7edb6752016-03-21 17:37:52 +010041
42global global_config
43global vimconn_imported
tierno73ad9e42016-09-12 18:11:11 +020044global logger
montesmoreno0c8def02016-12-22 12:16:23 +000045global default_volume_size
46default_volume_size = '5' #size in GB
tierno7edb6752016-03-21 17:37:52 +010047
tiernoae4a8d12016-07-08 12:30:39 +020048
tierno7edb6752016-03-21 17:37:52 +010049vimconn_imported={} #dictionary with VIM type as key, loaded module as value
tierno73ad9e42016-09-12 18:11:11 +020050logger = logging.getLogger('openmano.nfvo')
tierno7edb6752016-03-21 17:37:52 +010051
52class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020053 def __init__(self, message, http_code):
54 self.http_code = http_code
55 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010056
57
58def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
59 '''Obtain flavorList
60 return result, content:
61 <0, error_text upon error
62 nb_records, flavor_list on success
63 '''
64 WHERE_dict={}
65 WHERE_dict['vnf_id'] = vnf_id
66 if nfvo_tenant is not None:
67 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
68
69 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
70 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +020071 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
72 #print "get_flavor_list result:", result
73 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +010074 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +020075 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +010076 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +020077 return flavorList
tierno7edb6752016-03-21 17:37:52 +010078
79def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
80 '''Obtain imageList
81 return result, content:
82 <0, error_text upon error
83 nb_records, flavor_list on success
84 '''
85 WHERE_dict={}
86 WHERE_dict['vnf_id'] = vnf_id
87 if nfvo_tenant is not None:
88 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
89
90 #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 +020091 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 +010092 imageList=[]
tiernof97fd272016-07-11 14:32:37 +020093 for image in images:
tierno7edb6752016-03-21 17:37:52 +010094 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +020095 return imageList
tierno7edb6752016-03-21 17:37:52 +010096
tiernoa2793912016-10-04 08:15:08 +000097def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
98 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None):
tierno7edb6752016-03-21 17:37:52 +010099 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tiernobe41e222016-09-02 15:16:13 +0200100 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100101 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200102 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100103 '''
104 WHERE_dict={}
105 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
106 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000107 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100108 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
109 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000110 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
111 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100112 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'
tierno8008c3a2016-10-13 15:34:28 +0000113 select_ = ('type','d.config as config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
tierno7edb6752016-03-21 17:37:52 +0100114 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
tierno8008c3a2016-10-13 15:34:28 +0000115 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100116 else:
117 from_ = 'datacenters as d'
118 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200119 try:
120 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
121 vim_dict={}
122 for vim in vims:
123 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id')}
tierno8008c3a2016-10-13 15:34:28 +0000124 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200125 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000126 if vim.get('dt_config'):
127 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200128 if vim["type"] not in vimconn_imported:
129 module_info=None
130 try:
131 module = "vimconn_" + vim["type"]
132 module_info = imp.find_module(module)
133 vim_conn = imp.load_module(vim["type"], *module_info)
134 vimconn_imported[vim["type"]] = vim_conn
135 except (IOError, ImportError) as e:
136 if module_info and module_info[0]:
137 file.close(module_info[0])
138 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
139 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
140
tierno7edb6752016-03-21 17:37:52 +0100141 try:
tiernof97fd272016-07-11 14:32:37 +0200142 #if not tenant:
143 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
144 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
145 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tierno3ae39742016-09-07 12:17:51 +0200146 tenant_id=vim.get('vim_tenant_id',vim_tenant), tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tiernof97fd272016-07-11 14:32:37 +0200147 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200148 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernof97fd272016-07-11 14:32:37 +0200149 config=extra
150 )
151 except Exception as e:
152 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
153 return vim_dict
154 except db_base_Exception as e:
155 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
156
tierno7edb6752016-03-21 17:37:52 +0100157def rollback(mydb, vims, rollback_list):
158 undeleted_items=[]
159 #delete things by reverse order
160 for i in range(len(rollback_list)-1, -1, -1):
161 item = rollback_list[i]
162 if item["where"]=="vim":
163 if item["vim_id"] not in vims:
164 continue
165 vim=vims[ item["vim_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200166 try:
167 if item["what"]=="image":
168 vim.delete_image(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200169 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200170 elif item["what"]=="flavor":
171 vim.delete_flavor(item["uuid"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200172 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200173 elif item["what"]=="network":
174 vim.delete_network(item["uuid"])
175 elif item["what"]=="vm":
176 vim.delete_vminstance(item["uuid"])
177 except vimconn.vimconnException as e:
178 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
179 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200180 except db_base_Exception as e:
181 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 +0200182
tierno7edb6752016-03-21 17:37:52 +0100183 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200184 try:
185 if item["what"]=="image":
186 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
187 elif item["what"]=="flavor":
188 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
189 except db_base_Exception as e:
190 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
191 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno7edb6752016-03-21 17:37:52 +0100192 if len(undeleted_items)==0:
193 return True," Rollback successful."
194 else:
195 return False," Rollback fails to delete: " + str(undeleted_items)
196
197def check_vnf_descriptor(vnf_descriptor):
198 global global_config
199 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
200 vnfc_interfaces={}
201 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
202 name_list = []
203 #dataplane interfaces
204 for numa in vnfc.get("numas",() ):
205 for interface in numa.get("interfaces",()):
206 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200207 raise NfvoException("Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC"\
208 .format(vnfc["name"], interface["name"]),
209 HTTP_Bad_Request)
210 name_list.append( interface["name"] )
tierno7edb6752016-03-21 17:37:52 +0100211 #bridge interfaces
212 for interface in vnfc.get("bridge-ifaces",() ):
213 if interface["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200214 raise NfvoException("Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC"\
215 .format(vnfc["name"], interface["name"]),
216 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100217 name_list.append( interface["name"] )
218 vnfc_interfaces[ vnfc["name"] ] = name_list
tierno36c0b172017-01-12 18:32:28 +0100219 # check bood-data info
220 if "boot-data" in vnfc:
221 # check that user-data is incompatible with users and config-files
222 if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
223 raise NfvoException(
224 "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
225 HTTP_Bad_Request)
226
tierno7edb6752016-03-21 17:37:52 +0100227 #check if the info in external_connections matches with the one in the vnfcs
228 name_list=[]
229 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
230 if external_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200231 raise NfvoException("Error at vnf:external-connections:name, value '{}' already used as an external-connection"\
232 .format(external_connection["name"]),
233 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100234 name_list.append(external_connection["name"])
235 if external_connection["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200236 raise NfvoException("Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC"\
237 .format(external_connection["name"], external_connection["VNFC"]),
238 HTTP_Bad_Request)
239
tierno7edb6752016-03-21 17:37:52 +0100240 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200241 raise NfvoException("Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC"\
242 .format(external_connection["name"], external_connection["local_iface_name"]),
243 HTTP_Bad_Request )
tierno7edb6752016-03-21 17:37:52 +0100244
245 #check if the info in internal_connections matches with the one in the vnfcs
246 name_list=[]
247 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
248 if internal_connection["name"] in name_list:
tiernof97fd272016-07-11 14:32:37 +0200249 raise NfvoException("Error at vnf:internal-connections:name, value '%s' already used as an internal-connection"\
250 .format(internal_connection["name"]),
251 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100252 name_list.append(internal_connection["name"])
253 #We should check that internal-connections of type "ptp" have only 2 elements
254 if len(internal_connection["elements"])>2 and internal_connection["type"] == "ptp":
tiernof97fd272016-07-11 14:32:37 +0200255 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements, size must be 2 for a type:'ptp'"\
256 .format(internal_connection["name"]),
257 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100258 for port in internal_connection["elements"]:
259 if port["VNFC"] not in vnfc_interfaces:
tiernof97fd272016-07-11 14:32:37 +0200260 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC"\
261 .format(internal_connection["name"], port["VNFC"]),
262 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100263 if port["local_iface_name"] not in vnfc_interfaces[ port["VNFC"] ]:
tiernof97fd272016-07-11 14:32:37 +0200264 raise NfvoException("Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC"\
265 .format(internal_connection["name"], port["local_iface_name"]),
266 HTTP_Bad_Request)
267 return -HTTP_Bad_Request,
tierno7edb6752016-03-21 17:37:52 +0100268
tierno5e91eb82016-10-04 09:39:07 +0000269def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
tierno7edb6752016-03-21 17:37:52 +0100270 #look if image exist
271 if only_create_at_vim:
272 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000273 if return_on_error == None:
274 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100275 else:
garciadeblas14480452017-01-10 13:08:07 +0100276 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200277 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
278 else:
279 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200280 if len(images)>=1:
281 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100282 else:
garciadeblas14480452017-01-10 13:08:07 +0100283 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100284 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200285 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
286 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100287 }
garciadeblas14480452017-01-10 13:08:07 +0100288 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200289 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
290 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100291 #create image at every vim
292 for vim_id,vim in vims.iteritems():
293 image_created="false"
294 #look at database
tiernof97fd272016-07-11 14:32:37 +0200295 image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100296 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200297 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200298 if image_dict['location'] is not None:
299 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
300 else:
garciadeblas30833382017-01-09 09:46:31 +0100301 filter_dict = {}
302 filter_dict['name'] = image_dict['universal_name']
303 if image_dict.get('checksum') != None:
304 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000305 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200306 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100307 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200308 if len(vim_images) > 1:
garciadeblas3fa2c052017-01-05 12:00:08 +0100309 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), HTTP_Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000310 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100311 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200312 else:
garciadeblas14480452017-01-10 13:08:07 +0100313 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
314 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200315
tiernoae4a8d12016-07-08 12:30:39 +0200316 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100317 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tiernoae4a8d12016-07-08 12:30:39 +0200318 try:
garciadeblas14480452017-01-10 13:08:07 +0100319 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
320 if image_dict['location']:
321 image_vim_id = vim.new_image(image_dict)
322 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
323 image_created="true"
324 else:
325 raise vimconn.vimconnException("Cannot create image without location")
tiernoae4a8d12016-07-08 12:30:39 +0200326 except vimconn.vimconnException as e:
327 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100328 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200329 raise
tierno5e91eb82016-10-04 09:39:07 +0000330 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100331 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200332 continue
333 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000334 if return_on_error:
335 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
336 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200337 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000338 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100339 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200340 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200341 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100342 #add new vim_id at datacenters_images
343 mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created})
344 elif image_db[0]["vim_id"]!=image_vim_id:
345 #modify existing vim_id at datacenters_images
346 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
347
tiernof97fd272016-07-11 14:32:37 +0200348 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100349
tierno5e91eb82016-10-04 09:39:07 +0000350def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
tierno7edb6752016-03-21 17:37:52 +0100351 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
352 'ram':flavor_dict.get('ram'),
353 'vcpus':flavor_dict.get('vcpus'),
354 }
355 if 'extended' in flavor_dict and flavor_dict['extended']==None:
356 del flavor_dict['extended']
357 if 'extended' in flavor_dict:
358 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
359
360 #look if flavor exist
361 if only_create_at_vim:
362 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000363 if return_on_error == None:
364 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100365 else:
tiernof97fd272016-07-11 14:32:37 +0200366 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
367 if len(flavors)>=1:
368 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100369 else:
370 #create flavor
371 #create one by one the images of aditional disks
372 dev_image_list=[] #list of images
373 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
374 dev_nb=0
375 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200376 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100377 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200378 image_dict={}
379 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
380 image_dict['universal_name']=device.get('image name')
381 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
382 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100383 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200384 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100385 image_metadata_dict = device.get('image metadata', None)
386 image_metadata_str = None
387 if image_metadata_dict != None:
388 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
389 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200390 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
391 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100392 dev_image_list.append(image_id)
393 dev_nb += 1
394 temp_flavor_dict['name'] = flavor_dict['name']
395 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200396 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
397 flavor_mano_id= content
398 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100399 #create flavor at every vim
400 if 'uuid' in flavor_dict:
401 del flavor_dict['uuid']
402 flavor_vim_id=None
403 for vim_id,vim in vims.items():
404 flavor_created="false"
405 #look at database
tiernof97fd272016-07-11 14:32:37 +0200406 flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100407 #look at VIM if this flavor exist SKIPPED
408 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
409 #if res_vim < 0:
410 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
411 # continue
412 #elif res_vim==0:
413
414 #Create the flavor in VIM
415 #Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000416 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100417 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
418 #make a copy of original devices
419 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000420
tierno7edb6752016-03-21 17:37:52 +0100421 for device in flavor_dict["extended"].get("devices",[]):
422 dev={}
423 dev.update(device)
424 devices_original.append(dev)
425 if 'image' in device:
426 del device['image']
427 if 'image metadata' in device:
428 del device['image metadata']
429 dev_nb=0
430 for index in range(0,len(devices_original)) :
431 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000432 if "image" not in device and "image name" not in device:
433 if 'size' in device:
434 disk_list.append({'size': device.get('size', default_volume_size)})
tierno7edb6752016-03-21 17:37:52 +0100435 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200436 image_dict={}
437 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
438 image_dict['universal_name']=device.get('image name')
439 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
440 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100441 #image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200442 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100443 image_metadata_dict = device.get('image metadata', None)
444 image_metadata_str = None
445 if image_metadata_dict != None:
446 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
447 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200448 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 +0100449 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200450 image_vim_id=create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=True, return_on_error=return_on_error)
montesmoreno0c8def02016-12-22 12:16:23 +0000451
452 #save disk information (image must be based on and size
453 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
454
tierno7edb6752016-03-21 17:37:52 +0100455 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
456 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200457 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100458 #check that this vim_id exist in VIM, if not create
459 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200460 try:
461 vim.get_flavor(flavor_vim_id)
462 continue #flavor exist
463 except vimconn.vimconnException:
464 pass
tierno7edb6752016-03-21 17:37:52 +0100465 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200466 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
467 try:
468 flavor_vim_id = vim.new_flavor(flavor_dict)
tierno7edb6752016-03-21 17:37:52 +0100469 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
470 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200471 except vimconn.vimconnException as e:
472 if return_on_error:
473 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200474 raise
tiernoae4a8d12016-07-08 12:30:39 +0200475 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000476 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200477 continue
tierno7edb6752016-03-21 17:37:52 +0100478 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200479 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100480 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000481 extended_devices_yaml = None
482 if len(disk_list) > 0:
483 extended_devices = dict()
484 extended_devices['disks'] = disk_list
485 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
486 mydb.new_row('datacenters_flavors',
487 {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id,
488 'created':flavor_created,'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100489 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
490 #modify existing vim_id at datacenters_flavors
491 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
492
tiernof97fd272016-07-11 14:32:37 +0200493 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100494
495def new_vnf(mydb, tenant_id, vnf_descriptor):
496 global global_config
497
498 # Step 1. Check the VNF descriptor
tiernof97fd272016-07-11 14:32:37 +0200499 check_vnf_descriptor(vnf_descriptor)
tierno7edb6752016-03-21 17:37:52 +0100500 # Step 2. Check tenant exist
501 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200502 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100503 if "tenant_id" in vnf_descriptor["vnf"]:
504 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200505 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
506 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100507 else:
508 vnf_descriptor['vnf']['tenant_id'] = tenant_id
509 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200510 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100511 else:
512 vims={}
513
514 # Step 4. Review the descriptor and add missing fields
515 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +0200516 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +0100517 vnf_name = vnf_descriptor['vnf']['name']
518 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
519 if "physical" in vnf_descriptor['vnf']:
520 del vnf_descriptor['vnf']['physical']
521 #print vnf_descriptor
522 # Step 5. Check internal connections
523 # TODO: to be moved to step 1????
524 internal_connections=vnf_descriptor['vnf'].get('internal_connections',[])
525 for ic in internal_connections:
526 if len(ic['elements'])>2 and ic['type']=='ptp':
tiernof97fd272016-07-11 14:32:37 +0200527 raise NfvoException("Mismatch 'type':'ptp' with {} elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'data'".format(len(ic), ic['name']),
528 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100529 elif len(ic['elements'])==2 and ic['type']=='data':
tiernof97fd272016-07-11 14:32:37 +0200530 raise NfvoException("Mismatch 'type':'data' with 2 elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'ptp'".format(ic['name']),
531 HTTP_Bad_Request)
532
tierno7edb6752016-03-21 17:37:52 +0100533 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200534 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
535 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno7edb6752016-03-21 17:37:52 +0100536
537 #For each VNFC, we add it to the VNFCDict and we create a flavor.
538 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
539 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +0100540 try:
tiernof97fd272016-07-11 14:32:37 +0200541 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100542 for vnfc in vnf_descriptor['vnf']['VNFC']:
543 VNFCitem={}
544 VNFCitem["name"] = vnfc['name']
545 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
546
tiernof97fd272016-07-11 14:32:37 +0200547 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno7edb6752016-03-21 17:37:52 +0100548
549 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200550 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
tierno7edb6752016-03-21 17:37:52 +0100551 myflavorDict["description"] = VNFCitem["description"]
552 myflavorDict["ram"] = vnfc.get("ram", 0)
553 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
554 myflavorDict["disk"] = vnfc.get("disk", 1)
555 myflavorDict["extended"] = {}
556
557 devices = vnfc.get("devices")
558 if devices != None:
559 myflavorDict["extended"]["devices"] = devices
560
561 # TODO:
562 # 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
563 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
564
565 # Previous code has been commented
566 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
567 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
568 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
569 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
570 #else:
571 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
572 # if result2:
573 # print "Error creating flavor: unknown processor model. Rollback successful."
574 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
575 # else:
576 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
577 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
578
579 if 'numas' in vnfc and len(vnfc['numas'])>0:
580 myflavorDict['extended']['numas'] = vnfc['numas']
581
582 #print myflavorDict
583
584 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200585 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +0100586
tiernof97fd272016-07-11 14:32:37 +0200587 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100588 VNFCitem["flavor_id"] = flavor_id
589 VNFCDict[vnfc['name']] = VNFCitem
590
tiernof97fd272016-07-11 14:32:37 +0200591 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100592 # Step 6.3 New images are created in the VIM
593 #For each VNFC, we must create the appropriate image.
594 #This "for" loop might be integrated with the previous one
595 #In case this integration is made, the VNFCDict might become a VNFClist.
596 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +0200597 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200598 image_dict={}
599 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
600 image_dict['universal_name']=vnfc.get('image name')
601 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
602 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100603 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200604 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100605 image_metadata_dict = vnfc.get('image metadata', None)
606 image_metadata_str = None
607 if image_metadata_dict is not None:
608 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
609 image_dict['metadata']=image_metadata_str
610 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +0200611 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
612 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +0100613 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200614 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno36c0b172017-01-12 18:32:28 +0100615 if vnfc.get("boot-data"):
616 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +0100617
tiernof97fd272016-07-11 14:32:37 +0200618
619 # Step 7. Storing the VNF descriptor in the repository
620 if "descriptor" not in vnf_descriptor["vnf"]:
621 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +0100622
tiernof97fd272016-07-11 14:32:37 +0200623 # Step 8. Adding the VNF to the NFVO DB
624 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
625 return vnf_id
626 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +0100627 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +0200628 if isinstance(e, db_base_Exception):
629 error_text = "Exception at database"
630 elif isinstance(e, KeyError):
631 error_text = "KeyError exception "
632 e.http_code = HTTP_Internal_Server_Error
633 else:
634 error_text = "Exception at VIM"
635 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
636 #logger.error("start_scenario %s", error_text)
637 raise NfvoException(error_text, e.http_code)
638
garciadeblas9f8456e2016-09-05 05:02:59 +0200639def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
640 global global_config
641
642 # Step 1. Check the VNF descriptor
643 check_vnf_descriptor(vnf_descriptor)
644 # Step 2. Check tenant exist
645 if tenant_id != "any":
646 check_tenant(mydb, tenant_id)
647 if "tenant_id" in vnf_descriptor["vnf"]:
648 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
649 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
650 HTTP_Unauthorized)
651 else:
652 vnf_descriptor['vnf']['tenant_id'] = tenant_id
653 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
654 vims = get_vim(mydb, tenant_id)
655 else:
656 vims={}
657
658 # Step 4. Review the descriptor and add missing fields
659 #print vnf_descriptor
660 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
661 vnf_name = vnf_descriptor['vnf']['name']
662 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
663 if "physical" in vnf_descriptor['vnf']:
664 del vnf_descriptor['vnf']['physical']
665 #print vnf_descriptor
666 # Step 5. Check internal connections
667 # TODO: to be moved to step 1????
668 internal_connections=vnf_descriptor['vnf'].get('internal_connections',[])
669 for ic in internal_connections:
670 if len(ic['elements'])>2 and ic['type']=='e-line':
671 raise NfvoException("Mismatch 'type':'e-line' with {} elements at 'vnf':'internal-conections'['name':'{}']. Change 'type' to 'e-lan'".format(len(ic), ic['name']),
672 HTTP_Bad_Request)
673
674 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
675 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
676 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
677
678 #For each VNFC, we add it to the VNFCDict and we create a flavor.
679 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
680 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
681 try:
682 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
683 for vnfc in vnf_descriptor['vnf']['VNFC']:
684 VNFCitem={}
685 VNFCitem["name"] = vnfc['name']
686 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
687
688 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
689
690 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200691 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
garciadeblas9f8456e2016-09-05 05:02:59 +0200692 myflavorDict["description"] = VNFCitem["description"]
693 myflavorDict["ram"] = vnfc.get("ram", 0)
694 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
695 myflavorDict["disk"] = vnfc.get("disk", 1)
696 myflavorDict["extended"] = {}
697
698 devices = vnfc.get("devices")
699 if devices != None:
700 myflavorDict["extended"]["devices"] = devices
701
702 # TODO:
703 # 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
704 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
705
706 # Previous code has been commented
707 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
708 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
709 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
710 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
711 #else:
712 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
713 # if result2:
714 # print "Error creating flavor: unknown processor model. Rollback successful."
715 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
716 # else:
717 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
718 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
719
720 if 'numas' in vnfc and len(vnfc['numas'])>0:
721 myflavorDict['extended']['numas'] = vnfc['numas']
722
723 #print myflavorDict
724
725 # Step 6.2 New flavors are created in the VIM
726 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
727
728 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
729 VNFCitem["flavor_id"] = flavor_id
730 VNFCDict[vnfc['name']] = VNFCitem
731
732 logger.debug("Creating new images in the VIM for each VNFC")
733 # Step 6.3 New images are created in the VIM
734 #For each VNFC, we must create the appropriate image.
735 #This "for" loop might be integrated with the previous one
736 #In case this integration is made, the VNFCDict might become a VNFClist.
737 for vnfc in vnf_descriptor['vnf']['VNFC']:
738 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200739 image_dict={}
740 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
741 image_dict['universal_name']=vnfc.get('image name')
742 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
743 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100744 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200745 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +0200746 image_metadata_dict = vnfc.get('image metadata', None)
747 image_metadata_str = None
748 if image_metadata_dict is not None:
749 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
750 image_dict['metadata']=image_metadata_str
751 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
752 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
753 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
754 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200755 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno36c0b172017-01-12 18:32:28 +0100756 if vnfc.get("boot-data"):
757 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +0200758
garciadeblas9f8456e2016-09-05 05:02:59 +0200759 # Step 7. Storing the VNF descriptor in the repository
760 if "descriptor" not in vnf_descriptor["vnf"]:
761 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
762
763 # Step 8. Adding the VNF to the NFVO DB
764 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
765 return vnf_id
766 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
767 _, message = rollback(mydb, vims, rollback_list)
768 if isinstance(e, db_base_Exception):
769 error_text = "Exception at database"
770 elif isinstance(e, KeyError):
771 error_text = "KeyError exception "
772 e.http_code = HTTP_Internal_Server_Error
773 else:
774 error_text = "Exception at VIM"
775 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
776 #logger.error("start_scenario %s", error_text)
777 raise NfvoException(error_text, e.http_code)
778
tierno7edb6752016-03-21 17:37:52 +0100779def get_vnf_id(mydb, tenant_id, vnf_id):
780 #check valid tenant_id
tiernof97fd272016-07-11 14:32:37 +0200781 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100782 #obtain data
783 where_or = {}
784 if tenant_id != "any":
785 where_or["tenant_id"] = tenant_id
786 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200787 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 +0100788
tiernof97fd272016-07-11 14:32:37 +0200789 vnf_id=vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100790 filter_keys = ('uuid','name','description','public', "tenant_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +0200791 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +0100792 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
793 data={'vnf' : filtered_content}
794 #GET VM
tiernof97fd272016-07-11 14:32:37 +0200795 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tierno36c0b172017-01-12 18:32:28 +0100796 SELECT=('vms.uuid as uuid','vms.name as name', 'vms.description as description', 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +0100797 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200798 if len(content)==0:
799 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno36c0b172017-01-12 18:32:28 +0100800 # change boot_data into boot-data
801 for vm in content:
802 if vm.get("boot_data"):
803 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
804 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +0100805
806 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200807 #TODO: GET all the information from a VNFC and include it in the output.
808
tierno7edb6752016-03-21 17:37:52 +0100809 #GET NET
tiernof97fd272016-07-11 14:32:37 +0200810 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +0100811 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
812 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +0200813 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200814
815 #GET ip-profile for each net
816 for net in data['vnf']['nets']:
817 ipprofiles = mydb.get_rows(FROM='ip_profiles',
818 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
819 WHERE={'net_id': net["uuid"]} )
820 if len(ipprofiles)==1:
821 net["ip_profile"] = ipprofiles[0]
822 elif len(ipprofiles)>1:
823 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net['uuid']), HTTP_Bad_Request)
824
825
826 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
827
828 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +0200829 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 +0100830 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
831 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
832 WHERE={'vnfs.uuid': vnf_id},
833 WHERE_NOT={'interfaces.external_name': None} )
834 #print content
tiernof97fd272016-07-11 14:32:37 +0200835 data['vnf']['external-connections'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +0200836
tiernof97fd272016-07-11 14:32:37 +0200837 return data
tierno7edb6752016-03-21 17:37:52 +0100838
839
840def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
841 # Check tenant exist
842 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200843 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100844 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +0200845 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100846 else:
847 vims={}
848
849 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
850 where_or = {}
851 if tenant_id != "any":
852 where_or["tenant_id"] = tenant_id
853 where_or["public"] = True
tiernof97fd272016-07-11 14:32:37 +0200854 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
855 vnf_id = vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +0100856
857 # "Getting the list of flavors and tenants of the VNF"
tiernof97fd272016-07-11 14:32:37 +0200858 flavorList = get_flavorlist(mydb, vnf_id)
859 if len(flavorList)==0:
860 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100861
tiernof97fd272016-07-11 14:32:37 +0200862 imageList = get_imagelist(mydb, vnf_id)
863 if len(imageList)==0:
864 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno7edb6752016-03-21 17:37:52 +0100865
tiernof97fd272016-07-11 14:32:37 +0200866 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
867 if deleted == 0:
868 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100869
870 undeletedItems = []
871 for flavor in flavorList:
872 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +0200873 try:
874 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
875 if len(c) > 0:
876 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
877 continue
878 #flavor not used, must be deleted
879 #delelte at VIM
880 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +0100881 for flavor_vim in c:
882 if flavor_vim["datacenter_id"] not in vims:
883 continue
884 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
885 continue
886 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200887 try:
888 myvim.delete_flavor(flavor_vim["vim_id"])
889 except vimconn.vimconnNotFoundException as e:
890 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
891 except vimconn.vimconnException as e:
892 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
893 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
894 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200895 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
896 mydb.delete_row_by_id('flavors', flavor)
897 except db_base_Exception as e:
898 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +0100899 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +0200900
tierno7edb6752016-03-21 17:37:52 +0100901
902 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +0200903 try:
904 #check if image is used by other vnf
905 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
906 if len(c) > 0:
907 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
908 continue
909 #image not used, must be deleted
910 #delelte at VIM
911 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +0100912 for image_vim in c:
913 if image_vim["datacenter_id"] not in vims:
914 continue
915 if image_vim['created']=='false': #skip this image because not created by openmano
916 continue
917 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +0200918 try:
919 myvim.delete_image(image_vim["vim_id"])
920 except vimconn.vimconnNotFoundException as e:
921 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
922 except vimconn.vimconnException as e:
923 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
924 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
925 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +0200926 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
927 mydb.delete_row_by_id('images', image)
928 except db_base_Exception as e:
929 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +0100930 undeletedItems.append("image %s" % image)
931
tiernof97fd272016-07-11 14:32:37 +0200932 return vnf_id + " " + vnf["name"]
933 #if undeletedItems:
934 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +0100935
936def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
937 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
938 if result < 0:
939 return result, vims
940 elif result == 0:
941 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
942 myvim = vims.values()[0]
943 result,servers = myvim.get_hosts_info()
944 if result < 0:
945 return result, servers
946 topology = {'name':myvim['name'] , 'servers': servers}
947 return result, topology
948
949def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +0200950 vims = get_vim(mydb, nfvo_tenant_id)
951 if len(vims) == 0:
952 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
953 elif len(vims)>1:
954 #print "nfvo.datacenter_action() error. Several datacenters found"
955 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +0100956 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +0200957 try:
958 hosts = myvim.get_hosts()
959 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +0100960
tiernof97fd272016-07-11 14:32:37 +0200961 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
962 for host in hosts:
963 server={'name':host['name'], 'vms':[]}
964 for vm in host['instances']:
965 #get internal name and model
966 try:
967 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
968 WHERE={'vim_vm_id':vm['id']} )
969 if len(c) == 0:
970 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
971 continue
972 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
973
974 except db_base_Exception as e:
975 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
976 datacenter['Datacenters'][0]['servers'].append(server)
977 #return -400, "en construccion"
tierno7edb6752016-03-21 17:37:52 +0100978
tiernof97fd272016-07-11 14:32:37 +0200979 #print 'datacenters '+ json.dumps(datacenter, indent=4)
980 return datacenter
981 except vimconn.vimconnException as e:
982 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +0100983
984def new_scenario(mydb, tenant_id, topo):
985
986# result, vims = get_vim(mydb, tenant_id)
987# if result < 0:
988# return result, vims
989#1: parse input
990 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200991 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100992 if "tenant_id" in topo:
993 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200994 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
995 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100996 else:
997 tenant_id=None
998
999#1.1: get VNFs and external_networks (other_nets).
1000 vnfs={}
1001 other_nets={} #external_networks, bridge_networks and data_networkds
1002 nodes = topo['topology']['nodes']
1003 for k in nodes.keys():
1004 if nodes[k]['type'] == 'VNF':
1005 vnfs[k] = nodes[k]
1006 vnfs[k]['ifaces'] = {}
1007 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
1008 other_nets[k] = nodes[k]
1009 other_nets[k]['external']=True
1010 elif nodes[k]['type'] == 'network':
1011 other_nets[k] = nodes[k]
1012 other_nets[k]['external']=False
1013
1014
1015#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1016 for name,vnf in vnfs.items():
tiernocea279c2016-07-18 12:36:49 +02001017 where={}
1018 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001019 error_text = ""
1020 error_pos = "'topology':'nodes':'" + name + "'"
1021 if 'vnf_id' in vnf:
1022 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001023 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001024 if 'VNF model' in vnf:
1025 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001026 where['name'] = vnf['VNF model']
1027 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +02001028 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
1029
tiernocea279c2016-07-18 12:36:49 +02001030 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1031 FROM='vnfs',
1032 WHERE=where,
1033 WHERE_OR=where_or,
1034 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001035 if len(vnf_db)==0:
1036 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1037 elif len(vnf_db)>1:
1038 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001039 vnf['uuid']=vnf_db[0]['uuid']
1040 vnf['description']=vnf_db[0]['description']
1041 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +02001042 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 +01001043 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1044 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001045 for ext_iface in ext_ifaces:
1046 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1047
1048#1.4 get list of connections
1049 conections = topo['topology']['connections']
1050 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001051 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001052 for k in conections.keys():
1053 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1054 ifaces_list = conections[k]['nodes'].items()
1055 elif type(conections[k]['nodes'])==list: #list with dictionary
1056 ifaces_list=[]
1057 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1058 for k2 in conection_pair_list:
1059 ifaces_list += k2
1060
1061 con_type = conections[k].get("type", "link")
1062 if con_type != "link":
1063 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001064 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001065 other_nets[k] = {'external': False}
1066 if conections[k].get("graph"):
1067 other_nets[k]["graph"] = conections[k]["graph"]
1068 ifaces_list.append( (k, None) )
1069
1070
1071 if con_type == "external_network":
1072 other_nets[k]['external'] = True
1073 if conections[k].get("model"):
1074 other_nets[k]["model"] = conections[k]["model"]
1075 else:
1076 other_nets[k]["model"] = k
1077 if con_type == "dataplane_net" or con_type == "bridge_net":
1078 other_nets[k]["model"] = con_type
1079
tiernoefd80c92016-09-16 14:17:46 +02001080 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001081 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)
1082 #print set(ifaces_list)
1083 #check valid VNF and iface names
1084 for iface in ifaces_list:
1085 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001086 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1087 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001088 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001089 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1090 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001091
1092#1.5 unify connections from the pair list to a consolidated list
1093 index=0
1094 while index < len(conections_list):
1095 index2 = index+1
1096 while index2 < len(conections_list):
1097 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1098 conections_list[index] |= conections_list[index2]
1099 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001100 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001101 else:
1102 index2 += 1
1103 conections_list[index] = list(conections_list[index]) # from set to list again
1104 index += 1
1105 #for k in conections_list:
1106 # print k
1107
1108
1109
1110#1.6 Delete non external nets
1111# for k in other_nets.keys():
1112# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1113# for con in conections_list:
1114# delete_indexes=[]
1115# for index in range(0,len(con)):
1116# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1117# for index in delete_indexes:
1118# del con[index]
1119# del other_nets[k]
1120#1.7: Check external_ports are present at database table datacenter_nets
1121 for k,net in other_nets.items():
1122 error_pos = "'topology':'nodes':'" + k + "'"
1123 if net['external']==False:
1124 if 'name' not in net:
1125 net['name']=k
1126 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001127 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001128 if net['model']=='bridge_net':
1129 net['type']='bridge';
1130 elif net['model']=='dataplane_net':
1131 net['type']='data';
1132 else:
tiernof97fd272016-07-11 14:32:37 +02001133 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001134 else: #external
1135#IF we do not want to check that external network exist at datacenter
1136 pass
1137#ELSE
1138# error_text = ""
1139# WHERE_={}
1140# if 'net_id' in net:
1141# error_text += " 'net_id' " + net['net_id']
1142# WHERE_['uuid'] = net['net_id']
1143# if 'model' in net:
1144# error_text += " 'model' " + net['model']
1145# WHERE_['name'] = net['model']
1146# if len(WHERE_) == 0:
1147# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1148# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1149# FROM='datacenter_nets', WHERE=WHERE_ )
1150# if r<0:
1151# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1152# elif r==0:
1153# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1154# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1155# elif r>1:
1156# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1157# return -HTTP_Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
1158# other_nets[k].update(net_db[0])
1159#ENDIF
1160 net_list={}
1161 net_nb=0 #Number of nets
1162 for con in conections_list:
1163 #check if this is connected to a external net
1164 other_net_index=-1
1165 #print
1166 #print "con", con
1167 for index in range(0,len(con)):
1168 #check if this is connected to a external net
1169 for net_key in other_nets.keys():
1170 if con[index][0]==net_key:
1171 if other_net_index>=0:
1172 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 +02001173 #print "nfvo.new_scenario " + error_text
1174 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001175 else:
1176 other_net_index = index
1177 net_target = net_key
1178 break
1179 #print "other_net_index", other_net_index
1180 try:
1181 if other_net_index>=0:
1182 del con[other_net_index]
1183#IF we do not want to check that external network exist at datacenter
1184 if other_nets[net_target]['external'] :
1185 if "name" not in other_nets[net_target]:
1186 other_nets[net_target]['name'] = other_nets[net_target]['model']
1187 if other_nets[net_target]["type"] == "external_network":
1188 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1189 other_nets[net_target]["type"] = "data"
1190 else:
1191 other_nets[net_target]["type"] = "bridge"
1192#ELSE
1193# if other_nets[net_target]['external'] :
1194# 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
1195# if type_=='data' and other_nets[net_target]['type']=="ptp":
1196# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1197# print "nfvo.new_scenario " + error_text
1198# return -HTTP_Bad_Request, error_text
1199#ENDIF
1200 for iface in con:
1201 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1202 else:
1203 #create a net
1204 net_type_bridge=False
1205 net_type_data=False
1206 net_target = "__-__net"+str(net_nb)
tiernoefd80c92016-09-16 14:17:46 +02001207 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
1208 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno7edb6752016-03-21 17:37:52 +01001209 'external':False}
1210 for iface in con:
1211 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1212 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1213 if iface_type=='mgmt' or iface_type=='bridge':
1214 net_type_bridge = True
1215 else:
1216 net_type_data = True
1217 if net_type_bridge and net_type_data:
1218 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 +02001219 #print "nfvo.new_scenario " + error_text
1220 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001221 elif net_type_bridge:
1222 type_='bridge'
1223 else:
1224 type_='data' if len(con)>2 else 'ptp'
1225 net_list[net_target]['type'] = type_
1226 net_nb+=1
1227 except Exception:
1228 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001229 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01001230 #raise e
tiernof97fd272016-07-11 14:32:37 +02001231 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001232
1233#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
1234 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02001235 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01001236 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
1237 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02001238 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01001239 add_mgmt_net = False
1240 for vnf in vnfs.values():
1241 for iface in vnf['ifaces'].values():
1242 if iface['type']=='mgmt' and 'net_key' not in iface:
1243 #iface not connected
1244 iface['net_key'] = 'mgmt'
1245 add_mgmt_net = True
1246 if add_mgmt_net and 'mgmt' not in net_list:
1247 net_list['mgmt']=mgmt_net[0]
1248 net_list['mgmt']['external']=True
1249 net_list['mgmt']['graph']={'visible':False}
1250
1251 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001252 #print
1253 #print 'net_list', net_list
1254 #print
1255 #print 'vnfs', vnfs
1256 #print
tierno7edb6752016-03-21 17:37:52 +01001257
1258#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001259 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001260 'tenant_id':tenant_id, 'name':topo['name'],
1261 'description':topo.get('description',topo['name']),
1262 'public': topo.get('public', False)
1263 })
tierno7edb6752016-03-21 17:37:52 +01001264
tiernof97fd272016-07-11 14:32:37 +02001265 return c
tierno7edb6752016-03-21 17:37:52 +01001266
tierno392f2852016-05-13 12:28:55 +02001267def new_scenario_v02(mydb, tenant_id, scenario_dict):
1268 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001269 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001270 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001271 if "tenant_id" in scenario:
1272 if scenario["tenant_id"] != tenant_id:
1273 print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001274 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1275 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001276 else:
1277 tenant_id=None
1278
1279#1: Check that VNF are present at database table vnfs and update content into scenario dict
1280 for name,vnf in scenario["vnfs"].iteritems():
tiernocea279c2016-07-18 12:36:49 +02001281 where={}
1282 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001283 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001284 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01001285 if 'vnf_id' in vnf:
1286 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001287 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001288 if 'vnf_name' in vnf:
1289 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001290 where['name'] = vnf['vnf_name']
1291 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001292 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tiernocea279c2016-07-18 12:36:49 +02001293 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1294 FROM='vnfs',
1295 WHERE=where,
1296 WHERE_OR=where_or,
1297 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001298 if len(vnf_db)==0:
1299 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1300 elif len(vnf_db)>1:
1301 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001302 vnf['uuid']=vnf_db[0]['uuid']
1303 vnf['description']=vnf_db[0]['description']
1304 vnf['ifaces'] = {}
1305 #get external interfaces
tiernof97fd272016-07-11 14:32:37 +02001306 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 +01001307 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1308 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001309 for ext_iface in ext_ifaces:
1310 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1311
1312#2: Insert net_key at every vnf interface
1313 for net_name,net in scenario["networks"].iteritems():
1314 net_type_bridge=False
1315 net_type_data=False
1316 for iface_dict in net["interfaces"]:
1317 for vnf,iface in iface_dict.iteritems():
1318 if vnf not in scenario["vnfs"]:
1319 error_text = "Error at 'networks':'%s':'interfaces' VNF '%s' not match any VNF at 'vnfs'" % (net_name, vnf)
tiernof97fd272016-07-11 14:32:37 +02001320 #print "nfvo.new_scenario_v02 " + error_text
1321 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001322 if iface not in scenario["vnfs"][vnf]['ifaces']:
1323 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface not match any VNF interface" % (net_name, iface)
tiernof97fd272016-07-11 14:32:37 +02001324 #print "nfvo.new_scenario_v02 " + error_text
1325 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001326 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
1327 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface already connected at network '%s'" \
1328 % (net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
tiernof97fd272016-07-11 14:32:37 +02001329 #print "nfvo.new_scenario_v02 " + error_text
1330 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001331 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
1332 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
1333 if iface_type=='mgmt' or iface_type=='bridge':
1334 net_type_bridge = True
1335 else:
1336 net_type_data = True
1337 if net_type_bridge and net_type_data:
1338 error_text = "Error connection interfaces of bridge type and data type at 'networks':'%s':'interfaces'" % (net_name)
tiernof97fd272016-07-11 14:32:37 +02001339 #print "nfvo.new_scenario " + error_text
1340 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001341 elif net_type_bridge:
1342 type_='bridge'
1343 else:
1344 type_='data' if len(net["interfaces"])>2 else 'ptp'
1345 net['type'] = type_
1346 net['name'] = net_name
1347 net['external'] = net.get('external', False)
1348
1349#3: insert at database
1350 scenario["nets"] = scenario["networks"]
1351 scenario['tenant_id'] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001352 scenario_id = mydb.new_scenario( scenario)
1353 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01001354
1355def edit_scenario(mydb, tenant_id, scenario_id, data):
1356 data["uuid"] = scenario_id
1357 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001358 c = mydb.edit_scenario( data )
1359 return c
tierno7edb6752016-03-21 17:37:52 +01001360
1361def 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 +02001362 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00001363 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
1364 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02001365 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001366 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00001367
tierno7edb6752016-03-21 17:37:52 +01001368 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001369 try:
1370 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tiernof97fd272016-07-11 14:32:37 +02001371 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00001372 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02001373 scenarioDict['datacenter_id'] = datacenter_id
1374 #print '================scenarioDict======================='
1375 #print json.dumps(scenarioDict, indent=4)
1376 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno7edb6752016-03-21 17:37:52 +01001377
tiernoae4a8d12016-07-08 12:30:39 +02001378 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
1379 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001380
tiernoae4a8d12016-07-08 12:30:39 +02001381 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1382 auxNetDict['scenario'] = {}
1383
1384 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
1385 for sce_net in scenarioDict['nets']:
1386 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno7edb6752016-03-21 17:37:52 +01001387
tiernoae4a8d12016-07-08 12:30:39 +02001388 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01001389 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02001390 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01001391 myNetDict = {}
1392 myNetDict["name"] = myNetName
1393 myNetDict["type"] = myNetType
1394 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001395 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01001396 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02001397 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001398 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02001399 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02001400 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001401 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
1402 sce_net['vim_id'] = network_id
1403 auxNetDict['scenario'][sce_net['uuid']] = network_id
1404 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001405 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001406 else:
1407 if sce_net['vim_id'] == None:
1408 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
1409 _, message = rollback(mydb, vims, rollbackList)
1410 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02001411 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02001412 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
1413 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno7edb6752016-03-21 17:37:52 +01001414
tiernoae4a8d12016-07-08 12:30:39 +02001415 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
1416 #For each vnf net, we create it and we add it to instanceNetlist.
1417 for sce_vnf in scenarioDict['vnfs']:
1418 for net in sce_vnf['nets']:
1419 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
1420
1421 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
1422 myNetName = myNetName[0:255] #limit length
1423 myNetType = net['type']
1424 myNetDict = {}
1425 myNetDict["name"] = myNetName
1426 myNetDict["type"] = myNetType
1427 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001428 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02001429 #print myNetDict
1430 #TODO:
1431 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02001432 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001433 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
1434 net['vim_id'] = network_id
1435 if sce_vnf['uuid'] not in auxNetDict:
1436 auxNetDict[sce_vnf['uuid']] = {}
1437 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1438 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001439 net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001440
1441 #print "auxNetDict:"
1442 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
1443
1444 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
1445 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
1446 i = 0
1447 for sce_vnf in scenarioDict['vnfs']:
1448 for vm in sce_vnf['vms']:
1449 i += 1
1450 myVMDict = {}
1451 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01001452 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02001453 #myVMDict['description'] = vm['description']
1454 myVMDict['description'] = myVMDict['name'][0:99]
1455 if not startvms:
1456 myVMDict['start'] = "no"
1457 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1458 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
1459
1460 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001461 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
1462 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001463 vm['vim_image_id'] = image_id
1464
1465 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001466 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001467 if flavor_dict['extended']!=None:
1468 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tiernof97fd272016-07-11 14:32:37 +02001469 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001470 vm['vim_flavor_id'] = flavor_id
1471
1472
1473 myVMDict['imageRef'] = vm['vim_image_id']
1474 myVMDict['flavorRef'] = vm['vim_flavor_id']
1475 myVMDict['networks'] = []
1476 for iface in vm['interfaces']:
1477 netDict = {}
1478 if iface['type']=="data":
1479 netDict['type'] = iface['model']
1480 elif "model" in iface and iface["model"]!=None:
1481 netDict['model']=iface['model']
1482 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1483 #discover type of interface looking at flavor
1484 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1485 for flavor_iface in numa.get('interfaces',[]):
1486 if flavor_iface.get('name') == iface['internal_name']:
1487 if flavor_iface['dedicated'] == 'yes':
1488 netDict['type']="PF" #passthrough
1489 elif flavor_iface['dedicated'] == 'no':
1490 netDict['type']="VF" #siov
1491 elif flavor_iface['dedicated'] == 'yes:sriov':
1492 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1493 netDict["mac_address"] = flavor_iface.get("mac_address")
1494 break;
1495 netDict["use"]=iface['type']
1496 if netDict["use"]=="data" and not netDict.get("type"):
1497 #print "netDict", netDict
1498 #print "iface", iface
1499 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'])
1500 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02001501 raise NfvoException(e_text + "After database migration some information is not available. \
1502 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02001503 else:
tiernof97fd272016-07-11 14:32:37 +02001504 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02001505 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1506 netDict["type"]="virtual"
1507 if "vpci" in iface and iface["vpci"] is not None:
1508 netDict['vpci'] = iface['vpci']
1509 if "mac" in iface and iface["mac"] is not None:
1510 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001511 if "port-security" in iface and iface["port-security"] is not None:
1512 netDict['port_security'] = iface['port-security']
1513 if "floating-ip" in iface and iface["floating-ip"] is not None:
1514 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02001515 netDict['name'] = iface['internal_name']
1516 if iface['net_id'] is None:
1517 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001518 #print iface
1519 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02001520 if vnf_iface['interface_id']==iface['uuid']:
1521 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
1522 break
1523 else:
1524 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1525 #skip bridge ifaces not connected to any net
1526 #if 'net_id' not in netDict or netDict['net_id']==None:
1527 # continue
1528 myVMDict['networks'].append(netDict)
1529 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1530 #print myVMDict['name']
1531 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1532 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1533 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1534 vm_id = myvim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
1535 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'])
1536 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
1537 vm['vim_id'] = vm_id
1538 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1539 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1540 for net in myVMDict['networks']:
1541 if "vim_id" in net:
1542 for iface in vm['interfaces']:
1543 if net["name"]==iface["internal_name"]:
1544 iface["vim_id"]=net["vim_id"]
1545 break
1546
1547 logger.debug("start scenario Deployment done")
1548 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
1549 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001550 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
1551 return mydb.get_instance_scenario(instance_id)
1552
1553 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001554 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001555 if isinstance(e, db_base_Exception):
1556 error_text = "Exception at database"
1557 else:
1558 error_text = "Exception at VIM"
1559 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1560 #logger.error("start_scenario %s", error_text)
1561 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001562
tierno36c0b172017-01-12 18:32:28 +01001563def unify_cloud_config(cloud_config_preserve, cloud_config):
1564 ''' join the cloud config information into cloud_config_preserve.
1565 In case of conflict cloud_config_preserve preserves
1566 None is admited
1567 '''
1568 if not cloud_config_preserve and not cloud_config:
1569 return None
1570
1571 new_cloud_config = {"key-pairs":[], "users":[]}
1572 # key-pairs
1573 if cloud_config_preserve:
1574 for key in cloud_config_preserve.get("key-pairs", () ):
1575 if key not in new_cloud_config["key-pairs"]:
1576 new_cloud_config["key-pairs"].append(key)
1577 if cloud_config:
1578 for key in cloud_config.get("key-pairs", () ):
1579 if key not in new_cloud_config["key-pairs"]:
1580 new_cloud_config["key-pairs"].append(key)
1581 if not new_cloud_config["key-pairs"]:
1582 del new_cloud_config["key-pairs"]
1583
1584 # users
1585 if cloud_config:
1586 new_cloud_config["users"] += cloud_config.get("users", () )
1587 if cloud_config_preserve:
1588 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02001589 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01001590 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02001591 for index0 in range(0,len(users)):
1592 if index0 in index_to_delete:
1593 continue
1594 for index1 in range(index0+1,len(users)):
1595 if index1 in index_to_delete:
1596 continue
1597 if users[index0]["name"] == users[index1]["name"]:
1598 index_to_delete.append(index1)
1599 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01001600 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02001601 users[index0]["key-pairs"] = [key]
1602 elif key not in users[index0]["key-pairs"]:
1603 users[index0]["key-pairs"].append(key)
1604 index_to_delete.sort(reverse=True)
1605 for index in index_to_delete:
1606 del users[index]
tierno36c0b172017-01-12 18:32:28 +01001607 if not new_cloud_config["users"]:
1608 del new_cloud_config["users"]
1609
1610 #boot-data-drive
1611 if cloud_config and cloud_config.get("boot-data-drive") != None:
1612 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
1613 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
1614 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
1615
1616 # user-data
1617 if cloud_config and cloud_config.get("user-data") != None:
1618 new_cloud_config["user-data"] = cloud_config["user-data"]
1619 if cloud_config_preserve and cloud_config_preserve.get("user-data") != None:
1620 new_cloud_config["user-data"] = cloud_config_preserve["user-data"]
1621
1622 # config files
1623 new_cloud_config["config-files"] = []
1624 if cloud_config and cloud_config.get("config-files") != None:
1625 new_cloud_config["config-files"] += cloud_config["config-files"]
1626 if cloud_config_preserve:
1627 for file in cloud_config_preserve.get("config-files", ()):
1628 for index in range(0, len(new_cloud_config["config-files"])):
1629 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
1630 new_cloud_config["config-files"][index] = file
1631 break
1632 else:
1633 new_cloud_config["config-files"].append(file)
1634 if not new_cloud_config["config-files"]:
1635 del new_cloud_config["config-files"]
1636 return new_cloud_config
1637
1638
tiernoa4e1a6e2016-08-31 14:19:40 +02001639
tiernoa2793912016-10-04 08:15:08 +00001640def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02001641 datacenter_id = None
1642 datacenter_name = None
1643 if datacenter_id_name:
1644 if utils.check_valid_uuid(datacenter_id_name):
1645 datacenter_id = datacenter_id_name
1646 else:
1647 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00001648 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02001649 if len(vims) == 0:
1650 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1651 elif len(vims)>1:
1652 #print "nfvo.datacenter_action() error. Several datacenters found"
1653 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1654 return vims.keys()[0], vims.values()[0]
1655
garciadeblas9f8456e2016-09-05 05:02:59 +02001656def new_scenario_v03(mydb, tenant_id, scenario_dict):
1657 scenario = scenario_dict["scenario"]
1658 if tenant_id != "any":
1659 check_tenant(mydb, tenant_id)
1660 if "tenant_id" in scenario:
1661 if scenario["tenant_id"] != tenant_id:
1662 logger("Tenant '%s' not found", tenant_id)
1663 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1664 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
1665 else:
1666 tenant_id=None
1667
1668#1: Check that VNF are present at database table vnfs and update content into scenario dict
1669 for name,vnf in scenario["vnfs"].iteritems():
1670 where={}
1671 where_or={"tenant_id": tenant_id, 'public': "true"}
1672 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001673 error_pos = "'scenario':'vnfs':'" + name + "'"
garciadeblas9f8456e2016-09-05 05:02:59 +02001674 if 'vnf_id' in vnf:
1675 error_text += " 'vnf_id' " + vnf['vnf_id']
1676 where['uuid'] = vnf['vnf_id']
1677 if 'vnf_name' in vnf:
1678 error_text += " 'vnf_name' " + vnf['vnf_name']
1679 where['name'] = vnf['vnf_name']
1680 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001681 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
garciadeblas9f8456e2016-09-05 05:02:59 +02001682 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1683 FROM='vnfs',
1684 WHERE=where,
1685 WHERE_OR=where_or,
1686 WHERE_AND_OR="AND")
1687 if len(vnf_db)==0:
1688 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1689 elif len(vnf_db)>1:
1690 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
1691 vnf['uuid']=vnf_db[0]['uuid']
1692 vnf['description']=vnf_db[0]['description']
1693 vnf['ifaces'] = {}
1694 # get external interfaces
1695 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1696 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1697 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
1698 for ext_iface in ext_ifaces:
1699 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1700
1701 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
1702
1703#2: Insert net_key and ip_address at every vnf interface
1704 for net_name,net in scenario["networks"].iteritems():
1705 net_type_bridge=False
1706 net_type_data=False
1707 for iface_dict in net["interfaces"]:
1708 logger.debug("Iface_dict %s", iface_dict)
1709 vnf = iface_dict["vnf"]
1710 iface = iface_dict["vnf_interface"]
1711 if vnf not in scenario["vnfs"]:
1712 error_text = "Error at 'networks':'%s':'interfaces' VNF '%s' not match any VNF at 'vnfs'" % (net_name, vnf)
1713 #logger.debug(error_text)
1714 raise NfvoException(error_text, HTTP_Not_Found)
1715 if iface not in scenario["vnfs"][vnf]['ifaces']:
1716 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface not match any VNF interface" % (net_name, iface)
1717 #logger.debug(error_text)
1718 raise NfvoException(error_text, HTTP_Bad_Request)
1719 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
1720 error_text = "Error at 'networks':'%s':'interfaces':'%s' interface already connected at network '%s'" \
1721 % (net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
1722 #logger.debug(error_text)
1723 raise NfvoException(error_text, HTTP_Bad_Request)
1724 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
1725 scenario["vnfs"][vnf]['ifaces'][ iface ]['ip_address'] = iface_dict.get('ip_address',None)
1726 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
1727 if iface_type=='mgmt' or iface_type=='bridge':
1728 net_type_bridge = True
1729 else:
1730 net_type_data = True
1731 if net_type_bridge and net_type_data:
1732 error_text = "Error connection interfaces of bridge type and data type at 'networks':'%s':'interfaces'" % (net_name)
1733 #logger.debug(error_text)
1734 raise NfvoException(error_text, HTTP_Bad_Request)
1735 elif net_type_bridge:
1736 type_='bridge'
1737 else:
1738 type_='data' if len(net["interfaces"])>2 else 'ptp'
1739
1740 if ("implementation" in net):
1741 if (type_ == "bridge" and net["implementation"] == "underlay"):
1742 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at 'network':'%s'" % (net_name)
1743 #logger.debug(error_text)
1744 raise NfvoException(error_text, HTTP_Bad_Request)
1745 elif (type_ <> "bridge" and net["implementation"] == "overlay"):
1746 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at 'network':'%s'" % (net_name)
1747 #logger.debug(error_text)
1748 raise NfvoException(error_text, HTTP_Bad_Request)
1749 net.pop("implementation")
1750 if ("type" in net):
1751 if (type_ == "data" and net["type"] == "e-line"):
1752 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type 'e-line' at 'network':'%s'" % (net_name)
1753 #logger.debug(error_text)
1754 raise NfvoException(error_text, HTTP_Bad_Request)
1755 elif (type_ == "ptp" and net["type"] == "e-lan"):
1756 type_ = "data"
1757
1758 net['type'] = type_
1759 net['name'] = net_name
1760 net['external'] = net.get('external', False)
1761
1762#3: insert at database
1763 scenario["nets"] = scenario["networks"]
1764 scenario['tenant_id'] = tenant_id
1765 scenario_id = mydb.new_scenario2(scenario)
1766 return scenario_id
1767
1768def update(d, u):
1769 '''Takes dict d and updates it with the values in dict u.'''
1770 '''It merges all depth levels'''
1771 for k, v in u.iteritems():
1772 if isinstance(v, collections.Mapping):
1773 r = update(d.get(k, {}), v)
1774 d[k] = r
1775 else:
1776 d[k] = u[k]
1777 return d
1778
tierno7edb6752016-03-21 17:37:52 +01001779def create_instance(mydb, tenant_id, instance_dict):
tiernoae4a8d12016-07-08 12:30:39 +02001780 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno4319dad2016-09-05 12:11:11 +02001781 #logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01001782 scenario = instance_dict["scenario"]
tiernobe41e222016-09-02 15:16:13 +02001783
1784 #find main datacenter
1785 myvims = {}
tiernoa2793912016-10-04 08:15:08 +00001786 datacenter2tenant = {}
tierno7edb6752016-03-21 17:37:52 +01001787 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02001788 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
1789 myvims[default_datacenter_id] = vim
tiernoa2793912016-10-04 08:15:08 +00001790 datacenter2tenant[default_datacenter_id] = vim['config']['datacenter_tenant_id']
tierno392f2852016-05-13 12:28:55 +02001791 #myvim_tenant = myvim['tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001792# default_datacenter_name = vim['name']
tierno7edb6752016-03-21 17:37:52 +01001793 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001794
1795 #print "Checking that the scenario exists and getting the scenario dictionary"
tiernobe41e222016-09-02 15:16:13 +02001796 scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001797
garciadeblasbb6a1ed2016-09-30 14:02:09 +00001798 #logger.debug(">>>>>>> Dictionaries before merging")
1799 #logger.debug(">>>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
1800 #logger.debug(">>>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
garciadeblas9f8456e2016-09-05 05:02:59 +02001801
tiernobe41e222016-09-02 15:16:13 +02001802 scenarioDict['datacenter_id'] = default_datacenter_id
garciadeblas9f8456e2016-09-05 05:02:59 +02001803
tierno7edb6752016-03-21 17:37:52 +01001804 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1805 auxNetDict['scenario'] = {}
1806
tierno4319dad2016-09-05 12:11:11 +02001807 logger.debug("Creating instance from scenario-dict:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001808 instance_name = instance_dict["name"]
1809 instance_description = instance_dict.get("description")
1810 try:
1811 #0 check correct parameters
tiernobe41e222016-09-02 15:16:13 +02001812 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001813 found=False
1814 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001815 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01001816 found = True
1817 break
1818 if not found:
tiernobe41e222016-09-02 15:16:13 +02001819 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request)
1820 if "sites" not in net_instance_desc:
1821 net_instance_desc["sites"] = [ {} ]
1822 site_without_datacenter_field = False
1823 for site in net_instance_desc["sites"]:
1824 if site.get("datacenter"):
1825 if site["datacenter"] not in myvims:
1826 #Add this datacenter to myvims
1827 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
1828 myvims[d] = v
tiernoa2793912016-10-04 08:15:08 +00001829 datacenter2tenant[d] = v['config']['datacenter_tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001830 site["datacenter"] = d #change name to id
1831 else:
1832 if site_without_datacenter_field:
1833 raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
1834 site_without_datacenter_field = True
1835 site["datacenter"] = default_datacenter_id #change name to id
1836
1837 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01001838 found=False
1839 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001840 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01001841 found = True
1842 break
1843 if not found:
tiernobe41e222016-09-02 15:16:13 +02001844 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
1845 if "datacenter" in vnf_instance_desc:
1846 #Add this datacenter to myvims
1847 if vnf_instance_desc["datacenter"] not in myvims:
1848 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
1849 myvims[d] = v
tiernoa2793912016-10-04 08:15:08 +00001850 datacenter2tenant[d] = v['config']['datacenter_tenant_id']
1851 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01001852
tiernoa4e1a6e2016-08-31 14:19:40 +02001853 #0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01001854 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02001855
1856 #0.2 merge instance information into scenario
1857 #Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
1858 #However, this is not possible yet.
1859 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
1860 for scenario_net in scenarioDict['nets']:
1861 if net_name == scenario_net["name"]:
1862 if 'ip-profile' in net_instance_desc:
1863 ipprofile = net_instance_desc['ip-profile']
1864 ipprofile['subnet_address'] = ipprofile.pop('subnet-address',None)
1865 ipprofile['ip_version'] = ipprofile.pop('ip-version','IPv4')
1866 ipprofile['gateway_address'] = ipprofile.pop('gateway-address',None)
1867 ipprofile['dns_address'] = ipprofile.pop('dns-address',None)
1868 if 'dhcp' in ipprofile:
1869 ipprofile['dhcp_start_address'] = ipprofile['dhcp'].get('start-address',None)
1870 ipprofile['dhcp_enabled'] = ipprofile['dhcp'].get('enabled',True)
1871 ipprofile['dhcp_count'] = ipprofile['dhcp'].get('count',None)
1872 del ipprofile['dhcp']
garciadeblasedca7b32016-09-29 14:01:52 +00001873 if 'ip_profile' not in scenario_net:
1874 scenario_net['ip_profile'] = ipprofile
1875 else:
1876 update(scenario_net['ip_profile'],ipprofile)
tiernoe6c58ce2016-09-14 16:02:49 +02001877 for interface in net_instance_desc.get('interfaces', () ):
garciadeblas9f8456e2016-09-05 05:02:59 +02001878 if 'ip_address' in interface:
1879 for vnf in scenarioDict['vnfs']:
1880 if interface['vnf'] == vnf['name']:
1881 for vnf_interface in vnf['interfaces']:
1882 if interface['vnf_interface'] == vnf_interface['external_name']:
1883 vnf_interface['ip_address']=interface['ip_address']
1884
garciadeblasbb6a1ed2016-09-30 14:02:09 +00001885 #logger.debug(">>>>>>>> Merged dictionary")
tierno4319dad2016-09-05 12:11:11 +02001886 logger.debug("Creating instance scenario-dict MERGED:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02001887
tierno7edb6752016-03-21 17:37:52 +01001888
1889 #1. Creating new nets (sce_nets) in the VIM"
1890 for sce_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001891 sce_net["vim_id_sites"]={}
tierno7edb6752016-03-21 17:37:52 +01001892 descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{})
tiernobe41e222016-09-02 15:16:13 +02001893 net_name = descriptor_net.get("vim-network-name")
1894 auxNetDict['scenario'][sce_net['uuid']] = {}
1895
1896 sites = descriptor_net.get("sites", [ {} ])
1897 for site in sites:
1898 if site.get("datacenter"):
1899 vim = myvims[ site["datacenter"] ]
1900 datacenter_id = site["datacenter"]
tierno7edb6752016-03-21 17:37:52 +01001901 else:
tiernobe41e222016-09-02 15:16:13 +02001902 vim = myvims[ default_datacenter_id ]
1903 datacenter_id = default_datacenter_id
tiernobe41e222016-09-02 15:16:13 +02001904 net_type = sce_net['type']
1905 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True
1906 if sce_net["external"]:
1907 if not net_name:
1908 net_name = sce_net["name"]
1909 if "netmap-use" in site or "netmap-create" in site:
1910 create_network = False
1911 lookfor_network = False
1912 if "netmap-use" in site:
1913 lookfor_network = True
1914 if utils.check_valid_uuid(site["netmap-use"]):
1915 filter_text = "scenario id '%s'" % site["netmap-use"]
1916 lookfor_filter["id"] = site["netmap-use"]
1917 else:
1918 filter_text = "scenario name '%s'" % site["netmap-use"]
1919 lookfor_filter["name"] = site["netmap-use"]
1920 if "netmap-create" in site:
1921 create_network = True
1922 net_vim_name = net_name
1923 if site["netmap-create"]:
1924 net_vim_name = site["netmap-create"]
1925
1926 elif sce_net['vim_id'] != None:
1927 #there is a netmap at datacenter_nets database #TODO REVISE!!!!
1928 create_network = False
1929 lookfor_network = True
1930 lookfor_filter["id"] = sce_net['vim_id']
1931 filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"])
1932 #look for network at datacenter and return error
1933 else:
1934 #There is not a netmap, look at datacenter for a net with this name and create if not found
1935 create_network = True
1936 lookfor_network = True
1937 lookfor_filter["name"] = sce_net["name"]
1938 net_vim_name = sce_net["name"]
1939 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01001940 else:
tiernobe41e222016-09-02 15:16:13 +02001941 if not net_name:
1942 net_name = "%s.%s" %(instance_name, sce_net["name"])
1943 net_name = net_name[:255] #limit length
1944 net_vim_name = net_name
1945 create_network = True
1946 lookfor_network = False
1947
1948 if lookfor_network:
1949 vim_nets = vim.get_network_list(filter_dict=lookfor_filter)
1950 if len(vim_nets) > 1:
1951 raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1952 elif len(vim_nets) == 0:
1953 if not create_network:
1954 raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request )
1955 else:
1956 sce_net["vim_id_sites"][datacenter_id] = vim_nets[0]['id']
tiernobe41e222016-09-02 15:16:13 +02001957 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id']
1958 create_network = False
1959 if create_network:
1960 #if network is not external
garciadeblas9f8456e2016-09-05 05:02:59 +02001961 network_id = vim.new_network(net_vim_name, net_type, sce_net.get('ip_profile',None))
tiernobe41e222016-09-02 15:16:13 +02001962 sce_net["vim_id_sites"][datacenter_id] = network_id
1963 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = network_id
1964 rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001965 sce_net["created"] = True
tierno7edb6752016-03-21 17:37:52 +01001966
1967 #2. Creating new nets (vnf internal nets) in the VIM"
1968 #For each vnf net, we create it and we add it to instanceNetlist.
1969 for sce_vnf in scenarioDict['vnfs']:
1970 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02001971 if sce_vnf.get("datacenter"):
1972 vim = myvims[ sce_vnf["datacenter"] ]
1973 datacenter_id = sce_vnf["datacenter"]
1974 else:
1975 vim = myvims[ default_datacenter_id ]
1976 datacenter_id = default_datacenter_id
tierno7edb6752016-03-21 17:37:52 +01001977 descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{})
1978 net_name = descriptor_net.get("name")
1979 if not net_name:
1980 net_name = "%s.%s" %(instance_name, net["name"])
1981 net_name = net_name[:255] #limit length
1982 net_type = net['type']
garciadeblas9f8456e2016-09-05 05:02:59 +02001983 network_id = vim.new_network(net_name, net_type, net.get('ip_profile',None))
tierno7edb6752016-03-21 17:37:52 +01001984 net['vim_id'] = network_id
1985 if sce_vnf['uuid'] not in auxNetDict:
1986 auxNetDict[sce_vnf['uuid']] = {}
1987 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1988 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001989 net["created"] = True
1990
tierno7edb6752016-03-21 17:37:52 +01001991
tiernoae4a8d12016-07-08 12:30:39 +02001992 #print "auxNetDict:"
1993 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01001994
1995 #3. Creating new vm instances in the VIM
tiernoae4a8d12016-07-08 12:30:39 +02001996 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
tierno7edb6752016-03-21 17:37:52 +01001997 for sce_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02001998 if sce_vnf.get("datacenter"):
1999 vim = myvims[ sce_vnf["datacenter"] ]
2000 datacenter_id = sce_vnf["datacenter"]
2001 else:
2002 vim = myvims[ default_datacenter_id ]
2003 datacenter_id = default_datacenter_id
2004 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002005 i = 0
2006 for vm in sce_vnf['vms']:
2007 i += 1
2008 myVMDict = {}
tiernoae65a482016-11-24 16:20:05 +01002009 myVMDict['name'] = "{}.{}.{}".format(instance_name,sce_vnf['name'],chr(96+i))
tierno7edb6752016-03-21 17:37:52 +01002010 myVMDict['description'] = myVMDict['name'][0:99]
2011# if not startvms:
2012# myVMDict['start'] = "no"
2013 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2014 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002015 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00002016 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01002017 vm['vim_image_id'] = image_id
2018
2019 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002020 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01002021 if flavor_dict['extended']!=None:
2022 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
montesmoreno0c8def02016-12-22 12:16:23 +00002023 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
2024
2025
2026
2027
2028 #Obtain information for additional disks
2029 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id})
2030 if not extended_flavor_dict:
2031 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
2032 return
2033
2034 #extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
2035 myVMDict['disks'] = None
2036 extended_info = extended_flavor_dict[0]['extended']
2037 if extended_info != None:
2038 extended_flavor_dict_yaml = yaml.load(extended_info)
2039 if 'disks' in extended_flavor_dict_yaml:
2040 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
2041
2042
2043
2044
tierno7edb6752016-03-21 17:37:52 +01002045 vm['vim_flavor_id'] = flavor_id
2046
2047 myVMDict['imageRef'] = vm['vim_image_id']
2048 myVMDict['flavorRef'] = vm['vim_flavor_id']
2049 myVMDict['networks'] = []
tiernoa2793912016-10-04 08:15:08 +00002050 #TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno7edb6752016-03-21 17:37:52 +01002051 for iface in vm['interfaces']:
2052 netDict = {}
2053 if iface['type']=="data":
2054 netDict['type'] = iface['model']
2055 elif "model" in iface and iface["model"]!=None:
2056 netDict['model']=iface['model']
2057 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2058 #discover type of interface looking at flavor
2059 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2060 for flavor_iface in numa.get('interfaces',[]):
2061 if flavor_iface.get('name') == iface['internal_name']:
2062 if flavor_iface['dedicated'] == 'yes':
2063 netDict['type']="PF" #passthrough
2064 elif flavor_iface['dedicated'] == 'no':
2065 netDict['type']="VF" #siov
2066 elif flavor_iface['dedicated'] == 'yes:sriov':
2067 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2068 netDict["mac_address"] = flavor_iface.get("mac_address")
2069 break;
2070 netDict["use"]=iface['type']
2071 if netDict["use"]=="data" and not netDict.get("type"):
2072 #print "netDict", netDict
2073 #print "iface", iface
2074 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'])
2075 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02002076 raise NfvoException(e_text + "After database migration some information is not available. \
2077 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002078 else:
tiernoae4a8d12016-07-08 12:30:39 +02002079 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002080 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2081 netDict["type"]="virtual"
2082 if "vpci" in iface and iface["vpci"] is not None:
2083 netDict['vpci'] = iface['vpci']
2084 if "mac" in iface and iface["mac"] is not None:
2085 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002086 if "port-security" in iface and iface["port-security"] is not None:
2087 netDict['port_security'] = iface['port-security']
2088 if "floating-ip" in iface and iface["floating-ip"] is not None:
2089 netDict['floating_ip'] = iface['floating-ip']
tierno7edb6752016-03-21 17:37:52 +01002090 netDict['name'] = iface['internal_name']
2091 if iface['net_id'] is None:
2092 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002093 #print iface
2094 #print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01002095 if vnf_iface['interface_id']==iface['uuid']:
tiernobe41e222016-09-02 15:16:13 +02002096 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01002097 break
2098 else:
2099 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2100 #skip bridge ifaces not connected to any net
2101 #if 'net_id' not in netDict or netDict['net_id']==None:
2102 # continue
2103 myVMDict['networks'].append(netDict)
tiernoae4a8d12016-07-08 12:30:39 +02002104 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2105 #print myVMDict['name']
2106 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2107 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2108 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tierno36c0b172017-01-12 18:32:28 +01002109 if vm.get("boot_data"):
2110 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config)
2111 else:
2112 cloud_config_vm = cloud_config
tiernobe41e222016-09-02 15:16:13 +02002113 vm_id = vim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
tierno36c0b172017-01-12 18:32:28 +01002114 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'], cloud_config = cloud_config_vm,
montesmoreno0c8def02016-12-22 12:16:23 +00002115 disk_list = myVMDict['disks'])
2116
tierno7edb6752016-03-21 17:37:52 +01002117 vm['vim_id'] = vm_id
2118 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2119 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2120 for net in myVMDict['networks']:
2121 if "vim_id" in net:
2122 for iface in vm['interfaces']:
2123 if net["name"]==iface["internal_name"]:
2124 iface["vim_id"]=net["vim_id"]
2125 break
tiernoa2793912016-10-04 08:15:08 +00002126 scenarioDict["datacenter2tenant"] = datacenter2tenant
2127 logger.debug("create_instance Deployment done scenarioDict: %s",
2128 yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False) )
tiernof97fd272016-07-11 14:32:37 +02002129 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_name, instance_description, scenarioDict)
2130 return mydb.get_instance_scenario(instance_id)
2131 except (NfvoException, vimconn.vimconnException,db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02002132 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002133 if isinstance(e, db_base_Exception):
2134 error_text = "database Exception"
2135 elif isinstance(e, vimconn.vimconnException):
2136 error_text = "VIM Exception"
2137 else:
2138 error_text = "Exception"
2139 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2140 #logger.error("create_instance: %s", error_text)
2141 raise NfvoException(error_text, e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002142
tierno7edb6752016-03-21 17:37:52 +01002143def delete_instance(mydb, tenant_id, instance_id):
tiernoae4a8d12016-07-08 12:30:39 +02002144 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002145 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +02002146 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01002147 tenant_id = instanceDict["tenant_id"]
tiernoae4a8d12016-07-08 12:30:39 +02002148 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01002149
tiernoa2793912016-10-04 08:15:08 +00002150 #1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02002151 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002152
2153 #2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00002154 error_msg = ""
2155 myvims={}
tierno7edb6752016-03-21 17:37:52 +01002156
2157 #2.1 deleting VMs
2158 #vm_fail_list=[]
2159 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002160 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2161 if datacenter_key not in myvims:
2162 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
2163 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2164 if len(vims) == 0:
2165 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
2166 sce_vnf["datacenter_tenant_id"]))
2167 myvims[datacenter_key] = None
2168 else:
2169 myvims[datacenter_key] = vims.values()[0]
2170 myvim = myvims[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01002171 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002172 if not myvim:
2173 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
2174 continue
tiernoae4a8d12016-07-08 12:30:39 +02002175 try:
2176 myvim.delete_vminstance(vm['vim_vm_id'])
2177 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002178 error_msg+="\n VM VIM_id={} not found at datacenter={}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
tiernoae4a8d12016-07-08 12:30:39 +02002179 logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found",
2180 vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'])
2181 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002182 error_msg+="\n VM VIM_id={} at datacenter={} Error: {} {}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"], e.http_code, str(e))
2183 logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM_id '%s', from VNF_id '%s': %s",
tiernoae4a8d12016-07-08 12:30:39 +02002184 e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e))
tierno7edb6752016-03-21 17:37:52 +01002185
2186 #2.2 deleting NETS
2187 #net_fail_list=[]
2188 for net in instanceDict['nets']:
tierno66345bc2016-09-26 11:37:55 +02002189 if not net['created']:
tierno7edb6752016-03-21 17:37:52 +01002190 continue #skip not created nets
tiernoa2793912016-10-04 08:15:08 +00002191 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2192 if datacenter_key not in myvims:
2193 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
2194 datacenter_tenant_id=net["datacenter_tenant_id"])
2195 if len(vims) == 0:
2196 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2197 myvims[datacenter_key] = None
2198 else:
2199 myvims[datacenter_key] = vims.values()[0]
2200 myvim = myvims[datacenter_key]
2201
tierno7edb6752016-03-21 17:37:52 +01002202 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00002203 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
tierno7edb6752016-03-21 17:37:52 +01002204 continue
tiernoae4a8d12016-07-08 12:30:39 +02002205 try:
2206 myvim.delete_network(net['vim_net_id'])
2207 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002208 error_msg+="\n NET VIM_id={} not found at datacenter={}".format(net['vim_net_id'], net["datacenter_id"])
2209 logger.warn("NET '%s', VIM_id '%s', from VNF_net_id '%s' not found",
2210 net['uuid'], net['vim_net_id'], str(net['vnf_net_id']))
tiernoae4a8d12016-07-08 12:30:39 +02002211 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002212 error_msg+="\n NET VIM_id={} at datacenter={} Error: {} {}".format(net['vim_net_id'], net["datacenter_id"], e.http_code, str(e))
2213 logger.error("Error %d deleting NET '%s', VIM_id '%s', from VNF_net_id '%s': %s",
2214 e.http_code, net['uuid'], net['vim_net_id'], str(net['vnf_net_id']), str(e))
tierno7edb6752016-03-21 17:37:52 +01002215 if len(error_msg)>0:
tiernof97fd272016-07-11 14:32:37 +02002216 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 +01002217 else:
tiernof97fd272016-07-11 14:32:37 +02002218 return 'instance ' + message + ' deleted'
tierno7edb6752016-03-21 17:37:52 +01002219
2220def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
2221 '''Refreshes a scenario instance. It modifies instanceDict'''
2222 '''Returns:
2223 - 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
2224 - error_msg
2225 '''
2226 # Assumption: nfvo_tenant and instance_id were checked before entering into this function
tiernoae4a8d12016-07-08 12:30:39 +02002227 #print "nfvo.refresh_instance begins"
tierno7edb6752016-03-21 17:37:52 +01002228 #print json.dumps(instanceDict, indent=4)
2229
tiernoae4a8d12016-07-08 12:30:39 +02002230 #print "Getting the VIM URL and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002231 myvims={}
2232
tiernoae4a8d12016-07-08 12:30:39 +02002233 # 1. Getting VIM vm and net list
tierno7edb6752016-03-21 17:37:52 +01002234 vms_updated = [] #List of VM instance uuids in openmano that were updated
2235 vms_notupdated=[]
tiernoa2793912016-10-04 08:15:08 +00002236 vm_list = {}
tierno7edb6752016-03-21 17:37:52 +01002237 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002238 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2239 if datacenter_key not in vm_list:
2240 vm_list[datacenter_key] = []
2241 if datacenter_key not in myvims:
2242 vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
2243 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2244 if len(vims) == 0:
2245 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
2246 myvims[datacenter_key] = None
2247 else:
2248 myvims[datacenter_key] = vims.values()[0]
tierno7edb6752016-03-21 17:37:52 +01002249 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002250 vm_list[datacenter_key].append(vm['vim_vm_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002251 vms_notupdated.append(vm["uuid"])
2252
2253 nets_updated = [] #List of VM instance uuids in openmano that were updated
tierno7edb6752016-03-21 17:37:52 +01002254 nets_notupdated=[]
tiernoa2793912016-10-04 08:15:08 +00002255 net_list = {}
tierno7edb6752016-03-21 17:37:52 +01002256 for net in instanceDict['nets']:
tiernoa2793912016-10-04 08:15:08 +00002257 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2258 if datacenter_key not in net_list:
2259 net_list[datacenter_key] = []
2260 if datacenter_key not in myvims:
2261 vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
2262 datacenter_tenant_id=net["datacenter_tenant_id"])
2263 if len(vims) == 0:
2264 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2265 myvims[datacenter_key] = None
2266 else:
2267 myvims[datacenter_key] = vims.values()[0]
2268
2269 net_list[datacenter_key].append(net['vim_net_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002270 nets_notupdated.append(net["uuid"])
2271
tiernoa2793912016-10-04 08:15:08 +00002272 # 1. Getting the status of all VMs
2273 vm_dict={}
2274 for datacenter_key in myvims:
2275 if not vm_list.get(datacenter_key):
2276 continue
2277 failed = True
2278 failed_message=""
2279 if not myvims[datacenter_key]:
2280 failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2281 else:
2282 try:
2283 vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
2284 failed = False
2285 except vimconn.vimconnException as e:
2286 logger.error("VIM exception %s %s", type(e).__name__, str(e))
2287 failed_message = str(e)
2288 if failed:
2289 for vm in vm_list[datacenter_key]:
2290 vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
tiernoae4a8d12016-07-08 12:30:39 +02002291
tiernoa2793912016-10-04 08:15:08 +00002292 # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
2293 for sce_vnf in instanceDict['vnfs']:
2294 for vm in sce_vnf['vms']:
2295 vm_id = vm['vim_vm_id']
2296 interfaces = vm_dict[vm_id].pop('interfaces', [])
2297 #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
2298 has_mgmt_iface = False
2299 for iface in vm["interfaces"]:
2300 if iface["type"]=="mgmt":
2301 has_mgmt_iface = True
2302 if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
2303 vm_dict[vm_id]['status'] = "ACTIVE"
tiernoa3d49e62016-10-05 15:20:26 +00002304 if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
2305 vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
tiernoa2793912016-10-04 08:15:08 +00002306 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'):
2307 vm['status'] = vm_dict[vm_id]['status']
2308 vm['error_msg'] = vm_dict[vm_id].get('error_msg')
2309 vm['vim_info'] = vm_dict[vm_id].get('vim_info')
2310 # 2.1. Update in openmano DB the VMs whose status changed
tiernof97fd272016-07-11 14:32:37 +02002311 try:
tiernoa2793912016-10-04 08:15:08 +00002312 updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
2313 vms_notupdated.remove(vm["uuid"])
2314 if updates>0:
2315 vms_updated.append(vm["uuid"])
tiernof97fd272016-07-11 14:32:37 +02002316 except db_base_Exception as e:
2317 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tiernoa2793912016-10-04 08:15:08 +00002318 # 2.2. Update in openmano DB the interface VMs
2319 for interface in interfaces:
2320 #translate from vim_net_id to instance_net_id
2321 network_id_list=[]
2322 for net in instanceDict['nets']:
2323 if net["vim_net_id"] == interface["vim_net_id"]:
2324 network_id_list.append(net["uuid"])
2325 if not network_id_list:
2326 continue
2327 del interface["vim_net_id"]
2328 try:
2329 for network_id in network_id_list:
2330 mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
2331 except db_base_Exception as e:
2332 logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
2333
2334 # 3. Getting the status of all nets
2335 net_dict = {}
2336 for datacenter_key in myvims:
2337 if not net_list.get(datacenter_key):
2338 continue
2339 failed = True
2340 failed_message = ""
2341 if not myvims[datacenter_key]:
2342 failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2343 else:
2344 try:
2345 net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
2346 failed = False
2347 except vimconn.vimconnException as e:
2348 logger.error("VIM exception %s %s", type(e).__name__, str(e))
2349 failed_message = str(e)
2350 if failed:
2351 for net in net_list[datacenter_key]:
2352 net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2353
2354 # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
2355 # TODO: update nets inside a vnf
2356 for net in instanceDict['nets']:
2357 net_id = net['vim_net_id']
tiernoa3d49e62016-10-05 15:20:26 +00002358 if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
2359 net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
tiernoa2793912016-10-04 08:15:08 +00002360 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'):
2361 net['status'] = net_dict[net_id]['status']
2362 net['error_msg'] = net_dict[net_id].get('error_msg')
2363 net['vim_info'] = net_dict[net_id].get('vim_info')
2364 # 5.1. Update in openmano DB the nets whose status changed
2365 try:
2366 updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
2367 nets_notupdated.remove(net["uuid"])
2368 if updated>0:
2369 nets_updated.append(net["uuid"])
2370 except db_base_Exception as e:
2371 logger.error("nfvo.refresh_instance error database update: %s", str(e))
tierno7edb6752016-03-21 17:37:52 +01002372
2373 # Returns appropriate output
tiernoae4a8d12016-07-08 12:30:39 +02002374 #print "nfvo.refresh_instance finishes"
2375 logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
2376 str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01002377 instance_id = instanceDict['uuid']
tierno7edb6752016-03-21 17:37:52 +01002378 if len(vms_notupdated)+len(nets_notupdated)>0:
tiernoae4a8d12016-07-08 12:30:39 +02002379 error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
tierno7edb6752016-03-21 17:37:52 +01002380 return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
2381
tiernoae4a8d12016-07-08 12:30:39 +02002382 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01002383
2384def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02002385 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002386 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002387 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
2388
tiernoae4a8d12016-07-08 12:30:39 +02002389 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02002390 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
2391 if len(vims) == 0:
2392 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002393 myvim = vims.values()[0]
2394
2395
2396 input_vnfs = action_dict.pop("vnfs", [])
2397 input_vms = action_dict.pop("vms", [])
2398 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
2399 vm_result = {}
2400 vm_error = 0
2401 vm_ok = 0
2402 for sce_vnf in instanceDict['vnfs']:
2403 for vm in sce_vnf['vms']:
2404 if not action_over_all:
2405 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
2406 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
2407 continue
tiernoae4a8d12016-07-08 12:30:39 +02002408 try:
2409 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
tierno7edb6752016-03-21 17:37:52 +01002410 if "console" in action_dict:
tierno20fc2a22016-08-19 17:02:35 +02002411 if not global_config["http_console_proxy"]:
2412 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2413 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2414 protocol=data["protocol"],
2415 ip = data["server"],
2416 port = data["port"],
2417 suffix = data["suffix"]),
2418 "name":vm['name']
2419 }
2420 vm_ok +=1
2421 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
tierno7edb6752016-03-21 17:37:52 +01002422 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
2423 "description": "this console is only reachable by local interface",
2424 "name":vm['name']
2425 }
2426 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02002427 else:
tierno7edb6752016-03-21 17:37:52 +01002428 #print "console data", data
tierno20fc2a22016-08-19 17:02:35 +02002429 try:
2430 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
2431 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2432 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2433 protocol=data["protocol"],
2434 ip = global_config["http_console_host"],
2435 port = console_thread.port,
2436 suffix = data["suffix"]),
2437 "name":vm['name']
2438 }
2439 vm_ok +=1
2440 except NfvoException as e:
2441 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2442 vm_error+=1
2443
tierno7edb6752016-03-21 17:37:52 +01002444 else:
tiernof97fd272016-07-11 14:32:37 +02002445 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
tierno7edb6752016-03-21 17:37:52 +01002446 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02002447 except vimconn.vimconnException as e:
2448 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2449 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01002450
2451 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02002452 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002453 else:
tierno351863c2016-07-23 01:46:03 +02002454 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002455
2456def create_or_use_console_proxy_thread(console_server, console_port):
2457 #look for a non-used port
2458 console_thread_key = console_server + ":" + str(console_port)
2459 if console_thread_key in global_config["console_thread"]:
2460 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02002461 return global_config["console_thread"][console_thread_key]
tierno7edb6752016-03-21 17:37:52 +01002462
2463 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02002464 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01002465 if port in global_config["console_ports"]:
2466 continue
2467 try:
2468 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
2469 clithread.start()
2470 global_config["console_thread"][console_thread_key] = clithread
2471 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02002472 return clithread
tierno7edb6752016-03-21 17:37:52 +01002473 except cli.ConsoleProxyExceptionPortUsed as e:
2474 #port used, try with onoher
2475 continue
2476 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02002477 raise NfvoException(str(e), HTTP_Bad_Request)
2478 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002479
2480def check_tenant(mydb, tenant_id):
2481 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02002482 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
2483 if not tenant:
2484 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
2485 return
tierno7edb6752016-03-21 17:37:52 +01002486
2487def new_tenant(mydb, tenant_dict):
tiernof97fd272016-07-11 14:32:37 +02002488 tenant_id = mydb.new_row("nfvo_tenants", tenant_dict, add_uuid=True)
2489 return tenant_id
tierno7edb6752016-03-21 17:37:52 +01002490
2491def delete_tenant(mydb, tenant):
2492 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002493
2494 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
2495 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
2496 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01002497
2498def new_datacenter(mydb, datacenter_descriptor):
2499 if "config" in datacenter_descriptor:
2500 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02002501 #Check that datacenter-type is correct
2502 datacenter_type = datacenter_descriptor.get("type", "openvim");
2503 module_info = None
2504 try:
2505 module = "vimconn_" + datacenter_type
2506 module_info = imp.find_module(module)
2507 except (IOError, ImportError):
2508 if module_info and module_info[0]:
2509 file.close(module_info[0])
2510 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
2511
tiernof97fd272016-07-11 14:32:37 +02002512 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
2513 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002514
2515def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
2516 #obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02002517 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno7edb6752016-03-21 17:37:52 +01002518 #edit data
tiernof97fd272016-07-11 14:32:37 +02002519 datacenter_id = datacenter['uuid']
2520 where={'uuid': datacenter['uuid']}
tierno7edb6752016-03-21 17:37:52 +01002521 if "config" in datacenter_descriptor:
2522 if datacenter_descriptor['config']!=None:
2523 try:
2524 new_config_dict = datacenter_descriptor["config"]
2525 #delete null fields
2526 to_delete=[]
2527 for k in new_config_dict:
2528 if new_config_dict[k]==None:
2529 to_delete.append(k)
2530
tiernof97fd272016-07-11 14:32:37 +02002531 config_dict = yaml.load(datacenter["config"])
tierno7edb6752016-03-21 17:37:52 +01002532 config_dict.update(new_config_dict)
2533 #delete null fields
2534 for k in to_delete:
2535 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02002536 except Exception as e:
2537 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002538 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 +02002539 mydb.update_rows('datacenters', datacenter_descriptor, where)
2540 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002541
2542def delete_datacenter(mydb, datacenter):
2543 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002544 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
2545 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
2546 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01002547
tierno8008c3a2016-10-13 15:34:28 +00002548def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
tierno7edb6752016-03-21 17:37:52 +01002549 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002550 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002551 datacenter_name=myvim["name"]
2552
2553 create_vim_tenant=True if vim_tenant_id==None and vim_tenant_name==None else False
2554
2555 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002556 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002557 if vim_tenant_name==None:
2558 vim_tenant_name=tenant_dict['name']
2559
2560 #check that this association does not exist before
2561 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernof97fd272016-07-11 14:32:37 +02002562 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2563 if len(tenants_datacenters)>0:
2564 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002565
2566 vim_tenant_id_exist_atdb=False
2567 if not create_vim_tenant:
2568 where_={"datacenter_id": datacenter_id}
2569 if vim_tenant_id!=None:
2570 where_["vim_tenant_id"] = vim_tenant_id
2571 if vim_tenant_name!=None:
2572 where_["vim_tenant_name"] = vim_tenant_name
2573 #check if vim_tenant_id is already at database
tiernof97fd272016-07-11 14:32:37 +02002574 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
2575 if len(datacenter_tenants_dict)>=1:
tierno7edb6752016-03-21 17:37:52 +01002576 datacenter_tenants_dict = datacenter_tenants_dict[0]
2577 vim_tenant_id_exist_atdb=True
2578 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
2579 else: #result=0
2580 datacenter_tenants_dict = {}
2581 #insert at table datacenter_tenants
2582 else: #if vim_tenant_id==None:
2583 #create tenant at VIM if not provided
tiernoae4a8d12016-07-08 12:30:39 +02002584 try:
2585 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
2586 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002587 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 +01002588 datacenter_tenants_dict = {}
2589 datacenter_tenants_dict["created"]="true"
2590
2591 #fill datacenter_tenants table
2592 if not vim_tenant_id_exist_atdb:
2593 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
2594 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
2595 datacenter_tenants_dict["user"] = vim_username
2596 datacenter_tenants_dict["passwd"] = vim_password
2597 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tierno8008c3a2016-10-13 15:34:28 +00002598 if config:
2599 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
tiernof97fd272016-07-11 14:32:37 +02002600 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002601 datacenter_tenants_dict["uuid"] = id_
2602
2603 #fill tenants_datacenters table
2604 tenants_datacenter_dict["datacenter_tenant_id"]=datacenter_tenants_dict["uuid"]
tiernof97fd272016-07-11 14:32:37 +02002605 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
2606 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002607
2608def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
2609 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002610 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002611
2612 #get nfvo_tenant info
2613 if not tenant_id or tenant_id=="any":
2614 tenant_uuid = None
2615 else:
tiernof97fd272016-07-11 14:32:37 +02002616 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002617 tenant_uuid = tenant_dict['uuid']
2618
2619 #check that this association exist before
2620 tenants_datacenter_dict={"datacenter_id":datacenter_id }
2621 if tenant_uuid:
2622 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02002623 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2624 if len(tenant_datacenter_list)==0 and tenant_uuid:
2625 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002626
2627 #delete this association
tiernof97fd272016-07-11 14:32:37 +02002628 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01002629
2630 #get vim_tenant info and deletes
2631 warning=''
2632 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02002633 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2634 #try to delete vim:tenant
2635 try:
2636 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2637 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01002638 #delete tenant at VIM if created by NFVO
tiernoae4a8d12016-07-08 12:30:39 +02002639 try:
2640 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
2641 except vimconn.vimconnException as e:
2642 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
2643 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02002644 except db_base_Exception as e:
2645 logger.error("Cannot delete datacenter_tenants " + str(e))
2646 pass #the error will be caused because dependencies, vim_tenant can not be deleted
tierno7edb6752016-03-21 17:37:52 +01002647
tiernof97fd272016-07-11 14:32:37 +02002648 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01002649
2650def datacenter_action(mydb, tenant_id, datacenter, action_dict):
2651 #DEPRECATED
2652 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002653 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002654
2655 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02002656 try:
tiernof97fd272016-07-11 14:32:37 +02002657 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02002658 #print content
2659 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002660 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
2661 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002662 #update nets Change from VIM format to NFVO format
2663 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002664 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01002665 net_nfvo={'datacenter_id': datacenter_id}
2666 net_nfvo['name'] = net['name']
2667 #net_nfvo['description']= net['name']
2668 net_nfvo['vim_net_id'] = net['id']
2669 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2670 net_nfvo['shared'] = net['shared']
2671 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
2672 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002673 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
2674 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
2675 return inserted
tierno7edb6752016-03-21 17:37:52 +01002676 elif 'net-edit' in action_dict:
2677 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02002678 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002679 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01002680 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002681 return result
tierno7edb6752016-03-21 17:37:52 +01002682 elif 'net-delete' in action_dict:
2683 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02002684 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002685 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01002686 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02002687 return result
tierno7edb6752016-03-21 17:37:52 +01002688
2689 else:
tiernof97fd272016-07-11 14:32:37 +02002690 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002691
2692def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
2693 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002694 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002695
tierno42fcc3b2016-07-06 17:20:40 +02002696 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tiernof97fd272016-07-11 14:32:37 +02002697 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01002698 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02002699 return result
tierno7edb6752016-03-21 17:37:52 +01002700
2701def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
2702 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002703 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002704 filter_dict={}
2705 if action_dict:
2706 action_dict = action_dict["netmap"]
2707 if 'vim_id' in action_dict:
2708 filter_dict["id"] = action_dict['vim_id']
2709 if 'vim_name' in action_dict:
2710 filter_dict["name"] = action_dict['vim_name']
2711 else:
2712 filter_dict["shared"] = True
2713
tiernoae4a8d12016-07-08 12:30:39 +02002714 try:
tiernof97fd272016-07-11 14:32:37 +02002715 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02002716 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002717 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
2718 raise NfvoException(str(e), HTTP_Internal_Server_Error)
2719 if len(vim_nets)>1 and action_dict:
2720 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
2721 elif len(vim_nets)==0: # and action_dict:
2722 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002723 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02002724 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01002725 net_nfvo={'datacenter_id': datacenter_id}
2726 if action_dict and "name" in action_dict:
2727 net_nfvo['name'] = action_dict['name']
2728 else:
2729 net_nfvo['name'] = net['name']
2730 #net_nfvo['description']= net['name']
2731 net_nfvo['vim_net_id'] = net['id']
2732 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
2733 net_nfvo['shared'] = net['shared']
2734 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02002735 try:
2736 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002737 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02002738 net_nfvo["uuid"] = net_id
2739 except db_base_Exception as e:
2740 if action_dict:
2741 raise
2742 else:
2743 net_nfvo["status"] = "FAIL: " + str(e)
tierno7edb6752016-03-21 17:37:52 +01002744 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02002745 return net_list
tierno7edb6752016-03-21 17:37:52 +01002746
2747def vim_action_get(mydb, tenant_id, datacenter, item, name):
2748 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002749 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002750 filter_dict={}
2751 if name:
tierno42fcc3b2016-07-06 17:20:40 +02002752 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01002753 filter_dict["id"] = name
2754 else:
2755 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02002756 try:
2757 if item=="networks":
2758 #filter_dict['tenant_id'] = myvim['tenant_id']
2759 content = myvim.get_network_list(filter_dict=filter_dict)
2760 elif item=="tenants":
2761 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01002762 elif item == "images":
2763 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02002764 else:
tiernof97fd272016-07-11 14:32:37 +02002765 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02002766 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02002767 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02002768 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02002769 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02002770 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 +02002771 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02002772 else:
tiernof97fd272016-07-11 14:32:37 +02002773 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02002774 except vimconn.vimconnException as e:
2775 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02002776 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002777
2778def vim_action_delete(mydb, tenant_id, datacenter, item, name):
2779 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02002780 if tenant_id == "any":
2781 tenant_id=None
2782
tiernoa2793912016-10-04 08:15:08 +00002783 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02002784 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02002785 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
2786 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02002787 items = content.values()[0]
2788 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02002789 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002790 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02002791 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02002792 else: # it is a dict
2793 item_id = items["id"]
2794 item_name = str(items.get("name"))
tierno7edb6752016-03-21 17:37:52 +01002795
tiernoae4a8d12016-07-08 12:30:39 +02002796 try:
2797 if item=="networks":
2798 content = myvim.delete_network(item_id)
2799 elif item=="tenants":
2800 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01002801 elif item == "images":
2802 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02002803 else:
tiernof97fd272016-07-11 14:32:37 +02002804 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002805 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002806 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
2807 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002808
tiernof97fd272016-07-11 14:32:37 +02002809 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno7edb6752016-03-21 17:37:52 +01002810
2811def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
2812 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002813 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02002814 if tenant_id == "any":
2815 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00002816 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02002817 try:
2818 if item=="networks":
2819 net = descriptor["network"]
2820 net_name = net.pop("name")
2821 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02002822 net_public = net.pop("shared", False)
2823 net_ipprofile = net.pop("ip_profile", None)
2824 content = myvim.new_network(net_name, net_type, net_ipprofile, shared=net_public, **net)
tiernoae4a8d12016-07-08 12:30:39 +02002825 elif item=="tenants":
2826 tenant = descriptor["tenant"]
2827 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
2828 else:
tiernof97fd272016-07-11 14:32:37 +02002829 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02002830 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002831 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02002832
tierno7edb6752016-03-21 17:37:52 +01002833 return vim_action_get(mydb, tenant_id, datacenter, item, content)
2834
tierno66aa0372016-07-06 17:31:12 +02002835