blob: ebb30976c636430531291487307f6e64d3a38c9a [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
tierno92021022018-09-12 16:29:23 +02004# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
tierno7edb6752016-03-21 17:37:52 +01005# 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
tierno361275f2017-04-25 16:24:34 +020030# import imp
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010031import json
tierno7edb6752016-03-21 17:37:52 +010032import yaml
tierno42fcc3b2016-07-06 17:20:40 +020033import utils
tiernob8569aa2018-08-24 11:34:54 +020034from utils import deprecated
tierno42026a02017-02-10 15:13:40 +010035import vim_thread
tierno7edb6752016-03-21 17:37:52 +010036import console_proxy_thread as cli
tiernoae4a8d12016-07-08 12:30:39 +020037import vimconn
38import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020039import collections
tierno66eba6e2017-11-10 17:09:18 +010040import math
tierno8e690322017-08-10 15:58:50 +020041from uuid import uuid4
tiernof97fd272016-07-11 14:32:37 +020042from db_base import db_base_Exception
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010043
tiernob3d36742017-03-03 23:51:05 +010044import nfvo_db
45from threading import Lock
tierno868220c2017-09-26 00:11:05 +020046import time as t
tierno01b3e172017-04-21 10:52:34 +020047from lib_osm_openvim import ovim as ovim_module
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +020048from lib_osm_openvim.ovim import ovimException
gcalvinoe580c7d2017-09-22 14:09:51 +020049from Crypto.PublicKey import RSA
tierno7edb6752016-03-21 17:37:52 +010050
tiernof1ba57e2017-09-07 12:23:19 +020051import osm_im.vnfd as vnfd_catalog
52import osm_im.nsd as nsd_catalog
tiernof1ba57e2017-09-07 12:23:19 +020053from pyangbind.lib.serialise import pybindJSONDecoder
tiernofc5f80b2018-05-29 16:00:43 +020054from copy import deepcopy
55
tiernof1ba57e2017-09-07 12:23:19 +020056
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010057# WIM
58import wim.wimconn as wimconn
59import wim.wim_thread as wim_thread
60from .http_tools import errors as httperrors
61from .wim.engine import WimEngine
62from .wim.persistence import WimPersistence
63from copy import deepcopy
Anderson Bravalherie2c09f32018-11-30 09:55:29 +000064from pprint import pformat
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010065#
66
tierno7edb6752016-03-21 17:37:52 +010067global global_config
68global vimconn_imported
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010069# WIM
70global wim_engine
71wim_engine = None
72global wimconn_imported
73#
tierno73ad9e42016-09-12 18:11:11 +020074global logger
montesmoreno0c8def02016-12-22 12:16:23 +000075global default_volume_size
76default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010077global ovim
78ovim = None
tiernoc5651792017-03-27 10:50:43 +020079global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020080
tierno42026a02017-02-10 15:13:40 +010081vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
82vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010083vim_persistent_info = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010084# WIM
85wimconn_imported = {} # dictionary with WIM type as key, loaded module as value
86wim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
87wim_persistent_info = {}
88#
89
tierno73ad9e42016-09-12 18:11:11 +020090logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010091task_lock = Lock()
tiernob3d36742017-03-03 23:51:05 +010092last_task_id = 0.0
tierno868220c2017-09-26 00:11:05 +020093db = None
94db_lock = Lock()
tierno7edb6752016-03-21 17:37:52 +010095
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010096
97class NfvoException(httperrors.HttpMappedError):
98 """Common Class for NFVO errors"""
tierno7edb6752016-03-21 17:37:52 +010099
100
tiernob3d36742017-03-03 23:51:05 +0100101def get_task_id():
102 global last_task_id
tierno868220c2017-09-26 00:11:05 +0200103 task_id = t.time()
tiernob3d36742017-03-03 23:51:05 +0100104 if task_id <= last_task_id:
105 task_id = last_task_id + 0.000001
106 last_task_id = task_id
tierno868220c2017-09-26 00:11:05 +0200107 return "ACTION-{:.6f}".format(task_id)
108 # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6))
tiernob3d36742017-03-03 23:51:05 +0100109
110
tierno867ffe92017-03-27 12:50:34 +0200111def new_task(name, params, depends=None):
tierno868220c2017-09-26 00:11:05 +0200112 """Deprected!!!"""
tiernob3d36742017-03-03 23:51:05 +0100113 task_id = get_task_id()
114 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
115 if depends:
116 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +0100117 return task
118
119
120def is_task_id(id):
tierno868220c2017-09-26 00:11:05 +0200121 return True if id[:5] == "TASK-" else False
tiernob3d36742017-03-03 23:51:05 +0100122
123
tierno42026a02017-02-10 15:13:40 +0100124def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
125 name = datacenter_name[:16]
126 if name not in vim_threads["names"]:
127 vim_threads["names"].append(name)
128 return name
tiernob3d36742017-03-03 23:51:05 +0100129 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100130 if name not in vim_threads["names"]:
131 vim_threads["names"].append(name)
132 return name
133 name = datacenter_id + "-" + tenant_id
134 vim_threads["names"].append(name)
135 return name
136
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100137# -- Move
138def get_non_used_wim_name(wim_name, wim_id, tenant_name, tenant_id):
139 name = wim_name[:16]
140 if name not in wim_threads["names"]:
141 wim_threads["names"].append(name)
142 return name
143 name = wim_name[:16] + "." + tenant_name[:16]
144 if name not in wim_threads["names"]:
145 wim_threads["names"].append(name)
146 return name
147 name = wim_id + "-" + tenant_id
148 wim_threads["names"].append(name)
149 return name
tierno42026a02017-02-10 15:13:40 +0100150
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100151
152def start_service(mydb, persistence=None, wim=None):
tiernob3d36742017-03-03 23:51:05 +0100153 global db, global_config
Anderson Bravalheridfed5112019-02-08 01:44:14 +0000154 db = nfvo_db.nfvo_db(lock=db_lock)
155 mydb.lock = db_lock
tiernob3d36742017-03-03 23:51:05 +0100156 db.connect(global_config['db_host'], global_config['db_user'], global_config['db_passwd'], global_config['db_name'])
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100157 global ovim
158
Anderson Bravalheridfed5112019-02-08 01:44:14 +0000159 persistence = persistence or WimPersistence(db)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100160
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100161 # Initialize openvim for SDN control
162 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
163 # TODO: review ovim.py to delete not needed configuration
164 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200165 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100166 'network_vlan_range_start': 1000,
167 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200168 'db_name': global_config["db_ovim_name"],
169 'db_host': global_config["db_ovim_host"],
170 'db_user': global_config["db_ovim_user"],
171 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100172 'bridge_ifaces': {},
173 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100174 'network_type': 'bridge',
175 #TODO: log_level_of should not be needed. To be modified in ovim
176 'log_level_of': 'DEBUG'
177 }
tierno42026a02017-02-10 15:13:40 +0100178 try:
tierno3fcfdb72017-10-24 07:48:24 +0200179 # starts ovim library
tierno46df9672017-05-26 13:12:21 +0200180 ovim = ovim_module.ovim(ovim_configuration)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100181
182 global wim_engine
183 wim_engine = wim or WimEngine(persistence)
184 wim_engine.ovim = ovim
185
tierno46df9672017-05-26 13:12:21 +0200186 ovim.start_service()
187
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100188 #delete old unneeded vim_wim_actions
tierno3fcfdb72017-10-24 07:48:24 +0200189 clean_db(mydb)
190
191 # starts vim_threads
tierno46df9672017-05-26 13:12:21 +0200192 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
193 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
194 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
195 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
196 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
197 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100198 vims = mydb.get_rows(FROM=from_, SELECT=select_)
199 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200200 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
201 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100202 if vim["config"]:
203 extra.update(yaml.load(vim["config"]))
204 if vim.get('dt_config'):
205 extra.update(yaml.load(vim["dt_config"]))
206 if vim["type"] not in vimconn_imported:
207 module_info=None
208 try:
209 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200210 pkg = __import__("osm_ro." + module)
211 vim_conn = getattr(pkg, module)
212 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
213 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100214 vimconn_imported[vim["type"]] = vim_conn
215 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200216 # if module_info and module_info[0]:
217 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200218 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100219 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100220
tierno867ffe92017-03-27 12:50:34 +0200221 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100222 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100223 try:
224 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100225 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tierno42026a02017-02-10 15:13:40 +0100226 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100227 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
228 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
229 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
230 user=vim['user'], passwd=vim['passwd'],
231 config=extra, persistent_info=vim_persistent_info[thread_id]
232 )
tierno9c22f2d2017-10-09 16:23:55 +0200233 except vimconn.vimconnException as e:
234 myvim = e
235 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
236 vim['datacenter_id'], e))
tierno42026a02017-02-10 15:13:40 +0100237 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200238 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100239 httperrors.Internal_Server_Error)
tierno46df9672017-05-26 13:12:21 +0200240 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
241 vim['vim_tenant_id'])
tiernod3750b32018-07-20 15:33:08 +0200242 new_thread = vim_thread.vim_thread(task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200243 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100244 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100245 vim_threads["running"][thread_id] = new_thread
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100246
247 wim_engine.start_threads()
tierno42026a02017-02-10 15:13:40 +0100248 except db_base_Exception as e:
249 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200250 except ovim_module.ovimException as e:
251 message = str(e)
252 if message[:22] == "DATABASE wrong version":
253 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
254 "at host {dbhost}".format(
255 msg=message[22:-3], dbname=global_config["db_ovim_name"],
256 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
257 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100258 raise NfvoException(message, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100259
tierno867ffe92017-03-27 12:50:34 +0200260
tierno42026a02017-02-10 15:13:40 +0100261def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200262 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100263 if ovim:
264 ovim.stop_service()
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100265 for thread_id, thread in vim_threads["running"].items():
tierno868220c2017-09-26 00:11:05 +0200266 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +0100267 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100268 vim_threads["running"] = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100269
270 if wim_engine:
271 wim_engine.stop_threads()
272
tiernoc5651792017-03-27 10:50:43 +0200273 if global_config and global_config.get("console_thread"):
274 for thread in global_config["console_thread"]:
275 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100276
tierno6ddeded2017-05-16 15:40:26 +0200277def get_version():
278 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
279 global_config["version_date"] ))
280
tierno3fcfdb72017-10-24 07:48:24 +0200281def clean_db(mydb):
282 """
283 Clean unused or old entries at database to avoid unlimited growing
284 :param mydb: database connector
285 :return: None
286 """
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100287 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
tierno3fcfdb72017-10-24 07:48:24 +0200288 now = t.time()-3600*24*7
289 instance_action_id = None
290 nb_deleted = 0
291 while True:
292 actions_to_delete = mydb.get_rows(
293 SELECT=("item", "item_id", "instance_action_id"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100294 FROM="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
tierno3fcfdb72017-10-24 07:48:24 +0200295 "left join instance_scenarios as i on ia.instance_id=i.uuid",
296 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
297 "va.status": ("DONE", "SUPERSEDED")},
298 LIMIT=100
299 )
300 for to_delete in actions_to_delete:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100301 mydb.delete_row(FROM="vim_wim_actions", WHERE=to_delete)
tierno3fcfdb72017-10-24 07:48:24 +0200302 if instance_action_id != to_delete["instance_action_id"]:
303 instance_action_id = to_delete["instance_action_id"]
304 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
305 nb_deleted += len(actions_to_delete)
306 if len(actions_to_delete) < 100:
307 break
308 if nb_deleted:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100309 logger.debug("Removed {} unused vim_wim_actions".format(nb_deleted))
tierno3fcfdb72017-10-24 07:48:24 +0200310
tierno42026a02017-02-10 15:13:40 +0100311
tierno7edb6752016-03-21 17:37:52 +0100312def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
313 '''Obtain flavorList
314 return result, content:
315 <0, error_text upon error
316 nb_records, flavor_list on success
317 '''
318 WHERE_dict={}
319 WHERE_dict['vnf_id'] = vnf_id
320 if nfvo_tenant is not None:
321 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100322
tierno7edb6752016-03-21 17:37:52 +0100323 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
324 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200325 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
326 #print "get_flavor_list result:", result
327 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100328 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200329 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100330 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200331 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100332
tiernob3d36742017-03-03 23:51:05 +0100333
tierno7edb6752016-03-21 17:37:52 +0100334def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
tierno16e3dd42018-04-24 12:52:40 +0200335 """
336 Get used images of all vms belonging to this VNFD
337 :param mydb: database conector
338 :param vnf_id: vnfd uuid
339 :param nfvo_tenant: tenant, not used
340 :return: The list of image uuid used
341 """
342 image_list = []
343 vms = mydb.get_rows(SELECT=('image_id','image_list'), FROM='vms', WHERE={'vnf_id': vnf_id})
344 for vm in vms:
tierno89aada42018-12-19 16:00:25 +0000345 if vm["image_id"] and vm["image_id"] not in image_list:
tierno16e3dd42018-04-24 12:52:40 +0200346 image_list.append(vm["image_id"])
347 if vm["image_list"]:
348 vm_image_list = yaml.load(vm["image_list"])
349 for image_dict in vm_image_list:
350 if image_dict["image_id"] not in image_list:
351 image_list.append(image_dict["image_id"])
352 return image_list
tierno7edb6752016-03-21 17:37:52 +0100353
tiernob3d36742017-03-03 23:51:05 +0100354
tiernoa2793912016-10-04 08:15:08 +0000355def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
tiernocbb52052018-05-31 18:57:30 +0200356 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None, ignore_errors=False):
tierno7edb6752016-03-21 17:37:52 +0100357 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100358 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100359 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200360 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100361 '''
362 WHERE_dict={}
363 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
364 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000365 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100366 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
367 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000368 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
369 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100370 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 +0000371 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 +0100372 '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 +0000373 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100374 else:
375 from_ = 'datacenters as d'
376 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200377 try:
378 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
379 vim_dict={}
380 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200381 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
tierno16e3dd42018-04-24 12:52:40 +0200382 'datacenter_id': vim.get('datacenter_id'),
tiernob6434212018-04-26 16:27:47 +0200383 '_vim_type_internal': vim.get('type')}
tierno8008c3a2016-10-13 15:34:28 +0000384 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200385 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000386 if vim.get('dt_config'):
387 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200388 if vim["type"] not in vimconn_imported:
389 module_info=None
390 try:
391 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200392 pkg = __import__("osm_ro." + module)
393 vim_conn = getattr(pkg, module)
394 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
395 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200396 vimconn_imported[vim["type"]] = vim_conn
397 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200398 # if module_info and module_info[0]:
399 # file.close(module_info[0])
tiernocbb52052018-05-31 18:57:30 +0200400 if ignore_errors:
401 logger.error("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
402 vim["type"], module, type(e).__name__, str(e)))
403 continue
tiernof97fd272016-07-11 14:32:37 +0200404 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100405 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100406
tierno7edb6752016-03-21 17:37:52 +0100407 try:
tierno867ffe92017-03-27 12:50:34 +0200408 if 'datacenter_tenant_id' in vim:
409 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100410 if thread_id not in vim_persistent_info:
411 vim_persistent_info[thread_id] = {}
412 persistent_info = vim_persistent_info[thread_id]
413 else:
414 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200415 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100416 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tiernof97fd272016-07-11 14:32:37 +0200417 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
418 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100419 tenant_id=vim.get('vim_tenant_id',vim_tenant),
420 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100421 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200422 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100423 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200424 )
425 except Exception as e:
tiernocbb52052018-05-31 18:57:30 +0200426 if ignore_errors:
427 logger.error("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)))
428 continue
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100429 http_code = httperrors.Internal_Server_Error
tiernoa3572692018-05-14 13:09:33 +0200430 if isinstance(e, vimconn.vimconnException):
431 http_code = e.http_code
432 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), http_code)
tiernof97fd272016-07-11 14:32:37 +0200433 return vim_dict
434 except db_base_Exception as e:
435 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100436
tiernob3d36742017-03-03 23:51:05 +0100437
tierno7edb6752016-03-21 17:37:52 +0100438def rollback(mydb, vims, rollback_list):
439 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100440 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100441 for i in range(len(rollback_list)-1, -1, -1):
442 item = rollback_list[i]
443 if item["where"]=="vim":
444 if item["vim_id"] not in vims:
445 continue
tierno56d73d22017-08-02 13:53:02 +0200446 if is_task_id(item["uuid"]):
447 continue
448 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200449 try:
450 if item["what"]=="image":
451 vim.delete_image(item["uuid"])
tierno868220c2017-09-26 00:11:05 +0200452 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200453 elif item["what"]=="flavor":
454 vim.delete_flavor(item["uuid"])
tiernoad6bdd42018-01-10 10:43:46 +0100455 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200456 elif item["what"]=="network":
457 vim.delete_network(item["uuid"])
458 elif item["what"]=="vm":
459 vim.delete_vminstance(item["uuid"])
460 except vimconn.vimconnException as e:
461 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
462 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200463 except db_base_Exception as e:
464 logger.error("Error in rollback. Not possible to delete %s '%s' from DB.datacenters Message: %s", item['what'], item["uuid"], str(e))
tierno42026a02017-02-10 15:13:40 +0100465
tierno7edb6752016-03-21 17:37:52 +0100466 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200467 try:
468 if item["what"]=="image":
469 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
470 elif item["what"]=="flavor":
471 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
472 except db_base_Exception as e:
473 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
474 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100475 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100476 return True," Rollback successful."
477 else:
478 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100479
tiernob3d36742017-03-03 23:51:05 +0100480
tiernoafed5f12017-01-26 17:57:43 +0100481def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100482 global global_config
tierno42026a02017-02-10 15:13:40 +0100483 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100484 vnfc_interfaces={}
485 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100486 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100487 #dataplane interfaces
488 for numa in vnfc.get("numas",() ):
489 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100490 if interface["name"] in name_dict:
491 raise NfvoException(
492 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
493 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100494 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100495 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100496 #bridge interfaces
497 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100498 if interface["name"] in name_dict:
499 raise NfvoException(
500 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
501 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100502 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100503 name_dict[ interface["name"] ] = "overlay"
504 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100505 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200506 # if "boot-data" in vnfc:
507 # # check that user-data is incompatible with users and config-files
508 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
509 # raise NfvoException(
510 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100511 # httperrors.Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100512
tierno7edb6752016-03-21 17:37:52 +0100513 #check if the info in external_connections matches with the one in the vnfcs
514 name_list=[]
515 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
516 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100517 raise NfvoException(
518 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
519 external_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100520 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100521 name_list.append(external_connection["name"])
522 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100523 raise NfvoException(
524 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
525 external_connection["name"], external_connection["VNFC"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100526 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100527
tierno7edb6752016-03-21 17:37:52 +0100528 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100529 raise NfvoException(
530 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
531 external_connection["name"],
532 external_connection["local_iface_name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100533 httperrors.Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100534
tierno7edb6752016-03-21 17:37:52 +0100535 #check if the info in internal_connections matches with the one in the vnfcs
536 name_list=[]
537 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
538 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100539 raise NfvoException(
540 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
541 internal_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100542 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100543 name_list.append(internal_connection["name"])
544 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100545
546 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
547 raise NfvoException(
548 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
549 internal_connection["name"],
550 'ptp' if vnf_descriptor_version==1 else 'e-line',
551 'data' if vnf_descriptor_version==1 else "e-lan"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100552 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100553 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100554 vnf = port["VNFC"]
555 iface = port["local_iface_name"]
556 if vnf not in vnfc_interfaces:
557 raise NfvoException(
558 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
559 internal_connection["name"], vnf),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100560 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100561 if iface not in vnfc_interfaces[ vnf ]:
562 raise NfvoException(
563 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
564 internal_connection["name"], iface),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100565 httperrors.Bad_Request)
566 return -httperrors.Bad_Request,
tiernoafed5f12017-01-26 17:57:43 +0100567 if vnf_descriptor_version==1 and "type" not in internal_connection:
568 if vnfc_interfaces[vnf][iface] == "overlay":
569 internal_connection["type"] = "bridge"
570 else:
571 internal_connection["type"] = "data"
572 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
573 if vnfc_interfaces[vnf][iface] == "overlay":
574 internal_connection["implementation"] = "overlay"
575 else:
576 internal_connection["implementation"] = "underlay"
577 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
578 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
579 raise NfvoException(
580 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
581 internal_connection["name"],
582 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
583 'data' if vnf_descriptor_version==1 else 'underlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100584 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100585 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
586 vnfc_interfaces[vnf][iface] == "underlay":
587 raise NfvoException(
588 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
589 internal_connection["name"], iface,
590 'data' if vnf_descriptor_version==1 else 'underlay',
591 'bridge' if vnf_descriptor_version==1 else 'overlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100592 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100593
tierno7edb6752016-03-21 17:37:52 +0100594
tierno56d73d22017-08-02 13:53:02 +0200595def 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 +0100596 #look if image exist
597 if only_create_at_vim:
598 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000599 if return_on_error == None:
600 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100601 else:
garciadeblas14480452017-01-10 13:08:07 +0100602 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200603 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
604 else:
605 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200606 if len(images)>=1:
607 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100608 else:
garciadeblas14480452017-01-10 13:08:07 +0100609 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100610 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200611 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
612 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100613 }
garciadeblas14480452017-01-10 13:08:07 +0100614 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200615 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
616 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100617 #create image at every vim
618 for vim_id,vim in vims.iteritems():
tierno868220c2017-09-26 00:11:05 +0200619 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100620 image_created="false"
621 #look at database
tierno868220c2017-09-26 00:11:05 +0200622 image_db = mydb.get_rows(FROM="datacenters_images",
623 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100624 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200625 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200626 if image_dict['location'] is not None:
627 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
628 else:
garciadeblas30833382017-01-09 09:46:31 +0100629 filter_dict = {}
630 filter_dict['name'] = image_dict['universal_name']
631 if image_dict.get('checksum') != None:
632 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000633 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200634 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100635 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200636 if len(vim_images) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100637 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), httperrors.Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000638 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100639 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200640 else:
garciadeblas14480452017-01-10 13:08:07 +0100641 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
642 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200643
tiernoae4a8d12016-07-08 12:30:39 +0200644 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100645 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100646 try:
garciadeblas14480452017-01-10 13:08:07 +0100647 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
648 if image_dict['location']:
649 image_vim_id = vim.new_image(image_dict)
650 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
651 image_created="true"
652 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100653 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
654 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200655 except vimconn.vimconnException as e:
656 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100657 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200658 raise
tierno5e91eb82016-10-04 09:39:07 +0000659 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100660 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200661 continue
662 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000663 if return_on_error:
664 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
665 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200666 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000667 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100668 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200669 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200670 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100671 #add new vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200672 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
673 'image_id':image_mano_id,
674 'vim_id': image_vim_id,
675 'created':image_created})
tierno7edb6752016-03-21 17:37:52 +0100676 elif image_db[0]["vim_id"]!=image_vim_id:
677 #modify existing vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200678 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_vim_id':vim_id, 'image_id':image_mano_id})
tierno42026a02017-02-10 15:13:40 +0100679
tiernof97fd272016-07-11 14:32:37 +0200680 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100681
tiernob3d36742017-03-03 23:51:05 +0100682
tierno5e91eb82016-10-04 09:39:07 +0000683def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
garciadeblas79d1a1a2017-12-11 16:07:07 +0100684 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
tierno7edb6752016-03-21 17:37:52 +0100685 'ram':flavor_dict.get('ram'),
686 'vcpus':flavor_dict.get('vcpus'),
687 }
688 if 'extended' in flavor_dict and flavor_dict['extended']==None:
689 del flavor_dict['extended']
690 if 'extended' in flavor_dict:
691 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
692
693 #look if flavor exist
694 if only_create_at_vim:
695 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000696 if return_on_error == None:
697 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100698 else:
tiernof97fd272016-07-11 14:32:37 +0200699 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
700 if len(flavors)>=1:
701 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100702 else:
703 #create flavor
704 #create one by one the images of aditional disks
705 dev_image_list=[] #list of images
706 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
707 dev_nb=0
708 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200709 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100710 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200711 image_dict={}
712 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
713 image_dict['universal_name']=device.get('image name')
714 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
715 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100716 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200717 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100718 image_metadata_dict = device.get('image metadata', None)
719 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100720 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100721 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
722 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200723 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
724 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100725 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100726 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100727 temp_flavor_dict['name'] = flavor_dict['name']
728 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200729 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
730 flavor_mano_id= content
731 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100732 #create flavor at every vim
733 if 'uuid' in flavor_dict:
734 del flavor_dict['uuid']
735 flavor_vim_id=None
736 for vim_id,vim in vims.items():
tierno868220c2017-09-26 00:11:05 +0200737 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100738 flavor_created="false"
739 #look at database
tierno868220c2017-09-26 00:11:05 +0200740 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
741 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100742 #look at VIM if this flavor exist SKIPPED
743 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
744 #if res_vim < 0:
745 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
746 # continue
747 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100748
tiernof1ba57e2017-09-07 12:23:19 +0200749 # Create the flavor in VIM
750 # Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000751 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100752 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
tiernof1ba57e2017-09-07 12:23:19 +0200753 # make a copy of original devices
tierno7edb6752016-03-21 17:37:52 +0100754 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000755
tierno7edb6752016-03-21 17:37:52 +0100756 for device in flavor_dict["extended"].get("devices",[]):
757 dev={}
758 dev.update(device)
759 devices_original.append(dev)
760 if 'image' in device:
761 del device['image']
762 if 'image metadata' in device:
763 del device['image metadata']
tiernof1ba57e2017-09-07 12:23:19 +0200764 if 'image checksum' in device:
765 del device['image checksum']
766 dev_nb = 0
tierno7edb6752016-03-21 17:37:52 +0100767 for index in range(0,len(devices_original)) :
768 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000769 if "image" not in device and "image name" not in device:
tiernoecc68392018-09-06 13:47:11 +0200770 # if 'size' in device:
771 disk_list.append({'size': device.get('size', default_volume_size), 'name': device.get('name')})
tierno7edb6752016-03-21 17:37:52 +0100772 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200773 image_dict={}
774 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
775 image_dict['universal_name']=device.get('image name')
776 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
777 image_dict['location']=device.get('image')
tiernof1ba57e2017-09-07 12:23:19 +0200778 # image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200779 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100780 image_metadata_dict = device.get('image metadata', None)
781 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100782 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100783 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
784 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200785 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 +0100786 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200787 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 +0000788
789 #save disk information (image must be based on and size
790 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
791
tierno7edb6752016-03-21 17:37:52 +0100792 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
793 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200794 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100795 #check that this vim_id exist in VIM, if not create
796 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200797 try:
798 vim.get_flavor(flavor_vim_id)
799 continue #flavor exist
800 except vimconn.vimconnException:
801 pass
tierno7edb6752016-03-21 17:37:52 +0100802 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200803 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
804 try:
tiernocf157a82017-01-30 14:07:06 +0100805 flavor_vim_id = None
806 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
807 flavor_create="false"
808 except vimconn.vimconnException as e:
809 pass
810 try:
811 if not flavor_vim_id:
812 flavor_vim_id = vim.new_flavor(flavor_dict)
813 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
814 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200815 except vimconn.vimconnException as e:
816 if return_on_error:
817 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200818 raise
tiernoae4a8d12016-07-08 12:30:39 +0200819 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000820 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200821 continue
tierno7edb6752016-03-21 17:37:52 +0100822 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200823 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100824 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000825 extended_devices_yaml = None
826 if len(disk_list) > 0:
827 extended_devices = dict()
828 extended_devices['disks'] = disk_list
829 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
830 mydb.new_row('datacenters_flavors',
tierno868220c2017-09-26 00:11:05 +0200831 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
832 'created': flavor_created, 'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100833 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
834 #modify existing vim_id at datacenters_flavors
tierno868220c2017-09-26 00:11:05 +0200835 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
836 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100837
tiernof97fd272016-07-11 14:32:37 +0200838 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100839
tiernob3d36742017-03-03 23:51:05 +0100840
tiernof1ba57e2017-09-07 12:23:19 +0200841def get_str(obj, field, length):
842 """
843 Obtain the str value,
844 :param obj:
845 :param length:
846 :return:
847 """
848 value = obj.get(field)
849 if value is not None:
850 value = str(value)[:length]
851 return value
852
853def _lookfor_or_create_image(db_image, mydb, descriptor):
854 """
855 fill image content at db_image dictionary. Check if the image with this image and checksum exist
856 :param db_image: dictionary to insert data
857 :param mydb: database connector
858 :param descriptor: yang descriptor
859 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
860 """
861
862 db_image["name"] = get_str(descriptor, "image", 255)
863 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
864 if not db_image["checksum"]: # Ensure that if empty string, None is stored
865 db_image["checksum"] = None
866 if db_image["name"].startswith("/"):
867 db_image["location"] = db_image["name"]
868 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
869 else:
870 db_image["universal_name"] = db_image["name"]
871 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
872 'checksum': db_image['checksum']})
873 if existing_images:
874 return existing_images[0]["uuid"]
875 else:
876 image_uuid = str(uuid4())
877 db_image["uuid"] = image_uuid
878 return None
879
880def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
881 """
882 Parses an OSM IM vnfd_catalog and insert at DB
883 :param mydb:
884 :param tenant_id:
885 :param vnf_descriptor:
886 :return: The list of cretated vnf ids
887 """
888 try:
889 myvnfd = vnfd_catalog.vnfd()
tiernoa9550202017-09-22 13:31:35 +0200890 try:
tiernoad6bdd42018-01-10 10:43:46 +0100891 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True)
tiernoa9550202017-09-22 13:31:35 +0200892 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100893 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200894 db_vnfs = []
895 db_nets = []
896 db_vms = []
897 db_vms_index = 0
898 db_interfaces = []
899 db_images = []
900 db_flavors = []
tierno41a69812018-02-16 14:34:33 +0100901 db_ip_profiles_index = 0
902 db_ip_profiles = []
tiernof1ba57e2017-09-07 12:23:19 +0200903 uuid_list = []
904 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200905 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
906 if not vnfd_catalog_descriptor:
907 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
908 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
909 if not vnfd_descriptor_list:
910 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200911 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
912 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200913
914 # table vnf
915 vnf_uuid = str(uuid4())
916 uuid_list.append(vnf_uuid)
917 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100918 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200919 db_vnf = {
920 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100921 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200922 "name": get_str(vnfd, "name", 255),
923 "description": get_str(vnfd, "description", 255),
924 "tenant_id": tenant_id,
925 "vendor": get_str(vnfd, "vendor", 255),
926 "short_name": get_str(vnfd, "short-name", 255),
927 "descriptor": str(vnf_descriptor)[:60000]
928 }
929
tiernoe18ba432017-10-12 10:22:45 +0200930 for vnfd_descriptor in vnfd_descriptor_list:
931 if vnfd_descriptor["id"] == str(vnfd["id"]):
932 break
933
tierno41a69812018-02-16 14:34:33 +0100934 # table ip_profiles (ip-profiles)
935 ip_profile_name2db_table_index = {}
936 for ip_profile in vnfd.get("ip-profiles").itervalues():
937 db_ip_profile = {
938 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
939 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
940 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
941 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
942 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
943 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
944 }
945 dns_list = []
946 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
947 dns_list.append(str(dns.get("address")))
948 db_ip_profile["dns_address"] = ";".join(dns_list)
949 if ip_profile["ip-profile-params"].get('security-group'):
950 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
951 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
952 db_ip_profiles_index += 1
953 db_ip_profiles.append(db_ip_profile)
954
tiernof1ba57e2017-09-07 12:23:19 +0200955 # table nets (internal-vld)
956 net_id2uuid = {} # for mapping interface with network
957 for vld in vnfd.get("internal-vld").itervalues():
958 net_uuid = str(uuid4())
959 uuid_list.append(net_uuid)
960 db_net = {
961 "name": get_str(vld, "name", 255),
962 "vnf_id": vnf_uuid,
963 "uuid": net_uuid,
964 "description": get_str(vld, "description", 255),
tierno1df468d2018-07-06 14:25:16 +0200965 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +0200966 "type": "bridge", # TODO adjust depending on connection point type
967 }
968 net_id2uuid[vld.get("id")] = net_uuid
969 db_nets.append(db_net)
tierno41a69812018-02-16 14:34:33 +0100970 # ip-profile, link db_ip_profile with db_sce_net
971 if vld.get("ip-profile-ref"):
972 ip_profile_name = vld.get("ip-profile-ref")
973 if ip_profile_name not in ip_profile_name2db_table_index:
974 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
975 "'{}'. Reference to a non-existing 'ip_profiles'".format(
976 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100977 httperrors.Bad_Request)
tierno41a69812018-02-16 14:34:33 +0100978 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
979 else: #check no ip-address has been defined
tierno45140f52018-03-26 12:11:46 +0200980 for icp in vld.get("internal-connection-point").itervalues():
tierno41a69812018-02-16 14:34:33 +0100981 if icp.get("ip-address"):
982 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
983 "contains an ip-address but no ip-profile has been defined at VLD".format(
984 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100985 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200986
tiernocf596692017-11-20 15:47:51 +0100987 # connection points vaiable declaration
988 cp_name2iface_uuid = {}
989 cp_name2vm_uuid = {}
990 cp_name2db_interface = {}
tiernob6990792018-11-13 10:37:42 +0100991 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
tiernocf596692017-11-20 15:47:51 +0100992
tiernof1ba57e2017-09-07 12:23:19 +0200993 # table vms (vdus)
994 vdu_id2uuid = {}
995 vdu_id2db_table_index = {}
996 for vdu in vnfd.get("vdu").itervalues():
tierno41a69812018-02-16 14:34:33 +0100997
998 for vdu_descriptor in vnfd_descriptor["vdu"]:
999 if vdu_descriptor["id"] == str(vdu["id"]):
1000 break
tiernof1ba57e2017-09-07 12:23:19 +02001001 vm_uuid = str(uuid4())
1002 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +01001003 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +02001004 db_vm = {
1005 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +01001006 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +02001007 "name": get_str(vdu, "name", 255),
1008 "description": get_str(vdu, "description", 255),
tiernob6990792018-11-13 10:37:42 +01001009 "pdu_type": get_str(vdu, "pdu-type", 255),
tiernof1ba57e2017-09-07 12:23:19 +02001010 "vnf_id": vnf_uuid,
1011 }
1012 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
1013 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
1014 if vdu.get("count"):
1015 db_vm["count"] = int(vdu["count"])
1016
1017 # table image
1018 image_present = False
1019 if vdu.get("image"):
1020 image_present = True
1021 db_image = {}
1022 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
1023 if not image_uuid:
1024 image_uuid = db_image["uuid"]
1025 db_images.append(db_image)
1026 db_vm["image_id"] = image_uuid
tierno16e3dd42018-04-24 12:52:40 +02001027 if vdu.get("alternative-images"):
1028 vm_alternative_images = []
1029 for alt_image in vdu.get("alternative-images").itervalues():
1030 db_image = {}
1031 image_uuid = _lookfor_or_create_image(db_image, mydb, alt_image)
1032 if not image_uuid:
1033 image_uuid = db_image["uuid"]
1034 db_images.append(db_image)
1035 vm_alternative_images.append({
1036 "image_id": image_uuid,
1037 "vim_type": str(alt_image["vim-type"]),
1038 # "universal_name": str(alt_image["image"]),
1039 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1040 })
1041
1042 db_vm["image_list"] = yaml.safe_dump(vm_alternative_images, default_flow_style=True, width=256)
tiernof1ba57e2017-09-07 12:23:19 +02001043
1044 # volumes
1045 devices = []
1046 if vdu.get("volumes"):
tierno1df468d2018-07-06 14:25:16 +02001047 for volume_key in vdu["volumes"]:
tiernof1ba57e2017-09-07 12:23:19 +02001048 volume = vdu["volumes"][volume_key]
1049 if not image_present:
1050 # Convert the first volume to vnfc.image
1051 image_present = True
1052 db_image = {}
1053 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
1054 if not image_uuid:
1055 image_uuid = db_image["uuid"]
1056 db_images.append(db_image)
1057 db_vm["image_id"] = image_uuid
1058 else:
1059 # Add Openmano devices
tierno1df468d2018-07-06 14:25:16 +02001060 device = {"name": str(volume.get("name"))}
tiernof1ba57e2017-09-07 12:23:19 +02001061 device["type"] = str(volume.get("device-type"))
1062 if volume.get("size"):
1063 device["size"] = int(volume["size"])
1064 if volume.get("image"):
1065 device["image name"] = str(volume["image"])
1066 if volume.get("image-checksum"):
1067 device["image checksum"] = str(volume["image-checksum"])
tierno1df468d2018-07-06 14:25:16 +02001068
tiernof1ba57e2017-09-07 12:23:19 +02001069 devices.append(device)
1070
tierno89aada42018-12-19 16:00:25 +00001071 if not db_vm.get("image_id"):
1072 if not db_vm["pdu_type"]:
1073 raise NfvoException("Not defined image for VDU")
1074 # create a fake image
1075
tierno66eba6e2017-11-10 17:09:18 +01001076 # cloud-init
1077 boot_data = {}
1078 if vdu.get("cloud-init"):
1079 boot_data["user-data"] = str(vdu["cloud-init"])
1080 elif vdu.get("cloud-init-file"):
1081 # TODO Where this file content is present???
1082 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1083 boot_data["user-data"] = str(vdu["cloud-init-file"])
1084
1085 if vdu.get("supplemental-boot-data"):
1086 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1087 boot_data['boot-data-drive'] = True
1088 if vdu["supplemental-boot-data"].get('config-file'):
1089 om_cfgfile_list = list()
1090 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
1091 # TODO Where this file content is present???
1092 cfg_source = str(custom_config_file["source"])
1093 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1094 "content": cfg_source})
1095 boot_data['config-files'] = om_cfgfile_list
1096 if boot_data:
1097 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1098
1099 db_vms.append(db_vm)
1100 db_vms_index += 1
1101
1102 # table interfaces (internal/external interfaces)
1103 flavor_epa_interfaces = []
tierno66eba6e2017-11-10 17:09:18 +01001104 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
1105 for iface in vdu.get("interface").itervalues():
1106 flavor_epa_interface = {}
1107 iface_uuid = str(uuid4())
1108 uuid_list.append(iface_uuid)
1109 db_interface = {
1110 "uuid": iface_uuid,
1111 "internal_name": get_str(iface, "name", 255),
1112 "vm_id": vm_uuid,
1113 }
1114 flavor_epa_interface["name"] = db_interface["internal_name"]
1115 if iface.get("virtual-interface").get("vpci"):
1116 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1117 flavor_epa_interface["vpci"] = db_interface["vpci"]
1118
1119 if iface.get("virtual-interface").get("bandwidth"):
1120 bps = int(iface.get("virtual-interface").get("bandwidth"))
1121 db_interface["bw"] = int(math.ceil(bps/1000000.0))
1122 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1123
1124 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1125 db_interface["type"] = "mgmt"
garciadeblas31e141b2018-10-25 18:33:19 +02001126 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno66eba6e2017-11-10 17:09:18 +01001127 db_interface["type"] = "bridge"
1128 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1129 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1130 db_interface["type"] = "data"
1131 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1132 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1133 else "yes"
1134 flavor_epa_interfaces.append(flavor_epa_interface)
1135 else:
1136 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1137 "-interface':'type':'{}'. Interface type is not supported".format(
1138 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001139 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001140
tiernoe72710b2018-07-23 16:16:00 +02001141 if iface.get("mgmt-interface"):
1142 db_interface["type"] = "mgmt"
1143
tierno66eba6e2017-11-10 17:09:18 +01001144 if iface.get("external-connection-point-ref"):
1145 try:
1146 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1147 db_interface["external_name"] = get_str(cp, "name", 255)
1148 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1149 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1150 cp_name2db_interface[db_interface["external_name"]] = db_interface
1151 for cp_descriptor in vnfd_descriptor["connection-point"]:
1152 if cp_descriptor["name"] == db_interface["external_name"]:
1153 break
1154 else:
1155 raise KeyError()
1156
1157 if vdu_id in vdu_id2cp_name:
1158 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1159 else:
1160 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1161
1162 # port security
1163 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1164 db_interface["port_security"] = 0
1165 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1166 db_interface["port_security"] = 1
1167 except KeyError:
1168 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1169 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1170 " at connection-point".format(
1171 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1172 cp=iface.get("vnfd-connection-point-ref")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001173 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001174 elif iface.get("internal-connection-point-ref"):
1175 try:
tierno41a69812018-02-16 14:34:33 +01001176 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1177 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1178 break
1179 else:
1180 raise KeyError("does not exist at vdu:internal-connection-point")
1181 icp = None
1182 icp_vld = None
tierno66eba6e2017-11-10 17:09:18 +01001183 for vld in vnfd.get("internal-vld").itervalues():
1184 for cp in vld.get("internal-connection-point").itervalues():
1185 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
tierno41a69812018-02-16 14:34:33 +01001186 if icp:
1187 raise KeyError("is referenced by more than one 'internal-vld'")
1188 icp = cp
1189 icp_vld = vld
1190 if not icp:
1191 raise KeyError("is not referenced by any 'internal-vld'")
1192
1193 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1194 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1195 db_interface["port_security"] = 0
1196 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1197 db_interface["port_security"] = 1
1198 if icp.get("ip-address"):
1199 if not icp_vld.get("ip-profile-ref"):
1200 raise NfvoException
1201 db_interface["ip_address"] = str(icp.get("ip-address"))
1202 except KeyError as e:
tierno66eba6e2017-11-10 17:09:18 +01001203 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
tierno41a69812018-02-16 14:34:33 +01001204 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1205 " {msg}".format(
tierno66eba6e2017-11-10 17:09:18 +01001206 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
tierno41a69812018-02-16 14:34:33 +01001207 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001208 httperrors.Bad_Request)
tierno55d234c2018-07-04 18:29:21 +02001209 if iface.get("position"):
1210 db_interface["created_at"] = int(iface.get("position")) * 50
tierno41a69812018-02-16 14:34:33 +01001211 if iface.get("mac-address"):
1212 db_interface["mac"] = str(iface.get("mac-address"))
tierno66eba6e2017-11-10 17:09:18 +01001213 db_interfaces.append(db_interface)
1214
tiernof1ba57e2017-09-07 12:23:19 +02001215 # table flavors
1216 db_flavor = {
1217 "name": get_str(vdu, "name", 250) + "-flv",
1218 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1219 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
garciadeblas79d1a1a2017-12-11 16:07:07 +01001220 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
tiernof1ba57e2017-09-07 12:23:19 +02001221 }
tiernocf596692017-11-20 15:47:51 +01001222 # TODO revise the case of several numa-node-policy node
tiernof1ba57e2017-09-07 12:23:19 +02001223 extended = {}
1224 numa = {}
1225 if devices:
1226 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001227 if flavor_epa_interfaces:
1228 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001229 if vdu.get("guest-epa"): # TODO or dedicated_int:
1230 epa_vcpu_set = False
1231 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1232 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1233 if numa_node_policy.get("node"):
tiernocf596692017-11-20 15:47:51 +01001234 numa_node = numa_node_policy["node"].values()[0]
tiernof1ba57e2017-09-07 12:23:19 +02001235 if numa_node.get("num-cores"):
1236 numa["cores"] = numa_node["num-cores"]
1237 epa_vcpu_set = True
1238 if numa_node.get("paired-threads"):
1239 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001240 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001241 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001242 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001243 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001244 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001245 numa["paired-threads-id"].append(
1246 (str(pair["thread-a"]), str(pair["thread-b"]))
1247 )
1248 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001249 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001250 epa_vcpu_set = True
1251 if numa_node.get("memory-mb"):
1252 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1253 if vdu["guest-epa"].get("mempage-size"):
1254 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1255 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1256 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1257 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1258 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1259 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1260 numa["cores"] = max(db_flavor["vcpus"], 1)
1261 else:
1262 numa["threads"] = max(db_flavor["vcpus"], 1)
1263 if numa:
1264 extended["numas"] = [numa]
1265 if extended:
1266 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1267 db_flavor["extended"] = extended_text
1268 # look if flavor exist
garciadeblas79d1a1a2017-12-11 16:07:07 +01001269 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
tiernof1ba57e2017-09-07 12:23:19 +02001270 'ram': db_flavor.get('ram'),
1271 'vcpus': db_flavor.get('vcpus'),
1272 'extended': db_flavor.get('extended')
1273 }
1274 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1275 if existing_flavors:
1276 flavor_uuid = existing_flavors[0]["uuid"]
1277 else:
1278 flavor_uuid = str(uuid4())
1279 uuid_list.append(flavor_uuid)
1280 db_flavor["uuid"] = flavor_uuid
1281 db_flavors.append(db_flavor)
1282 db_vm["flavor_id"] = flavor_uuid
1283
tiernof1ba57e2017-09-07 12:23:19 +02001284 # VNF affinity and antiaffinity
1285 for pg in vnfd.get("placement-groups").itervalues():
1286 pg_name = get_str(pg, "name", 255)
1287 for vdu in pg.get("member-vdus").itervalues():
1288 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1289 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001290 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1291 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001292 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001293 httperrors.Bad_Request)
tiernob6990792018-11-13 10:37:42 +01001294 if vdu_id2db_table_index[vdu_id]:
1295 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
tiernof1ba57e2017-09-07 12:23:19 +02001296 # TODO consider the case of isolation and not colocation
1297 # if pg.get("strategy") == "ISOLATION":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001298
tiernof1ba57e2017-09-07 12:23:19 +02001299 # VNF mgmt configuration
1300 mgmt_access = {}
1301 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001302 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1303 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001304 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1305 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001306 vnf=vnfd_id, vdu=mgmt_vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001307 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001308 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001309 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1310 if vdu_id2cp_name.get(mgmt_vdu_id):
tiernob6990792018-11-13 10:37:42 +01001311 if cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]:
1312 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
tierno66eba6e2017-11-10 17:09:18 +01001313
tiernof1ba57e2017-09-07 12:23:19 +02001314 if vnfd["mgmt-interface"].get("ip-address"):
1315 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1316 if vnfd["mgmt-interface"].get("cp"):
1317 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob6990792018-11-13 10:37:42 +01001318 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
tiernob2880eb2017-10-04 15:04:53 +02001319 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001320 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001321 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001322 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1323 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001324 # mark this interface as of type mgmt
tiernob6990792018-11-13 10:37:42 +01001325 if cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]:
1326 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
tiernoe2ff1ce2017-11-02 17:01:10 +01001327
tiernoa9550202017-09-22 13:31:35 +02001328 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001329 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001330
tiernof1ba57e2017-09-07 12:23:19 +02001331 if default_user:
1332 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001333 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1334 "required", 6)
1335 if required:
1336 mgmt_access["required"] = required
1337
tiernof1ba57e2017-09-07 12:23:19 +02001338 if mgmt_access:
1339 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1340
1341 db_vnfs.append(db_vnf)
1342 db_tables=[
1343 {"vnfs": db_vnfs},
1344 {"nets": db_nets},
1345 {"images": db_images},
1346 {"flavors": db_flavors},
tierno41a69812018-02-16 14:34:33 +01001347 {"ip_profiles": db_ip_profiles},
tiernof1ba57e2017-09-07 12:23:19 +02001348 {"vms": db_vms},
1349 {"interfaces": db_interfaces},
1350 ]
1351
1352 logger.debug("create_vnf Deployment done vnfDict: %s",
1353 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1354 mydb.new_rows(db_tables, uuid_list)
1355 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001356 except NfvoException:
1357 raise
tiernof1ba57e2017-09-07 12:23:19 +02001358 except Exception as e:
1359 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001360 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001361
1362
tiernob8569aa2018-08-24 11:34:54 +02001363@deprecated("Use new_vnfd_v3")
tierno7edb6752016-03-21 17:37:52 +01001364def new_vnf(mydb, tenant_id, vnf_descriptor):
1365 global global_config
tierno42026a02017-02-10 15:13:40 +01001366
tierno7edb6752016-03-21 17:37:52 +01001367 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001368 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001369 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001370 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001371 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001372 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001373 if "tenant_id" in vnf_descriptor["vnf"]:
1374 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001375 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001376 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001377 else:
1378 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1379 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001380 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001381 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001382
1383 # Step 4. Review the descriptor and add missing fields
1384 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001385 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001386 vnf_name = vnf_descriptor['vnf']['name']
1387 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1388 if "physical" in vnf_descriptor['vnf']:
1389 del vnf_descriptor['vnf']['physical']
1390 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001391
tierno42026a02017-02-10 15:13:40 +01001392 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001393 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1394 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001395
tierno7edb6752016-03-21 17:37:52 +01001396 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1397 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1398 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001399 try:
tiernof97fd272016-07-11 14:32:37 +02001400 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001401 for vnfc in vnf_descriptor['vnf']['VNFC']:
1402 VNFCitem={}
1403 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001404 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001405 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001406
tiernof97fd272016-07-11 14:32:37 +02001407 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001408
tierno7edb6752016-03-21 17:37:52 +01001409 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001410 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 +01001411 myflavorDict["description"] = VNFCitem["description"]
1412 myflavorDict["ram"] = vnfc.get("ram", 0)
1413 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001414 myflavorDict["disk"] = vnfc.get("disk", 0)
tierno7edb6752016-03-21 17:37:52 +01001415 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001416
tierno7edb6752016-03-21 17:37:52 +01001417 devices = vnfc.get("devices")
1418 if devices != None:
1419 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001420
tierno7edb6752016-03-21 17:37:52 +01001421 # TODO:
1422 # 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
tierno42026a02017-02-10 15:13:40 +01001423 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1424
tierno7edb6752016-03-21 17:37:52 +01001425 # Previous code has been commented
1426 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1427 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1428 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1429 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1430 #else:
1431 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1432 # if result2:
1433 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001434 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
tierno7edb6752016-03-21 17:37:52 +01001435 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001436 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
tierno7edb6752016-03-21 17:37:52 +01001437 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001438
tierno7edb6752016-03-21 17:37:52 +01001439 if 'numas' in vnfc and len(vnfc['numas'])>0:
1440 myflavorDict['extended']['numas'] = vnfc['numas']
1441
1442 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001443
tierno7edb6752016-03-21 17:37:52 +01001444 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001445 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001446
tiernof97fd272016-07-11 14:32:37 +02001447 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001448 VNFCitem["flavor_id"] = flavor_id
1449 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001450
tiernof97fd272016-07-11 14:32:37 +02001451 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001452 # Step 6.3 New images are created in the VIM
1453 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001454 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001455 #In case this integration is made, the VNFCDict might become a VNFClist.
1456 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001457 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001458 image_dict={}
1459 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1460 image_dict['universal_name']=vnfc.get('image name')
1461 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1462 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001463 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001464 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001465 image_metadata_dict = vnfc.get('image metadata', None)
1466 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001467 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001468 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1469 image_dict['metadata']=image_metadata_str
1470 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001471 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1472 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001473 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001474 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001475 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001476 if vnfc.get("boot-data"):
1477 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001478
tierno42026a02017-02-10 15:13:40 +01001479
tiernof97fd272016-07-11 14:32:37 +02001480 # Step 7. Storing the VNF descriptor in the repository
1481 if "descriptor" not in vnf_descriptor["vnf"]:
1482 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001483
tiernof97fd272016-07-11 14:32:37 +02001484 # Step 8. Adding the VNF to the NFVO DB
1485 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1486 return vnf_id
1487 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001488 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001489 if isinstance(e, db_base_Exception):
1490 error_text = "Exception at database"
1491 elif isinstance(e, KeyError):
1492 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001493 e.http_code = httperrors.Internal_Server_Error
tiernof97fd272016-07-11 14:32:37 +02001494 else:
1495 error_text = "Exception at VIM"
1496 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1497 #logger.error("start_scenario %s", error_text)
1498 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001499
tiernob3d36742017-03-03 23:51:05 +01001500
tiernob8569aa2018-08-24 11:34:54 +02001501@deprecated("Use new_vnfd_v3")
garciadeblas9f8456e2016-09-05 05:02:59 +02001502def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1503 global global_config
tierno42026a02017-02-10 15:13:40 +01001504
garciadeblas9f8456e2016-09-05 05:02:59 +02001505 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001506 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001507 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001508 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001509 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001510 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001511 if "tenant_id" in vnf_descriptor["vnf"]:
1512 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1513 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001514 httperrors.Unauthorized)
garciadeblas9f8456e2016-09-05 05:02:59 +02001515 else:
1516 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1517 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001518 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001519 vims = get_vim(mydb, tenant_id, ignore_errors=True)
garciadeblas9f8456e2016-09-05 05:02:59 +02001520
1521 # Step 4. Review the descriptor and add missing fields
1522 #print vnf_descriptor
1523 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1524 vnf_name = vnf_descriptor['vnf']['name']
1525 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1526 if "physical" in vnf_descriptor['vnf']:
1527 del vnf_descriptor['vnf']['physical']
1528 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001529
tierno42026a02017-02-10 15:13:40 +01001530 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001531 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1532 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001533
garciadeblas9f8456e2016-09-05 05:02:59 +02001534 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1535 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1536 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1537 try:
1538 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1539 for vnfc in vnf_descriptor['vnf']['VNFC']:
1540 VNFCitem={}
1541 VNFCitem["name"] = vnfc['name']
1542 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001543
garciadeblas9f8456e2016-09-05 05:02:59 +02001544 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001545
garciadeblas9f8456e2016-09-05 05:02:59 +02001546 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001547 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 +02001548 myflavorDict["description"] = VNFCitem["description"]
1549 myflavorDict["ram"] = vnfc.get("ram", 0)
1550 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001551 myflavorDict["disk"] = vnfc.get("disk", 0)
garciadeblas9f8456e2016-09-05 05:02:59 +02001552 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001553
garciadeblas9f8456e2016-09-05 05:02:59 +02001554 devices = vnfc.get("devices")
1555 if devices != None:
1556 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001557
garciadeblas9f8456e2016-09-05 05:02:59 +02001558 # TODO:
1559 # 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
tierno42026a02017-02-10 15:13:40 +01001560 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1561
garciadeblas9f8456e2016-09-05 05:02:59 +02001562 # Previous code has been commented
1563 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1564 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1565 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1566 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1567 #else:
1568 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1569 # if result2:
1570 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001571 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
garciadeblas9f8456e2016-09-05 05:02:59 +02001572 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001573 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
garciadeblas9f8456e2016-09-05 05:02:59 +02001574 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001575
garciadeblas9f8456e2016-09-05 05:02:59 +02001576 if 'numas' in vnfc and len(vnfc['numas'])>0:
1577 myflavorDict['extended']['numas'] = vnfc['numas']
1578
1579 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001580
garciadeblas9f8456e2016-09-05 05:02:59 +02001581 # Step 6.2 New flavors are created in the VIM
1582 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1583
1584 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1585 VNFCitem["flavor_id"] = flavor_id
1586 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001587
garciadeblas9f8456e2016-09-05 05:02:59 +02001588 logger.debug("Creating new images in the VIM for each VNFC")
1589 # Step 6.3 New images are created in the VIM
1590 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001591 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001592 #In case this integration is made, the VNFCDict might become a VNFClist.
1593 for vnfc in vnf_descriptor['vnf']['VNFC']:
1594 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001595 image_dict={}
1596 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1597 image_dict['universal_name']=vnfc.get('image name')
1598 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1599 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001600 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001601 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001602 image_metadata_dict = vnfc.get('image metadata', None)
1603 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001604 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001605 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1606 image_dict['metadata']=image_metadata_str
1607 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1608 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1609 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1610 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001611 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001612 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001613 if vnfc.get("boot-data"):
1614 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001615
garciadeblas9f8456e2016-09-05 05:02:59 +02001616 # Step 7. Storing the VNF descriptor in the repository
1617 if "descriptor" not in vnf_descriptor["vnf"]:
1618 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001619
garciadeblas9f8456e2016-09-05 05:02:59 +02001620 # Step 8. Adding the VNF to the NFVO DB
1621 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1622 return vnf_id
1623 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1624 _, message = rollback(mydb, vims, rollback_list)
1625 if isinstance(e, db_base_Exception):
1626 error_text = "Exception at database"
1627 elif isinstance(e, KeyError):
1628 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001629 e.http_code = httperrors.Internal_Server_Error
garciadeblas9f8456e2016-09-05 05:02:59 +02001630 else:
1631 error_text = "Exception at VIM"
1632 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1633 #logger.error("start_scenario %s", error_text)
1634 raise NfvoException(error_text, e.http_code)
1635
tiernob3d36742017-03-03 23:51:05 +01001636
tierno7edb6752016-03-21 17:37:52 +01001637def get_vnf_id(mydb, tenant_id, vnf_id):
1638 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001639 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001640 #obtain data
1641 where_or = {}
1642 if tenant_id != "any":
1643 where_or["tenant_id"] = tenant_id
1644 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001645 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1646
tiernof1ba57e2017-09-07 12:23:19 +02001647 vnf_id = vnf["uuid"]
1648 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001649 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001650 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1651 data={'vnf' : filtered_content}
1652 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001653 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001654 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1655 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001656 WHERE={'vnfs.uuid': vnf_id} )
gcalvinobfa2fd92018-11-13 18:47:28 +01001657 if len(content) != 0:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00001658 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001659 # change boot_data into boot-data
gcalvino319b8a52018-11-05 15:33:23 +01001660 for vm in content:
1661 if vm.get("boot_data"):
1662 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1663 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001664
gcalvinobfa2fd92018-11-13 18:47:28 +01001665 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001666 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001667
tierno7edb6752016-03-21 17:37:52 +01001668 #GET NET
tierno42026a02017-02-10 15:13:40 +01001669 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001670 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1671 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001672 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001673
1674 #GET ip-profile for each net
1675 for net in data['vnf']['nets']:
1676 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1677 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1678 WHERE={'net_id': net["uuid"]} )
1679 if len(ipprofiles)==1:
1680 net["ip_profile"] = ipprofiles[0]
1681 elif len(ipprofiles)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001682 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net['uuid']), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001683
1684
garciadeblas9f8456e2016-09-05 05:02:59 +02001685 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
tierno42026a02017-02-10 15:13:40 +01001686
garciadeblas9f8456e2016-09-05 05:02:59 +02001687 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001688 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 +01001689 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1690 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001691 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001692 #print content
tiernof97fd272016-07-11 14:32:37 +02001693 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001694
tiernof97fd272016-07-11 14:32:37 +02001695 return data
tierno7edb6752016-03-21 17:37:52 +01001696
1697
1698def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1699 # Check tenant exist
1700 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001701 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001702 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernocbb52052018-05-31 18:57:30 +02001703 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001704 else:
1705 vims={}
1706
1707 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1708 where_or = {}
1709 if tenant_id != "any":
1710 where_or["tenant_id"] = tenant_id
1711 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001712 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001713 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001714
tierno7edb6752016-03-21 17:37:52 +01001715 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001716 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001717 if len(flavorList)==0:
1718 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001719
tiernof97fd272016-07-11 14:32:37 +02001720 imageList = get_imagelist(mydb, vnf_id)
1721 if len(imageList)==0:
1722 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001723
tiernof97fd272016-07-11 14:32:37 +02001724 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1725 if deleted == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001726 raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno42026a02017-02-10 15:13:40 +01001727
tierno7edb6752016-03-21 17:37:52 +01001728 undeletedItems = []
1729 for flavor in flavorList:
1730 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001731 try:
1732 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1733 if len(c) > 0:
1734 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1735 continue
1736 #flavor not used, must be deleted
1737 #delelte at VIM
tierno96ebf002017-12-13 10:55:38 +01001738 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
tierno7edb6752016-03-21 17:37:52 +01001739 for flavor_vim in c:
tierno96ebf002017-12-13 10:55:38 +01001740 if not flavor_vim['created']: # skip this flavor because not created by openmano
tierno7edb6752016-03-21 17:37:52 +01001741 continue
tierno96ebf002017-12-13 10:55:38 +01001742 # look for vim
1743 myvim = None
1744 for vim in vims.values():
1745 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1746 myvim = vim
1747 break
1748 if not myvim:
tierno7edb6752016-03-21 17:37:52 +01001749 continue
tiernoae4a8d12016-07-08 12:30:39 +02001750 try:
1751 myvim.delete_flavor(flavor_vim["vim_id"])
tierno96ebf002017-12-13 10:55:38 +01001752 except vimconn.vimconnNotFoundException:
1753 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1754 flavor_vim["datacenter_vim_id"] )
tiernoae4a8d12016-07-08 12:30:39 +02001755 except vimconn.vimconnException as e:
1756 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
tierno96ebf002017-12-13 10:55:38 +01001757 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1758 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1759 flavor_vim["datacenter_vim_id"]))
1760 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
tiernof97fd272016-07-11 14:32:37 +02001761 mydb.delete_row_by_id('flavors', flavor)
1762 except db_base_Exception as e:
1763 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno96ebf002017-12-13 10:55:38 +01001764 undeletedItems.append("flavor {}".format(flavor))
tiernof97fd272016-07-11 14:32:37 +02001765
tierno42026a02017-02-10 15:13:40 +01001766
tierno7edb6752016-03-21 17:37:52 +01001767 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001768 try:
1769 #check if image is used by other vnf
tierno16e3dd42018-04-24 12:52:40 +02001770 c = mydb.get_rows(FROM='vms', WHERE=[{'image_id': image}, {'image_list LIKE ': '%' + image + '%'}])
tiernof97fd272016-07-11 14:32:37 +02001771 if len(c) > 0:
1772 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1773 continue
1774 #image not used, must be deleted
1775 #delelte at VIM
1776 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001777 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001778 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001779 continue
1780 if image_vim['created']=='false': #skip this image because not created by openmano
1781 continue
1782 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001783 try:
1784 myvim.delete_image(image_vim["vim_id"])
1785 except vimconn.vimconnNotFoundException as e:
1786 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1787 except vimconn.vimconnException as e:
1788 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1789 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1790 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001791 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1792 mydb.delete_row_by_id('images', image)
1793 except db_base_Exception as e:
1794 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001795 undeletedItems.append("image %s" % image)
1796
tiernof97fd272016-07-11 14:32:37 +02001797 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001798 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001799 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001800
tiernob3d36742017-03-03 23:51:05 +01001801
tiernob8569aa2018-08-24 11:34:54 +02001802@deprecated("Not used")
tierno7edb6752016-03-21 17:37:52 +01001803def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1804 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1805 if result < 0:
1806 return result, vims
1807 elif result == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001808 return -httperrors.Not_Found, "datacenter '%s' not found" % datacenter_name
tierno7edb6752016-03-21 17:37:52 +01001809 myvim = vims.values()[0]
1810 result,servers = myvim.get_hosts_info()
1811 if result < 0:
1812 return result, servers
1813 topology = {'name':myvim['name'] , 'servers': servers}
1814 return result, topology
1815
tiernob3d36742017-03-03 23:51:05 +01001816
tierno7edb6752016-03-21 17:37:52 +01001817def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001818 vims = get_vim(mydb, nfvo_tenant_id)
1819 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001820 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001821 elif len(vims)>1:
1822 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001823 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001824 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001825 try:
1826 hosts = myvim.get_hosts()
1827 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001828
tiernof97fd272016-07-11 14:32:37 +02001829 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1830 for host in hosts:
1831 server={'name':host['name'], 'vms':[]}
1832 for vm in host['instances']:
1833 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001834 try:
tiernof97fd272016-07-11 14:32:37 +02001835 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1836 WHERE={'vim_vm_id':vm['id']} )
1837 if len(c) == 0:
1838 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1839 continue
1840 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001841
tiernof97fd272016-07-11 14:32:37 +02001842 except db_base_Exception as e:
1843 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1844 datacenter['Datacenters'][0]['servers'].append(server)
1845 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001846
tiernof97fd272016-07-11 14:32:37 +02001847 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1848 return datacenter
1849 except vimconn.vimconnException as e:
1850 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001851
tiernob3d36742017-03-03 23:51:05 +01001852
tiernob8569aa2018-08-24 11:34:54 +02001853@deprecated("Use new_nsd_v3")
tierno7edb6752016-03-21 17:37:52 +01001854def new_scenario(mydb, tenant_id, topo):
1855
1856# result, vims = get_vim(mydb, tenant_id)
1857# if result < 0:
1858# return result, vims
1859#1: parse input
1860 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001861 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001862 if "tenant_id" in topo:
1863 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001864 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001865 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001866 else:
1867 tenant_id=None
1868
tierno42026a02017-02-10 15:13:40 +01001869#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001870 vnfs={}
1871 other_nets={} #external_networks, bridge_networks and data_networkds
1872 nodes = topo['topology']['nodes']
1873 for k in nodes.keys():
1874 if nodes[k]['type'] == 'VNF':
1875 vnfs[k] = nodes[k]
1876 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001877 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001878 other_nets[k] = nodes[k]
1879 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001880 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001881 other_nets[k] = nodes[k]
1882 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001883
tierno7edb6752016-03-21 17:37:52 +01001884
1885#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1886 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001887 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001888 error_text = ""
1889 error_pos = "'topology':'nodes':'" + name + "'"
1890 if 'vnf_id' in vnf:
1891 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001892 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001893 if 'VNF model' in vnf:
1894 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001895 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001896 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001897 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001898
tiernocea279c2016-07-18 12:36:49 +02001899 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1900 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001901 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001902 if len(vnf_db)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001903 raise NfvoException("unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001904 elif len(vnf_db)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001905 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001906 vnf['uuid']=vnf_db[0]['uuid']
1907 vnf['description']=vnf_db[0]['description']
1908 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001909 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1910 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
tierno3fcfdb72017-10-24 07:48:24 +02001911 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001912 for ext_iface in ext_ifaces:
1913 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1914
1915#1.4 get list of connections
1916 conections = topo['topology']['connections']
1917 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001918 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001919 for k in conections.keys():
1920 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1921 ifaces_list = conections[k]['nodes'].items()
1922 elif type(conections[k]['nodes'])==list: #list with dictionary
1923 ifaces_list=[]
1924 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1925 for k2 in conection_pair_list:
1926 ifaces_list += k2
1927
1928 con_type = conections[k].get("type", "link")
1929 if con_type != "link":
1930 if k in other_nets:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001931 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001932 other_nets[k] = {'external': False}
1933 if conections[k].get("graph"):
1934 other_nets[k]["graph"] = conections[k]["graph"]
1935 ifaces_list.append( (k, None) )
1936
tierno42026a02017-02-10 15:13:40 +01001937
tierno7edb6752016-03-21 17:37:52 +01001938 if con_type == "external_network":
1939 other_nets[k]['external'] = True
1940 if conections[k].get("model"):
1941 other_nets[k]["model"] = conections[k]["model"]
1942 else:
1943 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001944 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001945 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001946
tiernoefd80c92016-09-16 14:17:46 +02001947 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001948 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)
1949 #print set(ifaces_list)
1950 #check valid VNF and iface names
1951 for iface in ifaces_list:
1952 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001953 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001954 str(k), iface[0]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001955 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001956 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001957 str(k), iface[0], iface[1]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001958
1959#1.5 unify connections from the pair list to a consolidated list
1960 index=0
1961 while index < len(conections_list):
1962 index2 = index+1
1963 while index2 < len(conections_list):
1964 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1965 conections_list[index] |= conections_list[index2]
1966 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001967 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001968 else:
1969 index2 += 1
1970 conections_list[index] = list(conections_list[index]) # from set to list again
1971 index += 1
1972 #for k in conections_list:
1973 # print k
tierno42026a02017-02-10 15:13:40 +01001974
tierno7edb6752016-03-21 17:37:52 +01001975
1976
1977#1.6 Delete non external nets
1978# for k in other_nets.keys():
1979# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1980# for con in conections_list:
1981# delete_indexes=[]
1982# for index in range(0,len(con)):
1983# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1984# for index in delete_indexes:
1985# del con[index]
1986# del other_nets[k]
1987#1.7: Check external_ports are present at database table datacenter_nets
1988 for k,net in other_nets.items():
1989 error_pos = "'topology':'nodes':'" + k + "'"
1990 if net['external']==False:
1991 if 'name' not in net:
1992 net['name']=k
1993 if 'model' not in net:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001994 raise NfvoException("needed a 'model' at " + error_pos, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001995 if net['model']=='bridge_net':
1996 net['type']='bridge';
1997 elif net['model']=='dataplane_net':
1998 net['type']='data';
1999 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002000 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002001 else: #external
2002#IF we do not want to check that external network exist at datacenter
2003 pass
tierno42026a02017-02-10 15:13:40 +01002004#ELSE
tierno7edb6752016-03-21 17:37:52 +01002005# error_text = ""
2006# WHERE_={}
2007# if 'net_id' in net:
2008# error_text += " 'net_id' " + net['net_id']
2009# WHERE_['uuid'] = net['net_id']
2010# if 'model' in net:
2011# error_text += " 'model' " + net['model']
2012# WHERE_['name'] = net['model']
2013# if len(WHERE_) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002014# return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002015# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2016# FROM='datacenter_nets', WHERE=WHERE_ )
2017# if r<0:
2018# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2019# elif r==0:
2020# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002021# return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002022# elif r>1:
tierno42026a02017-02-10 15:13:40 +01002023# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002024# return -httperrors.Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
tierno7edb6752016-03-21 17:37:52 +01002025# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01002026#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002027 net_list={}
2028 net_nb=0 #Number of nets
2029 for con in conections_list:
2030 #check if this is connected to a external net
2031 other_net_index=-1
2032 #print
2033 #print "con", con
2034 for index in range(0,len(con)):
2035 #check if this is connected to a external net
2036 for net_key in other_nets.keys():
2037 if con[index][0]==net_key:
2038 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01002039 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 +02002040 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002041 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002042 else:
2043 other_net_index = index
2044 net_target = net_key
2045 break
2046 #print "other_net_index", other_net_index
2047 try:
2048 if other_net_index>=0:
2049 del con[other_net_index]
2050#IF we do not want to check that external network exist at datacenter
2051 if other_nets[net_target]['external'] :
2052 if "name" not in other_nets[net_target]:
2053 other_nets[net_target]['name'] = other_nets[net_target]['model']
2054 if other_nets[net_target]["type"] == "external_network":
2055 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
2056 other_nets[net_target]["type"] = "data"
2057 else:
2058 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01002059#ELSE
tierno7edb6752016-03-21 17:37:52 +01002060# if other_nets[net_target]['external'] :
2061# 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
2062# if type_=='data' and other_nets[net_target]['type']=="ptp":
2063# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2064# print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002065# return -httperrors.Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01002066#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002067 for iface in con:
2068 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2069 else:
2070 #create a net
2071 net_type_bridge=False
2072 net_type_data=False
2073 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01002074 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02002075 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01002076 'external':False}
tierno7edb6752016-03-21 17:37:52 +01002077 for iface in con:
2078 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2079 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
2080 if iface_type=='mgmt' or iface_type=='bridge':
2081 net_type_bridge = True
2082 else:
2083 net_type_data = True
2084 if net_type_bridge and net_type_data:
2085 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 +02002086 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002087 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002088 elif net_type_bridge:
2089 type_='bridge'
2090 else:
2091 type_='data' if len(con)>2 else 'ptp'
2092 net_list[net_target]['type'] = type_
2093 net_nb+=1
2094 except Exception:
2095 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02002096 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01002097 #raise e
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002098 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002099
2100#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01002101 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02002102 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01002103 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01002104 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02002105 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01002106 add_mgmt_net = False
2107 for vnf in vnfs.values():
2108 for iface in vnf['ifaces'].values():
2109 if iface['type']=='mgmt' and 'net_key' not in iface:
2110 #iface not connected
2111 iface['net_key'] = 'mgmt'
2112 add_mgmt_net = True
2113 if add_mgmt_net and 'mgmt' not in net_list:
2114 net_list['mgmt']=mgmt_net[0]
2115 net_list['mgmt']['external']=True
2116 net_list['mgmt']['graph']={'visible':False}
2117
2118 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02002119 #print
2120 #print 'net_list', net_list
2121 #print
2122 #print 'vnfs', vnfs
2123 #print
tierno7edb6752016-03-21 17:37:52 +01002124
2125#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02002126 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02002127 'tenant_id':tenant_id, 'name':topo['name'],
2128 'description':topo.get('description',topo['name']),
2129 'public': topo.get('public', False)
2130 })
tierno42026a02017-02-10 15:13:40 +01002131
tiernof97fd272016-07-11 14:32:37 +02002132 return c
tierno7edb6752016-03-21 17:37:52 +01002133
tiernob3d36742017-03-03 23:51:05 +01002134
tiernob8569aa2018-08-24 11:34:54 +02002135@deprecated("Use new_nsd_v3")
tierno5bb59dc2017-02-13 14:53:54 +01002136def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2137 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02002138 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01002139 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01002140 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002141 if "tenant_id" in scenario:
2142 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01002143 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02002144 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002145 scenario["tenant_id"], tenant_id), httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01002146 else:
2147 tenant_id=None
2148
tierno5bb59dc2017-02-13 14:53:54 +01002149 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01002150 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02002151 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01002152 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02002153 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01002154 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002155 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02002156 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02002157 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002158 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02002159 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02002160 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002161 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002162 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002163 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002164 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002165 if len(vnf_db) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002166 raise NfvoException("Unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002167 elif len(vnf_db) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002168 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002169 vnf['uuid'] = vnf_db[0]['uuid']
2170 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002171 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002172 # get external interfaces
2173 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2174 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
tierno3fcfdb72017-10-24 07:48:24 +02002175 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002176 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002177 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2178 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002179
tierno5bb59dc2017-02-13 14:53:54 +01002180 # 2: Insert net_key and ip_address at every vnf interface
2181 for net_name, net in scenario["networks"].items():
2182 net_type_bridge = False
2183 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002184 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002185 if version == "0.2":
2186 temp_dict = iface_dict
2187 ip_address = None
2188 elif version == "0.3":
2189 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2190 ip_address = iface_dict.get('ip_address', None)
2191 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002192 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002193 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2194 net_name, vnf)
2195 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002196 raise NfvoException(error_text, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002197 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002198 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2199 .format(net_name, iface)
2200 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002201 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002202 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002203 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2204 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2205 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002206 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002207 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002208 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002209 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002210 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002211 net_type_bridge = True
2212 else:
2213 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002214
tierno7edb6752016-03-21 17:37:52 +01002215 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002216 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2217 .format(net_name)
2218 # logger.debug("nfvo.new_scenario " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002219 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002220 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002221 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002222 else:
tierno5bb59dc2017-02-13 14:53:54 +01002223 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2224
2225 if net.get("implementation"): # for v0.3
2226 if type_ == "bridge" and net["implementation"] == "underlay":
2227 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2228 "'network':'{}'".format(net_name)
2229 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002230 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002231 elif type_ != "bridge" and net["implementation"] == "overlay":
2232 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2233 "'network':'{}'".format(net_name)
2234 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002235 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002236 net.pop("implementation")
2237 if "type" in net and version == "0.3": # for v0.3
2238 if type_ == "data" and net["type"] == "e-line":
2239 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2240 "'e-line' at 'network':'{}'".format(net_name)
2241 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002242 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002243 elif type_ == "ptp" and net["type"] == "e-lan":
2244 type_ = "data"
2245
tierno7edb6752016-03-21 17:37:52 +01002246 net['type'] = type_
2247 net['name'] = net_name
2248 net['external'] = net.get('external', False)
2249
tierno5bb59dc2017-02-13 14:53:54 +01002250 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002251 scenario["nets"] = scenario["networks"]
2252 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002253 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002254 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002255
tiernob3d36742017-03-03 23:51:05 +01002256
tiernof1ba57e2017-09-07 12:23:19 +02002257def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2258 """
2259 Parses an OSM IM nsd_catalog and insert at DB
2260 :param mydb:
2261 :param tenant_id:
2262 :param nsd_descriptor:
Igor D.Ccaadc442017-11-06 12:48:48 +00002263 :return: The list of created NSD ids
tiernof1ba57e2017-09-07 12:23:19 +02002264 """
2265 try:
2266 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002267 try:
2268 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd)
2269 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002270 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002271 db_scenarios = []
2272 db_sce_nets = []
2273 db_sce_vnfs = []
2274 db_sce_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002275 db_sce_vnffgs = []
2276 db_sce_rsps = []
2277 db_sce_rsp_hops = []
2278 db_sce_classifiers = []
2279 db_sce_classifier_matches = []
tiernof1ba57e2017-09-07 12:23:19 +02002280 db_ip_profiles = []
2281 db_ip_profiles_index = 0
2282 uuid_list = []
2283 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002284 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2285 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002286
Igor D.Ccaadc442017-11-06 12:48:48 +00002287 # table scenarios
tiernof1ba57e2017-09-07 12:23:19 +02002288 scenario_uuid = str(uuid4())
2289 uuid_list.append(scenario_uuid)
2290 nsd_uuid_list.append(scenario_uuid)
2291 db_scenario = {
2292 "uuid": scenario_uuid,
2293 "osm_id": get_str(nsd, "id", 255),
2294 "name": get_str(nsd, "name", 255),
2295 "description": get_str(nsd, "description", 255),
2296 "tenant_id": tenant_id,
2297 "vendor": get_str(nsd, "vendor", 255),
2298 "short_name": get_str(nsd, "short-name", 255),
2299 "descriptor": str(nsd_descriptor)[:60000],
2300 }
2301 db_scenarios.append(db_scenario)
2302
2303 # table sce_vnfs (constituent-vnfd)
2304 vnf_index2scevnf_uuid = {}
2305 vnf_index2vnf_uuid = {}
2306 for vnf in nsd.get("constituent-vnfd").itervalues():
2307 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2308 'tenant_id': tenant_id})
2309 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002310 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2311 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2312 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002313 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002314 sce_vnf_uuid = str(uuid4())
2315 uuid_list.append(sce_vnf_uuid)
2316 db_sce_vnf = {
2317 "uuid": sce_vnf_uuid,
2318 "scenario_id": scenario_uuid,
tierno92c36fd2018-05-04 12:21:10 +02002319 # "name": get_str(vnf, "member-vnf-index", 255),
2320 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 50),
tiernof1ba57e2017-09-07 12:23:19 +02002321 "vnf_id": existing_vnf[0]["uuid"],
tierno16e3dd42018-04-24 12:52:40 +02002322 "member_vnf_index": str(vnf["member-vnf-index"]),
tiernof1ba57e2017-09-07 12:23:19 +02002323 # TODO 'start-by-default': True
2324 }
tierno16e3dd42018-04-24 12:52:40 +02002325 vnf_index2scevnf_uuid[str(vnf['member-vnf-index'])] = sce_vnf_uuid
2326 vnf_index2vnf_uuid[str(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
tiernof1ba57e2017-09-07 12:23:19 +02002327 db_sce_vnfs.append(db_sce_vnf)
2328
2329 # table ip_profiles (ip-profiles)
2330 ip_profile_name2db_table_index = {}
2331 for ip_profile in nsd.get("ip-profiles").itervalues():
2332 db_ip_profile = {
2333 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2334 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2335 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2336 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2337 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2338 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2339 }
2340 dns_list = []
2341 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2342 dns_list.append(str(dns.get("address")))
2343 db_ip_profile["dns_address"] = ";".join(dns_list)
2344 if ip_profile["ip-profile-params"].get('security-group'):
2345 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2346 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2347 db_ip_profiles_index += 1
2348 db_ip_profiles.append(db_ip_profile)
2349
2350 # table sce_nets (internal-vld)
2351 for vld in nsd.get("vld").itervalues():
2352 sce_net_uuid = str(uuid4())
2353 uuid_list.append(sce_net_uuid)
2354 db_sce_net = {
2355 "uuid": sce_net_uuid,
2356 "name": get_str(vld, "name", 255),
2357 "scenario_id": scenario_uuid,
2358 # "type": #TODO
2359 "multipoint": not vld.get("type") == "ELINE",
tierno1df468d2018-07-06 14:25:16 +02002360 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +02002361 # "external": #TODO
2362 "description": get_str(vld, "description", 255),
2363 }
2364 # guess type of network
2365 if vld.get("mgmt-network"):
2366 db_sce_net["type"] = "bridge"
2367 db_sce_net["external"] = True
2368 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2369 db_sce_net["type"] = "data"
2370 else:
tierno66eba6e2017-11-10 17:09:18 +01002371 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2372 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002373 db_sce_nets.append(db_sce_net)
2374
2375 # ip-profile, link db_ip_profile with db_sce_net
2376 if vld.get("ip-profile-ref"):
2377 ip_profile_name = vld.get("ip-profile-ref")
2378 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002379 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2380 " Reference to a non-existing 'ip_profiles'".format(
2381 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002382 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002383 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
tierno8f79ea12018-05-03 17:37:40 +02002384 elif vld.get("vim-network-name"):
2385 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
tiernof1ba57e2017-09-07 12:23:19 +02002386
2387 # table sce_interfaces (vld:vnfd-connection-point-ref)
2388 for iface in vld.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002389 vnf_index = str(iface['member-vnf-index-ref'])
tiernof1ba57e2017-09-07 12:23:19 +02002390 # check correct parameters
2391 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002392 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2393 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2394 "'nsd':'constituent-vnfd'".format(
2395 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002396 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002397
tierno66eba6e2017-11-10 17:09:18 +01002398 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002399 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2400 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2401 'external_name': get_str(iface, "vnfd-connection-point-ref",
2402 255)})
2403 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002404 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2405 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2406 "connection-point name at VNFD '{}'".format(
2407 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2408 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002409 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002410 interface_uuid = existing_ifaces[0]["uuid"]
tierno66eba6e2017-11-10 17:09:18 +01002411 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2412 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002413 sce_interface_uuid = str(uuid4())
2414 uuid_list.append(sce_net_uuid)
tierno41a69812018-02-16 14:34:33 +01002415 iface_ip_address = None
2416 if iface.get("ip-address"):
2417 iface_ip_address = str(iface.get("ip-address"))
tiernof1ba57e2017-09-07 12:23:19 +02002418 db_sce_interface = {
2419 "uuid": sce_interface_uuid,
2420 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2421 "sce_net_id": sce_net_uuid,
2422 "interface_id": interface_uuid,
tierno41a69812018-02-16 14:34:33 +01002423 "ip_address": iface_ip_address,
tiernof1ba57e2017-09-07 12:23:19 +02002424 }
2425 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002426 if not db_sce_net["type"]:
2427 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002428
Igor D.Ccaadc442017-11-06 12:48:48 +00002429 # table sce_vnffgs (vnffgd)
2430 for vnffg in nsd.get("vnffgd").itervalues():
2431 sce_vnffg_uuid = str(uuid4())
2432 uuid_list.append(sce_vnffg_uuid)
2433 db_sce_vnffg = {
2434 "uuid": sce_vnffg_uuid,
2435 "name": get_str(vnffg, "name", 255),
2436 "scenario_id": scenario_uuid,
2437 "vendor": get_str(vnffg, "vendor", 255),
2438 "description": get_str(vld, "description", 255),
2439 }
2440 db_sce_vnffgs.append(db_sce_vnffg)
2441
2442 # deal with rsps
2443 db_sce_rsps = []
2444 for rsp in vnffg.get("rsp").itervalues():
2445 sce_rsp_uuid = str(uuid4())
2446 uuid_list.append(sce_rsp_uuid)
2447 db_sce_rsp = {
2448 "uuid": sce_rsp_uuid,
2449 "name": get_str(rsp, "name", 255),
2450 "sce_vnffg_id": sce_vnffg_uuid,
2451 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2452 }
2453 db_sce_rsps.append(db_sce_rsp)
2454 db_sce_rsp_hops = []
2455 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002456 vnf_index = str(iface['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002457 if_order = int(iface['order'])
2458 # check correct parameters
2459 if vnf_index not in vnf_index2vnf_uuid:
2460 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2461 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2462 "'nsd':'constituent-vnfd'".format(
2463 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002464 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002465
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002466 ingress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2467 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2468 WHERE={
2469 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2470 'external_name': get_str(iface, "vnfd-ingress-connection-point-ref",
2471 255)})
2472 if not ingress_existing_ifaces:
Igor D.Ccaadc442017-11-06 12:48:48 +00002473 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002474 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
Igor D.Ccaadc442017-11-06 12:48:48 +00002475 "connection-point name at VNFD '{}'".format(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002476 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-ingress-connection-point-ref"]),
2477 str(iface.get("vnfd-id-ref"))[:255]), httperrors.Bad_Request)
2478
2479 egress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2480 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2481 WHERE={
2482 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2483 'external_name': get_str(iface, "vnfd-egress-connection-point-ref",
2484 255)})
2485 if not egress_existing_ifaces:
2486 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2487 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2488 "connection-point name at VNFD '{}'".format(
2489 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-egress-connection-point-ref"]),
2490 str(iface.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request)
2491
2492 ingress_interface_uuid = ingress_existing_ifaces[0]["uuid"]
2493 egress_interface_uuid = egress_existing_ifaces[0]["uuid"]
Igor D.Ccaadc442017-11-06 12:48:48 +00002494 sce_rsp_hop_uuid = str(uuid4())
2495 uuid_list.append(sce_rsp_hop_uuid)
2496 db_sce_rsp_hop = {
2497 "uuid": sce_rsp_hop_uuid,
2498 "if_order": if_order,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002499 "ingress_interface_id": ingress_interface_uuid,
2500 "egress_interface_id": egress_interface_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00002501 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2502 "sce_rsp_id": sce_rsp_uuid,
2503 }
2504 db_sce_rsp_hops.append(db_sce_rsp_hop)
2505
2506 # deal with classifiers
2507 db_sce_classifiers = []
2508 for classifier in vnffg.get("classifier").itervalues():
2509 sce_classifier_uuid = str(uuid4())
2510 uuid_list.append(sce_classifier_uuid)
2511
2512 # source VNF
tierno16e3dd42018-04-24 12:52:40 +02002513 vnf_index = str(classifier['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002514 if vnf_index not in vnf_index2vnf_uuid:
2515 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2516 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2517 "'nsd':'constituent-vnfd'".format(
2518 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002519 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002520 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2521 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2522 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2523 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2524 255)})
2525 if not existing_ifaces:
2526 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2527 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2528 "connection-point name at VNFD '{}'".format(
2529 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2530 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002531 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002532 interface_uuid = existing_ifaces[0]["uuid"]
2533
2534 db_sce_classifier = {
2535 "uuid": sce_classifier_uuid,
2536 "name": get_str(classifier, "name", 255),
2537 "sce_vnffg_id": sce_vnffg_uuid,
2538 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2539 "interface_id": interface_uuid,
2540 }
2541 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2542 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2543 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2544 db_sce_classifiers.append(db_sce_classifier)
2545
2546 db_sce_classifier_matches = []
2547 for match in classifier.get("match-attributes").itervalues():
2548 sce_classifier_match_uuid = str(uuid4())
2549 uuid_list.append(sce_classifier_match_uuid)
2550 db_sce_classifier_match = {
2551 "uuid": sce_classifier_match_uuid,
2552 "ip_proto": get_str(match, "ip-proto", 2),
2553 "source_ip": get_str(match, "source-ip-address", 16),
2554 "destination_ip": get_str(match, "destination-ip-address", 16),
2555 "source_port": get_str(match, "source-port", 5),
2556 "destination_port": get_str(match, "destination-port", 5),
2557 "sce_classifier_id": sce_classifier_uuid,
2558 }
2559 db_sce_classifier_matches.append(db_sce_classifier_match)
2560 # TODO: vnf/cp keys
2561
2562 # remove unneeded id's in sce_rsps
2563 for rsp in db_sce_rsps:
2564 rsp.pop('id')
2565
tiernof1ba57e2017-09-07 12:23:19 +02002566 db_tables = [
2567 {"scenarios": db_scenarios},
2568 {"sce_nets": db_sce_nets},
2569 {"ip_profiles": db_ip_profiles},
2570 {"sce_vnfs": db_sce_vnfs},
2571 {"sce_interfaces": db_sce_interfaces},
Igor D.Ccaadc442017-11-06 12:48:48 +00002572 {"sce_vnffgs": db_sce_vnffgs},
2573 {"sce_rsps": db_sce_rsps},
2574 {"sce_rsp_hops": db_sce_rsp_hops},
2575 {"sce_classifiers": db_sce_classifiers},
2576 {"sce_classifier_matches": db_sce_classifier_matches},
tiernof1ba57e2017-09-07 12:23:19 +02002577 ]
2578
Igor D.Ccaadc442017-11-06 12:48:48 +00002579 logger.debug("new_nsd_v3 done: %s",
tiernof1ba57e2017-09-07 12:23:19 +02002580 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2581 mydb.new_rows(db_tables, uuid_list)
2582 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002583 except NfvoException:
2584 raise
tiernof1ba57e2017-09-07 12:23:19 +02002585 except Exception as e:
2586 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002587 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002588
2589
tierno7edb6752016-03-21 17:37:52 +01002590def edit_scenario(mydb, tenant_id, scenario_id, data):
2591 data["uuid"] = scenario_id
2592 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002593 c = mydb.edit_scenario( data )
2594 return c
tierno7edb6752016-03-21 17:37:52 +01002595
tiernob3d36742017-03-03 23:51:05 +01002596
tiernob8569aa2018-08-24 11:34:54 +02002597@deprecated("Use create_instance")
tierno7edb6752016-03-21 17:37:52 +01002598def 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 +02002599 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002600 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2601 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002602 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002603 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002604
tierno7edb6752016-03-21 17:37:52 +01002605 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002606 try:
2607 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002608 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002609 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002610 scenarioDict['datacenter_id'] = datacenter_id
2611 #print '================scenarioDict======================='
2612 #print json.dumps(scenarioDict, indent=4)
2613 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002614
tiernoae4a8d12016-07-08 12:30:39 +02002615 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2616 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002617
tiernoae4a8d12016-07-08 12:30:39 +02002618 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2619 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002620
tiernoae4a8d12016-07-08 12:30:39 +02002621 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2622 for sce_net in scenarioDict['nets']:
2623 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002624
tiernoae4a8d12016-07-08 12:30:39 +02002625 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002626 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002627 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002628 myNetDict = {}
2629 myNetDict["name"] = myNetName
2630 myNetDict["type"] = myNetType
2631 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002632 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002633 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002634 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002635 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002636 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02002637 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002638 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2639 sce_net['vim_id'] = network_id
2640 auxNetDict['scenario'][sce_net['uuid']] = network_id
2641 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002642 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002643 else:
2644 if sce_net['vim_id'] == None:
2645 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2646 _, message = rollback(mydb, vims, rollbackList)
2647 logger.error("nfvo.start_scenario: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002648 raise NfvoException(error_text, httperrors.Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002649 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2650 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002651
tiernoae4a8d12016-07-08 12:30:39 +02002652 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2653 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002654
tiernoae4a8d12016-07-08 12:30:39 +02002655 for sce_vnf in scenarioDict['vnfs']:
2656 for net in sce_vnf['nets']:
2657 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002658
tiernoae4a8d12016-07-08 12:30:39 +02002659 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2660 myNetName = myNetName[0:255] #limit length
2661 myNetType = net['type']
2662 myNetDict = {}
2663 myNetDict["name"] = myNetName
2664 myNetDict["type"] = myNetType
2665 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002666 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002667 #print myNetDict
2668 #TODO:
2669 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02002670 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002671 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2672 net['vim_id'] = network_id
2673 if sce_vnf['uuid'] not in auxNetDict:
2674 auxNetDict[sce_vnf['uuid']] = {}
2675 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2676 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002677 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002678
tiernoae4a8d12016-07-08 12:30:39 +02002679 #print "auxNetDict:"
2680 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002681
tiernoae4a8d12016-07-08 12:30:39 +02002682 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2683 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2684 i = 0
2685 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002686 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002687 for vm in sce_vnf['vms']:
2688 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002689 if vm_av and vm_av not in vnf_availability_zones:
2690 vnf_availability_zones.append(vm_av)
2691
2692 # check if there is enough availability zones available at vim level.
2693 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2694 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002695 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno5a3273c2017-08-29 11:43:46 +02002696
tiernoae4a8d12016-07-08 12:30:39 +02002697 for vm in sce_vnf['vms']:
2698 i += 1
2699 myVMDict = {}
2700 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002701 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002702 #myVMDict['description'] = vm['description']
2703 myVMDict['description'] = myVMDict['name'][0:99]
2704 if not startvms:
2705 myVMDict['start'] = "no"
2706 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2707 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002708
tiernoae4a8d12016-07-08 12:30:39 +02002709 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002710 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002711 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002712 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002713
tiernoae4a8d12016-07-08 12:30:39 +02002714 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002715 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002716 if flavor_dict['extended']!=None:
2717 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002718 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002719 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002720
2721
tiernoae4a8d12016-07-08 12:30:39 +02002722 myVMDict['imageRef'] = vm['vim_image_id']
2723 myVMDict['flavorRef'] = vm['vim_flavor_id']
2724 myVMDict['networks'] = []
2725 for iface in vm['interfaces']:
2726 netDict = {}
2727 if iface['type']=="data":
2728 netDict['type'] = iface['model']
2729 elif "model" in iface and iface["model"]!=None:
2730 netDict['model']=iface['model']
2731 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2732 #discover type of interface looking at flavor
2733 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2734 for flavor_iface in numa.get('interfaces',[]):
2735 if flavor_iface.get('name') == iface['internal_name']:
2736 if flavor_iface['dedicated'] == 'yes':
2737 netDict['type']="PF" #passthrough
2738 elif flavor_iface['dedicated'] == 'no':
2739 netDict['type']="VF" #siov
2740 elif flavor_iface['dedicated'] == 'yes:sriov':
2741 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2742 netDict["mac_address"] = flavor_iface.get("mac_address")
2743 break;
2744 netDict["use"]=iface['type']
2745 if netDict["use"]=="data" and not netDict.get("type"):
2746 #print "netDict", netDict
2747 #print "iface", iface
2748 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'])
2749 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002750 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002751 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002752 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002753 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002754 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2755 netDict["type"]="virtual"
2756 if "vpci" in iface and iface["vpci"] is not None:
2757 netDict['vpci'] = iface['vpci']
2758 if "mac" in iface and iface["mac"] is not None:
2759 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002760 if "port-security" in iface and iface["port-security"] is not None:
2761 netDict['port_security'] = iface['port-security']
2762 if "floating-ip" in iface and iface["floating-ip"] is not None:
2763 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002764 netDict['name'] = iface['internal_name']
2765 if iface['net_id'] is None:
2766 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002767 #print iface
2768 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002769 if vnf_iface['interface_id']==iface['uuid']:
2770 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2771 break
2772 else:
2773 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2774 #skip bridge ifaces not connected to any net
2775 #if 'net_id' not in netDict or netDict['net_id']==None:
2776 # continue
2777 myVMDict['networks'].append(netDict)
2778 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2779 #print myVMDict['name']
2780 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2781 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2782 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002783
2784 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002785 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002786 else:
tierno5a3273c2017-08-29 11:43:46 +02002787 av_index = None
mirabal29356312017-07-27 12:21:22 +02002788
tierno98e909c2017-10-14 13:27:03 +02002789 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002790 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002791 availability_zone_index=av_index,
2792 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002793 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2794 vm['vim_id'] = vm_id
2795 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2796 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2797 for net in myVMDict['networks']:
2798 if "vim_id" in net:
2799 for iface in vm['interfaces']:
2800 if net["name"]==iface["internal_name"]:
2801 iface["vim_id"]=net["vim_id"]
2802 break
tierno42026a02017-02-10 15:13:40 +01002803
tiernoae4a8d12016-07-08 12:30:39 +02002804 logger.debug("start scenario Deployment done")
2805 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2806 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002807 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2808 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002809
tiernof97fd272016-07-11 14:32:37 +02002810 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002811 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002812 if isinstance(e, db_base_Exception):
2813 error_text = "Exception at database"
2814 else:
2815 error_text = "Exception at VIM"
2816 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2817 #logger.error("start_scenario %s", error_text)
2818 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002819
tierno36c0b172017-01-12 18:32:28 +01002820def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002821 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002822 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002823 None is allowed
2824 """
tierno36c0b172017-01-12 18:32:28 +01002825 if not cloud_config_preserve and not cloud_config:
2826 return None
2827
2828 new_cloud_config = {"key-pairs":[], "users":[]}
2829 # key-pairs
2830 if cloud_config_preserve:
2831 for key in cloud_config_preserve.get("key-pairs", () ):
2832 if key not in new_cloud_config["key-pairs"]:
2833 new_cloud_config["key-pairs"].append(key)
2834 if cloud_config:
2835 for key in cloud_config.get("key-pairs", () ):
2836 if key not in new_cloud_config["key-pairs"]:
2837 new_cloud_config["key-pairs"].append(key)
2838 if not new_cloud_config["key-pairs"]:
2839 del new_cloud_config["key-pairs"]
2840
2841 # users
2842 if cloud_config:
2843 new_cloud_config["users"] += cloud_config.get("users", () )
2844 if cloud_config_preserve:
2845 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002846 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002847 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002848 for index0 in range(0,len(users)):
2849 if index0 in index_to_delete:
2850 continue
2851 for index1 in range(index0+1,len(users)):
2852 if index1 in index_to_delete:
2853 continue
2854 if users[index0]["name"] == users[index1]["name"]:
2855 index_to_delete.append(index1)
2856 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002857 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002858 users[index0]["key-pairs"] = [key]
2859 elif key not in users[index0]["key-pairs"]:
2860 users[index0]["key-pairs"].append(key)
2861 index_to_delete.sort(reverse=True)
2862 for index in index_to_delete:
2863 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002864 if not new_cloud_config["users"]:
2865 del new_cloud_config["users"]
2866
2867 #boot-data-drive
2868 if cloud_config and cloud_config.get("boot-data-drive") != None:
2869 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2870 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2871 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2872
2873 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002874 new_cloud_config["user-data"] = []
2875 if cloud_config and cloud_config.get("user-data"):
2876 if isinstance(cloud_config["user-data"], list):
2877 new_cloud_config["user-data"] += cloud_config["user-data"]
2878 else:
2879 new_cloud_config["user-data"].append(cloud_config["user-data"])
2880 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2881 if isinstance(cloud_config_preserve["user-data"], list):
2882 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2883 else:
2884 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2885 if not new_cloud_config["user-data"]:
2886 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002887
2888 # config files
2889 new_cloud_config["config-files"] = []
2890 if cloud_config and cloud_config.get("config-files") != None:
2891 new_cloud_config["config-files"] += cloud_config["config-files"]
2892 if cloud_config_preserve:
2893 for file in cloud_config_preserve.get("config-files", ()):
2894 for index in range(0, len(new_cloud_config["config-files"])):
2895 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2896 new_cloud_config["config-files"][index] = file
2897 break
2898 else:
2899 new_cloud_config["config-files"].append(file)
2900 if not new_cloud_config["config-files"]:
2901 del new_cloud_config["config-files"]
2902 return new_cloud_config
2903
2904
tierno867ffe92017-03-27 12:50:34 +02002905def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002906 datacenter_id = None
2907 datacenter_name = None
2908 thread = None
tierno867ffe92017-03-27 12:50:34 +02002909 try:
2910 if datacenter_tenant_id:
2911 thread_id = datacenter_tenant_id
2912 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002913 else:
tierno867ffe92017-03-27 12:50:34 +02002914 where_={"td.nfvo_tenant_id": tenant_id}
2915 if datacenter_id_name:
2916 if utils.check_valid_uuid(datacenter_id_name):
2917 datacenter_id = datacenter_id_name
2918 where_["dt.datacenter_id"] = datacenter_id
2919 else:
2920 datacenter_name = datacenter_id_name
2921 where_["d.name"] = datacenter_name
2922 if datacenter_tenant_id:
2923 where_["dt.uuid"] = datacenter_tenant_id
2924 datacenters = mydb.get_rows(
2925 SELECT=("dt.uuid as datacenter_tenant_id",),
2926 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2927 "join datacenters as d on d.uuid=dt.datacenter_id",
2928 WHERE=where_)
2929 if len(datacenters) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002930 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno867ffe92017-03-27 12:50:34 +02002931 elif datacenters:
2932 thread_id = datacenters[0]["datacenter_tenant_id"]
2933 thread = vim_threads["running"].get(thread_id)
2934 if not thread:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002935 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tierno867ffe92017-03-27 12:50:34 +02002936 return thread_id, thread
2937 except db_base_Exception as e:
2938 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002939
tiernof5755962017-07-13 15:44:34 +02002940
tiernoa15c4b92017-10-05 12:41:44 +02002941def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2942 WHERE_dict={}
2943 if utils.check_valid_uuid(datacenter_id_name):
2944 WHERE_dict['d.uuid'] = datacenter_id_name
2945 else:
2946 WHERE_dict['d.name'] = datacenter_id_name
2947
2948 if tenant_id:
2949 WHERE_dict['nfvo_tenant_id'] = tenant_id
2950 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2951 " dt on td.datacenter_tenant_id=dt.uuid"
2952 else:
2953 from_ = 'datacenters as d'
tiernod3750b32018-07-20 15:33:08 +02002954 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid, d.name as name",), WHERE=WHERE_dict )
tiernoa15c4b92017-10-05 12:41:44 +02002955 if len(vimaccounts) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002956 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernoa15c4b92017-10-05 12:41:44 +02002957 elif len(vimaccounts)>1:
2958 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002959 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02002960 return vimaccounts[0]["uuid"], vimaccounts[0]["name"]
tiernoa15c4b92017-10-05 12:41:44 +02002961
2962
tiernoa2793912016-10-04 08:15:08 +00002963def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002964 datacenter_id = None
2965 datacenter_name = None
2966 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002967 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02002968 datacenter_id = datacenter_id_name
2969 else:
2970 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00002971 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02002972 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002973 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernobe41e222016-09-02 15:16:13 +02002974 elif len(vims)>1:
2975 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002976 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernobe41e222016-09-02 15:16:13 +02002977 return vims.keys()[0], vims.values()[0]
2978
tiernob3d36742017-03-03 23:51:05 +01002979
garciadeblas9f8456e2016-09-05 05:02:59 +02002980def update(d, u):
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002981 """Takes dict d and updates it with the values in dict u.
2982 It merges all depth levels"""
garciadeblas9f8456e2016-09-05 05:02:59 +02002983 for k, v in u.iteritems():
2984 if isinstance(v, collections.Mapping):
2985 r = update(d.get(k, {}), v)
2986 d[k] = r
2987 else:
2988 d[k] = u[k]
2989 return d
2990
tierno16e3dd42018-04-24 12:52:40 +02002991
tierno7edb6752016-03-21 17:37:52 +01002992def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01002993 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2994 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01002995 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01002996
tierno868220c2017-09-26 00:11:05 +02002997 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02002998 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02002999 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01003000 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02003001 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3002 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02003003 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02003004 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02003005 # myvim_tenant = myvim['tenant_id']
tierno16e3dd42018-04-24 12:52:40 +02003006 rollbackList = []
tierno42026a02017-02-10 15:13:40 +01003007
tierno868220c2017-09-26 00:11:05 +02003008 # print "Checking that the scenario exists and getting the scenario dictionary"
tierno7fe82642018-11-26 14:14:51 +00003009 if isinstance(scenario, str):
3010 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
3011 datacenter_id=default_datacenter_id)
3012 else:
3013 scenarioDict = scenario
3014 scenarioDict["uuid"] = None
tierno42026a02017-02-10 15:13:40 +01003015
tierno868220c2017-09-26 00:11:05 +02003016 # logger.debug(">>>>>> Dictionaries before merging")
3017 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
3018 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01003019
tierno868220c2017-09-26 00:11:05 +02003020 db_instance_vnfs = []
3021 db_instance_vms = []
3022 db_instance_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00003023 db_instance_sfis = []
3024 db_instance_sfs = []
3025 db_instance_classifications = []
3026 db_instance_sfps = []
tierno868220c2017-09-26 00:11:05 +02003027 db_ip_profiles = []
3028 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02003029 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02003030 task_index = 0
tierno8e690322017-08-10 15:58:50 +02003031 instance_name = instance_dict["name"]
3032 instance_uuid = str(uuid4())
3033 uuid_list.append(instance_uuid)
3034 db_instance_scenario = {
3035 "uuid": instance_uuid,
3036 "name": instance_name,
3037 "tenant_id": tenant_id,
3038 "scenario_id": scenarioDict['uuid'],
3039 "datacenter_id": default_datacenter_id,
3040 # filled bellow 'datacenter_tenant_id'
3041 "description": instance_dict.get("description"),
3042 }
tierno8e690322017-08-10 15:58:50 +02003043 if scenarioDict.get("cloud-config"):
3044 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
3045 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003046 instance_action_id = get_task_id()
3047 db_instance_action = {
3048 "uuid": instance_action_id, # same uuid for the instance and the action on create
3049 "tenant_id": tenant_id,
3050 "instance_id": instance_uuid,
3051 "description": "CREATE",
3052 }
garciadeblas9f8456e2016-09-05 05:02:59 +02003053
tierno868220c2017-09-26 00:11:05 +02003054 # Auxiliary dictionaries from x to y
tierno8e690322017-08-10 15:58:50 +02003055 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02003056 net2task_id = {'scenario': {}}
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003057 # Mapping between local networks and WIMs
3058 wim_usage = {}
tierno42026a02017-02-10 15:13:40 +01003059
tierno1df468d2018-07-06 14:25:16 +02003060 def ip_profile_IM2RO(ip_profile_im):
3061 # translate from input format to database format
3062 ip_profile_ro = {}
3063 if 'subnet-address' in ip_profile_im:
3064 ip_profile_ro['subnet_address'] = ip_profile_im['subnet-address']
3065 if 'ip-version' in ip_profile_im:
3066 ip_profile_ro['ip_version'] = ip_profile_im['ip-version']
3067 if 'gateway-address' in ip_profile_im:
3068 ip_profile_ro['gateway_address'] = ip_profile_im['gateway-address']
3069 if 'dns-address' in ip_profile_im:
3070 ip_profile_ro['dns_address'] = ip_profile_im['dns-address']
3071 if isinstance(ip_profile_ro['dns_address'], (list, tuple)):
3072 ip_profile_ro['dns_address'] = ";".join(ip_profile_ro['dns_address'])
3073 if 'dhcp' in ip_profile_im:
3074 ip_profile_ro['dhcp_start_address'] = ip_profile_im['dhcp'].get('start-address')
3075 ip_profile_ro['dhcp_enabled'] = ip_profile_im['dhcp'].get('enabled', True)
3076 ip_profile_ro['dhcp_count'] = ip_profile_im['dhcp'].get('count')
3077 return ip_profile_ro
3078
tierno868220c2017-09-26 00:11:05 +02003079 # logger.debug("Creating instance from scenario-dict:\n%s",
3080 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01003081 try:
tiernob3d36742017-03-03 23:51:05 +01003082 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02003083 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003084 for scenario_net in scenarioDict['nets']:
tierno1df468d2018-07-06 14:25:16 +02003085 if net_name == scenario_net.get("name") or net_name == scenario_net.get("osm_id") or net_name == scenario_net.get("uuid"):
tierno7edb6752016-03-21 17:37:52 +01003086 break
tierno1df468d2018-07-06 14:25:16 +02003087 else:
3088 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003089 httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003090 if "sites" not in net_instance_desc:
3091 net_instance_desc["sites"] = [ {} ]
3092 site_without_datacenter_field = False
3093 for site in net_instance_desc["sites"]:
3094 if site.get("datacenter"):
tiernod3750b32018-07-20 15:33:08 +02003095 site["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003096 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02003097 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02003098 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
3099 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003100 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
3101 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02003102 else:
3103 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02003104 raise NfvoException("Found more than one entries without datacenter field at "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003105 "instance:networks:{}:sites".format(net_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003106 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02003107 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01003108
tiernobe41e222016-09-02 15:16:13 +02003109 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003110 for scenario_vnf in scenarioDict['vnfs']:
tierno1df468d2018-07-06 14:25:16 +02003111 if vnf_name == scenario_vnf['member_vnf_index'] or vnf_name == scenario_vnf['uuid'] or vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01003112 break
tierno1df468d2018-07-06 14:25:16 +02003113 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003114 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003115 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02003116 # Add this datacenter to myvims
tiernod3750b32018-07-20 15:33:08 +02003117 vnf_instance_desc["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003118 if vnf_instance_desc["datacenter"] not in myvims:
3119 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3120 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003121 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00003122 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01003123
tierno1df468d2018-07-06 14:25:16 +02003124 for net_id, net_instance_desc in vnf_instance_desc.get("networks", {}).iteritems():
3125 for scenario_net in scenario_vnf['nets']:
3126 if net_id == scenario_net['osm_id'] or net_id == scenario_net['uuid'] or net_id == scenario_net["name"]:
3127 break
3128 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003129 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003130 if net_instance_desc.get("vim-network-name"):
3131 scenario_net["vim-network-name"] = net_instance_desc["vim-network-name"]
gcalvino0a480542018-12-17 16:19:33 +01003132 if net_instance_desc.get("vim-network-id"):
3133 scenario_net["vim-network-id"] = net_instance_desc["vim-network-id"]
tierno1df468d2018-07-06 14:25:16 +02003134 if net_instance_desc.get("name"):
3135 scenario_net["name"] = net_instance_desc["name"]
3136 if 'ip-profile' in net_instance_desc:
3137 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3138 if 'ip_profile' not in scenario_net:
3139 scenario_net['ip_profile'] = ipprofile_db
3140 else:
3141 update(scenario_net['ip_profile'], ipprofile_db)
3142
3143 for vdu_id, vdu_instance_desc in vnf_instance_desc.get("vdus", {}).iteritems():
3144 for scenario_vm in scenario_vnf['vms']:
3145 if vdu_id == scenario_vm['osm_id'] or vdu_id == scenario_vm["name"]:
3146 break
3147 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003148 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003149 scenario_vm["instance_parameters"] = vdu_instance_desc
3150 for iface_id, iface_instance_desc in vdu_instance_desc.get("interfaces", {}).iteritems():
3151 for scenario_interface in scenario_vm['interfaces']:
3152 if iface_id == scenario_interface['internal_name'] or iface_id == scenario_interface["external_name"]:
3153 scenario_interface.update(iface_instance_desc)
3154 break
3155 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003156 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003157
tierno868220c2017-09-26 00:11:05 +02003158 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01003159 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02003160
tierno868220c2017-09-26 00:11:05 +02003161 # 0.2 merge instance information into scenario
3162 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3163 # However, this is not possible yet.
tierno41a69812018-02-16 14:34:33 +01003164 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
garciadeblas9f8456e2016-09-05 05:02:59 +02003165 for scenario_net in scenarioDict['nets']:
3166 if net_name == scenario_net["name"]:
3167 if 'ip-profile' in net_instance_desc:
tierno1df468d2018-07-06 14:25:16 +02003168 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
garciadeblasedca7b32016-09-29 14:01:52 +00003169 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02003170 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00003171 else:
tierno455612d2017-05-30 16:40:10 +02003172 update(scenario_net['ip_profile'], ipprofile_db)
tierno41a69812018-02-16 14:34:33 +01003173 for interface in net_instance_desc.get('interfaces', ()):
garciadeblas9f8456e2016-09-05 05:02:59 +02003174 if 'ip_address' in interface:
3175 for vnf in scenarioDict['vnfs']:
3176 if interface['vnf'] == vnf['name']:
3177 for vnf_interface in vnf['interfaces']:
3178 if interface['vnf_interface'] == vnf_interface['external_name']:
tierno41a69812018-02-16 14:34:33 +01003179 vnf_interface['ip_address'] = interface['ip_address']
garciadeblas9f8456e2016-09-05 05:02:59 +02003180
tierno868220c2017-09-26 00:11:05 +02003181 # logger.debug(">>>>>>>> Merged dictionary")
3182 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3183 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02003184
tiernob3d36742017-03-03 23:51:05 +01003185 # 1. Creating new nets (sce_nets) in the VIM"
tierno8f79ea12018-05-03 17:37:40 +02003186 number_mgmt_networks = 0
tierno8e690322017-08-10 15:58:50 +02003187 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01003188 for sce_net in scenarioDict['nets']:
tierno7fe82642018-11-26 14:14:51 +00003189 sce_net_uuid = sce_net.get('uuid', sce_net["name"])
tierno1df468d2018-07-06 14:25:16 +02003190 # get involved datacenters where this network need to be created
3191 involved_datacenters = []
tierno7fe82642018-11-26 14:14:51 +00003192 for sce_vnf in scenarioDict.get("vnfs", ()):
tierno1df468d2018-07-06 14:25:16 +02003193 vnf_datacenter = sce_vnf.get("datacenter", default_datacenter_id)
3194 if vnf_datacenter in involved_datacenters:
3195 continue
3196 if sce_vnf.get("interfaces"):
3197 for sce_vnf_ifaces in sce_vnf["interfaces"]:
3198 if sce_vnf_ifaces.get("sce_net_id") == sce_net["uuid"]:
3199 involved_datacenters.append(vnf_datacenter)
3200 break
gcalvinod6fac4d2018-11-05 10:42:06 +01003201 if not involved_datacenters:
3202 involved_datacenters.append(default_datacenter_id)
tierno1df468d2018-07-06 14:25:16 +02003203
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003204 # --> WIM
3205 # TODO: use this information during network creation
tierno4070e442019-01-23 10:19:23 +00003206 wim_account_id = wim_account_name = None
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003207 if len(involved_datacenters) > 1 and 'uuid' in sce_net:
3208 # OBS: sce_net without uuid are used internally to VNFs
3209 # and the assumption is that VNFs will not be split among
3210 # different datacenters
tierno4070e442019-01-23 10:19:23 +00003211 wim_account = wim_engine.find_suitable_wim_account(
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003212 involved_datacenters, tenant_id)
tierno4070e442019-01-23 10:19:23 +00003213 wim_account_id = wim_account['uuid']
3214 wim_account_name = wim_account['name']
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003215 wim_usage[sce_net['uuid']] = wim_account_id
3216 # <-- WIM
3217
tierno1df468d2018-07-06 14:25:16 +02003218 descriptor_net = {}
3219 if instance_dict.get("networks") and instance_dict["networks"].get(sce_net["name"]):
3220 descriptor_net = instance_dict["networks"][sce_net["name"]]
tiernobe41e222016-09-02 15:16:13 +02003221 net_name = descriptor_net.get("vim-network-name")
tierno7fe82642018-11-26 14:14:51 +00003222 # add datacenters from instantiation parameters
3223 if descriptor_net.get("sites"):
3224 for site in descriptor_net["sites"]:
3225 if site.get("datacenter") and site["datacenter"] not in involved_datacenters:
3226 involved_datacenters.append(site["datacenter"])
3227 sce_net2instance[sce_net_uuid] = {}
3228 net2task_id['scenario'][sce_net_uuid] = {}
tiernobe41e222016-09-02 15:16:13 +02003229
tierno1df468d2018-07-06 14:25:16 +02003230 if sce_net["external"]:
3231 number_mgmt_networks += 1
3232
3233 for datacenter_id in involved_datacenters:
3234 netmap_use = None
3235 netmap_create = None
3236 if descriptor_net.get("sites"):
3237 for site in descriptor_net["sites"]:
3238 if site.get("datacenter") == datacenter_id:
3239 netmap_use = site.get("netmap-use")
3240 netmap_create = site.get("netmap-create")
3241 break
3242
3243 vim = myvims[datacenter_id]
3244 myvim_thread_id = myvim_threads_id[datacenter_id]
3245
tiernobe41e222016-09-02 15:16:13 +02003246 net_type = sce_net['type']
tiernob6990792018-11-13 10:37:42 +01003247 net_vim_name = None
tierno868220c2017-09-26 00:11:05 +02003248 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01003249
tiernof1ba57e2017-09-07 12:23:19 +02003250 if not net_name:
3251 if sce_net["external"]:
3252 net_name = sce_net["name"]
3253 else:
tierno1df468d2018-07-06 14:25:16 +02003254 net_name = "{}-{}".format(instance_name, sce_net["name"])
tiernof1ba57e2017-09-07 12:23:19 +02003255 net_name = net_name[:255] # limit length
3256
tierno1df468d2018-07-06 14:25:16 +02003257 if netmap_use or netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003258 create_network = False
3259 lookfor_network = False
tierno1df468d2018-07-06 14:25:16 +02003260 if netmap_use:
tiernof1ba57e2017-09-07 12:23:19 +02003261 lookfor_network = True
tierno1df468d2018-07-06 14:25:16 +02003262 if utils.check_valid_uuid(netmap_use):
3263 lookfor_filter["id"] = netmap_use
tiernof1ba57e2017-09-07 12:23:19 +02003264 else:
tierno1df468d2018-07-06 14:25:16 +02003265 lookfor_filter["name"] = netmap_use
3266 if netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003267 create_network = True
3268 net_vim_name = net_name
tierno1df468d2018-07-06 14:25:16 +02003269 if isinstance(netmap_create, str):
3270 net_vim_name = netmap_create
tierno8f79ea12018-05-03 17:37:40 +02003271 elif sce_net.get("vim_network_name"):
3272 create_network = False
3273 lookfor_network = True
3274 lookfor_filter["name"] = sce_net.get("vim_network_name")
tiernof1ba57e2017-09-07 12:23:19 +02003275 elif sce_net["external"]:
tiernod108c412018-12-18 15:19:27 +00003276 if sce_net.get('vim_id'):
tierno868220c2017-09-26 00:11:05 +02003277 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02003278 create_network = False
3279 lookfor_network = True
3280 lookfor_filter["id"] = sce_net['vim_id']
tierno8f79ea12018-05-03 17:37:40 +02003281 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3282 if number_mgmt_networks > 1:
3283 raise NfvoException("Found several VLD of type mgmt. "
3284 "You must concrete what vim-network must be use for each one",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003285 httperrors.Bad_Request)
tierno8f79ea12018-05-03 17:37:40 +02003286 create_network = False
3287 lookfor_network = True
3288 if vim["config"].get("management_network_id"):
3289 lookfor_filter["id"] = vim["config"]["management_network_id"]
3290 else:
3291 lookfor_filter["name"] = vim["config"]["management_network_name"]
tiernobe41e222016-09-02 15:16:13 +02003292 else:
tierno868220c2017-09-26 00:11:05 +02003293 # There is not a netmap, look at datacenter for a net with this name and create if not found
tiernobe41e222016-09-02 15:16:13 +02003294 create_network = True
3295 lookfor_network = True
3296 lookfor_filter["name"] = sce_net["name"]
3297 net_vim_name = sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01003298 else:
tiernobe41e222016-09-02 15:16:13 +02003299 net_vim_name = net_name
3300 create_network = True
3301 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01003302
tiernof1450872017-10-17 23:15:08 +02003303 task_extra = {}
3304 if create_network:
3305 task_action = "CREATE"
tierno4070e442019-01-23 10:19:23 +00003306 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None), wim_account_name)
tiernof1450872017-10-17 23:15:08 +02003307 if lookfor_network:
3308 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02003309 elif lookfor_network:
3310 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02003311 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01003312
tierno8e690322017-08-10 15:58:50 +02003313 # fill database content
3314 net_uuid = str(uuid4())
3315 uuid_list.append(net_uuid)
tierno7fe82642018-11-26 14:14:51 +00003316 sce_net2instance[sce_net_uuid][datacenter_id] = net_uuid
tierno8e690322017-08-10 15:58:50 +02003317 db_net = {
3318 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02003319 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003320 "vim_name": net_vim_name,
tierno8e690322017-08-10 15:58:50 +02003321 "instance_scenario_id": instance_uuid,
tierno7fe82642018-11-26 14:14:51 +00003322 "sce_net_id": sce_net.get("uuid"),
tierno8e690322017-08-10 15:58:50 +02003323 "created": create_network,
3324 'datacenter_id': datacenter_id,
3325 'datacenter_tenant_id': myvim_thread_id,
tiernod2836fc2018-05-30 15:03:27 +02003326 'status': 'BUILD' # if create_network else "ACTIVE"
tierno8e690322017-08-10 15:58:50 +02003327 }
3328 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003329 db_vim_action = {
3330 "instance_action_id": instance_action_id,
3331 "status": "SCHEDULED",
3332 "task_index": task_index,
3333 "datacenter_vim_id": myvim_thread_id,
3334 "action": task_action,
3335 "item": "instance_nets",
3336 "item_id": net_uuid,
tiernof1450872017-10-17 23:15:08 +02003337 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003338 }
tierno7fe82642018-11-26 14:14:51 +00003339 net2task_id['scenario'][sce_net_uuid][datacenter_id] = task_index
tierno868220c2017-09-26 00:11:05 +02003340 task_index += 1
3341 db_vim_actions.append(db_vim_action)
3342
tierno8e690322017-08-10 15:58:50 +02003343 if 'ip_profile' in sce_net:
3344 db_ip_profile={
3345 'instance_net_id': net_uuid,
3346 'ip_version': sce_net['ip_profile']['ip_version'],
3347 'subnet_address': sce_net['ip_profile']['subnet_address'],
3348 'gateway_address': sce_net['ip_profile']['gateway_address'],
3349 'dns_address': sce_net['ip_profile']['dns_address'],
3350 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3351 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3352 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3353 }
3354 db_ip_profiles.append(db_ip_profile)
3355
tierno16e3dd42018-04-24 12:52:40 +02003356 # Create VNFs
3357 vnf_params = {
3358 "default_datacenter_id": default_datacenter_id,
3359 "myvim_threads_id": myvim_threads_id,
3360 "instance_uuid": instance_uuid,
3361 "instance_name": instance_name,
3362 "instance_action_id": instance_action_id,
3363 "myvims": myvims,
3364 "cloud_config": cloud_config,
3365 "RO_pub_key": tenant[0].get('RO_pub_key'),
tierno67881db2018-10-24 18:46:03 +02003366 "instance_parameters": instance_dict,
tierno16e3dd42018-04-24 12:52:40 +02003367 }
3368 vnf_params_out = {
3369 "task_index": task_index,
3370 "uuid_list": uuid_list,
3371 "db_instance_nets": db_instance_nets,
3372 "db_vim_actions": db_vim_actions,
3373 "db_ip_profiles": db_ip_profiles,
3374 "db_instance_vnfs": db_instance_vnfs,
3375 "db_instance_vms": db_instance_vms,
3376 "db_instance_interfaces": db_instance_interfaces,
3377 "net2task_id": net2task_id,
3378 "sce_net2instance": sce_net2instance,
3379 }
tierno55d234c2018-07-04 18:29:21 +02003380 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
tierno7fe82642018-11-26 14:14:51 +00003381 for sce_vnf in scenarioDict.get('vnfs', ()): # sce_vnf_list:
tierno16e3dd42018-04-24 12:52:40 +02003382 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3383 task_index = vnf_params_out["task_index"]
3384 uuid_list = vnf_params_out["uuid_list"]
mirabal29356312017-07-27 12:21:22 +02003385
tierno16e3dd42018-04-24 12:52:40 +02003386 # Create VNFFGs
3387 # task_depends_on = []
tierno7fe82642018-11-26 14:14:51 +00003388 for vnffg in scenarioDict.get('vnffgs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003389 for rsp in vnffg['rsps']:
3390 sfs_created = []
3391 for cp in rsp['connection_points']:
3392 count = mydb.get_rows(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003393 SELECT='vms.count',
3394 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h "
3395 "on interfaces.uuid=h.ingress_interface_id",
Igor D.Ccaadc442017-11-06 12:48:48 +00003396 WHERE={'h.uuid': cp['uuid']})[0]['count']
3397 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3398 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3399 dependencies = []
3400 for instance_vm in instance_vms:
3401 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3402 if action:
3403 dependencies.append(action['task_index'])
3404 # TODO: throw exception if count != len(instance_vms)
3405 # TODO: and action shouldn't ever be None
3406 sfis_created = []
3407 for i in range(count):
3408 # create sfis
3409 sfi_uuid = str(uuid4())
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003410 extra_params = {
3411 "ingress_interface_id": cp["ingress_interface_id"],
3412 "egress_interface_id": cp["egress_interface_id"]
3413 }
Igor D.Ccaadc442017-11-06 12:48:48 +00003414 uuid_list.append(sfi_uuid)
3415 db_sfi = {
3416 "uuid": sfi_uuid,
3417 "instance_scenario_id": instance_uuid,
3418 'sce_rsp_hop_id': cp['uuid'],
3419 'datacenter_id': datacenter_id,
3420 'datacenter_tenant_id': myvim_thread_id,
3421 "vim_sfi_id": None, # vim thread will populate
3422 }
3423 db_instance_sfis.append(db_sfi)
3424 db_vim_action = {
3425 "instance_action_id": instance_action_id,
3426 "task_index": task_index,
3427 "datacenter_vim_id": myvim_thread_id,
3428 "action": "CREATE",
3429 "status": "SCHEDULED",
3430 "item": "instance_sfis",
3431 "item_id": sfi_uuid,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003432 "extra": yaml.safe_dump({"params": extra_params, "depends_on": [dependencies[i]]},
Igor D.Ccaadc442017-11-06 12:48:48 +00003433 default_flow_style=True, width=256)
3434 }
3435 sfis_created.append(task_index)
3436 task_index += 1
3437 db_vim_actions.append(db_vim_action)
3438 # create sfs
3439 sf_uuid = str(uuid4())
3440 uuid_list.append(sf_uuid)
3441 db_sf = {
3442 "uuid": sf_uuid,
3443 "instance_scenario_id": instance_uuid,
3444 'sce_rsp_hop_id': cp['uuid'],
3445 'datacenter_id': datacenter_id,
3446 'datacenter_tenant_id': myvim_thread_id,
3447 "vim_sf_id": None, # vim thread will populate
3448 }
3449 db_instance_sfs.append(db_sf)
3450 db_vim_action = {
3451 "instance_action_id": instance_action_id,
3452 "task_index": task_index,
3453 "datacenter_vim_id": myvim_thread_id,
3454 "action": "CREATE",
3455 "status": "SCHEDULED",
3456 "item": "instance_sfs",
3457 "item_id": sf_uuid,
3458 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3459 default_flow_style=True, width=256)
3460 }
3461 sfs_created.append(task_index)
3462 task_index += 1
3463 db_vim_actions.append(db_vim_action)
3464 classifier = rsp['classifier']
3465
3466 # TODO the following ~13 lines can be reused for the sfi case
3467 count = mydb.get_rows(
3468 SELECT=('vms.count'),
3469 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3470 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3471 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3472 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3473 dependencies = []
3474 for instance_vm in instance_vms:
3475 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3476 if action:
3477 dependencies.append(action['task_index'])
3478 # TODO: throw exception if count != len(instance_vms)
3479 # TODO: and action shouldn't ever be None
3480 classifications_created = []
3481 for i in range(count):
3482 for match in classifier['matches']:
3483 # create classifications
3484 classification_uuid = str(uuid4())
3485 uuid_list.append(classification_uuid)
3486 db_classification = {
3487 "uuid": classification_uuid,
3488 "instance_scenario_id": instance_uuid,
3489 'sce_classifier_match_id': match['uuid'],
3490 'datacenter_id': datacenter_id,
3491 'datacenter_tenant_id': myvim_thread_id,
3492 "vim_classification_id": None, # vim thread will populate
3493 }
3494 db_instance_classifications.append(db_classification)
3495 classification_params = {
3496 "ip_proto": match["ip_proto"],
3497 "source_ip": match["source_ip"],
3498 "destination_ip": match["destination_ip"],
3499 "source_port": match["source_port"],
3500 "destination_port": match["destination_port"]
3501 }
3502 db_vim_action = {
3503 "instance_action_id": instance_action_id,
3504 "task_index": task_index,
3505 "datacenter_vim_id": myvim_thread_id,
3506 "action": "CREATE",
3507 "status": "SCHEDULED",
3508 "item": "instance_classifications",
3509 "item_id": classification_uuid,
3510 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3511 default_flow_style=True, width=256)
3512 }
3513 classifications_created.append(task_index)
3514 task_index += 1
3515 db_vim_actions.append(db_vim_action)
3516
3517 # create sfps
3518 sfp_uuid = str(uuid4())
3519 uuid_list.append(sfp_uuid)
3520 db_sfp = {
3521 "uuid": sfp_uuid,
3522 "instance_scenario_id": instance_uuid,
3523 'sce_rsp_id': rsp['uuid'],
3524 'datacenter_id': datacenter_id,
3525 'datacenter_tenant_id': myvim_thread_id,
3526 "vim_sfp_id": None, # vim thread will populate
3527 }
3528 db_instance_sfps.append(db_sfp)
3529 db_vim_action = {
3530 "instance_action_id": instance_action_id,
3531 "task_index": task_index,
3532 "datacenter_vim_id": myvim_thread_id,
3533 "action": "CREATE",
3534 "status": "SCHEDULED",
3535 "item": "instance_sfps",
3536 "item_id": sfp_uuid,
3537 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3538 default_flow_style=True, width=256)
3539 }
3540 task_index += 1
3541 db_vim_actions.append(db_vim_action)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003542 db_instance_action["number_tasks"] = task_index
3543
3544 # --> WIM
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003545 logger.debug('wim_usage:\n%s\n\n', pformat(wim_usage))
3546 wan_links = wim_engine.derive_wan_links(wim_usage, db_instance_nets, tenant_id)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003547 wim_actions = wim_engine.create_actions(wan_links)
3548 wim_actions, db_instance_action = (
3549 wim_engine.incorporate_actions(wim_actions, db_instance_action))
3550 # <-- WIM
Igor D.Ccaadc442017-11-06 12:48:48 +00003551
tierno867ffe92017-03-27 12:50:34 +02003552 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003553
3554 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3555 db_instance_scenario['datacenter_id'] = default_datacenter_id
3556 db_tables=[
3557 {"instance_scenarios": db_instance_scenario},
3558 {"instance_vnfs": db_instance_vnfs},
3559 {"instance_nets": db_instance_nets},
3560 {"ip_profiles": db_ip_profiles},
3561 {"instance_vms": db_instance_vms},
3562 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003563 {"instance_actions": db_instance_action},
Igor D.Ccaadc442017-11-06 12:48:48 +00003564 {"instance_sfis": db_instance_sfis},
3565 {"instance_sfs": db_instance_sfs},
3566 {"instance_classifications": db_instance_classifications},
3567 {"instance_sfps": db_instance_sfps},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003568 {"instance_wim_nets": wan_links},
3569 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno8e690322017-08-10 15:58:50 +02003570 ]
3571
tierno868220c2017-09-26 00:11:05 +02003572 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003573 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3574 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003575 for myvim_thread_id in myvim_threads_id.values():
3576 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003577
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003578 wim_engine.dispatch(wim_actions)
3579
tierno868220c2017-09-26 00:11:05 +02003580 returned_instance = mydb.get_instance_scenario(instance_uuid)
3581 returned_instance["action_id"] = instance_action_id
3582 return returned_instance
3583 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003584 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003585 if isinstance(e, db_base_Exception):
3586 error_text = "database Exception"
3587 elif isinstance(e, vimconn.vimconnException):
3588 error_text = "VIM Exception"
3589 else:
3590 error_text = "Exception"
3591 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003592 # logger.error("create_instance: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003593 logger.exception(e)
tiernof97fd272016-07-11 14:32:37 +02003594 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003595
tiernob3d36742017-03-03 23:51:05 +01003596
tierno16e3dd42018-04-24 12:52:40 +02003597def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3598 default_datacenter_id = params["default_datacenter_id"]
3599 myvim_threads_id = params["myvim_threads_id"]
3600 instance_uuid = params["instance_uuid"]
3601 instance_name = params["instance_name"]
3602 instance_action_id = params["instance_action_id"]
3603 myvims = params["myvims"]
3604 cloud_config = params["cloud_config"]
3605 RO_pub_key = params["RO_pub_key"]
3606
3607 task_index = params_out["task_index"]
3608 uuid_list = params_out["uuid_list"]
3609 db_instance_nets = params_out["db_instance_nets"]
3610 db_vim_actions = params_out["db_vim_actions"]
3611 db_ip_profiles = params_out["db_ip_profiles"]
3612 db_instance_vnfs = params_out["db_instance_vnfs"]
3613 db_instance_vms = params_out["db_instance_vms"]
3614 db_instance_interfaces = params_out["db_instance_interfaces"]
3615 net2task_id = params_out["net2task_id"]
3616 sce_net2instance = params_out["sce_net2instance"]
3617
3618 vnf_net2instance = {}
3619
3620 # 2. Creating new nets (vnf internal nets) in the VIM"
3621 # For each vnf net, we create it and we add it to instanceNetlist.
3622 if sce_vnf.get("datacenter"):
3623 datacenter_id = sce_vnf["datacenter"]
3624 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3625 else:
3626 datacenter_id = default_datacenter_id
3627 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3628 for net in sce_vnf['nets']:
3629 # TODO revis
3630 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3631 # net_name = descriptor_net.get("name")
3632 net_name = None
3633 if not net_name:
tierno1df468d2018-07-06 14:25:16 +02003634 net_name = "{}-{}".format(instance_name, net["name"])
tierno16e3dd42018-04-24 12:52:40 +02003635 net_name = net_name[:255] # limit length
3636 net_type = net['type']
3637
3638 if sce_vnf['uuid'] not in vnf_net2instance:
3639 vnf_net2instance[sce_vnf['uuid']] = {}
3640 if sce_vnf['uuid'] not in net2task_id:
3641 net2task_id[sce_vnf['uuid']] = {}
3642 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3643
3644 # fill database content
3645 net_uuid = str(uuid4())
3646 uuid_list.append(net_uuid)
3647 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3648 db_net = {
3649 "uuid": net_uuid,
3650 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003651 "vim_name": net_name,
tierno16e3dd42018-04-24 12:52:40 +02003652 "instance_scenario_id": instance_uuid,
3653 "net_id": net["uuid"],
3654 "created": True,
3655 'datacenter_id': datacenter_id,
3656 'datacenter_tenant_id': myvim_thread_id,
3657 }
3658 db_instance_nets.append(db_net)
3659
gcalvino0a480542018-12-17 16:19:33 +01003660 lookfor_filter = {}
tierno1df468d2018-07-06 14:25:16 +02003661 if net.get("vim-network-name"):
gcalvino0a480542018-12-17 16:19:33 +01003662 lookfor_filter["name"] = net["vim-network-name"]
3663 if net.get("vim-network-id"):
3664 lookfor_filter["id"] = net["vim-network-id"]
3665 if lookfor_filter:
tierno1df468d2018-07-06 14:25:16 +02003666 task_action = "FIND"
3667 task_extra = {"params": (lookfor_filter,)}
3668 else:
3669 task_action = "CREATE"
3670 task_extra = {"params": (net_name, net_type, net.get('ip_profile', None))}
3671
tierno16e3dd42018-04-24 12:52:40 +02003672 db_vim_action = {
3673 "instance_action_id": instance_action_id,
3674 "task_index": task_index,
3675 "datacenter_vim_id": myvim_thread_id,
3676 "status": "SCHEDULED",
tierno1df468d2018-07-06 14:25:16 +02003677 "action": task_action,
tierno16e3dd42018-04-24 12:52:40 +02003678 "item": "instance_nets",
3679 "item_id": net_uuid,
tierno1df468d2018-07-06 14:25:16 +02003680 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno16e3dd42018-04-24 12:52:40 +02003681 }
3682 task_index += 1
3683 db_vim_actions.append(db_vim_action)
3684
3685 if 'ip_profile' in net:
3686 db_ip_profile = {
3687 'instance_net_id': net_uuid,
3688 'ip_version': net['ip_profile']['ip_version'],
3689 'subnet_address': net['ip_profile']['subnet_address'],
3690 'gateway_address': net['ip_profile']['gateway_address'],
3691 'dns_address': net['ip_profile']['dns_address'],
3692 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3693 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3694 'dhcp_count': net['ip_profile']['dhcp_count'],
3695 }
3696 db_ip_profiles.append(db_ip_profile)
3697
3698 # print "vnf_net2instance:"
3699 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3700
3701 # 3. Creating new vm instances in the VIM
3702 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3703 ssh_access = None
3704 if sce_vnf.get('mgmt_access'):
3705 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3706 vnf_availability_zones = []
gcalvinod6fac4d2018-11-05 10:42:06 +01003707 for vm in sce_vnf.get('vms'):
tierno16e3dd42018-04-24 12:52:40 +02003708 vm_av = vm.get('availability_zone')
3709 if vm_av and vm_av not in vnf_availability_zones:
3710 vnf_availability_zones.append(vm_av)
3711
3712 # check if there is enough availability zones available at vim level.
3713 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3714 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003715 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno16e3dd42018-04-24 12:52:40 +02003716
3717 if sce_vnf.get("datacenter"):
3718 vim = myvims[sce_vnf["datacenter"]]
3719 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3720 datacenter_id = sce_vnf["datacenter"]
3721 else:
3722 vim = myvims[default_datacenter_id]
3723 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3724 datacenter_id = default_datacenter_id
3725 sce_vnf["datacenter_id"] = datacenter_id
3726 i = 0
3727
3728 vnf_uuid = str(uuid4())
3729 uuid_list.append(vnf_uuid)
3730 db_instance_vnf = {
3731 'uuid': vnf_uuid,
3732 'instance_scenario_id': instance_uuid,
3733 'vnf_id': sce_vnf['vnf_id'],
3734 'sce_vnf_id': sce_vnf['uuid'],
3735 'datacenter_id': datacenter_id,
3736 'datacenter_tenant_id': myvim_thread_id,
3737 }
3738 db_instance_vnfs.append(db_instance_vnf)
3739
3740 for vm in sce_vnf['vms']:
tiernob6990792018-11-13 10:37:42 +01003741 # skip PDUs
3742 if vm.get("pdu_type"):
3743 continue
3744
tierno16e3dd42018-04-24 12:52:40 +02003745 myVMDict = {}
tierno7f426e92018-06-28 15:21:32 +02003746 sce_vnf_name = sce_vnf['member_vnf_index'] if sce_vnf['member_vnf_index'] else sce_vnf['name']
3747 myVMDict['name'] = "{}-{}-{}".format(instance_name[:64], sce_vnf_name[:64], vm["name"][:64])
tierno16e3dd42018-04-24 12:52:40 +02003748 myVMDict['description'] = myVMDict['name'][0:99]
3749 # if not startvms:
3750 # myVMDict['start'] = "no"
tierno1df468d2018-07-06 14:25:16 +02003751 if vm.get("instance_parameters") and vm["instance_parameters"].get("name"):
3752 myVMDict['name'] = vm["instance_parameters"].get("name")
tierno16e3dd42018-04-24 12:52:40 +02003753 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3754 # create image at vim in case it not exist
3755 image_uuid = vm['image_id']
3756 if vm.get("image_list"):
3757 for alternative_image in vm["image_list"]:
tiernob6434212018-04-26 16:27:47 +02003758 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
tierno16e3dd42018-04-24 12:52:40 +02003759 image_uuid = alternative_image['image_id']
3760 break
3761 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
3762 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
3763 vm['vim_image_id'] = image_id
3764
3765 # create flavor at vim in case it not exist
3766 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
3767 if flavor_dict['extended'] != None:
3768 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
3769 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3770
3771 # Obtain information for additional disks
3772 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
3773 WHERE={'vim_id': flavor_id})
3774 if not extended_flavor_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003775 raise NfvoException("flavor '{}' not found".format(flavor_id), httperrors.Not_Found)
tierno16e3dd42018-04-24 12:52:40 +02003776
3777 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
3778 myVMDict['disks'] = None
3779 extended_info = extended_flavor_dict[0]['extended']
3780 if extended_info != None:
3781 extended_flavor_dict_yaml = yaml.load(extended_info)
3782 if 'disks' in extended_flavor_dict_yaml:
3783 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
tierno1df468d2018-07-06 14:25:16 +02003784 if vm.get("instance_parameters") and vm["instance_parameters"].get("devices"):
3785 for disk in myVMDict['disks']:
3786 if disk.get("name") in vm["instance_parameters"]["devices"]:
3787 disk.update(vm["instance_parameters"]["devices"][disk.get("name")])
tierno16e3dd42018-04-24 12:52:40 +02003788
3789 vm['vim_flavor_id'] = flavor_id
3790 myVMDict['imageRef'] = vm['vim_image_id']
3791 myVMDict['flavorRef'] = vm['vim_flavor_id']
3792 myVMDict['availability_zone'] = vm.get('availability_zone')
3793 myVMDict['networks'] = []
3794 task_depends_on = []
3795 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno67881db2018-10-24 18:46:03 +02003796 is_management_vm = False
tierno16e3dd42018-04-24 12:52:40 +02003797 db_vm_ifaces = []
3798 for iface in vm['interfaces']:
3799 netDict = {}
3800 if iface['type'] == "data":
3801 netDict['type'] = iface['model']
3802 elif "model" in iface and iface["model"] != None:
3803 netDict['model'] = iface['model']
3804 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3805 # is obtained from iterface table model
3806 # discover type of interface looking at flavor
3807 for numa in flavor_dict.get('extended', {}).get('numas', []):
3808 for flavor_iface in numa.get('interfaces', []):
3809 if flavor_iface.get('name') == iface['internal_name']:
3810 if flavor_iface['dedicated'] == 'yes':
3811 netDict['type'] = "PF" # passthrough
3812 elif flavor_iface['dedicated'] == 'no':
3813 netDict['type'] = "VF" # siov
3814 elif flavor_iface['dedicated'] == 'yes:sriov':
3815 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
3816 netDict["mac_address"] = flavor_iface.get("mac_address")
3817 break
3818 netDict["use"] = iface['type']
3819 if netDict["use"] == "data" and not netDict.get("type"):
3820 # print "netDict", netDict
3821 # print "iface", iface
3822 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3823 sce_vnf['name'], vm['name'], iface['internal_name'])
3824 if flavor_dict.get('extended') == None:
3825 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003826 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tierno16e3dd42018-04-24 12:52:40 +02003827 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003828 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tierno67881db2018-10-24 18:46:03 +02003829 if netDict["use"] == "mgmt":
3830 is_management_vm = True
3831 netDict["type"] = "virtual"
3832 if netDict["use"] == "bridge":
tierno16e3dd42018-04-24 12:52:40 +02003833 netDict["type"] = "virtual"
3834 if iface.get("vpci"):
3835 netDict['vpci'] = iface['vpci']
3836 if iface.get("mac"):
3837 netDict['mac_address'] = iface['mac']
tierno6082b7d2018-08-31 11:24:08 +00003838 if iface.get("mac_address"):
3839 netDict['mac_address'] = iface['mac_address']
tierno16e3dd42018-04-24 12:52:40 +02003840 if iface.get("ip_address"):
3841 netDict['ip_address'] = iface['ip_address']
3842 if iface.get("port-security") is not None:
3843 netDict['port_security'] = iface['port-security']
3844 if iface.get("floating-ip") is not None:
3845 netDict['floating_ip'] = iface['floating-ip']
3846 netDict['name'] = iface['internal_name']
3847 if iface['net_id'] is None:
3848 for vnf_iface in sce_vnf["interfaces"]:
3849 # print iface
3850 # print vnf_iface
3851 if vnf_iface['interface_id'] == iface['uuid']:
3852 netDict['net_id'] = "TASK-{}".format(
3853 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3854 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
3855 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3856 break
3857 else:
3858 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
3859 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
3860 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
3861 # skip bridge ifaces not connected to any net
3862 if 'net_id' not in netDict or netDict['net_id'] == None:
3863 continue
3864 myVMDict['networks'].append(netDict)
3865 db_vm_iface = {
3866 # "uuid"
3867 # 'instance_vm_id': instance_vm_uuid,
3868 "instance_net_id": instance_net_id,
3869 'interface_id': iface['uuid'],
3870 # 'vim_interface_id': ,
3871 'type': 'external' if iface['external_name'] is not None else 'internal',
3872 'ip_address': iface.get('ip_address'),
3873 'mac_address': iface.get('mac'),
3874 'floating_ip': int(iface.get('floating-ip', False)),
3875 'port_security': int(iface.get('port-security', True))
3876 }
3877 db_vm_ifaces.append(db_vm_iface)
3878 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3879 # print myVMDict['name']
3880 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3881 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3882 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3883
3884 # We add the RO key to cloud_config if vnf will need ssh access
3885 cloud_config_vm = cloud_config
tierno67881db2018-10-24 18:46:03 +02003886 if is_management_vm and params["instance_parameters"].get("mgmt_keys"):
3887 cloud_config_vm = unify_cloud_config({"key-pairs": params["instance_parameters"]["mgmt_keys"]},
3888 cloud_config_vm)
3889
3890 if vm.get("instance_parameters") and vm["instance_parameters"].get("mgmt_keys"):
3891 cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
3892 cloud_config_vm)
3893 # if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3894 # RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3895 # cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
tierno16e3dd42018-04-24 12:52:40 +02003896 if vm.get("boot_data"):
3897 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3898
3899 if myVMDict.get('availability_zone'):
3900 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
3901 else:
3902 av_index = None
3903 for vm_index in range(0, vm.get('count', 1)):
tiernofc5f80b2018-05-29 16:00:43 +02003904 vm_name = myVMDict['name'] + "-" + str(vm_index+1)
3905 task_params = (vm_name, myVMDict['description'], myVMDict.get('start', None),
tierno16e3dd42018-04-24 12:52:40 +02003906 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3907 myVMDict['disks'], av_index, vnf_availability_zones)
3908 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3909 for net in myVMDict['networks']:
3910 if "vim_id" in net:
3911 for iface in vm['interfaces']:
3912 if net["name"] == iface["internal_name"]:
3913 iface["vim_id"] = net["vim_id"]
3914 break
3915 vm_uuid = str(uuid4())
3916 uuid_list.append(vm_uuid)
3917 db_vm = {
3918 "uuid": vm_uuid,
3919 'instance_vnf_id': vnf_uuid,
3920 # TODO delete "vim_vm_id": vm_id,
3921 "vm_id": vm["uuid"],
tiernofc5f80b2018-05-29 16:00:43 +02003922 "vim_name": vm_name,
tierno16e3dd42018-04-24 12:52:40 +02003923 # "status":
3924 }
3925 db_instance_vms.append(db_vm)
3926
3927 iface_index = 0
3928 for db_vm_iface in db_vm_ifaces:
3929 iface_uuid = str(uuid4())
3930 uuid_list.append(iface_uuid)
3931 db_vm_iface_instance = {
3932 "uuid": iface_uuid,
3933 "instance_vm_id": vm_uuid
3934 }
3935 db_vm_iface_instance.update(db_vm_iface)
3936 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3937 ip = db_vm_iface_instance.get("ip_address")
3938 i = ip.rfind(".")
3939 if i > 0:
3940 try:
3941 i += 1
3942 ip = ip[i:] + str(int(ip[:i]) + 1)
3943 db_vm_iface_instance["ip_address"] = ip
3944 except:
3945 db_vm_iface_instance["ip_address"] = None
3946 db_instance_interfaces.append(db_vm_iface_instance)
3947 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3948 iface_index += 1
3949
3950 db_vim_action = {
3951 "instance_action_id": instance_action_id,
3952 "task_index": task_index,
3953 "datacenter_vim_id": myvim_thread_id,
3954 "action": "CREATE",
3955 "status": "SCHEDULED",
3956 "item": "instance_vms",
3957 "item_id": vm_uuid,
3958 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3959 default_flow_style=True, width=256)
3960 }
3961 task_index += 1
3962 db_vim_actions.append(db_vim_action)
3963 params_out["task_index"] = task_index
3964 params_out["uuid_list"] = uuid_list
3965
3966
tierno7edb6752016-03-21 17:37:52 +01003967def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02003968 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003969 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02003970 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01003971 tenant_id = instanceDict["tenant_id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003972
3973 # --> WIM
3974 # We need to retrieve the WIM Actions now, before the instance_scenario is
3975 # deleted. The reason for that is that: ON CASCADE rules will delete the
3976 # instance_wim_nets record in the database
3977 wim_actions = wim_engine.delete_actions(instance_scenario_id=instance_id)
3978 # <-- WIM
3979
tierno868220c2017-09-26 00:11:05 +02003980 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno868220c2017-09-26 00:11:05 +02003981 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02003982 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003983
tierno868220c2017-09-26 00:11:05 +02003984 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00003985 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01003986 myvims = {}
3987 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02003988 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02003989 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01003990
tierno868220c2017-09-26 00:11:05 +02003991 task_index = 0
3992 instance_action_id = get_task_id()
3993 db_vim_actions = []
3994 db_instance_action = {
3995 "uuid": instance_action_id, # same uuid for the instance and the action on create
3996 "tenant_id": tenant_id,
3997 "instance_id": instance_id,
3998 "description": "DELETE",
3999 # "number_tasks": 0 # filled bellow
4000 }
4001
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004002 # 2.1 deleting VNFFGs
tierno69b590e2018-03-13 18:52:23 +01004003 for sfp in instanceDict.get('sfps', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004004 vimthread_affected[sfp["datacenter_tenant_id"]] = None
4005 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
4006 if datacenter_key not in myvims:
4007 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004008 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004009 except NfvoException as e:
4010 logger.error(str(e))
4011 myvim_thread = None
4012 myvim_threads[datacenter_key] = myvim_thread
4013 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
4014 datacenter_tenant_id=sfp["datacenter_tenant_id"])
4015 if len(vims) == 0:
4016 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
4017 myvims[datacenter_key] = None
4018 else:
4019 myvims[datacenter_key] = vims.values()[0]
4020 myvim = myvims[datacenter_key]
4021 myvim_thread = myvim_threads[datacenter_key]
4022
4023 if not myvim:
4024 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
4025 continue
4026 extra = {"params": (sfp['vim_sfp_id'])}
4027 db_vim_action = {
4028 "instance_action_id": instance_action_id,
4029 "task_index": task_index,
4030 "datacenter_vim_id": sfp["datacenter_tenant_id"],
4031 "action": "DELETE",
4032 "status": "SCHEDULED",
4033 "item": "instance_sfps",
4034 "item_id": sfp["uuid"],
4035 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4036 }
4037 task_index += 1
4038 db_vim_actions.append(db_vim_action)
4039
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004040 for classification in instanceDict['classifications']:
4041 vimthread_affected[classification["datacenter_tenant_id"]] = None
4042 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
4043 if datacenter_key not in myvims:
4044 try:
4045 _, myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
4046 except NfvoException as e:
4047 logger.error(str(e))
4048 myvim_thread = None
4049 myvim_threads[datacenter_key] = myvim_thread
4050 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
4051 datacenter_tenant_id=classification["datacenter_tenant_id"])
4052 if len(vims) == 0:
4053 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"],
4054 classification["datacenter_tenant_id"]))
4055 myvims[datacenter_key] = None
4056 else:
4057 myvims[datacenter_key] = vims.values()[0]
4058 myvim = myvims[datacenter_key]
4059 myvim_thread = myvim_threads[datacenter_key]
4060
4061 if not myvim:
4062 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'],
4063 classification["datacenter_id"])
4064 continue
4065 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4066 extra = {"params": (classification['vim_classification_id']), "depends_on": depends_on}
4067 db_vim_action = {
4068 "instance_action_id": instance_action_id,
4069 "task_index": task_index,
4070 "datacenter_vim_id": classification["datacenter_tenant_id"],
4071 "action": "DELETE",
4072 "status": "SCHEDULED",
4073 "item": "instance_classifications",
4074 "item_id": classification["uuid"],
4075 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4076 }
4077 task_index += 1
4078 db_vim_actions.append(db_vim_action)
4079
tierno69b590e2018-03-13 18:52:23 +01004080 for sf in instanceDict.get('sfs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004081 vimthread_affected[sf["datacenter_tenant_id"]] = None
4082 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
4083 if datacenter_key not in myvims:
4084 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004085 _, myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004086 except NfvoException as e:
4087 logger.error(str(e))
4088 myvim_thread = None
4089 myvim_threads[datacenter_key] = myvim_thread
4090 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
4091 datacenter_tenant_id=sf["datacenter_tenant_id"])
4092 if len(vims) == 0:
4093 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
4094 myvims[datacenter_key] = None
4095 else:
4096 myvims[datacenter_key] = vims.values()[0]
4097 myvim = myvims[datacenter_key]
4098 myvim_thread = myvim_threads[datacenter_key]
4099
4100 if not myvim:
4101 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
4102 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004103 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4104 extra = {"params": (sf['vim_sf_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004105 db_vim_action = {
4106 "instance_action_id": instance_action_id,
4107 "task_index": task_index,
4108 "datacenter_vim_id": sf["datacenter_tenant_id"],
4109 "action": "DELETE",
4110 "status": "SCHEDULED",
4111 "item": "instance_sfs",
4112 "item_id": sf["uuid"],
4113 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4114 }
4115 task_index += 1
4116 db_vim_actions.append(db_vim_action)
4117
tierno69b590e2018-03-13 18:52:23 +01004118 for sfi in instanceDict.get('sfis', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004119 vimthread_affected[sfi["datacenter_tenant_id"]] = None
4120 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4121 if datacenter_key not in myvims:
4122 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004123 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004124 except NfvoException as e:
4125 logger.error(str(e))
4126 myvim_thread = None
4127 myvim_threads[datacenter_key] = myvim_thread
4128 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
4129 datacenter_tenant_id=sfi["datacenter_tenant_id"])
4130 if len(vims) == 0:
4131 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
4132 myvims[datacenter_key] = None
4133 else:
4134 myvims[datacenter_key] = vims.values()[0]
4135 myvim = myvims[datacenter_key]
4136 myvim_thread = myvim_threads[datacenter_key]
4137
4138 if not myvim:
4139 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
4140 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004141 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfs"]
4142 extra = {"params": (sfi['vim_sfi_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004143 db_vim_action = {
4144 "instance_action_id": instance_action_id,
4145 "task_index": task_index,
4146 "datacenter_vim_id": sfi["datacenter_tenant_id"],
4147 "action": "DELETE",
4148 "status": "SCHEDULED",
4149 "item": "instance_sfis",
4150 "item_id": sfi["uuid"],
4151 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4152 }
4153 task_index += 1
4154 db_vim_actions.append(db_vim_action)
4155
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004156 # 2.2 deleting VMs
4157 # vm_fail_list=[]
gcalvinod6fac4d2018-11-05 10:42:06 +01004158 for sce_vnf in instanceDict.get('vnfs', ()):
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004159 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4160 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
Igor D.Ccaadc442017-11-06 12:48:48 +00004161 if datacenter_key not in myvims:
4162 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004163 _, myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004164 except NfvoException as e:
4165 logger.error(str(e))
4166 myvim_thread = None
4167 myvim_threads[datacenter_key] = myvim_thread
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004168 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
4169 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004170 if len(vims) == 0:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004171 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
4172 sce_vnf["datacenter_tenant_id"]))
4173 myvims[datacenter_key] = None
4174 else:
4175 myvims[datacenter_key] = vims.values()[0]
4176 myvim = myvims[datacenter_key]
4177 myvim_thread = myvim_threads[datacenter_key]
4178
4179 for vm in sce_vnf['vms']:
4180 if not myvim:
4181 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
4182 continue
4183 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4184 db_vim_action = {
4185 "instance_action_id": instance_action_id,
4186 "task_index": task_index,
4187 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
4188 "action": "DELETE",
4189 "status": "SCHEDULED",
4190 "item": "instance_vms",
4191 "item_id": vm["uuid"],
4192 "extra": yaml.safe_dump({"params": vm["interfaces"], "depends_on": sfi_dependencies},
4193 default_flow_style=True, width=256)
4194 }
4195 db_vim_actions.append(db_vim_action)
4196 for interface in vm["interfaces"]:
4197 if not interface.get("instance_net_id"):
4198 continue
4199 if interface["instance_net_id"] not in net2vm_dependencies:
4200 net2vm_dependencies[interface["instance_net_id"]] = []
4201 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
4202 task_index += 1
4203
4204 # 2.3 deleting NETS
4205 # net_fail_list=[]
4206 for net in instanceDict['nets']:
4207 vimthread_affected[net["datacenter_tenant_id"]] = None
4208 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4209 if datacenter_key not in myvims:
4210 try:
gcalvinod6fac4d2018-11-05 10:42:06 +01004211 _,myvim_thread = get_vim_thread(mydb, tenant_id, net["datacenter_id"], net["datacenter_tenant_id"])
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004212 except NfvoException as e:
4213 logger.error(str(e))
4214 myvim_thread = None
4215 myvim_threads[datacenter_key] = myvim_thread
4216 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
4217 datacenter_tenant_id=net["datacenter_tenant_id"])
4218 if len(vims) == 0:
4219 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
Igor D.Ccaadc442017-11-06 12:48:48 +00004220 myvims[datacenter_key] = None
4221 else:
4222 myvims[datacenter_key] = vims.values()[0]
4223 myvim = myvims[datacenter_key]
4224 myvim_thread = myvim_threads[datacenter_key]
4225
4226 if not myvim:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004227 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004228 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004229 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
4230 if net2vm_dependencies.get(net["uuid"]):
4231 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
4232 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4233 if len(sfi_dependencies) > 0:
4234 if "depends_on" in extra:
4235 extra["depends_on"] += sfi_dependencies
4236 else:
4237 extra["depends_on"] = sfi_dependencies
Igor D.Ccaadc442017-11-06 12:48:48 +00004238 db_vim_action = {
4239 "instance_action_id": instance_action_id,
4240 "task_index": task_index,
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004241 "datacenter_vim_id": net["datacenter_tenant_id"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004242 "action": "DELETE",
4243 "status": "SCHEDULED",
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004244 "item": "instance_nets",
4245 "item_id": net["uuid"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004246 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4247 }
4248 task_index += 1
4249 db_vim_actions.append(db_vim_action)
4250
tierno868220c2017-09-26 00:11:05 +02004251 db_instance_action["number_tasks"] = task_index
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004252
4253 # --> WIM
4254 wim_actions, db_instance_action = (
4255 wim_engine.incorporate_actions(wim_actions, db_instance_action))
4256 # <-- WIM
4257
tierno868220c2017-09-26 00:11:05 +02004258 db_tables = [
4259 {"instance_actions": db_instance_action},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004260 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno868220c2017-09-26 00:11:05 +02004261 ]
4262
4263 logger.debug("delete_instance done DB tables: %s",
4264 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4265 mydb.new_rows(db_tables, ())
4266 for myvim_thread_id in vimthread_affected.keys():
4267 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4268
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004269 wim_engine.dispatch(wim_actions)
4270
tiernob3d36742017-03-03 23:51:05 +01004271 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02004272 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4273 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01004274 else:
tierno868220c2017-09-26 00:11:05 +02004275 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01004276
tierno7f426e92018-06-28 15:21:32 +02004277def get_instance_id(mydb, tenant_id, instance_id):
4278 global ovim
4279 #check valid tenant_id
4280 check_tenant(mydb, tenant_id)
4281 #obtain data
4282
4283 instance_dict = mydb.get_instance_scenario(instance_id, tenant_id, verbose=True)
4284 for net in instance_dict["nets"]:
4285 if net.get("sdn_net_id"):
4286 net_sdn = ovim.show_network(net["sdn_net_id"])
4287 net["sdn_info"] = {
4288 "admin_state_up": net_sdn.get("admin_state_up"),
4289 "flows": net_sdn.get("flows"),
4290 "last_error": net_sdn.get("last_error"),
4291 "ports": net_sdn.get("ports"),
4292 "type": net_sdn.get("type"),
4293 "status": net_sdn.get("status"),
4294 "vlan": net_sdn.get("vlan"),
4295 }
4296 return instance_dict
tiernob3d36742017-03-03 23:51:05 +01004297
tiernob8569aa2018-08-24 11:34:54 +02004298@deprecated("Instance is automatically refreshed by vim_threads")
tierno7edb6752016-03-21 17:37:52 +01004299def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4300 '''Refreshes a scenario instance. It modifies instanceDict'''
4301 '''Returns:
4302 - 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
4303 - error_msg
4304 '''
tierno867ffe92017-03-27 12:50:34 +02004305 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4306 # #print "nfvo.refresh_instance begins"
4307 # #print json.dumps(instanceDict, indent=4)
4308 #
4309 # #print "Getting the VIM URL and the VIM tenant_id"
4310 # myvims={}
4311 #
4312 # # 1. Getting VIM vm and net list
4313 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4314 # vms_notupdated=[]
4315 # vm_list = {}
4316 # for sce_vnf in instanceDict['vnfs']:
4317 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4318 # if datacenter_key not in vm_list:
4319 # vm_list[datacenter_key] = []
4320 # if datacenter_key not in myvims:
4321 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4322 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4323 # if len(vims) == 0:
4324 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4325 # myvims[datacenter_key] = None
4326 # else:
4327 # myvims[datacenter_key] = vims.values()[0]
4328 # for vm in sce_vnf['vms']:
4329 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4330 # vms_notupdated.append(vm["uuid"])
4331 #
4332 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4333 # nets_notupdated=[]
4334 # net_list = {}
4335 # for net in instanceDict['nets']:
4336 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4337 # if datacenter_key not in net_list:
4338 # net_list[datacenter_key] = []
4339 # if datacenter_key not in myvims:
4340 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4341 # datacenter_tenant_id=net["datacenter_tenant_id"])
4342 # if len(vims) == 0:
4343 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4344 # myvims[datacenter_key] = None
4345 # else:
4346 # myvims[datacenter_key] = vims.values()[0]
4347 #
4348 # net_list[datacenter_key].append(net['vim_net_id'])
4349 # nets_notupdated.append(net["uuid"])
4350 #
4351 # # 1. Getting the status of all VMs
4352 # vm_dict={}
4353 # for datacenter_key in myvims:
4354 # if not vm_list.get(datacenter_key):
4355 # continue
4356 # failed = True
4357 # failed_message=""
4358 # if not myvims[datacenter_key]:
4359 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4360 # else:
4361 # try:
4362 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4363 # failed = False
4364 # except vimconn.vimconnException as e:
4365 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4366 # failed_message = str(e)
4367 # if failed:
4368 # for vm in vm_list[datacenter_key]:
4369 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4370 #
4371 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4372 # for sce_vnf in instanceDict['vnfs']:
4373 # for vm in sce_vnf['vms']:
4374 # vm_id = vm['vim_vm_id']
4375 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4376 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4377 # has_mgmt_iface = False
4378 # for iface in vm["interfaces"]:
4379 # if iface["type"]=="mgmt":
4380 # has_mgmt_iface = True
4381 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4382 # vm_dict[vm_id]['status'] = "ACTIVE"
4383 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4384 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4385 # 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'):
4386 # vm['status'] = vm_dict[vm_id]['status']
4387 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4388 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4389 # # 2.1. Update in openmano DB the VMs whose status changed
4390 # try:
4391 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4392 # vms_notupdated.remove(vm["uuid"])
4393 # if updates>0:
4394 # vms_updated.append(vm["uuid"])
4395 # except db_base_Exception as e:
4396 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4397 # # 2.2. Update in openmano DB the interface VMs
4398 # for interface in interfaces:
4399 # #translate from vim_net_id to instance_net_id
4400 # network_id_list=[]
4401 # for net in instanceDict['nets']:
4402 # if net["vim_net_id"] == interface["vim_net_id"]:
4403 # network_id_list.append(net["uuid"])
4404 # if not network_id_list:
4405 # continue
4406 # del interface["vim_net_id"]
4407 # try:
4408 # for network_id in network_id_list:
4409 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4410 # except db_base_Exception as e:
4411 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4412 #
4413 # # 3. Getting the status of all nets
4414 # net_dict = {}
4415 # for datacenter_key in myvims:
4416 # if not net_list.get(datacenter_key):
4417 # continue
4418 # failed = True
4419 # failed_message = ""
4420 # if not myvims[datacenter_key]:
4421 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4422 # else:
4423 # try:
4424 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4425 # failed = False
4426 # except vimconn.vimconnException as e:
4427 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4428 # failed_message = str(e)
4429 # if failed:
4430 # for net in net_list[datacenter_key]:
4431 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4432 #
4433 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4434 # # TODO: update nets inside a vnf
4435 # for net in instanceDict['nets']:
4436 # net_id = net['vim_net_id']
4437 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4438 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4439 # 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'):
4440 # net['status'] = net_dict[net_id]['status']
4441 # net['error_msg'] = net_dict[net_id].get('error_msg')
4442 # net['vim_info'] = net_dict[net_id].get('vim_info')
4443 # # 5.1. Update in openmano DB the nets whose status changed
4444 # try:
4445 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4446 # nets_notupdated.remove(net["uuid"])
4447 # if updated>0:
4448 # nets_updated.append(net["uuid"])
4449 # except db_base_Exception as e:
4450 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4451 #
4452 # # Returns appropriate output
4453 # #print "nfvo.refresh_instance finishes"
4454 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4455 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01004456 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02004457 # if len(vms_notupdated)+len(nets_notupdated)>0:
4458 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4459 # return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
tierno42026a02017-02-10 15:13:40 +01004460
tiernoae4a8d12016-07-08 12:30:39 +02004461 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01004462
4463def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02004464 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004465 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01004466 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4467
tiernoae4a8d12016-07-08 12:30:39 +02004468 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02004469 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4470 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004471 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004472 myvim = vims.values()[0]
tiernofc5f80b2018-05-29 16:00:43 +02004473 vm_result = {}
4474 vm_error = 0
4475 vm_ok = 0
tierno42026a02017-02-10 15:13:40 +01004476
tiernofc5f80b2018-05-29 16:00:43 +02004477 myvim_threads_id = {}
4478 if action_dict.get("vdu-scaling"):
4479 db_instance_vms = []
4480 db_vim_actions = []
4481 db_instance_interfaces = []
4482 instance_action_id = get_task_id()
4483 db_instance_action = {
4484 "uuid": instance_action_id, # same uuid for the instance and the action on create
4485 "tenant_id": nfvo_tenant,
4486 "instance_id": instance_id,
4487 "description": "SCALE",
4488 }
4489 vm_result["instance_action_id"] = instance_action_id
tierno67881db2018-10-24 18:46:03 +02004490 vm_result["created"] = []
4491 vm_result["deleted"] = []
tiernofc5f80b2018-05-29 16:00:43 +02004492 task_index = 0
4493 for vdu in action_dict["vdu-scaling"]:
tierno868220c2017-09-26 00:11:05 +02004494 vdu_id = vdu.get("vdu-id")
tiernofc5f80b2018-05-29 16:00:43 +02004495 osm_vdu_id = vdu.get("osm_vdu_id")
4496 member_vnf_index = vdu.get("member-vnf-index")
tierno868220c2017-09-26 00:11:05 +02004497 vdu_count = vdu.get("count", 1)
tiernofc5f80b2018-05-29 16:00:43 +02004498 if vdu_id:
tierno67881db2018-10-24 18:46:03 +02004499 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004500 FROM="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4501 WHERE={"vms.uuid": vdu_id},
4502 ORDER_BY="vms.created_at"
4503 )
tierno67881db2018-10-24 18:46:03 +02004504 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004505 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id), httperrors.Not_Found)
tiernofc5f80b2018-05-29 16:00:43 +02004506 else:
4507 if not osm_vdu_id and not member_vnf_index:
tiernoa43bd9e2018-11-26 09:28:58 +00004508 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
tierno67881db2018-10-24 18:46:03 +02004509 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004510 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4511 FROM="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4512 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4513 " join vms on ivms.vm_id=vms.uuid",
tiernoa43bd9e2018-11-26 09:28:58 +00004514 WHERE={"vms.osm_id": osm_vdu_id, "svnfs.member_vnf_index": member_vnf_index,
4515 "ivnfs.instance_scenario_id": instance_id},
tiernofc5f80b2018-05-29 16:00:43 +02004516 ORDER_BY="ivms.created_at"
4517 )
tierno67881db2018-10-24 18:46:03 +02004518 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004519 raise NfvoException("Cannot find the vdu with osm_vdu_id {} and member-vnf-index {}".format(osm_vdu_id, member_vnf_index), httperrors.Not_Found)
tierno67881db2018-10-24 18:46:03 +02004520 vdu_id = target_vms[-1]["uuid"]
4521 target_vm = target_vms[-1]
tiernofc5f80b2018-05-29 16:00:43 +02004522 datacenter = target_vm["datacenter_id"]
4523 myvim_threads_id[datacenter], _ = get_vim_thread(mydb, nfvo_tenant, datacenter)
tiernofc5f80b2018-05-29 16:00:43 +02004524
tierno67881db2018-10-24 18:46:03 +02004525 if vdu["type"] == "delete":
4526 for index in range(0, vdu_count):
4527 target_vm = target_vms[-1-index]
4528 vdu_id = target_vm["uuid"]
4529 # look for nm
4530 vm_interfaces = None
4531 for sce_vnf in instanceDict['vnfs']:
4532 for vm in sce_vnf['vms']:
4533 if vm["uuid"] == vdu_id:
4534 vm_interfaces = vm["interfaces"]
4535 break
4536
4537 db_vim_action = {
4538 "instance_action_id": instance_action_id,
4539 "task_index": task_index,
4540 "datacenter_vim_id": target_vm["datacenter_tenant_id"],
4541 "action": "DELETE",
4542 "status": "SCHEDULED",
4543 "item": "instance_vms",
4544 "item_id": vdu_id,
4545 "extra": yaml.safe_dump({"params": vm_interfaces},
4546 default_flow_style=True, width=256)
4547 }
4548 task_index += 1
4549 db_vim_actions.append(db_vim_action)
4550 vm_result["deleted"].append(vdu_id)
4551 # delete from database
4552 db_instance_vms.append({"TO-DELETE": vdu_id})
tiernofc5f80b2018-05-29 16:00:43 +02004553
4554 else: # vdu["type"] == "create":
4555 iface2iface = {}
4556 where = {"item": "instance_vms", "item_id": target_vm["uuid"], "action": "CREATE"}
4557
garciadeblas72cd59f2018-12-05 10:59:40 +01004558 vim_action_to_clone = mydb.get_rows(FROM="vim_wim_actions", WHERE=where)
tiernofc5f80b2018-05-29 16:00:43 +02004559 if not vim_action_to_clone:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004560 raise NfvoException("Cannot find the vim_action at database with {}".format(where), httperrors.Internal_Server_Error)
tiernofc5f80b2018-05-29 16:00:43 +02004561 vim_action_to_clone = vim_action_to_clone[0]
4562 extra = yaml.safe_load(vim_action_to_clone["extra"])
4563
4564 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4565 # TODO do the same for flavor and image when available
4566 task_depends_on = []
4567 task_params = extra["params"]
4568 task_params_networks = deepcopy(task_params[5])
4569 for iface in task_params[5]:
4570 if iface["net_id"].startswith("TASK-"):
4571 if "." not in iface["net_id"]:
4572 task_depends_on.append("{}.{}".format(vim_action_to_clone["instance_action_id"],
4573 iface["net_id"][5:]))
4574 iface["net_id"] = "TASK-{}.{}".format(vim_action_to_clone["instance_action_id"],
4575 iface["net_id"][5:])
4576 else:
4577 task_depends_on.append(iface["net_id"][5:])
4578 if "mac_address" in iface:
4579 del iface["mac_address"]
4580
4581 vm_ifaces_to_clone = mydb.get_rows(FROM="instance_interfaces", WHERE={"instance_vm_id": target_vm["uuid"]})
4582 for index in range(0, vdu_count):
4583 vm_uuid = str(uuid4())
4584 vm_name = target_vm.get('vim_name')
4585 try:
4586 suffix = vm_name.rfind("-")
tierno67881db2018-10-24 18:46:03 +02004587 vm_name = vm_name[:suffix+1] + str(index + 1 + int(vm_name[suffix+1:]))
tiernofc5f80b2018-05-29 16:00:43 +02004588 except Exception:
4589 pass
4590 db_instance_vm = {
4591 "uuid": vm_uuid,
4592 'instance_vnf_id': target_vm['instance_vnf_id'],
4593 'vm_id': target_vm['vm_id'],
4594 'vim_name': vm_name
4595 }
4596 db_instance_vms.append(db_instance_vm)
4597
4598 for vm_iface in vm_ifaces_to_clone:
4599 iface_uuid = str(uuid4())
4600 iface2iface[vm_iface["uuid"]] = iface_uuid
4601 db_vm_iface = {
4602 "uuid": iface_uuid,
4603 'instance_vm_id': vm_uuid,
4604 "instance_net_id": vm_iface["instance_net_id"],
4605 'interface_id': vm_iface['interface_id'],
4606 'type': vm_iface['type'],
4607 'floating_ip': vm_iface['floating_ip'],
4608 'port_security': vm_iface['port_security']
4609 }
4610 db_instance_interfaces.append(db_vm_iface)
4611 task_params_copy = deepcopy(task_params)
4612 for iface in task_params_copy[5]:
4613 iface["uuid"] = iface2iface[iface["uuid"]]
4614 # increment ip_address
4615 if "ip_address" in iface:
4616 ip = iface.get("ip_address")
4617 i = ip.rfind(".")
4618 if i > 0:
4619 try:
4620 i += 1
4621 ip = ip[i:] + str(int(ip[:i]) + 1)
4622 iface["ip_address"] = ip
4623 except:
4624 iface["ip_address"] = None
4625 if vm_name:
4626 task_params_copy[0] = vm_name
4627 db_vim_action = {
4628 "instance_action_id": instance_action_id,
4629 "task_index": task_index,
4630 "datacenter_vim_id": vim_action_to_clone["datacenter_vim_id"],
4631 "action": "CREATE",
4632 "status": "SCHEDULED",
4633 "item": "instance_vms",
4634 "item_id": vm_uuid,
4635 # ALF
4636 # ALF
4637 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4638 # ALF
4639 # ALF
4640 "extra": yaml.safe_dump({"params": task_params_copy, "depends_on": task_depends_on}, default_flow_style=True, width=256)
4641 }
4642 task_index += 1
4643 db_vim_actions.append(db_vim_action)
tierno67881db2018-10-24 18:46:03 +02004644 vm_result["created"].append(vm_uuid)
tiernofc5f80b2018-05-29 16:00:43 +02004645
4646 db_instance_action["number_tasks"] = task_index
4647 db_tables = [
4648 {"instance_vms": db_instance_vms},
4649 {"instance_interfaces": db_instance_interfaces},
4650 {"instance_actions": db_instance_action},
4651 # TODO revise sfps
4652 # {"instance_sfis": db_instance_sfis},
4653 # {"instance_sfs": db_instance_sfs},
4654 # {"instance_classifications": db_instance_classifications},
4655 # {"instance_sfps": db_instance_sfps},
garciadeblasaba7a0d2018-12-05 12:42:35 +01004656 {"vim_wim_actions": db_vim_actions}
tiernofc5f80b2018-05-29 16:00:43 +02004657 ]
4658 logger.debug("create_vdu done DB tables: %s",
4659 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4660 mydb.new_rows(db_tables, [])
4661 for myvim_thread in myvim_threads_id.values():
4662 vim_threads["running"][myvim_thread].insert_task(db_vim_actions)
4663
4664 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004665
4666 input_vnfs = action_dict.pop("vnfs", [])
4667 input_vms = action_dict.pop("vms", [])
tierno92c36fd2018-05-04 12:21:10 +02004668 action_over_all = True if not input_vnfs and not input_vms else False
tierno7edb6752016-03-21 17:37:52 +01004669 for sce_vnf in instanceDict['vnfs']:
4670 for vm in sce_vnf['vms']:
tierno92c36fd2018-05-04 12:21:10 +02004671 if not action_over_all and sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4672 sce_vnf['member_vnf_index'] not in input_vnfs and \
4673 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
4674 continue
tiernoae4a8d12016-07-08 12:30:39 +02004675 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004676 if "add_public_key" in action_dict:
4677 mgmt_access = {}
4678 if sce_vnf.get('mgmt_access'):
4679 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4680 ssh_access = mgmt_access['config-access']['ssh-access']
4681 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01004682 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004683 if ssh_access['required'] and ssh_access['default-user']:
4684 if 'ip_address' in vm:
4685 mgmt_ip = vm['ip_address'].split(';')
4686 password = mgmt_access['config-access'].get('password')
4687 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4688 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4689 action_dict['add_public_key'],
4690 password=password, ro_key=priv_RO_key)
4691 else:
4692 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004693 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004694 except KeyError:
4695 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004696 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004697 else:
4698 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004699 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004700 else:
4701 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4702 if "console" in action_dict:
4703 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02004704 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4705 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4706 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02004707 ip = data["server"],
4708 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02004709 suffix = data["suffix"]),
4710 "name":vm['name']
4711 }
4712 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004713 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004714 vm_result[ vm['uuid'] ] = {"vim_result": -httperrors.Unauthorized,
gcalvinoe580c7d2017-09-22 14:09:51 +02004715 "description": "this console is only reachable by local interface",
4716 "name":vm['name']
4717 }
tierno20fc2a22016-08-19 17:02:35 +02004718 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004719 else:
4720 #print "console data", data
4721 try:
4722 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4723 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4724 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4725 protocol=data["protocol"],
4726 ip = global_config["http_console_host"],
4727 port = console_thread.port,
4728 suffix = data["suffix"]),
4729 "name":vm['name']
4730 }
4731 vm_ok +=1
4732 except NfvoException as e:
4733 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4734 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02004735
gcalvinoe580c7d2017-09-22 14:09:51 +02004736 else:
4737 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4738 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02004739 except vimconn.vimconnException as e:
4740 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4741 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01004742
4743 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02004744 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004745 else:
tierno351863c2016-07-23 01:46:03 +02004746 return vm_result
tierno42026a02017-02-10 15:13:40 +01004747
tierno868220c2017-09-26 00:11:05 +02004748def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
tierno16e3dd42018-04-24 12:52:40 +02004749 filter = {}
tierno868220c2017-09-26 00:11:05 +02004750 if nfvo_tenant and nfvo_tenant != "any":
4751 filter["tenant_id"] = nfvo_tenant
4752 if instance_id and instance_id != "any":
4753 filter["instance_id"] = instance_id
4754 if action_id:
4755 filter["uuid"] = action_id
4756 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
tierno16e3dd42018-04-24 12:52:40 +02004757 if action_id:
4758 if not rows:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004759 raise NfvoException("Not found any action with this criteria", httperrors.Not_Found)
4760 vim_wim_actions = mydb.get_rows(FROM="vim_wim_actions", WHERE={"instance_action_id": action_id})
4761 rows[0]["vim_wim_actions"] = vim_wim_actions
tierno31e121f2018-12-03 12:04:48 +00004762 # for backward compatibility set vim_actions = vim_wim_actions
4763 rows[0]["vim_actions"] = vim_wim_actions
tiernofc5f80b2018-05-29 16:00:43 +02004764 return {"actions": rows}
tierno868220c2017-09-26 00:11:05 +02004765
tiernob3d36742017-03-03 23:51:05 +01004766
tierno7edb6752016-03-21 17:37:52 +01004767def create_or_use_console_proxy_thread(console_server, console_port):
4768 #look for a non-used port
4769 console_thread_key = console_server + ":" + str(console_port)
4770 if console_thread_key in global_config["console_thread"]:
4771 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02004772 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01004773
tierno7edb6752016-03-21 17:37:52 +01004774 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02004775 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01004776 if port in global_config["console_ports"]:
4777 continue
4778 try:
4779 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4780 clithread.start()
4781 global_config["console_thread"][console_thread_key] = clithread
4782 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02004783 return clithread
tierno7edb6752016-03-21 17:37:52 +01004784 except cli.ConsoleProxyExceptionPortUsed as e:
4785 #port used, try with onoher
4786 continue
4787 except cli.ConsoleProxyException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004788 raise NfvoException(str(e), httperrors.Bad_Request)
4789 raise NfvoException("Not found any free 'http_console_ports'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004790
tiernob3d36742017-03-03 23:51:05 +01004791
tierno7edb6752016-03-21 17:37:52 +01004792def check_tenant(mydb, tenant_id):
4793 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02004794 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4795 if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004796 raise NfvoException("tenant '{}' not found".format(tenant_id), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02004797 return
tierno7edb6752016-03-21 17:37:52 +01004798
4799def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01004800
gcalvinoe580c7d2017-09-22 14:09:51 +02004801 tenant_uuid = str(uuid4())
4802 tenant_dict['uuid'] = tenant_uuid
4803 try:
4804 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4805 tenant_dict['RO_pub_key'] = pub_key
4806 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02004807 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02004808 except db_base_Exception as e:
tierno9c5c8322018-03-23 15:44:03 +01004809 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
gcalvinoe580c7d2017-09-22 14:09:51 +02004810 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01004811
tierno7edb6752016-03-21 17:37:52 +01004812def delete_tenant(mydb, tenant):
4813 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01004814
tiernof97fd272016-07-11 14:32:37 +02004815 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4816 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4817 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01004818
tiernob3d36742017-03-03 23:51:05 +01004819
tierno7edb6752016-03-21 17:37:52 +01004820def new_datacenter(mydb, datacenter_descriptor):
tierno1c848c02018-05-21 16:40:33 +02004821 sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004822 if "config" in datacenter_descriptor:
tiernoedf3f4f2018-05-17 23:02:47 +02004823 sdn_port_mapping = datacenter_descriptor["config"].pop("sdn-port-mapping", None)
4824 datacenter_descriptor["config"] = yaml.safe_dump(datacenter_descriptor["config"], default_flow_style=True,
4825 width=256)
4826 # Check that datacenter-type is correct
tierno3ae39742016-09-07 12:17:51 +02004827 datacenter_type = datacenter_descriptor.get("type", "openvim");
tiernoedf3f4f2018-05-17 23:02:47 +02004828 # module_info = None
tierno3ae39742016-09-07 12:17:51 +02004829 try:
4830 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02004831 pkg = __import__("osm_ro." + module)
tiernoedf3f4f2018-05-17 23:02:47 +02004832 # vim_conn = getattr(pkg, module)
tierno361275f2017-04-25 16:24:34 +02004833 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02004834 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02004835 # if module_info and module_info[0]:
4836 # file.close(module_info[0])
tiernoedf3f4f2018-05-17 23:02:47 +02004837 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type,
4838 module),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004839 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01004840
gcalvinoc62cfa52017-10-05 18:21:25 +02004841 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernoedf3f4f2018-05-17 23:02:47 +02004842 if sdn_port_mapping:
4843 try:
4844 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, sdn_port_mapping)
4845 except Exception as e:
4846 mydb.delete_row_by_id("datacenters", datacenter_id) # Rollback
4847 raise e
tiernof97fd272016-07-11 14:32:37 +02004848 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004849
tiernob3d36742017-03-03 23:51:05 +01004850
tierno7edb6752016-03-21 17:37:52 +01004851def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02004852 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02004853 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02004854
4855 # edit data
tiernof97fd272016-07-11 14:32:37 +02004856 datacenter_id = datacenter['uuid']
tiernod72182f2018-08-29 10:56:13 +02004857 where = {'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02004858 remove_port_mapping = False
tiernoedf3f4f2018-05-17 23:02:47 +02004859 new_sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004860 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02004861 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01004862 try:
4863 new_config_dict = datacenter_descriptor["config"]
tiernoedf3f4f2018-05-17 23:02:47 +02004864 if "sdn-port-mapping" in new_config_dict:
4865 remove_port_mapping = True
4866 new_sdn_port_mapping = new_config_dict.pop("sdn-port-mapping")
tiernod72182f2018-08-29 10:56:13 +02004867 # delete null fields
4868 to_delete = []
tierno7edb6752016-03-21 17:37:52 +01004869 for k in new_config_dict:
tiernod72182f2018-08-29 10:56:13 +02004870 if new_config_dict[k] is None:
tierno7edb6752016-03-21 17:37:52 +01004871 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02004872 if k == 'sdn-controller':
4873 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01004874
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004875 config_text = datacenter.get("config")
4876 if not config_text:
4877 config_text = '{}'
4878 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01004879 config_dict.update(new_config_dict)
tiernod72182f2018-08-29 10:56:13 +02004880 # delete null fields
tierno7edb6752016-03-21 17:37:52 +01004881 for k in to_delete:
4882 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02004883 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004884 raise NfvoException("Bad format at datacenter:config " + str(e), httperrors.Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02004885 if config_dict:
4886 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4887 else:
4888 datacenter_descriptor["config"] = None
4889 if remove_port_mapping:
4890 try:
4891 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4892 except ovimException as e:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004893 raise NfvoException("Error deleting datacenter-port-mapping " + str(e), httperrors.Conflict)
tierno8fe7a492017-07-11 13:50:04 +02004894
tiernof97fd272016-07-11 14:32:37 +02004895 mydb.update_rows('datacenters', datacenter_descriptor, where)
tiernoedf3f4f2018-05-17 23:02:47 +02004896 if new_sdn_port_mapping:
4897 try:
4898 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, new_sdn_port_mapping)
4899 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004900 # Rollback
4901 mydb.update_rows('datacenters', datacenter, where)
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004902 raise NfvoException("Error adding datacenter-port-mapping " + str(e), httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02004903 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004904
tiernob3d36742017-03-03 23:51:05 +01004905
tierno7edb6752016-03-21 17:37:52 +01004906def delete_datacenter(mydb, datacenter):
4907 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02004908 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
4909 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02004910 try:
4911 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
4912 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004913 raise NfvoException("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02004914 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01004915
tiernob3d36742017-03-03 23:51:05 +01004916
tiernod3750b32018-07-20 15:33:08 +02004917def create_vim_account(mydb, nfvo_tenant, datacenter_id, name=None, vim_id=None, vim_tenant=None, vim_tenant_name=None,
4918 vim_username=None, vim_password=None, config=None):
tierno9c22f2d2017-10-09 16:23:55 +02004919 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02004920 try:
tiernod3750b32018-07-20 15:33:08 +02004921 if not datacenter_id:
4922 if not vim_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004923 raise NfvoException("You must provide 'vim_id", http_code=httperrors.Bad_Request)
tiernod3750b32018-07-20 15:33:08 +02004924 datacenter_id = vim_id
4925 datacenter_id, datacenter_name = get_datacenter_uuid(mydb, None, datacenter_id)
tierno7edb6752016-03-21 17:37:52 +01004926
tiernod3750b32018-07-20 15:33:08 +02004927 create_vim_tenant = True if not vim_tenant and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01004928
tierno0ea2a7e2017-10-18 00:06:26 +02004929 # get nfvo_tenant info
4930 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
4931 if vim_tenant_name==None:
4932 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01004933
tierno0ea2a7e2017-10-18 00:06:26 +02004934 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernod3750b32018-07-20 15:33:08 +02004935 # #check that this association does not exist before
4936 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4937 # if len(tenants_datacenters)>0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004938 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004939
tierno0ea2a7e2017-10-18 00:06:26 +02004940 vim_tenant_id_exist_atdb=False
4941 if not create_vim_tenant:
4942 where_={"datacenter_id": datacenter_id}
tiernod3750b32018-07-20 15:33:08 +02004943 if vim_tenant!=None:
4944 where_["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004945 if vim_tenant_name!=None:
4946 where_["vim_tenant_name"] = vim_tenant_name
4947 #check if vim_tenant_id is already at database
4948 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
4949 if len(datacenter_tenants_dict)>=1:
4950 datacenter_tenants_dict = datacenter_tenants_dict[0]
4951 vim_tenant_id_exist_atdb=True
4952 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
4953 else: #result=0
4954 datacenter_tenants_dict = {}
4955 #insert at table datacenter_tenants
tiernod3750b32018-07-20 15:33:08 +02004956 else: #if vim_tenant==None:
tierno0ea2a7e2017-10-18 00:06:26 +02004957 #create tenant at VIM if not provided
4958 try:
4959 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
4960 vim_passwd=vim_password)
4961 datacenter_name = myvim["name"]
tiernod3750b32018-07-20 15:33:08 +02004962 vim_tenant = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
tierno0ea2a7e2017-10-18 00:06:26 +02004963 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004964 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id, str(e)), httperrors.Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01004965 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02004966 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01004967
tierno0ea2a7e2017-10-18 00:06:26 +02004968 #fill datacenter_tenants table
4969 if not vim_tenant_id_exist_atdb:
tiernod3750b32018-07-20 15:33:08 +02004970 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004971 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
4972 datacenter_tenants_dict["user"] = vim_username
4973 datacenter_tenants_dict["passwd"] = vim_password
4974 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernod3750b32018-07-20 15:33:08 +02004975 if name:
4976 datacenter_tenants_dict["name"] = name
4977 else:
4978 datacenter_tenants_dict["name"] = datacenter_name
tierno0ea2a7e2017-10-18 00:06:26 +02004979 if config:
4980 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
4981 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
4982 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01004983
tierno0ea2a7e2017-10-18 00:06:26 +02004984 #fill tenants_datacenters table
4985 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
4986 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
4987 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tiernod3750b32018-07-20 15:33:08 +02004988
tierno0ea2a7e2017-10-18 00:06:26 +02004989 # create thread
tierno0ea2a7e2017-10-18 00:06:26 +02004990 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tiernod3750b32018-07-20 15:33:08 +02004991 new_thread = vim_thread.vim_thread(task_lock, thread_name, datacenter_name, datacenter_tenant_id,
tierno0ea2a7e2017-10-18 00:06:26 +02004992 db=db, db_lock=db_lock, ovim=ovim)
4993 new_thread.start()
4994 thread_id = datacenter_tenants_dict["uuid"]
4995 vim_threads["running"][thread_id] = new_thread
tiernod3750b32018-07-20 15:33:08 +02004996 return thread_id
tierno0ea2a7e2017-10-18 00:06:26 +02004997 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004998 raise NfvoException(str(e), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01004999
tierno99314902017-04-26 13:23:09 +02005000
tiernod3750b32018-07-20 15:33:08 +02005001def edit_vim_account(mydb, nfvo_tenant, datacenter_tenant_id, datacenter_id=None, name=None, vim_tenant=None,
5002 vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005003
tiernod3750b32018-07-20 15:33:08 +02005004 # get vim_account; check is valid for this tenant
5005 from_ = "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
5006 where_ = {"td.nfvo_tenant_id": nfvo_tenant}
5007 if datacenter_tenant_id:
5008 where_["dt.uuid"] = datacenter_tenant_id
5009 if datacenter_id:
5010 where_["dt.datacenter_id"] = datacenter_id
5011 vim_accounts = mydb.get_rows(SELECT="dt.uuid as uuid, config", FROM=from_, WHERE=where_)
5012 if not vim_accounts:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005013 raise NfvoException("vim_account not found for this tenant", http_code=httperrors.Not_Found)
tiernod3750b32018-07-20 15:33:08 +02005014 elif len(vim_accounts) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005015 raise NfvoException("found more than one vim_account for this tenant", http_code=httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02005016 datacenter_tenant_id = vim_accounts[0]["uuid"]
5017 original_config = vim_accounts[0]["config"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005018
tiernod3750b32018-07-20 15:33:08 +02005019 update_ = {}
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005020 if config:
tiernod3750b32018-07-20 15:33:08 +02005021 original_config_dict = yaml.load(original_config)
5022 original_config_dict.update(config)
5023 update["config"] = yaml.safe_dump(original_config_dict, default_flow_style=True, width=256)
5024 if name:
5025 update_['name'] = name
5026 if vim_tenant:
5027 update_['vim_tenant_id'] = vim_tenant
5028 if vim_tenant_name:
5029 update_['vim_tenant_name'] = vim_tenant_name
5030 if vim_username:
5031 update_['user'] = vim_username
5032 if vim_password:
5033 update_['passwd'] = vim_password
5034 if update_:
5035 mydb.update_rows("datacenter_tenants", UPDATE=update_, WHERE={"uuid": datacenter_tenant_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005036
tiernod3750b32018-07-20 15:33:08 +02005037 vim_threads["running"][datacenter_tenant_id].insert_task("reload")
5038 return datacenter_tenant_id
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005039
tiernod3750b32018-07-20 15:33:08 +02005040def delete_vim_account(mydb, tenant_id, vim_account_id, datacenter=None):
tierno7edb6752016-03-21 17:37:52 +01005041 #get nfvo_tenant info
5042 if not tenant_id or tenant_id=="any":
5043 tenant_uuid = None
5044 else:
tiernof97fd272016-07-11 14:32:37 +02005045 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01005046 tenant_uuid = tenant_dict['uuid']
5047
5048 #check that this association exist before
tiernod3750b32018-07-20 15:33:08 +02005049 tenants_datacenter_dict = {}
5050 if datacenter:
5051 datacenter_id, _ = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
5052 tenants_datacenter_dict["datacenter_id"] = datacenter_id
5053 elif vim_account_id:
5054 tenants_datacenter_dict["datacenter_tenant_id"] = vim_account_id
tierno7edb6752016-03-21 17:37:52 +01005055 if tenant_uuid:
5056 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02005057 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5058 if len(tenant_datacenter_list)==0 and tenant_uuid:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005059 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005060
5061 #delete this association
tiernof97fd272016-07-11 14:32:37 +02005062 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01005063
5064 #get vim_tenant info and deletes
5065 warning=''
5066 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02005067 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5068 #try to delete vim:tenant
5069 try:
5070 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5071 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01005072 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01005073 try:
tierno0ea2a7e2017-10-18 00:06:26 +02005074 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005075 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
5076 except vimconn.vimconnException as e:
5077 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
5078 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02005079 except db_base_Exception as e:
5080 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01005081 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02005082 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tiernoa3572692018-05-14 13:09:33 +02005083 thread = vim_threads["running"].get(thread_id)
5084 if thread:
5085 thread.insert_task("exit")
5086 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02005087 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01005088
tiernob3d36742017-03-03 23:51:05 +01005089
tierno7edb6752016-03-21 17:37:52 +01005090def datacenter_action(mydb, tenant_id, datacenter, action_dict):
5091 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01005092 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005093 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005094
5095 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02005096 try:
tiernof97fd272016-07-11 14:32:37 +02005097 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02005098 #print content
5099 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005100 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005101 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01005102 #update nets Change from VIM format to NFVO format
5103 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005104 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01005105 net_nfvo={'datacenter_id': datacenter_id}
5106 net_nfvo['name'] = net['name']
5107 #net_nfvo['description']= net['name']
5108 net_nfvo['vim_net_id'] = net['id']
5109 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5110 net_nfvo['shared'] = net['shared']
5111 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5112 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02005113 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
5114 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
5115 return inserted
tierno7edb6752016-03-21 17:37:52 +01005116 elif 'net-edit' in action_dict:
5117 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02005118 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005119 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01005120 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005121 return result
tierno7edb6752016-03-21 17:37:52 +01005122 elif 'net-delete' in action_dict:
5123 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02005124 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005125 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01005126 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005127 return result
tierno7edb6752016-03-21 17:37:52 +01005128
5129 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005130 raise NfvoException("Unknown action " + str(action_dict), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005131
tiernob3d36742017-03-03 23:51:05 +01005132
tierno7edb6752016-03-21 17:37:52 +01005133def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
5134 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005135 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005136
tierno42fcc3b2016-07-06 17:20:40 +02005137 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01005138 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01005139 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02005140 return result
tierno7edb6752016-03-21 17:37:52 +01005141
tiernob3d36742017-03-03 23:51:05 +01005142
tierno7edb6752016-03-21 17:37:52 +01005143def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
5144 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005145 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005146 filter_dict={}
5147 if action_dict:
5148 action_dict = action_dict["netmap"]
5149 if 'vim_id' in action_dict:
5150 filter_dict["id"] = action_dict['vim_id']
5151 if 'vim_name' in action_dict:
5152 filter_dict["name"] = action_dict['vim_name']
5153 else:
5154 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01005155
tiernoae4a8d12016-07-08 12:30:39 +02005156 try:
tiernof97fd272016-07-11 14:32:37 +02005157 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005158 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005159 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005160 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tiernof97fd272016-07-11 14:32:37 +02005161 if len(vim_nets)>1 and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005162 raise NfvoException("more than two networks found, specify with vim_id", httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02005163 elif len(vim_nets)==0: # and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005164 raise NfvoException("Not found a network at VIM with " + str(filter_dict), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005165 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005166 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01005167 net_nfvo={'datacenter_id': datacenter_id}
5168 if action_dict and "name" in action_dict:
5169 net_nfvo['name'] = action_dict['name']
5170 else:
5171 net_nfvo['name'] = net['name']
5172 #net_nfvo['description']= net['name']
5173 net_nfvo['vim_net_id'] = net['id']
5174 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5175 net_nfvo['shared'] = net['shared']
5176 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02005177 try:
5178 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01005179 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02005180 net_nfvo["uuid"] = net_id
5181 except db_base_Exception as e:
5182 if action_dict:
5183 raise
5184 else:
5185 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01005186 net_list.append(net_nfvo)
5187 return net_list
tierno7edb6752016-03-21 17:37:52 +01005188
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005189def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
5190 # obtain all network data
5191 try:
5192 if utils.check_valid_uuid(network_id):
5193 filter_dict = {"id": network_id}
5194 else:
5195 filter_dict = {"name": network_id}
5196
5197 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5198 network = myvim.get_network_list(filter_dict=filter_dict)
5199 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02005200 raise NfvoException("Not possible to get_sdn_net_id from VIM: {}".format(str(e)), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005201
5202 # ensure the network is defined
5203 if len(network) == 0:
5204 raise NfvoException("Network {} is not present in the system".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005205 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005206
5207 # ensure there is only one network with the provided name
5208 if len(network) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005209 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005210
5211 # ensure it is a dataplane network
5212 if network[0]['type'] != 'data':
5213 return None
5214
5215 # ensure we use the id
5216 network_id = network[0]['id']
5217
5218 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5219 # and with instance_scenario_id==NULL
5220 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5221 search_dict = {'vim_net_id': network_id}
5222
5223 try:
5224 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5225 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
5226 except db_base_Exception as e:
5227 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005228 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005229
5230 sdn_net_counter = 0
5231 for net in result:
5232 if net['sdn_net_id'] != None:
5233 sdn_net_counter+=1
5234 sdn_net_id = net['sdn_net_id']
5235
5236 if sdn_net_counter == 0:
5237 return None
5238 elif sdn_net_counter == 1:
5239 return sdn_net_id
5240 else:
5241 raise NfvoException("More than one SDN network is associated to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005242 network_id), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005243
5244def get_sdn_controller_id(mydb, datacenter):
5245 # Obtain sdn controller id
5246 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
5247 if not config:
5248 return None
5249
5250 return yaml.load(config).get('sdn-controller')
5251
5252def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
5253 try:
5254 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5255 if not sdn_network_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005256 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005257
5258 #Obtain sdn controller id
5259 controller_id = get_sdn_controller_id(mydb, datacenter)
5260 if not controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005261 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005262
5263 #Obtain sdn controller info
5264 sdn_controller = ovim.show_of_controller(controller_id)
5265
5266 port_data = {
5267 'name': 'external_port',
5268 'net_id': sdn_network_id,
5269 'ofc_id': controller_id,
5270 'switch_dpid': sdn_controller['dpid'],
5271 'switch_port': descriptor['port']
5272 }
5273
5274 if 'vlan' in descriptor:
5275 port_data['vlan'] = descriptor['vlan']
5276 if 'mac' in descriptor:
5277 port_data['mac'] = descriptor['mac']
5278
5279 result = ovim.new_port(port_data)
5280 except ovimException as e:
5281 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005282 sdn_network_id, network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005283 except db_base_Exception as e:
5284 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005285 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005286
5287 return 'Port uuid: '+ result
5288
5289def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
5290 if port_id:
5291 filter = {'uuid': port_id}
5292 else:
5293 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5294 if not sdn_network_id:
5295 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005296 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005297 #in case no port_id is specified only ports marked as 'external_port' will be detached
5298 filter = {'name': 'external_port', 'net_id': sdn_network_id}
5299
5300 try:
5301 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
5302 except ovimException as e:
5303 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005304 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005305
5306 if len(port_list) == 0:
5307 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005308 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005309
5310 port_uuid_list = []
5311 for port in port_list:
5312 try:
5313 port_uuid_list.append(port['uuid'])
5314 ovim.delete_port(port['uuid'])
5315 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005316 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005317
5318 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01005319
tierno7edb6752016-03-21 17:37:52 +01005320def vim_action_get(mydb, tenant_id, datacenter, item, name):
5321 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005322 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005323 filter_dict={}
5324 if name:
tierno42fcc3b2016-07-06 17:20:40 +02005325 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01005326 filter_dict["id"] = name
5327 else:
5328 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02005329 try:
5330 if item=="networks":
5331 #filter_dict['tenant_id'] = myvim['tenant_id']
5332 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005333
5334 if len(content) == 0:
5335 raise NfvoException("Network {} is not present in the system. ".format(name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005336 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005337
5338 #Update the networks with the attached ports
5339 for net in content:
5340 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
5341 if sdn_network_id != None:
5342 try:
5343 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5344 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
5345 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005346 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005347 #Remove field name and if port name is external_port save it as 'type'
5348 for port in port_list:
5349 if port['name'] == 'external_port':
5350 port['type'] = "External"
5351 del port['name']
5352 net['sdn_network_id'] = sdn_network_id
5353 net['sdn_attached_ports'] = port_list
5354
tiernoae4a8d12016-07-08 12:30:39 +02005355 elif item=="tenants":
5356 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01005357 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005358
tierno4540ea52017-01-18 17:44:32 +01005359 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005360 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005361 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02005362 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02005363 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02005364 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02005365 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02005366 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 +02005367 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005368 else:
tiernof97fd272016-07-11 14:32:37 +02005369 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02005370 except vimconn.vimconnException as e:
5371 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02005372 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01005373
tiernob3d36742017-03-03 23:51:05 +01005374
tierno7edb6752016-03-21 17:37:52 +01005375def vim_action_delete(mydb, tenant_id, datacenter, item, name):
5376 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02005377 if tenant_id == "any":
5378 tenant_id=None
5379
tiernoa2793912016-10-04 08:15:08 +00005380 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02005381 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02005382 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
5383 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02005384 items = content.values()[0]
5385 if type(items)==list and len(items)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005386 raise NfvoException("Not found " + item, httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005387 elif type(items)==list and len(items)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005388 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005389 else: # it is a dict
5390 item_id = items["id"]
5391 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01005392
tiernoae4a8d12016-07-08 12:30:39 +02005393 try:
5394 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005395 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5396 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
5397 if sdn_network_id != None:
5398 #Delete any port attachment to this network
5399 try:
5400 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
5401 except ovimException as e:
5402 raise NfvoException(
5403 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005404 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005405
5406 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5407 for port in port_list:
5408 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
5409
5410 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5411 try:
5412 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
5413 except db_base_Exception as e:
5414 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
tierno9c5c8322018-03-23 15:44:03 +01005415 str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005416
5417 #Delete the SDN network
5418 try:
5419 ovim.delete_network(sdn_network_id)
5420 except ovimException as e:
5421 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
5422 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005423 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005424
tiernoae4a8d12016-07-08 12:30:39 +02005425 content = myvim.delete_network(item_id)
5426 elif item=="tenants":
5427 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01005428 elif item == "images":
5429 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02005430 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005431 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005432 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005433 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5434 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005435
tiernof97fd272016-07-11 14:32:37 +02005436 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01005437
tiernob3d36742017-03-03 23:51:05 +01005438
tierno7edb6752016-03-21 17:37:52 +01005439def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
5440 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005441 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02005442 if tenant_id == "any":
5443 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00005444 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005445 try:
5446 if item=="networks":
5447 net = descriptor["network"]
5448 net_name = net.pop("name")
5449 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02005450 net_public = net.pop("shared", False)
5451 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01005452 net_vlan = net.pop("vlan", None)
5453 content = myvim.new_network(net_name, net_type, net_ipprofile, shared=net_public, vlan=net_vlan) #, **net)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005454
5455 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5456 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
tierno00e3df72017-11-29 17:20:13 +01005457 #obtain datacenter_tenant_id
5458 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
5459 FROM='datacenter_tenants',
5460 WHERE={'datacenter_id': datacenter})[0]['uuid']
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005461 try:
5462 sdn_network = {}
5463 sdn_network['vlan'] = net_vlan
5464 sdn_network['type'] = net_type
5465 sdn_network['name'] = net_name
tierno00e3df72017-11-29 17:20:13 +01005466 sdn_network['region'] = datacenter_tenant_id
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005467 ovim_content = ovim.new_network(sdn_network)
5468 except ovimException as e:
tierno00e3df72017-11-29 17:20:13 +01005469 logger.error("ovimException creating SDN network={} ".format(
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005470 sdn_network) + str(e), exc_info=True)
5471 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005472 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005473
5474 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5475 # use instance_scenario_id=None to distinguish from real instaces of nets
tierno00e3df72017-11-29 17:20:13 +01005476 correspondence = {'instance_scenario_id': None,
5477 'sdn_net_id': ovim_content,
5478 'vim_net_id': content,
5479 'datacenter_tenant_id': datacenter_tenant_id
5480 }
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005481 try:
5482 mydb.new_row('instance_nets', correspondence, add_uuid=True)
5483 except db_base_Exception as e:
tierno00e3df72017-11-29 17:20:13 +01005484 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005485 correspondence, e), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005486 elif item=="tenants":
5487 tenant = descriptor["tenant"]
5488 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
5489 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005490 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005491 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005492 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005493
tierno7edb6752016-03-21 17:37:52 +01005494 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005495
5496def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005497 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005498 logger.debug('New SDN controller created with uuid {}'.format(data))
5499 return data
5500
5501def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005502 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005503 msg = 'SDN controller {} updated'.format(data)
5504 logger.debug(msg)
5505 return msg
5506
5507def sdn_controller_list(mydb, tenant_id, controller_id=None):
5508 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005509 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005510 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005511 data = ovim.show_of_controller(controller_id)
5512
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005513 msg = 'SDN controller list:\n {}'.format(data)
5514 logger.debug(msg)
5515 return data
5516
5517def sdn_controller_delete(mydb, tenant_id, controller_id):
5518 select_ = ('uuid', 'config')
5519 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5520 for datacenter in datacenters:
5521 if datacenter['config']:
5522 config = yaml.load(datacenter['config'])
5523 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005524 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), httperrors.Conflict)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005525
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005526 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005527 msg = 'SDN controller {} deleted'.format(data)
5528 logger.debug(msg)
5529 return msg
5530
5531def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5532 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5533 if len(controller) < 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005534 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), httperrors.Not_Found)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005535
5536 try:
5537 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
5538 except:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005539 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005540
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005541 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5542 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005543
5544 maps = list()
5545 for compute_node in sdn_port_mapping:
5546 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5547 element = dict()
5548 element["compute_node"] = compute_node["compute_node"]
5549 for port in compute_node["ports"]:
tierno7f426e92018-06-28 15:21:32 +02005550 pci = port.get("pci")
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005551 element["switch_port"] = port.get("switch_port")
5552 element["switch_mac"] = port.get("switch_mac")
tierno4070e442019-01-23 10:19:23 +00005553 if not element["switch_port"] and not element["switch_mac"]:
5554 raise NfvoException ("The mapping must contain 'switch_port' or 'switch_mac'", httperrors.Bad_Request)
tierno7f426e92018-06-28 15:21:32 +02005555 for pci_expanded in utils.expand_brackets(pci):
5556 element["pci"] = pci_expanded
5557 maps.append(dict(element))
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005558
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005559 return ovim.set_of_port_mapping(maps, ofc_id=sdn_controller_id, switch_dpid=switch_dpid, region=datacenter_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005560
5561def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005562 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005563
5564 result = {
5565 "sdn-controller": None,
5566 "datacenter-id": datacenter_id,
5567 "dpid": None,
5568 "ports_mapping": list()
5569 }
5570
5571 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5572 if datacenter['config']:
5573 config = yaml.load(datacenter['config'])
5574 if 'sdn-controller' in config:
5575 controller_id = config['sdn-controller']
5576 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5577 result["sdn-controller"] = controller_id
5578 result["dpid"] = sdn_controller["dpid"]
5579
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005580 if result["sdn-controller"] == None:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005581 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005582 if result["dpid"] == None:
5583 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005584 httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005585
5586 if len(maps) == 0:
5587 return result
5588
5589 ports_correspondence_dict = dict()
5590 for link in maps:
5591 if result["sdn-controller"] != link["ofc_id"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005592 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005593 if result["dpid"] != link["switch_dpid"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005594 raise NfvoException("The dpid specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005595 element = dict()
5596 element["pci"] = link["pci"]
5597 if link["switch_port"]:
5598 element["switch_port"] = link["switch_port"]
5599 if link["switch_mac"]:
5600 element["switch_mac"] = link["switch_mac"]
5601
5602 if not link["compute_node"] in ports_correspondence_dict:
5603 content = dict()
5604 content["compute_node"] = link["compute_node"]
5605 content["ports"] = list()
5606 ports_correspondence_dict[link["compute_node"]] = content
5607
5608 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5609
5610 for key in sorted(ports_correspondence_dict):
5611 result["ports_mapping"].append(ports_correspondence_dict[key])
5612
5613 return result
5614
5615def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02005616 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02005617
5618def create_RO_keypair(tenant_id):
5619 """
5620 Creates a public / private keys for a RO tenant and returns their values
5621 Params:
5622 tenant_id: ID of the tenant
5623 Return:
5624 public_key: Public key for the RO tenant
5625 private_key: Encrypted private key for RO tenant
5626 """
5627
5628 bits = 2048
5629 key = RSA.generate(bits)
5630 try:
5631 public_key = key.publickey().exportKey('OpenSSH')
5632 if isinstance(public_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005633 raise NfvoException("Unable to create public key: {}".format(public_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005634 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5635 except (ValueError, NameError) as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005636 raise NfvoException("Unable to create private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005637 return public_key, private_key
5638
5639def decrypt_key (key, tenant_id):
5640 """
5641 Decrypts an encrypted RSA key
5642 Params:
5643 key: Private key to be decrypted
5644 tenant_id: ID of the tenant
5645 Return:
5646 unencrypted_key: Unencrypted private key for RO tenant
5647 """
5648 try:
5649 key = RSA.importKey(key,tenant_id)
5650 unencrypted_key = key.exportKey('PEM')
5651 if isinstance(unencrypted_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005652 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005653 except ValueError as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005654 raise NfvoException("Unable to decrypt the private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005655 return unencrypted_key