blob: 0782023c2547c962fca66f96f469c78386c4bf27 [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
tierno98c11d82019-05-06 13:24:12 +0000129 if tenant_name:
130 name = datacenter_name[:16] + "." + tenant_name[:16]
131 if name not in vim_threads["names"]:
132 vim_threads["names"].append(name)
133 return name
134 name = datacenter_id
tierno42026a02017-02-10 15:13:40 +0100135 vim_threads["names"].append(name)
136 return name
137
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100138# -- Move
139def get_non_used_wim_name(wim_name, wim_id, tenant_name, tenant_id):
140 name = wim_name[:16]
141 if name not in wim_threads["names"]:
142 wim_threads["names"].append(name)
143 return name
144 name = wim_name[:16] + "." + tenant_name[:16]
145 if name not in wim_threads["names"]:
146 wim_threads["names"].append(name)
147 return name
148 name = wim_id + "-" + tenant_id
149 wim_threads["names"].append(name)
150 return name
tierno42026a02017-02-10 15:13:40 +0100151
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100152
153def start_service(mydb, persistence=None, wim=None):
tiernob3d36742017-03-03 23:51:05 +0100154 global db, global_config
Anderson Bravalheridfed5112019-02-08 01:44:14 +0000155 db = nfvo_db.nfvo_db(lock=db_lock)
156 mydb.lock = db_lock
tiernob3d36742017-03-03 23:51:05 +0100157 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 +0100158 global ovim
159
Anderson Bravalheridfed5112019-02-08 01:44:14 +0000160 persistence = persistence or WimPersistence(db)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100161
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100162 # Initialize openvim for SDN control
163 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
164 # TODO: review ovim.py to delete not needed configuration
165 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200166 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100167 'network_vlan_range_start': 1000,
168 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200169 'db_name': global_config["db_ovim_name"],
170 'db_host': global_config["db_ovim_host"],
171 'db_user': global_config["db_ovim_user"],
172 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100173 'bridge_ifaces': {},
174 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100175 'network_type': 'bridge',
176 #TODO: log_level_of should not be needed. To be modified in ovim
177 'log_level_of': 'DEBUG'
178 }
tierno42026a02017-02-10 15:13:40 +0100179 try:
tierno3fcfdb72017-10-24 07:48:24 +0200180 # starts ovim library
tierno46df9672017-05-26 13:12:21 +0200181 ovim = ovim_module.ovim(ovim_configuration)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100182
183 global wim_engine
184 wim_engine = wim or WimEngine(persistence)
185 wim_engine.ovim = ovim
186
tierno46df9672017-05-26 13:12:21 +0200187 ovim.start_service()
188
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100189 #delete old unneeded vim_wim_actions
tierno3fcfdb72017-10-24 07:48:24 +0200190 clean_db(mydb)
191
192 # starts vim_threads
tierno46df9672017-05-26 13:12:21 +0200193 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
194 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
195 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
196 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
197 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
198 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100199 vims = mydb.get_rows(FROM=from_, SELECT=select_)
200 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200201 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
202 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100203 if vim["config"]:
204 extra.update(yaml.load(vim["config"]))
205 if vim.get('dt_config'):
206 extra.update(yaml.load(vim["dt_config"]))
207 if vim["type"] not in vimconn_imported:
208 module_info=None
209 try:
210 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200211 pkg = __import__("osm_ro." + module)
212 vim_conn = getattr(pkg, module)
213 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
214 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100215 vimconn_imported[vim["type"]] = vim_conn
216 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200217 # if module_info and module_info[0]:
218 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200219 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100220 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100221
tierno867ffe92017-03-27 12:50:34 +0200222 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100223 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100224 try:
225 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100226 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tierno42026a02017-02-10 15:13:40 +0100227 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100228 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
229 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
230 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
231 user=vim['user'], passwd=vim['passwd'],
232 config=extra, persistent_info=vim_persistent_info[thread_id]
233 )
tierno9c22f2d2017-10-09 16:23:55 +0200234 except vimconn.vimconnException as e:
235 myvim = e
236 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
237 vim['datacenter_id'], e))
tierno42026a02017-02-10 15:13:40 +0100238 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200239 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100240 httperrors.Internal_Server_Error)
tierno98c11d82019-05-06 13:24:12 +0000241 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['datacenter_id'], vim['vim_tenant_name'],
tierno46df9672017-05-26 13:12:21 +0200242 vim['vim_tenant_id'])
tiernod3750b32018-07-20 15:33:08 +0200243 new_thread = vim_thread.vim_thread(task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200244 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100245 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100246 vim_threads["running"][thread_id] = new_thread
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100247
248 wim_engine.start_threads()
tierno42026a02017-02-10 15:13:40 +0100249 except db_base_Exception as e:
250 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200251 except ovim_module.ovimException as e:
252 message = str(e)
253 if message[:22] == "DATABASE wrong version":
254 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
255 "at host {dbhost}".format(
256 msg=message[22:-3], dbname=global_config["db_ovim_name"],
257 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
258 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100259 raise NfvoException(message, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100260
tierno867ffe92017-03-27 12:50:34 +0200261
tierno42026a02017-02-10 15:13:40 +0100262def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200263 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100264 if ovim:
265 ovim.stop_service()
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100266 for thread_id, thread in vim_threads["running"].items():
tierno868220c2017-09-26 00:11:05 +0200267 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +0100268 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100269 vim_threads["running"] = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100270
271 if wim_engine:
272 wim_engine.stop_threads()
273
tiernoc5651792017-03-27 10:50:43 +0200274 if global_config and global_config.get("console_thread"):
275 for thread in global_config["console_thread"]:
276 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100277
tierno6ddeded2017-05-16 15:40:26 +0200278def get_version():
279 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
280 global_config["version_date"] ))
281
tierno3fcfdb72017-10-24 07:48:24 +0200282def clean_db(mydb):
283 """
284 Clean unused or old entries at database to avoid unlimited growing
285 :param mydb: database connector
286 :return: None
287 """
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100288 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
tierno3fcfdb72017-10-24 07:48:24 +0200289 now = t.time()-3600*24*7
290 instance_action_id = None
291 nb_deleted = 0
292 while True:
293 actions_to_delete = mydb.get_rows(
294 SELECT=("item", "item_id", "instance_action_id"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100295 FROM="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
tierno3fcfdb72017-10-24 07:48:24 +0200296 "left join instance_scenarios as i on ia.instance_id=i.uuid",
297 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
298 "va.status": ("DONE", "SUPERSEDED")},
299 LIMIT=100
300 )
301 for to_delete in actions_to_delete:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100302 mydb.delete_row(FROM="vim_wim_actions", WHERE=to_delete)
tierno3fcfdb72017-10-24 07:48:24 +0200303 if instance_action_id != to_delete["instance_action_id"]:
304 instance_action_id = to_delete["instance_action_id"]
305 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
306 nb_deleted += len(actions_to_delete)
307 if len(actions_to_delete) < 100:
308 break
tierno3c44e7b2019-03-04 17:32:01 +0000309 # clean locks
310 mydb.update_rows("vim_wim_actions", UPDATE={"worker": None}, WHERE={"worker<>": None})
311
tierno3fcfdb72017-10-24 07:48:24 +0200312 if nb_deleted:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100313 logger.debug("Removed {} unused vim_wim_actions".format(nb_deleted))
tierno3fcfdb72017-10-24 07:48:24 +0200314
tierno42026a02017-02-10 15:13:40 +0100315
tierno7edb6752016-03-21 17:37:52 +0100316def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
317 '''Obtain flavorList
318 return result, content:
319 <0, error_text upon error
320 nb_records, flavor_list on success
321 '''
322 WHERE_dict={}
323 WHERE_dict['vnf_id'] = vnf_id
324 if nfvo_tenant is not None:
325 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100326
tierno7edb6752016-03-21 17:37:52 +0100327 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
328 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200329 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
330 #print "get_flavor_list result:", result
331 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100332 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200333 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100334 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200335 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100336
tiernob3d36742017-03-03 23:51:05 +0100337
tierno7edb6752016-03-21 17:37:52 +0100338def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
tierno16e3dd42018-04-24 12:52:40 +0200339 """
340 Get used images of all vms belonging to this VNFD
341 :param mydb: database conector
342 :param vnf_id: vnfd uuid
343 :param nfvo_tenant: tenant, not used
344 :return: The list of image uuid used
345 """
346 image_list = []
347 vms = mydb.get_rows(SELECT=('image_id','image_list'), FROM='vms', WHERE={'vnf_id': vnf_id})
348 for vm in vms:
tierno89aada42018-12-19 16:00:25 +0000349 if vm["image_id"] and vm["image_id"] not in image_list:
tierno16e3dd42018-04-24 12:52:40 +0200350 image_list.append(vm["image_id"])
351 if vm["image_list"]:
352 vm_image_list = yaml.load(vm["image_list"])
353 for image_dict in vm_image_list:
354 if image_dict["image_id"] not in image_list:
355 image_list.append(image_dict["image_id"])
356 return image_list
tierno7edb6752016-03-21 17:37:52 +0100357
tiernob3d36742017-03-03 23:51:05 +0100358
tiernoa2793912016-10-04 08:15:08 +0000359def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
tiernocbb52052018-05-31 18:57:30 +0200360 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None, ignore_errors=False):
tierno7edb6752016-03-21 17:37:52 +0100361 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100362 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100363 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200364 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100365 '''
366 WHERE_dict={}
367 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
368 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000369 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100370 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
371 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000372 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
373 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100374 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 +0000375 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 +0100376 '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 +0000377 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100378 else:
379 from_ = 'datacenters as d'
380 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200381 try:
382 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
383 vim_dict={}
384 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200385 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
tierno16e3dd42018-04-24 12:52:40 +0200386 'datacenter_id': vim.get('datacenter_id'),
tiernob6434212018-04-26 16:27:47 +0200387 '_vim_type_internal': vim.get('type')}
tierno8008c3a2016-10-13 15:34:28 +0000388 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200389 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000390 if vim.get('dt_config'):
391 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200392 if vim["type"] not in vimconn_imported:
393 module_info=None
394 try:
395 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200396 pkg = __import__("osm_ro." + module)
397 vim_conn = getattr(pkg, module)
398 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
399 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200400 vimconn_imported[vim["type"]] = vim_conn
401 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200402 # if module_info and module_info[0]:
403 # file.close(module_info[0])
tiernocbb52052018-05-31 18:57:30 +0200404 if ignore_errors:
405 logger.error("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
406 vim["type"], module, type(e).__name__, str(e)))
407 continue
tiernof97fd272016-07-11 14:32:37 +0200408 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100409 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100410
tierno7edb6752016-03-21 17:37:52 +0100411 try:
tierno867ffe92017-03-27 12:50:34 +0200412 if 'datacenter_tenant_id' in vim:
413 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100414 if thread_id not in vim_persistent_info:
415 vim_persistent_info[thread_id] = {}
416 persistent_info = vim_persistent_info[thread_id]
417 else:
418 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200419 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100420 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tiernof97fd272016-07-11 14:32:37 +0200421 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
422 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100423 tenant_id=vim.get('vim_tenant_id',vim_tenant),
424 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100425 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200426 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100427 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200428 )
429 except Exception as e:
tiernocbb52052018-05-31 18:57:30 +0200430 if ignore_errors:
431 logger.error("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)))
432 continue
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100433 http_code = httperrors.Internal_Server_Error
tiernoa3572692018-05-14 13:09:33 +0200434 if isinstance(e, vimconn.vimconnException):
435 http_code = e.http_code
436 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), http_code)
tiernof97fd272016-07-11 14:32:37 +0200437 return vim_dict
438 except db_base_Exception as e:
439 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100440
tiernob3d36742017-03-03 23:51:05 +0100441
tierno7edb6752016-03-21 17:37:52 +0100442def rollback(mydb, vims, rollback_list):
443 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100444 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100445 for i in range(len(rollback_list)-1, -1, -1):
446 item = rollback_list[i]
447 if item["where"]=="vim":
448 if item["vim_id"] not in vims:
449 continue
tierno56d73d22017-08-02 13:53:02 +0200450 if is_task_id(item["uuid"]):
451 continue
452 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200453 try:
454 if item["what"]=="image":
455 vim.delete_image(item["uuid"])
tierno868220c2017-09-26 00:11:05 +0200456 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200457 elif item["what"]=="flavor":
458 vim.delete_flavor(item["uuid"])
tiernoad6bdd42018-01-10 10:43:46 +0100459 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200460 elif item["what"]=="network":
461 vim.delete_network(item["uuid"])
462 elif item["what"]=="vm":
463 vim.delete_vminstance(item["uuid"])
464 except vimconn.vimconnException as e:
465 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
466 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200467 except db_base_Exception as e:
468 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 +0100469
tierno7edb6752016-03-21 17:37:52 +0100470 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200471 try:
472 if item["what"]=="image":
473 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
474 elif item["what"]=="flavor":
475 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
476 except db_base_Exception as e:
477 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
478 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100479 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100480 return True," Rollback successful."
481 else:
482 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100483
tiernob3d36742017-03-03 23:51:05 +0100484
tiernoafed5f12017-01-26 17:57:43 +0100485def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100486 global global_config
tierno42026a02017-02-10 15:13:40 +0100487 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100488 vnfc_interfaces={}
489 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100490 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100491 #dataplane interfaces
492 for numa in vnfc.get("numas",() ):
493 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100494 if interface["name"] in name_dict:
495 raise NfvoException(
496 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
497 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100498 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100499 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100500 #bridge interfaces
501 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100502 if interface["name"] in name_dict:
503 raise NfvoException(
504 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
505 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100506 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100507 name_dict[ interface["name"] ] = "overlay"
508 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100509 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200510 # if "boot-data" in vnfc:
511 # # check that user-data is incompatible with users and config-files
512 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
513 # raise NfvoException(
514 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100515 # httperrors.Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100516
tierno7edb6752016-03-21 17:37:52 +0100517 #check if the info in external_connections matches with the one in the vnfcs
518 name_list=[]
519 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
520 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100521 raise NfvoException(
522 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
523 external_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100524 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100525 name_list.append(external_connection["name"])
526 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100527 raise NfvoException(
528 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
529 external_connection["name"], external_connection["VNFC"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100530 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100531
tierno7edb6752016-03-21 17:37:52 +0100532 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100533 raise NfvoException(
534 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
535 external_connection["name"],
536 external_connection["local_iface_name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100537 httperrors.Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100538
tierno7edb6752016-03-21 17:37:52 +0100539 #check if the info in internal_connections matches with the one in the vnfcs
540 name_list=[]
541 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
542 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100543 raise NfvoException(
544 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
545 internal_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100546 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100547 name_list.append(internal_connection["name"])
548 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100549
550 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
551 raise NfvoException(
552 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
553 internal_connection["name"],
554 'ptp' if vnf_descriptor_version==1 else 'e-line',
555 'data' if vnf_descriptor_version==1 else "e-lan"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100556 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100557 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100558 vnf = port["VNFC"]
559 iface = port["local_iface_name"]
560 if vnf not in vnfc_interfaces:
561 raise NfvoException(
562 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
563 internal_connection["name"], vnf),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100564 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100565 if iface not in vnfc_interfaces[ vnf ]:
566 raise NfvoException(
567 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
568 internal_connection["name"], iface),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100569 httperrors.Bad_Request)
570 return -httperrors.Bad_Request,
tiernoafed5f12017-01-26 17:57:43 +0100571 if vnf_descriptor_version==1 and "type" not in internal_connection:
572 if vnfc_interfaces[vnf][iface] == "overlay":
573 internal_connection["type"] = "bridge"
574 else:
575 internal_connection["type"] = "data"
576 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
577 if vnfc_interfaces[vnf][iface] == "overlay":
578 internal_connection["implementation"] = "overlay"
579 else:
580 internal_connection["implementation"] = "underlay"
581 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
582 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
583 raise NfvoException(
584 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
585 internal_connection["name"],
586 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
587 'data' if vnf_descriptor_version==1 else 'underlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100588 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100589 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
590 vnfc_interfaces[vnf][iface] == "underlay":
591 raise NfvoException(
592 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
593 internal_connection["name"], iface,
594 'data' if vnf_descriptor_version==1 else 'underlay',
595 'bridge' if vnf_descriptor_version==1 else 'overlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100596 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100597
tierno7edb6752016-03-21 17:37:52 +0100598
tierno56d73d22017-08-02 13:53:02 +0200599def 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 +0100600 #look if image exist
601 if only_create_at_vim:
602 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000603 if return_on_error == None:
604 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100605 else:
garciadeblas14480452017-01-10 13:08:07 +0100606 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200607 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
608 else:
609 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200610 if len(images)>=1:
611 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100612 else:
garciadeblas14480452017-01-10 13:08:07 +0100613 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100614 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200615 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
616 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100617 }
garciadeblas14480452017-01-10 13:08:07 +0100618 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200619 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
620 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100621 #create image at every vim
622 for vim_id,vim in vims.iteritems():
tierno868220c2017-09-26 00:11:05 +0200623 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100624 image_created="false"
625 #look at database
tierno868220c2017-09-26 00:11:05 +0200626 image_db = mydb.get_rows(FROM="datacenters_images",
627 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100628 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200629 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200630 if image_dict['location'] is not None:
631 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
632 else:
garciadeblas30833382017-01-09 09:46:31 +0100633 filter_dict = {}
634 filter_dict['name'] = image_dict['universal_name']
635 if image_dict.get('checksum') != None:
636 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000637 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200638 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100639 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200640 if len(vim_images) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100641 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), httperrors.Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000642 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100643 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200644 else:
garciadeblas14480452017-01-10 13:08:07 +0100645 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
646 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200647
tiernoae4a8d12016-07-08 12:30:39 +0200648 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100649 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100650 try:
garciadeblas14480452017-01-10 13:08:07 +0100651 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
652 if image_dict['location']:
653 image_vim_id = vim.new_image(image_dict)
654 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
655 image_created="true"
656 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100657 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
658 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200659 except vimconn.vimconnException as e:
660 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100661 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200662 raise
tierno5e91eb82016-10-04 09:39:07 +0000663 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100664 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200665 continue
666 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000667 if return_on_error:
668 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
669 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200670 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000671 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100672 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200673 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200674 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100675 #add new vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200676 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
677 'image_id':image_mano_id,
678 'vim_id': image_vim_id,
679 'created':image_created})
tierno7edb6752016-03-21 17:37:52 +0100680 elif image_db[0]["vim_id"]!=image_vim_id:
681 #modify existing vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200682 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 +0100683
tiernof97fd272016-07-11 14:32:37 +0200684 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100685
tiernob3d36742017-03-03 23:51:05 +0100686
tierno5e91eb82016-10-04 09:39:07 +0000687def 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 +0100688 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
tierno7edb6752016-03-21 17:37:52 +0100689 'ram':flavor_dict.get('ram'),
690 'vcpus':flavor_dict.get('vcpus'),
691 }
692 if 'extended' in flavor_dict and flavor_dict['extended']==None:
693 del flavor_dict['extended']
694 if 'extended' in flavor_dict:
695 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
696
697 #look if flavor exist
698 if only_create_at_vim:
699 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000700 if return_on_error == None:
701 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100702 else:
tiernof97fd272016-07-11 14:32:37 +0200703 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
704 if len(flavors)>=1:
705 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100706 else:
707 #create flavor
708 #create one by one the images of aditional disks
709 dev_image_list=[] #list of images
710 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
711 dev_nb=0
712 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200713 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100714 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200715 image_dict={}
716 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
717 image_dict['universal_name']=device.get('image name')
718 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
719 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100720 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200721 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100722 image_metadata_dict = device.get('image metadata', None)
723 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100724 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100725 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
726 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200727 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
728 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100729 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100730 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100731 temp_flavor_dict['name'] = flavor_dict['name']
732 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200733 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
734 flavor_mano_id= content
735 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100736 #create flavor at every vim
737 if 'uuid' in flavor_dict:
738 del flavor_dict['uuid']
739 flavor_vim_id=None
740 for vim_id,vim in vims.items():
tierno868220c2017-09-26 00:11:05 +0200741 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100742 flavor_created="false"
743 #look at database
tierno868220c2017-09-26 00:11:05 +0200744 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
745 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100746 #look at VIM if this flavor exist SKIPPED
747 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
748 #if res_vim < 0:
749 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
750 # continue
751 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100752
tiernof1ba57e2017-09-07 12:23:19 +0200753 # Create the flavor in VIM
754 # Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000755 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100756 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
tiernof1ba57e2017-09-07 12:23:19 +0200757 # make a copy of original devices
tierno7edb6752016-03-21 17:37:52 +0100758 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000759
tierno7edb6752016-03-21 17:37:52 +0100760 for device in flavor_dict["extended"].get("devices",[]):
761 dev={}
762 dev.update(device)
763 devices_original.append(dev)
764 if 'image' in device:
765 del device['image']
766 if 'image metadata' in device:
767 del device['image metadata']
tiernof1ba57e2017-09-07 12:23:19 +0200768 if 'image checksum' in device:
769 del device['image checksum']
770 dev_nb = 0
tierno7edb6752016-03-21 17:37:52 +0100771 for index in range(0,len(devices_original)) :
772 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000773 if "image" not in device and "image name" not in device:
tiernoecc68392018-09-06 13:47:11 +0200774 # if 'size' in device:
775 disk_list.append({'size': device.get('size', default_volume_size), 'name': device.get('name')})
tierno7edb6752016-03-21 17:37:52 +0100776 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200777 image_dict={}
778 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
779 image_dict['universal_name']=device.get('image name')
780 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
781 image_dict['location']=device.get('image')
tiernof1ba57e2017-09-07 12:23:19 +0200782 # image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200783 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100784 image_metadata_dict = device.get('image metadata', None)
785 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100786 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100787 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
788 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200789 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 +0100790 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200791 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 +0000792
793 #save disk information (image must be based on and size
794 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
795
tierno7edb6752016-03-21 17:37:52 +0100796 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
797 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200798 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100799 #check that this vim_id exist in VIM, if not create
800 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200801 try:
802 vim.get_flavor(flavor_vim_id)
803 continue #flavor exist
804 except vimconn.vimconnException:
805 pass
tierno7edb6752016-03-21 17:37:52 +0100806 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200807 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
808 try:
tiernocf157a82017-01-30 14:07:06 +0100809 flavor_vim_id = None
810 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
tiernob7aa1bb2019-07-24 15:47:16 +0000811 flavor_created="false"
tiernocf157a82017-01-30 14:07:06 +0100812 except vimconn.vimconnException as e:
813 pass
814 try:
815 if not flavor_vim_id:
816 flavor_vim_id = vim.new_flavor(flavor_dict)
817 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
818 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200819 except vimconn.vimconnException as e:
820 if return_on_error:
821 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200822 raise
tiernoae4a8d12016-07-08 12:30:39 +0200823 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000824 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200825 continue
tierno7edb6752016-03-21 17:37:52 +0100826 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200827 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100828 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000829 extended_devices_yaml = None
830 if len(disk_list) > 0:
831 extended_devices = dict()
832 extended_devices['disks'] = disk_list
833 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
834 mydb.new_row('datacenters_flavors',
tierno868220c2017-09-26 00:11:05 +0200835 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
836 'created': flavor_created, 'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100837 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
838 #modify existing vim_id at datacenters_flavors
tierno868220c2017-09-26 00:11:05 +0200839 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
840 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100841
tiernof97fd272016-07-11 14:32:37 +0200842 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100843
tiernob3d36742017-03-03 23:51:05 +0100844
tiernof1ba57e2017-09-07 12:23:19 +0200845def get_str(obj, field, length):
846 """
847 Obtain the str value,
848 :param obj:
849 :param length:
850 :return:
851 """
852 value = obj.get(field)
853 if value is not None:
854 value = str(value)[:length]
855 return value
856
857def _lookfor_or_create_image(db_image, mydb, descriptor):
858 """
859 fill image content at db_image dictionary. Check if the image with this image and checksum exist
860 :param db_image: dictionary to insert data
861 :param mydb: database connector
862 :param descriptor: yang descriptor
863 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
864 """
865
866 db_image["name"] = get_str(descriptor, "image", 255)
867 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
868 if not db_image["checksum"]: # Ensure that if empty string, None is stored
869 db_image["checksum"] = None
870 if db_image["name"].startswith("/"):
871 db_image["location"] = db_image["name"]
872 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
873 else:
874 db_image["universal_name"] = db_image["name"]
875 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
876 'checksum': db_image['checksum']})
877 if existing_images:
878 return existing_images[0]["uuid"]
879 else:
880 image_uuid = str(uuid4())
881 db_image["uuid"] = image_uuid
882 return None
883
anwarsae5f52c2019-04-22 10:35:27 +0530884def get_resource_allocation_params(quota_descriptor):
885 """
886 read the quota_descriptor from vnfd and fetch the resource allocation properties from the descriptor object
887 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
888 :return: quota params for limit, reserve, shares from the descriptor object
889 """
890 quota = {}
891 if quota_descriptor.get("limit"):
892 quota["limit"] = int(quota_descriptor["limit"])
893 if quota_descriptor.get("reserve"):
894 quota["reserve"] = int(quota_descriptor["reserve"])
895 if quota_descriptor.get("shares"):
896 quota["shares"] = int(quota_descriptor["shares"])
897 return quota
898
tiernof1ba57e2017-09-07 12:23:19 +0200899def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
900 """
901 Parses an OSM IM vnfd_catalog and insert at DB
902 :param mydb:
903 :param tenant_id:
904 :param vnf_descriptor:
905 :return: The list of cretated vnf ids
906 """
907 try:
908 myvnfd = vnfd_catalog.vnfd()
tiernoa9550202017-09-22 13:31:35 +0200909 try:
tiernof6bbe222019-04-09 14:19:40 +0000910 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True,
911 skip_unknown=True)
tiernoa9550202017-09-22 13:31:35 +0200912 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100913 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200914 db_vnfs = []
915 db_nets = []
916 db_vms = []
917 db_vms_index = 0
918 db_interfaces = []
919 db_images = []
920 db_flavors = []
tierno41a69812018-02-16 14:34:33 +0100921 db_ip_profiles_index = 0
922 db_ip_profiles = []
tiernof1ba57e2017-09-07 12:23:19 +0200923 uuid_list = []
924 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200925 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
926 if not vnfd_catalog_descriptor:
927 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
928 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
929 if not vnfd_descriptor_list:
930 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200931 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
932 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200933
934 # table vnf
935 vnf_uuid = str(uuid4())
936 uuid_list.append(vnf_uuid)
937 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100938 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200939 db_vnf = {
940 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100941 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200942 "name": get_str(vnfd, "name", 255),
943 "description": get_str(vnfd, "description", 255),
944 "tenant_id": tenant_id,
945 "vendor": get_str(vnfd, "vendor", 255),
946 "short_name": get_str(vnfd, "short-name", 255),
947 "descriptor": str(vnf_descriptor)[:60000]
948 }
949
tiernoe18ba432017-10-12 10:22:45 +0200950 for vnfd_descriptor in vnfd_descriptor_list:
951 if vnfd_descriptor["id"] == str(vnfd["id"]):
952 break
953
tierno41a69812018-02-16 14:34:33 +0100954 # table ip_profiles (ip-profiles)
955 ip_profile_name2db_table_index = {}
956 for ip_profile in vnfd.get("ip-profiles").itervalues():
957 db_ip_profile = {
958 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
959 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
960 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
961 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
962 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
963 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
964 }
965 dns_list = []
966 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
967 dns_list.append(str(dns.get("address")))
968 db_ip_profile["dns_address"] = ";".join(dns_list)
969 if ip_profile["ip-profile-params"].get('security-group'):
970 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
971 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
972 db_ip_profiles_index += 1
973 db_ip_profiles.append(db_ip_profile)
974
tiernof1ba57e2017-09-07 12:23:19 +0200975 # table nets (internal-vld)
976 net_id2uuid = {} # for mapping interface with network
977 for vld in vnfd.get("internal-vld").itervalues():
978 net_uuid = str(uuid4())
979 uuid_list.append(net_uuid)
980 db_net = {
981 "name": get_str(vld, "name", 255),
982 "vnf_id": vnf_uuid,
983 "uuid": net_uuid,
984 "description": get_str(vld, "description", 255),
tierno1df468d2018-07-06 14:25:16 +0200985 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +0200986 "type": "bridge", # TODO adjust depending on connection point type
987 }
988 net_id2uuid[vld.get("id")] = net_uuid
989 db_nets.append(db_net)
tierno41a69812018-02-16 14:34:33 +0100990 # ip-profile, link db_ip_profile with db_sce_net
991 if vld.get("ip-profile-ref"):
992 ip_profile_name = vld.get("ip-profile-ref")
993 if ip_profile_name not in ip_profile_name2db_table_index:
994 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
995 "'{}'. Reference to a non-existing 'ip_profiles'".format(
996 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100997 httperrors.Bad_Request)
tierno41a69812018-02-16 14:34:33 +0100998 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
999 else: #check no ip-address has been defined
tierno45140f52018-03-26 12:11:46 +02001000 for icp in vld.get("internal-connection-point").itervalues():
tierno41a69812018-02-16 14:34:33 +01001001 if icp.get("ip-address"):
1002 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
1003 "contains an ip-address but no ip-profile has been defined at VLD".format(
1004 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001005 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001006
tiernocf596692017-11-20 15:47:51 +01001007 # connection points vaiable declaration
1008 cp_name2iface_uuid = {}
1009 cp_name2vm_uuid = {}
1010 cp_name2db_interface = {}
tiernob6990792018-11-13 10:37:42 +01001011 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
tiernocf596692017-11-20 15:47:51 +01001012
tiernof1ba57e2017-09-07 12:23:19 +02001013 # table vms (vdus)
1014 vdu_id2uuid = {}
1015 vdu_id2db_table_index = {}
1016 for vdu in vnfd.get("vdu").itervalues():
tierno41a69812018-02-16 14:34:33 +01001017
1018 for vdu_descriptor in vnfd_descriptor["vdu"]:
1019 if vdu_descriptor["id"] == str(vdu["id"]):
1020 break
tiernof1ba57e2017-09-07 12:23:19 +02001021 vm_uuid = str(uuid4())
1022 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +01001023 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +02001024 db_vm = {
1025 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +01001026 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +02001027 "name": get_str(vdu, "name", 255),
1028 "description": get_str(vdu, "description", 255),
tiernob6990792018-11-13 10:37:42 +01001029 "pdu_type": get_str(vdu, "pdu-type", 255),
tiernof1ba57e2017-09-07 12:23:19 +02001030 "vnf_id": vnf_uuid,
1031 }
1032 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
1033 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
1034 if vdu.get("count"):
1035 db_vm["count"] = int(vdu["count"])
1036
1037 # table image
1038 image_present = False
1039 if vdu.get("image"):
1040 image_present = True
1041 db_image = {}
1042 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
1043 if not image_uuid:
1044 image_uuid = db_image["uuid"]
1045 db_images.append(db_image)
1046 db_vm["image_id"] = image_uuid
tierno16e3dd42018-04-24 12:52:40 +02001047 if vdu.get("alternative-images"):
1048 vm_alternative_images = []
1049 for alt_image in vdu.get("alternative-images").itervalues():
1050 db_image = {}
1051 image_uuid = _lookfor_or_create_image(db_image, mydb, alt_image)
1052 if not image_uuid:
1053 image_uuid = db_image["uuid"]
1054 db_images.append(db_image)
1055 vm_alternative_images.append({
1056 "image_id": image_uuid,
1057 "vim_type": str(alt_image["vim-type"]),
1058 # "universal_name": str(alt_image["image"]),
1059 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1060 })
1061
1062 db_vm["image_list"] = yaml.safe_dump(vm_alternative_images, default_flow_style=True, width=256)
tiernof1ba57e2017-09-07 12:23:19 +02001063
1064 # volumes
1065 devices = []
1066 if vdu.get("volumes"):
tierno1df468d2018-07-06 14:25:16 +02001067 for volume_key in vdu["volumes"]:
tiernof1ba57e2017-09-07 12:23:19 +02001068 volume = vdu["volumes"][volume_key]
1069 if not image_present:
1070 # Convert the first volume to vnfc.image
1071 image_present = True
1072 db_image = {}
1073 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
1074 if not image_uuid:
1075 image_uuid = db_image["uuid"]
1076 db_images.append(db_image)
1077 db_vm["image_id"] = image_uuid
1078 else:
1079 # Add Openmano devices
tierno1df468d2018-07-06 14:25:16 +02001080 device = {"name": str(volume.get("name"))}
tiernof1ba57e2017-09-07 12:23:19 +02001081 device["type"] = str(volume.get("device-type"))
1082 if volume.get("size"):
1083 device["size"] = int(volume["size"])
1084 if volume.get("image"):
1085 device["image name"] = str(volume["image"])
1086 if volume.get("image-checksum"):
1087 device["image checksum"] = str(volume["image-checksum"])
tierno1df468d2018-07-06 14:25:16 +02001088
tiernof1ba57e2017-09-07 12:23:19 +02001089 devices.append(device)
1090
tierno89aada42018-12-19 16:00:25 +00001091 if not db_vm.get("image_id"):
1092 if not db_vm["pdu_type"]:
1093 raise NfvoException("Not defined image for VDU")
1094 # create a fake image
1095
tierno66eba6e2017-11-10 17:09:18 +01001096 # cloud-init
1097 boot_data = {}
1098 if vdu.get("cloud-init"):
1099 boot_data["user-data"] = str(vdu["cloud-init"])
1100 elif vdu.get("cloud-init-file"):
1101 # TODO Where this file content is present???
1102 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1103 boot_data["user-data"] = str(vdu["cloud-init-file"])
1104
1105 if vdu.get("supplemental-boot-data"):
1106 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1107 boot_data['boot-data-drive'] = True
1108 if vdu["supplemental-boot-data"].get('config-file'):
1109 om_cfgfile_list = list()
1110 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
1111 # TODO Where this file content is present???
1112 cfg_source = str(custom_config_file["source"])
1113 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1114 "content": cfg_source})
1115 boot_data['config-files'] = om_cfgfile_list
1116 if boot_data:
1117 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1118
1119 db_vms.append(db_vm)
1120 db_vms_index += 1
1121
1122 # table interfaces (internal/external interfaces)
1123 flavor_epa_interfaces = []
tierno66eba6e2017-11-10 17:09:18 +01001124 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
1125 for iface in vdu.get("interface").itervalues():
1126 flavor_epa_interface = {}
1127 iface_uuid = str(uuid4())
1128 uuid_list.append(iface_uuid)
1129 db_interface = {
1130 "uuid": iface_uuid,
1131 "internal_name": get_str(iface, "name", 255),
1132 "vm_id": vm_uuid,
1133 }
1134 flavor_epa_interface["name"] = db_interface["internal_name"]
1135 if iface.get("virtual-interface").get("vpci"):
1136 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1137 flavor_epa_interface["vpci"] = db_interface["vpci"]
1138
1139 if iface.get("virtual-interface").get("bandwidth"):
1140 bps = int(iface.get("virtual-interface").get("bandwidth"))
1141 db_interface["bw"] = int(math.ceil(bps/1000000.0))
1142 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1143
1144 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1145 db_interface["type"] = "mgmt"
garciadeblas31e141b2018-10-25 18:33:19 +02001146 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno66eba6e2017-11-10 17:09:18 +01001147 db_interface["type"] = "bridge"
1148 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1149 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1150 db_interface["type"] = "data"
1151 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1152 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1153 else "yes"
1154 flavor_epa_interfaces.append(flavor_epa_interface)
1155 else:
1156 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1157 "-interface':'type':'{}'. Interface type is not supported".format(
1158 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001159 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001160
tiernoe72710b2018-07-23 16:16:00 +02001161 if iface.get("mgmt-interface"):
1162 db_interface["type"] = "mgmt"
1163
tierno66eba6e2017-11-10 17:09:18 +01001164 if iface.get("external-connection-point-ref"):
1165 try:
1166 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1167 db_interface["external_name"] = get_str(cp, "name", 255)
1168 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1169 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1170 cp_name2db_interface[db_interface["external_name"]] = db_interface
1171 for cp_descriptor in vnfd_descriptor["connection-point"]:
1172 if cp_descriptor["name"] == db_interface["external_name"]:
1173 break
1174 else:
1175 raise KeyError()
1176
1177 if vdu_id in vdu_id2cp_name:
1178 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1179 else:
1180 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1181
1182 # port security
1183 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1184 db_interface["port_security"] = 0
1185 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1186 db_interface["port_security"] = 1
1187 except KeyError:
1188 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1189 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1190 " at connection-point".format(
1191 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1192 cp=iface.get("vnfd-connection-point-ref")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001193 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001194 elif iface.get("internal-connection-point-ref"):
1195 try:
tierno41a69812018-02-16 14:34:33 +01001196 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1197 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1198 break
1199 else:
1200 raise KeyError("does not exist at vdu:internal-connection-point")
1201 icp = None
1202 icp_vld = None
tierno66eba6e2017-11-10 17:09:18 +01001203 for vld in vnfd.get("internal-vld").itervalues():
1204 for cp in vld.get("internal-connection-point").itervalues():
1205 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
tierno41a69812018-02-16 14:34:33 +01001206 if icp:
1207 raise KeyError("is referenced by more than one 'internal-vld'")
1208 icp = cp
1209 icp_vld = vld
1210 if not icp:
1211 raise KeyError("is not referenced by any 'internal-vld'")
1212
1213 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1214 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1215 db_interface["port_security"] = 0
1216 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1217 db_interface["port_security"] = 1
1218 if icp.get("ip-address"):
1219 if not icp_vld.get("ip-profile-ref"):
1220 raise NfvoException
1221 db_interface["ip_address"] = str(icp.get("ip-address"))
1222 except KeyError as e:
tierno66eba6e2017-11-10 17:09:18 +01001223 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
tierno41a69812018-02-16 14:34:33 +01001224 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1225 " {msg}".format(
tierno66eba6e2017-11-10 17:09:18 +01001226 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
tierno41a69812018-02-16 14:34:33 +01001227 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001228 httperrors.Bad_Request)
tierno55d234c2018-07-04 18:29:21 +02001229 if iface.get("position"):
1230 db_interface["created_at"] = int(iface.get("position")) * 50
tierno41a69812018-02-16 14:34:33 +01001231 if iface.get("mac-address"):
1232 db_interface["mac"] = str(iface.get("mac-address"))
tierno66eba6e2017-11-10 17:09:18 +01001233 db_interfaces.append(db_interface)
1234
tiernof1ba57e2017-09-07 12:23:19 +02001235 # table flavors
1236 db_flavor = {
1237 "name": get_str(vdu, "name", 250) + "-flv",
1238 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1239 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
garciadeblas79d1a1a2017-12-11 16:07:07 +01001240 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
tiernof1ba57e2017-09-07 12:23:19 +02001241 }
tiernocf596692017-11-20 15:47:51 +01001242 # TODO revise the case of several numa-node-policy node
tiernof1ba57e2017-09-07 12:23:19 +02001243 extended = {}
1244 numa = {}
1245 if devices:
1246 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001247 if flavor_epa_interfaces:
1248 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001249 if vdu.get("guest-epa"): # TODO or dedicated_int:
1250 epa_vcpu_set = False
1251 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1252 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1253 if numa_node_policy.get("node"):
tiernocf596692017-11-20 15:47:51 +01001254 numa_node = numa_node_policy["node"].values()[0]
tiernof1ba57e2017-09-07 12:23:19 +02001255 if numa_node.get("num-cores"):
1256 numa["cores"] = numa_node["num-cores"]
1257 epa_vcpu_set = True
1258 if numa_node.get("paired-threads"):
1259 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001260 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001261 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001262 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001263 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001264 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001265 numa["paired-threads-id"].append(
1266 (str(pair["thread-a"]), str(pair["thread-b"]))
1267 )
1268 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001269 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001270 epa_vcpu_set = True
1271 if numa_node.get("memory-mb"):
1272 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1273 if vdu["guest-epa"].get("mempage-size"):
1274 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1275 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1276 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1277 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1278 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1279 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1280 numa["cores"] = max(db_flavor["vcpus"], 1)
1281 else:
1282 numa["threads"] = max(db_flavor["vcpus"], 1)
anwarsae5f52c2019-04-22 10:35:27 +05301283 epa_vcpu_set = True
1284 if vdu["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
calvinosanch1d55a232019-08-05 11:03:46 +00001285 cpuquota = get_resource_allocation_params(vdu["guest-epa"].get("cpu-quota"))
1286 if cpuquota:
1287 extended["cpu-quota"] = cpuquota
anwarsae5f52c2019-04-22 10:35:27 +05301288 if vdu["guest-epa"].get("mem-quota"):
calvinosanch1d55a232019-08-05 11:03:46 +00001289 vduquota = get_resource_allocation_params(vdu["guest-epa"].get("mem-quota"))
1290 if vduquota:
1291 extended["mem-quota"] = vduquota
anwarsae5f52c2019-04-22 10:35:27 +05301292 if vdu["guest-epa"].get("disk-io-quota"):
calvinosanch1d55a232019-08-05 11:03:46 +00001293 diskioquota = get_resource_allocation_params(vdu["guest-epa"].get("disk-io-quota"))
1294 if diskioquota:
1295 extended["disk-io-quota"] = diskioquota
anwarsae5f52c2019-04-22 10:35:27 +05301296 if vdu["guest-epa"].get("vif-quota"):
calvinosanch1d55a232019-08-05 11:03:46 +00001297 vifquota = get_resource_allocation_params(vdu["guest-epa"].get("vif-quota"))
1298 if vifquota:
1299 extended["vif-quota"] = vifquota
tiernof1ba57e2017-09-07 12:23:19 +02001300 if numa:
1301 extended["numas"] = [numa]
1302 if extended:
1303 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1304 db_flavor["extended"] = extended_text
1305 # look if flavor exist
garciadeblas79d1a1a2017-12-11 16:07:07 +01001306 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
tiernof1ba57e2017-09-07 12:23:19 +02001307 'ram': db_flavor.get('ram'),
1308 'vcpus': db_flavor.get('vcpus'),
1309 'extended': db_flavor.get('extended')
1310 }
1311 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1312 if existing_flavors:
1313 flavor_uuid = existing_flavors[0]["uuid"]
1314 else:
1315 flavor_uuid = str(uuid4())
1316 uuid_list.append(flavor_uuid)
1317 db_flavor["uuid"] = flavor_uuid
1318 db_flavors.append(db_flavor)
1319 db_vm["flavor_id"] = flavor_uuid
1320
tiernof1ba57e2017-09-07 12:23:19 +02001321 # VNF affinity and antiaffinity
1322 for pg in vnfd.get("placement-groups").itervalues():
1323 pg_name = get_str(pg, "name", 255)
1324 for vdu in pg.get("member-vdus").itervalues():
1325 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1326 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001327 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1328 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001329 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001330 httperrors.Bad_Request)
tierno55fe3972019-03-29 08:50:12 +00001331 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
tiernof1ba57e2017-09-07 12:23:19 +02001332 # TODO consider the case of isolation and not colocation
1333 # if pg.get("strategy") == "ISOLATION":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001334
tiernof1ba57e2017-09-07 12:23:19 +02001335 # VNF mgmt configuration
1336 mgmt_access = {}
1337 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001338 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1339 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001340 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1341 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001342 vnf=vnfd_id, vdu=mgmt_vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001343 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001344 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001345 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1346 if vdu_id2cp_name.get(mgmt_vdu_id):
tiernob6990792018-11-13 10:37:42 +01001347 if cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]:
1348 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
tierno66eba6e2017-11-10 17:09:18 +01001349
tiernof1ba57e2017-09-07 12:23:19 +02001350 if vnfd["mgmt-interface"].get("ip-address"):
1351 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1352 if vnfd["mgmt-interface"].get("cp"):
1353 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob6990792018-11-13 10:37:42 +01001354 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
tiernob2880eb2017-10-04 15:04:53 +02001355 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001356 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001357 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001358 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1359 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001360 # mark this interface as of type mgmt
tiernob6990792018-11-13 10:37:42 +01001361 if cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]:
1362 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
tiernoe2ff1ce2017-11-02 17:01:10 +01001363
tiernoa9550202017-09-22 13:31:35 +02001364 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001365 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001366
tiernof1ba57e2017-09-07 12:23:19 +02001367 if default_user:
1368 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001369 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1370 "required", 6)
1371 if required:
1372 mgmt_access["required"] = required
1373
tiernof1ba57e2017-09-07 12:23:19 +02001374 if mgmt_access:
1375 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1376
1377 db_vnfs.append(db_vnf)
1378 db_tables=[
1379 {"vnfs": db_vnfs},
1380 {"nets": db_nets},
1381 {"images": db_images},
1382 {"flavors": db_flavors},
tierno41a69812018-02-16 14:34:33 +01001383 {"ip_profiles": db_ip_profiles},
tiernof1ba57e2017-09-07 12:23:19 +02001384 {"vms": db_vms},
1385 {"interfaces": db_interfaces},
1386 ]
1387
1388 logger.debug("create_vnf Deployment done vnfDict: %s",
1389 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1390 mydb.new_rows(db_tables, uuid_list)
1391 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001392 except NfvoException:
1393 raise
tiernof1ba57e2017-09-07 12:23:19 +02001394 except Exception as e:
1395 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001396 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001397
1398
tiernob8569aa2018-08-24 11:34:54 +02001399@deprecated("Use new_vnfd_v3")
tierno7edb6752016-03-21 17:37:52 +01001400def new_vnf(mydb, tenant_id, vnf_descriptor):
1401 global global_config
tierno42026a02017-02-10 15:13:40 +01001402
tierno7edb6752016-03-21 17:37:52 +01001403 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001404 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001405 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001406 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001407 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001408 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001409 if "tenant_id" in vnf_descriptor["vnf"]:
1410 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001411 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 +01001412 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001413 else:
1414 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1415 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001416 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001417 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001418
1419 # Step 4. Review the descriptor and add missing fields
1420 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001421 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001422 vnf_name = vnf_descriptor['vnf']['name']
1423 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1424 if "physical" in vnf_descriptor['vnf']:
1425 del vnf_descriptor['vnf']['physical']
1426 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001427
tierno42026a02017-02-10 15:13:40 +01001428 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001429 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1430 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001431
tierno7edb6752016-03-21 17:37:52 +01001432 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1433 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1434 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001435 try:
tiernof97fd272016-07-11 14:32:37 +02001436 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001437 for vnfc in vnf_descriptor['vnf']['VNFC']:
1438 VNFCitem={}
1439 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001440 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001441 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001442
tiernof97fd272016-07-11 14:32:37 +02001443 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001444
tierno7edb6752016-03-21 17:37:52 +01001445 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001446 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 +01001447 myflavorDict["description"] = VNFCitem["description"]
1448 myflavorDict["ram"] = vnfc.get("ram", 0)
1449 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001450 myflavorDict["disk"] = vnfc.get("disk", 0)
tierno7edb6752016-03-21 17:37:52 +01001451 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001452
tierno7edb6752016-03-21 17:37:52 +01001453 devices = vnfc.get("devices")
1454 if devices != None:
1455 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001456
tierno7edb6752016-03-21 17:37:52 +01001457 # TODO:
1458 # 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 +01001459 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1460
tierno7edb6752016-03-21 17:37:52 +01001461 # Previous code has been commented
1462 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1463 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1464 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1465 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1466 #else:
1467 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1468 # if result2:
1469 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001470 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
tierno7edb6752016-03-21 17:37:52 +01001471 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001472 # 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 +01001473 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001474
tierno7edb6752016-03-21 17:37:52 +01001475 if 'numas' in vnfc and len(vnfc['numas'])>0:
1476 myflavorDict['extended']['numas'] = vnfc['numas']
1477
1478 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001479
tierno7edb6752016-03-21 17:37:52 +01001480 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001481 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001482
tiernof97fd272016-07-11 14:32:37 +02001483 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001484 VNFCitem["flavor_id"] = flavor_id
1485 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001486
tiernof97fd272016-07-11 14:32:37 +02001487 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001488 # Step 6.3 New images are created in the VIM
1489 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001490 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001491 #In case this integration is made, the VNFCDict might become a VNFClist.
1492 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001493 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001494 image_dict={}
1495 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1496 image_dict['universal_name']=vnfc.get('image name')
1497 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1498 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001499 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001500 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001501 image_metadata_dict = vnfc.get('image metadata', None)
1502 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001503 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001504 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1505 image_dict['metadata']=image_metadata_str
1506 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001507 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1508 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001509 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001510 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001511 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001512 if vnfc.get("boot-data"):
1513 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001514
tierno42026a02017-02-10 15:13:40 +01001515
tiernof97fd272016-07-11 14:32:37 +02001516 # Step 7. Storing the VNF descriptor in the repository
1517 if "descriptor" not in vnf_descriptor["vnf"]:
1518 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001519
tiernof97fd272016-07-11 14:32:37 +02001520 # Step 8. Adding the VNF to the NFVO DB
1521 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1522 return vnf_id
1523 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001524 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001525 if isinstance(e, db_base_Exception):
1526 error_text = "Exception at database"
1527 elif isinstance(e, KeyError):
1528 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001529 e.http_code = httperrors.Internal_Server_Error
tiernof97fd272016-07-11 14:32:37 +02001530 else:
1531 error_text = "Exception at VIM"
1532 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1533 #logger.error("start_scenario %s", error_text)
1534 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001535
tiernob3d36742017-03-03 23:51:05 +01001536
tiernob8569aa2018-08-24 11:34:54 +02001537@deprecated("Use new_vnfd_v3")
garciadeblas9f8456e2016-09-05 05:02:59 +02001538def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1539 global global_config
tierno42026a02017-02-10 15:13:40 +01001540
garciadeblas9f8456e2016-09-05 05:02:59 +02001541 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001542 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001543 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001544 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001545 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001546 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001547 if "tenant_id" in vnf_descriptor["vnf"]:
1548 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1549 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 +01001550 httperrors.Unauthorized)
garciadeblas9f8456e2016-09-05 05:02:59 +02001551 else:
1552 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1553 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001554 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001555 vims = get_vim(mydb, tenant_id, ignore_errors=True)
garciadeblas9f8456e2016-09-05 05:02:59 +02001556
1557 # Step 4. Review the descriptor and add missing fields
1558 #print vnf_descriptor
1559 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1560 vnf_name = vnf_descriptor['vnf']['name']
1561 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1562 if "physical" in vnf_descriptor['vnf']:
1563 del vnf_descriptor['vnf']['physical']
1564 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001565
tierno42026a02017-02-10 15:13:40 +01001566 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001567 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1568 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001569
garciadeblas9f8456e2016-09-05 05:02:59 +02001570 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1571 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1572 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1573 try:
1574 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1575 for vnfc in vnf_descriptor['vnf']['VNFC']:
1576 VNFCitem={}
1577 VNFCitem["name"] = vnfc['name']
1578 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001579
garciadeblas9f8456e2016-09-05 05:02:59 +02001580 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001581
garciadeblas9f8456e2016-09-05 05:02:59 +02001582 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001583 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 +02001584 myflavorDict["description"] = VNFCitem["description"]
1585 myflavorDict["ram"] = vnfc.get("ram", 0)
1586 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001587 myflavorDict["disk"] = vnfc.get("disk", 0)
garciadeblas9f8456e2016-09-05 05:02:59 +02001588 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001589
garciadeblas9f8456e2016-09-05 05:02:59 +02001590 devices = vnfc.get("devices")
1591 if devices != None:
1592 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001593
garciadeblas9f8456e2016-09-05 05:02:59 +02001594 # TODO:
1595 # 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 +01001596 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1597
garciadeblas9f8456e2016-09-05 05:02:59 +02001598 # Previous code has been commented
1599 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1600 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1601 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1602 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1603 #else:
1604 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1605 # if result2:
1606 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001607 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
garciadeblas9f8456e2016-09-05 05:02:59 +02001608 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001609 # 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 +02001610 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001611
garciadeblas9f8456e2016-09-05 05:02:59 +02001612 if 'numas' in vnfc and len(vnfc['numas'])>0:
1613 myflavorDict['extended']['numas'] = vnfc['numas']
1614
1615 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001616
garciadeblas9f8456e2016-09-05 05:02:59 +02001617 # Step 6.2 New flavors are created in the VIM
1618 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1619
1620 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1621 VNFCitem["flavor_id"] = flavor_id
1622 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001623
garciadeblas9f8456e2016-09-05 05:02:59 +02001624 logger.debug("Creating new images in the VIM for each VNFC")
1625 # Step 6.3 New images are created in the VIM
1626 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001627 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001628 #In case this integration is made, the VNFCDict might become a VNFClist.
1629 for vnfc in vnf_descriptor['vnf']['VNFC']:
1630 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001631 image_dict={}
1632 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1633 image_dict['universal_name']=vnfc.get('image name')
1634 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1635 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001636 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001637 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001638 image_metadata_dict = vnfc.get('image metadata', None)
1639 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001640 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001641 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1642 image_dict['metadata']=image_metadata_str
1643 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1644 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1645 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1646 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001647 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001648 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001649 if vnfc.get("boot-data"):
1650 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001651
garciadeblas9f8456e2016-09-05 05:02:59 +02001652 # Step 7. Storing the VNF descriptor in the repository
1653 if "descriptor" not in vnf_descriptor["vnf"]:
1654 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001655
garciadeblas9f8456e2016-09-05 05:02:59 +02001656 # Step 8. Adding the VNF to the NFVO DB
1657 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1658 return vnf_id
1659 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1660 _, message = rollback(mydb, vims, rollback_list)
1661 if isinstance(e, db_base_Exception):
1662 error_text = "Exception at database"
1663 elif isinstance(e, KeyError):
1664 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001665 e.http_code = httperrors.Internal_Server_Error
garciadeblas9f8456e2016-09-05 05:02:59 +02001666 else:
1667 error_text = "Exception at VIM"
1668 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1669 #logger.error("start_scenario %s", error_text)
1670 raise NfvoException(error_text, e.http_code)
1671
tiernob3d36742017-03-03 23:51:05 +01001672
tierno7edb6752016-03-21 17:37:52 +01001673def get_vnf_id(mydb, tenant_id, vnf_id):
1674 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001675 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001676 #obtain data
1677 where_or = {}
1678 if tenant_id != "any":
1679 where_or["tenant_id"] = tenant_id
1680 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001681 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1682
tiernof1ba57e2017-09-07 12:23:19 +02001683 vnf_id = vnf["uuid"]
1684 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001685 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001686 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1687 data={'vnf' : filtered_content}
1688 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001689 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001690 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1691 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001692 WHERE={'vnfs.uuid': vnf_id} )
gcalvinobfa2fd92018-11-13 18:47:28 +01001693 if len(content) != 0:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00001694 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001695 # change boot_data into boot-data
gcalvino319b8a52018-11-05 15:33:23 +01001696 for vm in content:
1697 if vm.get("boot_data"):
1698 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1699 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001700
gcalvinobfa2fd92018-11-13 18:47:28 +01001701 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001702 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001703
tierno7edb6752016-03-21 17:37:52 +01001704 #GET NET
tierno42026a02017-02-10 15:13:40 +01001705 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001706 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1707 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001708 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001709
1710 #GET ip-profile for each net
1711 for net in data['vnf']['nets']:
1712 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1713 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1714 WHERE={'net_id': net["uuid"]} )
1715 if len(ipprofiles)==1:
1716 net["ip_profile"] = ipprofiles[0]
1717 elif len(ipprofiles)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001718 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 +01001719
1720
garciadeblas9f8456e2016-09-05 05:02:59 +02001721 #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 +01001722
garciadeblas9f8456e2016-09-05 05:02:59 +02001723 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001724 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 +01001725 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1726 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001727 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001728 #print content
tiernof97fd272016-07-11 14:32:37 +02001729 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001730
tiernof97fd272016-07-11 14:32:37 +02001731 return data
tierno7edb6752016-03-21 17:37:52 +01001732
1733
1734def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1735 # Check tenant exist
1736 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001737 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001738 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernocbb52052018-05-31 18:57:30 +02001739 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001740 else:
1741 vims={}
1742
1743 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1744 where_or = {}
1745 if tenant_id != "any":
1746 where_or["tenant_id"] = tenant_id
1747 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001748 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 +02001749 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001750
tierno7edb6752016-03-21 17:37:52 +01001751 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001752 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001753 if len(flavorList)==0:
1754 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001755
tiernof97fd272016-07-11 14:32:37 +02001756 imageList = get_imagelist(mydb, vnf_id)
1757 if len(imageList)==0:
1758 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001759
tiernof97fd272016-07-11 14:32:37 +02001760 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1761 if deleted == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001762 raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno42026a02017-02-10 15:13:40 +01001763
tierno7edb6752016-03-21 17:37:52 +01001764 undeletedItems = []
1765 for flavor in flavorList:
1766 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001767 try:
1768 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1769 if len(c) > 0:
1770 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1771 continue
1772 #flavor not used, must be deleted
1773 #delelte at VIM
tierno96ebf002017-12-13 10:55:38 +01001774 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
tierno7edb6752016-03-21 17:37:52 +01001775 for flavor_vim in c:
tierno96ebf002017-12-13 10:55:38 +01001776 if not flavor_vim['created']: # skip this flavor because not created by openmano
tierno7edb6752016-03-21 17:37:52 +01001777 continue
tierno96ebf002017-12-13 10:55:38 +01001778 # look for vim
1779 myvim = None
1780 for vim in vims.values():
1781 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1782 myvim = vim
1783 break
1784 if not myvim:
tierno7edb6752016-03-21 17:37:52 +01001785 continue
tiernoae4a8d12016-07-08 12:30:39 +02001786 try:
1787 myvim.delete_flavor(flavor_vim["vim_id"])
tierno96ebf002017-12-13 10:55:38 +01001788 except vimconn.vimconnNotFoundException:
1789 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1790 flavor_vim["datacenter_vim_id"] )
tiernoae4a8d12016-07-08 12:30:39 +02001791 except vimconn.vimconnException as e:
1792 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
tierno96ebf002017-12-13 10:55:38 +01001793 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1794 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1795 flavor_vim["datacenter_vim_id"]))
1796 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
tiernof97fd272016-07-11 14:32:37 +02001797 mydb.delete_row_by_id('flavors', flavor)
1798 except db_base_Exception as e:
1799 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno96ebf002017-12-13 10:55:38 +01001800 undeletedItems.append("flavor {}".format(flavor))
tiernof97fd272016-07-11 14:32:37 +02001801
tierno42026a02017-02-10 15:13:40 +01001802
tierno7edb6752016-03-21 17:37:52 +01001803 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001804 try:
1805 #check if image is used by other vnf
tierno16e3dd42018-04-24 12:52:40 +02001806 c = mydb.get_rows(FROM='vms', WHERE=[{'image_id': image}, {'image_list LIKE ': '%' + image + '%'}])
tiernof97fd272016-07-11 14:32:37 +02001807 if len(c) > 0:
1808 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1809 continue
1810 #image not used, must be deleted
1811 #delelte at VIM
1812 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001813 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001814 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001815 continue
1816 if image_vim['created']=='false': #skip this image because not created by openmano
1817 continue
1818 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001819 try:
1820 myvim.delete_image(image_vim["vim_id"])
1821 except vimconn.vimconnNotFoundException as e:
1822 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1823 except vimconn.vimconnException as e:
1824 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1825 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1826 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001827 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1828 mydb.delete_row_by_id('images', image)
1829 except db_base_Exception as e:
1830 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001831 undeletedItems.append("image %s" % image)
1832
tiernof97fd272016-07-11 14:32:37 +02001833 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001834 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001835 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001836
tiernob3d36742017-03-03 23:51:05 +01001837
tiernob8569aa2018-08-24 11:34:54 +02001838@deprecated("Not used")
tierno7edb6752016-03-21 17:37:52 +01001839def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1840 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1841 if result < 0:
1842 return result, vims
1843 elif result == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001844 return -httperrors.Not_Found, "datacenter '%s' not found" % datacenter_name
tierno7edb6752016-03-21 17:37:52 +01001845 myvim = vims.values()[0]
1846 result,servers = myvim.get_hosts_info()
1847 if result < 0:
1848 return result, servers
1849 topology = {'name':myvim['name'] , 'servers': servers}
1850 return result, topology
1851
tiernob3d36742017-03-03 23:51:05 +01001852
tierno7edb6752016-03-21 17:37:52 +01001853def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001854 vims = get_vim(mydb, nfvo_tenant_id)
1855 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001856 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001857 elif len(vims)>1:
1858 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001859 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001860 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001861 try:
1862 hosts = myvim.get_hosts()
1863 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001864
tiernof97fd272016-07-11 14:32:37 +02001865 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1866 for host in hosts:
1867 server={'name':host['name'], 'vms':[]}
1868 for vm in host['instances']:
1869 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001870 try:
tiernof97fd272016-07-11 14:32:37 +02001871 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1872 WHERE={'vim_vm_id':vm['id']} )
1873 if len(c) == 0:
1874 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1875 continue
1876 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001877
tiernof97fd272016-07-11 14:32:37 +02001878 except db_base_Exception as e:
1879 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1880 datacenter['Datacenters'][0]['servers'].append(server)
1881 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001882
tiernof97fd272016-07-11 14:32:37 +02001883 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1884 return datacenter
1885 except vimconn.vimconnException as e:
1886 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001887
tiernob3d36742017-03-03 23:51:05 +01001888
tiernob8569aa2018-08-24 11:34:54 +02001889@deprecated("Use new_nsd_v3")
tierno7edb6752016-03-21 17:37:52 +01001890def new_scenario(mydb, tenant_id, topo):
1891
1892# result, vims = get_vim(mydb, tenant_id)
1893# if result < 0:
1894# return result, vims
1895#1: parse input
1896 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001897 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001898 if "tenant_id" in topo:
1899 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001900 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 +01001901 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001902 else:
1903 tenant_id=None
1904
tierno42026a02017-02-10 15:13:40 +01001905#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001906 vnfs={}
1907 other_nets={} #external_networks, bridge_networks and data_networkds
1908 nodes = topo['topology']['nodes']
1909 for k in nodes.keys():
1910 if nodes[k]['type'] == 'VNF':
1911 vnfs[k] = nodes[k]
1912 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001913 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001914 other_nets[k] = nodes[k]
1915 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001916 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001917 other_nets[k] = nodes[k]
1918 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001919
tierno7edb6752016-03-21 17:37:52 +01001920
1921#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1922 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001923 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001924 error_text = ""
1925 error_pos = "'topology':'nodes':'" + name + "'"
1926 if 'vnf_id' in vnf:
1927 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001928 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001929 if 'VNF model' in vnf:
1930 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001931 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001932 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001933 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001934
tiernocea279c2016-07-18 12:36:49 +02001935 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1936 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001937 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001938 if len(vnf_db)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001939 raise NfvoException("unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001940 elif len(vnf_db)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001941 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001942 vnf['uuid']=vnf_db[0]['uuid']
1943 vnf['description']=vnf_db[0]['description']
1944 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001945 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1946 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 +02001947 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001948 for ext_iface in ext_ifaces:
1949 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1950
1951#1.4 get list of connections
1952 conections = topo['topology']['connections']
1953 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001954 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001955 for k in conections.keys():
1956 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1957 ifaces_list = conections[k]['nodes'].items()
1958 elif type(conections[k]['nodes'])==list: #list with dictionary
1959 ifaces_list=[]
1960 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1961 for k2 in conection_pair_list:
1962 ifaces_list += k2
1963
1964 con_type = conections[k].get("type", "link")
1965 if con_type != "link":
1966 if k in other_nets:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001967 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001968 other_nets[k] = {'external': False}
1969 if conections[k].get("graph"):
1970 other_nets[k]["graph"] = conections[k]["graph"]
1971 ifaces_list.append( (k, None) )
1972
tierno42026a02017-02-10 15:13:40 +01001973
tierno7edb6752016-03-21 17:37:52 +01001974 if con_type == "external_network":
1975 other_nets[k]['external'] = True
1976 if conections[k].get("model"):
1977 other_nets[k]["model"] = conections[k]["model"]
1978 else:
1979 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001980 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001981 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001982
tiernoefd80c92016-09-16 14:17:46 +02001983 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001984 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)
1985 #print set(ifaces_list)
1986 #check valid VNF and iface names
1987 for iface in ifaces_list:
1988 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001989 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001990 str(k), iface[0]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001991 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001992 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001993 str(k), iface[0], iface[1]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001994
1995#1.5 unify connections from the pair list to a consolidated list
1996 index=0
1997 while index < len(conections_list):
1998 index2 = index+1
1999 while index2 < len(conections_list):
2000 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
2001 conections_list[index] |= conections_list[index2]
2002 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02002003 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01002004 else:
2005 index2 += 1
2006 conections_list[index] = list(conections_list[index]) # from set to list again
2007 index += 1
2008 #for k in conections_list:
2009 # print k
tierno42026a02017-02-10 15:13:40 +01002010
tierno7edb6752016-03-21 17:37:52 +01002011
2012
2013#1.6 Delete non external nets
2014# for k in other_nets.keys():
2015# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
2016# for con in conections_list:
2017# delete_indexes=[]
2018# for index in range(0,len(con)):
2019# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
2020# for index in delete_indexes:
2021# del con[index]
2022# del other_nets[k]
2023#1.7: Check external_ports are present at database table datacenter_nets
2024 for k,net in other_nets.items():
2025 error_pos = "'topology':'nodes':'" + k + "'"
2026 if net['external']==False:
2027 if 'name' not in net:
2028 net['name']=k
2029 if 'model' not in net:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002030 raise NfvoException("needed a 'model' at " + error_pos, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002031 if net['model']=='bridge_net':
2032 net['type']='bridge';
2033 elif net['model']=='dataplane_net':
2034 net['type']='data';
2035 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002036 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002037 else: #external
2038#IF we do not want to check that external network exist at datacenter
2039 pass
tierno42026a02017-02-10 15:13:40 +01002040#ELSE
tierno7edb6752016-03-21 17:37:52 +01002041# error_text = ""
2042# WHERE_={}
2043# if 'net_id' in net:
2044# error_text += " 'net_id' " + net['net_id']
2045# WHERE_['uuid'] = net['net_id']
2046# if 'model' in net:
2047# error_text += " 'model' " + net['model']
2048# WHERE_['name'] = net['model']
2049# if len(WHERE_) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002050# return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002051# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2052# FROM='datacenter_nets', WHERE=WHERE_ )
2053# if r<0:
2054# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2055# elif r==0:
2056# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002057# return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002058# elif r>1:
tierno42026a02017-02-10 15:13:40 +01002059# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002060# 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 +01002061# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01002062#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002063 net_list={}
2064 net_nb=0 #Number of nets
2065 for con in conections_list:
2066 #check if this is connected to a external net
2067 other_net_index=-1
2068 #print
2069 #print "con", con
2070 for index in range(0,len(con)):
2071 #check if this is connected to a external net
2072 for net_key in other_nets.keys():
2073 if con[index][0]==net_key:
2074 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01002075 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 +02002076 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002077 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002078 else:
2079 other_net_index = index
2080 net_target = net_key
2081 break
2082 #print "other_net_index", other_net_index
2083 try:
2084 if other_net_index>=0:
2085 del con[other_net_index]
2086#IF we do not want to check that external network exist at datacenter
2087 if other_nets[net_target]['external'] :
2088 if "name" not in other_nets[net_target]:
2089 other_nets[net_target]['name'] = other_nets[net_target]['model']
2090 if other_nets[net_target]["type"] == "external_network":
2091 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
2092 other_nets[net_target]["type"] = "data"
2093 else:
2094 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01002095#ELSE
tierno7edb6752016-03-21 17:37:52 +01002096# if other_nets[net_target]['external'] :
2097# 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
2098# if type_=='data' and other_nets[net_target]['type']=="ptp":
2099# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2100# print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002101# return -httperrors.Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01002102#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002103 for iface in con:
2104 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2105 else:
2106 #create a net
2107 net_type_bridge=False
2108 net_type_data=False
2109 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01002110 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02002111 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01002112 'external':False}
tierno7edb6752016-03-21 17:37:52 +01002113 for iface in con:
2114 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2115 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
2116 if iface_type=='mgmt' or iface_type=='bridge':
2117 net_type_bridge = True
2118 else:
2119 net_type_data = True
2120 if net_type_bridge and net_type_data:
2121 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 +02002122 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002123 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002124 elif net_type_bridge:
2125 type_='bridge'
2126 else:
2127 type_='data' if len(con)>2 else 'ptp'
2128 net_list[net_target]['type'] = type_
2129 net_nb+=1
2130 except Exception:
2131 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02002132 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01002133 #raise e
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002134 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002135
2136#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01002137 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02002138 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01002139 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01002140 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02002141 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01002142 add_mgmt_net = False
2143 for vnf in vnfs.values():
2144 for iface in vnf['ifaces'].values():
2145 if iface['type']=='mgmt' and 'net_key' not in iface:
2146 #iface not connected
2147 iface['net_key'] = 'mgmt'
2148 add_mgmt_net = True
2149 if add_mgmt_net and 'mgmt' not in net_list:
2150 net_list['mgmt']=mgmt_net[0]
2151 net_list['mgmt']['external']=True
2152 net_list['mgmt']['graph']={'visible':False}
2153
2154 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02002155 #print
2156 #print 'net_list', net_list
2157 #print
2158 #print 'vnfs', vnfs
2159 #print
tierno7edb6752016-03-21 17:37:52 +01002160
2161#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02002162 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02002163 'tenant_id':tenant_id, 'name':topo['name'],
2164 'description':topo.get('description',topo['name']),
2165 'public': topo.get('public', False)
2166 })
tierno42026a02017-02-10 15:13:40 +01002167
tiernof97fd272016-07-11 14:32:37 +02002168 return c
tierno7edb6752016-03-21 17:37:52 +01002169
tiernob3d36742017-03-03 23:51:05 +01002170
tiernob8569aa2018-08-24 11:34:54 +02002171@deprecated("Use new_nsd_v3")
tierno5bb59dc2017-02-13 14:53:54 +01002172def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2173 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02002174 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01002175 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01002176 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002177 if "tenant_id" in scenario:
2178 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01002179 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02002180 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002181 scenario["tenant_id"], tenant_id), httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01002182 else:
2183 tenant_id=None
2184
tierno5bb59dc2017-02-13 14:53:54 +01002185 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01002186 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02002187 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01002188 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02002189 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01002190 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002191 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02002192 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02002193 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002194 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02002195 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02002196 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002197 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002198 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002199 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002200 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002201 if len(vnf_db) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002202 raise NfvoException("Unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002203 elif len(vnf_db) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002204 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002205 vnf['uuid'] = vnf_db[0]['uuid']
2206 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002207 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002208 # get external interfaces
2209 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2210 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 +02002211 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002212 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002213 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2214 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002215
tierno5bb59dc2017-02-13 14:53:54 +01002216 # 2: Insert net_key and ip_address at every vnf interface
2217 for net_name, net in scenario["networks"].items():
2218 net_type_bridge = False
2219 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002220 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002221 if version == "0.2":
2222 temp_dict = iface_dict
2223 ip_address = None
2224 elif version == "0.3":
2225 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2226 ip_address = iface_dict.get('ip_address', None)
2227 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002228 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002229 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2230 net_name, vnf)
2231 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002232 raise NfvoException(error_text, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002233 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002234 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2235 .format(net_name, iface)
2236 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002237 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002238 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002239 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2240 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2241 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002242 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002243 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002244 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002245 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002246 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002247 net_type_bridge = True
2248 else:
2249 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002250
tierno7edb6752016-03-21 17:37:52 +01002251 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002252 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2253 .format(net_name)
2254 # logger.debug("nfvo.new_scenario " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002255 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002256 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002257 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002258 else:
tierno5bb59dc2017-02-13 14:53:54 +01002259 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2260
2261 if net.get("implementation"): # for v0.3
2262 if type_ == "bridge" and net["implementation"] == "underlay":
2263 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2264 "'network':'{}'".format(net_name)
2265 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002266 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002267 elif type_ != "bridge" and net["implementation"] == "overlay":
2268 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2269 "'network':'{}'".format(net_name)
2270 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002271 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002272 net.pop("implementation")
2273 if "type" in net and version == "0.3": # for v0.3
2274 if type_ == "data" and net["type"] == "e-line":
2275 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2276 "'e-line' at 'network':'{}'".format(net_name)
2277 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002278 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002279 elif type_ == "ptp" and net["type"] == "e-lan":
2280 type_ = "data"
2281
tierno7edb6752016-03-21 17:37:52 +01002282 net['type'] = type_
2283 net['name'] = net_name
2284 net['external'] = net.get('external', False)
2285
tierno5bb59dc2017-02-13 14:53:54 +01002286 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002287 scenario["nets"] = scenario["networks"]
2288 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002289 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002290 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002291
tiernob3d36742017-03-03 23:51:05 +01002292
tiernof1ba57e2017-09-07 12:23:19 +02002293def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2294 """
2295 Parses an OSM IM nsd_catalog and insert at DB
2296 :param mydb:
2297 :param tenant_id:
2298 :param nsd_descriptor:
Igor D.Ccaadc442017-11-06 12:48:48 +00002299 :return: The list of created NSD ids
tiernof1ba57e2017-09-07 12:23:19 +02002300 """
2301 try:
2302 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002303 try:
tiernof6bbe222019-04-09 14:19:40 +00002304 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd, skip_unknown=True)
tiernoa9550202017-09-22 13:31:35 +02002305 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002306 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002307 db_scenarios = []
2308 db_sce_nets = []
2309 db_sce_vnfs = []
2310 db_sce_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002311 db_sce_vnffgs = []
2312 db_sce_rsps = []
2313 db_sce_rsp_hops = []
2314 db_sce_classifiers = []
2315 db_sce_classifier_matches = []
tiernof1ba57e2017-09-07 12:23:19 +02002316 db_ip_profiles = []
2317 db_ip_profiles_index = 0
2318 uuid_list = []
2319 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002320 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2321 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002322
Igor D.Ccaadc442017-11-06 12:48:48 +00002323 # table scenarios
tiernof1ba57e2017-09-07 12:23:19 +02002324 scenario_uuid = str(uuid4())
2325 uuid_list.append(scenario_uuid)
2326 nsd_uuid_list.append(scenario_uuid)
2327 db_scenario = {
2328 "uuid": scenario_uuid,
2329 "osm_id": get_str(nsd, "id", 255),
2330 "name": get_str(nsd, "name", 255),
2331 "description": get_str(nsd, "description", 255),
2332 "tenant_id": tenant_id,
2333 "vendor": get_str(nsd, "vendor", 255),
2334 "short_name": get_str(nsd, "short-name", 255),
2335 "descriptor": str(nsd_descriptor)[:60000],
2336 }
2337 db_scenarios.append(db_scenario)
2338
2339 # table sce_vnfs (constituent-vnfd)
2340 vnf_index2scevnf_uuid = {}
2341 vnf_index2vnf_uuid = {}
2342 for vnf in nsd.get("constituent-vnfd").itervalues():
2343 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2344 'tenant_id': tenant_id})
2345 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002346 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2347 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2348 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002349 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002350 sce_vnf_uuid = str(uuid4())
2351 uuid_list.append(sce_vnf_uuid)
2352 db_sce_vnf = {
2353 "uuid": sce_vnf_uuid,
2354 "scenario_id": scenario_uuid,
tierno92c36fd2018-05-04 12:21:10 +02002355 # "name": get_str(vnf, "member-vnf-index", 255),
2356 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 50),
tiernof1ba57e2017-09-07 12:23:19 +02002357 "vnf_id": existing_vnf[0]["uuid"],
tierno16e3dd42018-04-24 12:52:40 +02002358 "member_vnf_index": str(vnf["member-vnf-index"]),
tiernof1ba57e2017-09-07 12:23:19 +02002359 # TODO 'start-by-default': True
2360 }
tierno16e3dd42018-04-24 12:52:40 +02002361 vnf_index2scevnf_uuid[str(vnf['member-vnf-index'])] = sce_vnf_uuid
2362 vnf_index2vnf_uuid[str(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
tiernof1ba57e2017-09-07 12:23:19 +02002363 db_sce_vnfs.append(db_sce_vnf)
2364
2365 # table ip_profiles (ip-profiles)
2366 ip_profile_name2db_table_index = {}
2367 for ip_profile in nsd.get("ip-profiles").itervalues():
2368 db_ip_profile = {
2369 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2370 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2371 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2372 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2373 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2374 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2375 }
2376 dns_list = []
2377 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2378 dns_list.append(str(dns.get("address")))
2379 db_ip_profile["dns_address"] = ";".join(dns_list)
2380 if ip_profile["ip-profile-params"].get('security-group'):
2381 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2382 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2383 db_ip_profiles_index += 1
2384 db_ip_profiles.append(db_ip_profile)
2385
2386 # table sce_nets (internal-vld)
2387 for vld in nsd.get("vld").itervalues():
2388 sce_net_uuid = str(uuid4())
2389 uuid_list.append(sce_net_uuid)
2390 db_sce_net = {
2391 "uuid": sce_net_uuid,
2392 "name": get_str(vld, "name", 255),
2393 "scenario_id": scenario_uuid,
2394 # "type": #TODO
2395 "multipoint": not vld.get("type") == "ELINE",
tierno1df468d2018-07-06 14:25:16 +02002396 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +02002397 # "external": #TODO
2398 "description": get_str(vld, "description", 255),
2399 }
2400 # guess type of network
2401 if vld.get("mgmt-network"):
2402 db_sce_net["type"] = "bridge"
2403 db_sce_net["external"] = True
2404 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2405 db_sce_net["type"] = "data"
2406 else:
tierno66eba6e2017-11-10 17:09:18 +01002407 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2408 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002409 db_sce_nets.append(db_sce_net)
2410
2411 # ip-profile, link db_ip_profile with db_sce_net
2412 if vld.get("ip-profile-ref"):
2413 ip_profile_name = vld.get("ip-profile-ref")
2414 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002415 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2416 " Reference to a non-existing 'ip_profiles'".format(
2417 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002418 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002419 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
tierno8f79ea12018-05-03 17:37:40 +02002420 elif vld.get("vim-network-name"):
2421 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
tiernof1ba57e2017-09-07 12:23:19 +02002422
2423 # table sce_interfaces (vld:vnfd-connection-point-ref)
2424 for iface in vld.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002425 vnf_index = str(iface['member-vnf-index-ref'])
tiernof1ba57e2017-09-07 12:23:19 +02002426 # check correct parameters
2427 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002428 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2429 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2430 "'nsd':'constituent-vnfd'".format(
2431 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002432 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002433
tierno66eba6e2017-11-10 17:09:18 +01002434 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002435 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2436 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2437 'external_name': get_str(iface, "vnfd-connection-point-ref",
2438 255)})
2439 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002440 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2441 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2442 "connection-point name at VNFD '{}'".format(
2443 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2444 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002445 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002446 interface_uuid = existing_ifaces[0]["uuid"]
garciadeblasebd66722019-01-31 16:01:31 +00002447 if existing_ifaces[0]["iface_type"] == "data":
tierno66eba6e2017-11-10 17:09:18 +01002448 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002449 sce_interface_uuid = str(uuid4())
2450 uuid_list.append(sce_net_uuid)
tierno41a69812018-02-16 14:34:33 +01002451 iface_ip_address = None
2452 if iface.get("ip-address"):
2453 iface_ip_address = str(iface.get("ip-address"))
tiernof1ba57e2017-09-07 12:23:19 +02002454 db_sce_interface = {
2455 "uuid": sce_interface_uuid,
2456 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2457 "sce_net_id": sce_net_uuid,
2458 "interface_id": interface_uuid,
tierno41a69812018-02-16 14:34:33 +01002459 "ip_address": iface_ip_address,
tiernof1ba57e2017-09-07 12:23:19 +02002460 }
2461 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002462 if not db_sce_net["type"]:
2463 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002464
Igor D.Ccaadc442017-11-06 12:48:48 +00002465 # table sce_vnffgs (vnffgd)
2466 for vnffg in nsd.get("vnffgd").itervalues():
2467 sce_vnffg_uuid = str(uuid4())
2468 uuid_list.append(sce_vnffg_uuid)
2469 db_sce_vnffg = {
2470 "uuid": sce_vnffg_uuid,
2471 "name": get_str(vnffg, "name", 255),
2472 "scenario_id": scenario_uuid,
2473 "vendor": get_str(vnffg, "vendor", 255),
2474 "description": get_str(vld, "description", 255),
2475 }
2476 db_sce_vnffgs.append(db_sce_vnffg)
2477
2478 # deal with rsps
Igor D.Ccaadc442017-11-06 12:48:48 +00002479 for rsp in vnffg.get("rsp").itervalues():
2480 sce_rsp_uuid = str(uuid4())
2481 uuid_list.append(sce_rsp_uuid)
2482 db_sce_rsp = {
2483 "uuid": sce_rsp_uuid,
2484 "name": get_str(rsp, "name", 255),
2485 "sce_vnffg_id": sce_vnffg_uuid,
2486 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2487 }
2488 db_sce_rsps.append(db_sce_rsp)
Igor D.Ccaadc442017-11-06 12:48:48 +00002489 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002490 vnf_index = str(iface['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002491 if_order = int(iface['order'])
2492 # check correct parameters
2493 if vnf_index not in vnf_index2vnf_uuid:
2494 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2495 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2496 "'nsd':'constituent-vnfd'".format(
2497 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002498 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002499
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002500 ingress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2501 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2502 WHERE={
2503 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2504 'external_name': get_str(iface, "vnfd-ingress-connection-point-ref",
2505 255)})
2506 if not ingress_existing_ifaces:
Igor D.Ccaadc442017-11-06 12:48:48 +00002507 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002508 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
Igor D.Ccaadc442017-11-06 12:48:48 +00002509 "connection-point name at VNFD '{}'".format(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002510 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-ingress-connection-point-ref"]),
2511 str(iface.get("vnfd-id-ref"))[:255]), httperrors.Bad_Request)
2512
2513 egress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2514 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2515 WHERE={
2516 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2517 'external_name': get_str(iface, "vnfd-egress-connection-point-ref",
2518 255)})
2519 if not egress_existing_ifaces:
2520 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2521 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2522 "connection-point name at VNFD '{}'".format(
2523 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-egress-connection-point-ref"]),
2524 str(iface.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request)
2525
2526 ingress_interface_uuid = ingress_existing_ifaces[0]["uuid"]
2527 egress_interface_uuid = egress_existing_ifaces[0]["uuid"]
Igor D.Ccaadc442017-11-06 12:48:48 +00002528 sce_rsp_hop_uuid = str(uuid4())
2529 uuid_list.append(sce_rsp_hop_uuid)
2530 db_sce_rsp_hop = {
2531 "uuid": sce_rsp_hop_uuid,
2532 "if_order": if_order,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002533 "ingress_interface_id": ingress_interface_uuid,
2534 "egress_interface_id": egress_interface_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00002535 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2536 "sce_rsp_id": sce_rsp_uuid,
2537 }
2538 db_sce_rsp_hops.append(db_sce_rsp_hop)
2539
2540 # deal with classifiers
Igor D.Ccaadc442017-11-06 12:48:48 +00002541 for classifier in vnffg.get("classifier").itervalues():
2542 sce_classifier_uuid = str(uuid4())
2543 uuid_list.append(sce_classifier_uuid)
2544
2545 # source VNF
tierno16e3dd42018-04-24 12:52:40 +02002546 vnf_index = str(classifier['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002547 if vnf_index not in vnf_index2vnf_uuid:
2548 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2549 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2550 "'nsd':'constituent-vnfd'".format(
2551 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002552 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002553 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2554 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2555 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2556 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2557 255)})
2558 if not existing_ifaces:
2559 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2560 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2561 "connection-point name at VNFD '{}'".format(
2562 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2563 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002564 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002565 interface_uuid = existing_ifaces[0]["uuid"]
2566
2567 db_sce_classifier = {
2568 "uuid": sce_classifier_uuid,
2569 "name": get_str(classifier, "name", 255),
2570 "sce_vnffg_id": sce_vnffg_uuid,
2571 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2572 "interface_id": interface_uuid,
2573 }
2574 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2575 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2576 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2577 db_sce_classifiers.append(db_sce_classifier)
2578
Igor D.Ccaadc442017-11-06 12:48:48 +00002579 for match in classifier.get("match-attributes").itervalues():
2580 sce_classifier_match_uuid = str(uuid4())
2581 uuid_list.append(sce_classifier_match_uuid)
2582 db_sce_classifier_match = {
2583 "uuid": sce_classifier_match_uuid,
2584 "ip_proto": get_str(match, "ip-proto", 2),
2585 "source_ip": get_str(match, "source-ip-address", 16),
2586 "destination_ip": get_str(match, "destination-ip-address", 16),
2587 "source_port": get_str(match, "source-port", 5),
2588 "destination_port": get_str(match, "destination-port", 5),
2589 "sce_classifier_id": sce_classifier_uuid,
2590 }
2591 db_sce_classifier_matches.append(db_sce_classifier_match)
2592 # TODO: vnf/cp keys
2593
2594 # remove unneeded id's in sce_rsps
2595 for rsp in db_sce_rsps:
2596 rsp.pop('id')
2597
tiernof1ba57e2017-09-07 12:23:19 +02002598 db_tables = [
2599 {"scenarios": db_scenarios},
2600 {"sce_nets": db_sce_nets},
2601 {"ip_profiles": db_ip_profiles},
2602 {"sce_vnfs": db_sce_vnfs},
2603 {"sce_interfaces": db_sce_interfaces},
Igor D.Ccaadc442017-11-06 12:48:48 +00002604 {"sce_vnffgs": db_sce_vnffgs},
2605 {"sce_rsps": db_sce_rsps},
2606 {"sce_rsp_hops": db_sce_rsp_hops},
2607 {"sce_classifiers": db_sce_classifiers},
2608 {"sce_classifier_matches": db_sce_classifier_matches},
tiernof1ba57e2017-09-07 12:23:19 +02002609 ]
2610
Igor D.Ccaadc442017-11-06 12:48:48 +00002611 logger.debug("new_nsd_v3 done: %s",
tiernof1ba57e2017-09-07 12:23:19 +02002612 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2613 mydb.new_rows(db_tables, uuid_list)
2614 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002615 except NfvoException:
2616 raise
tiernof1ba57e2017-09-07 12:23:19 +02002617 except Exception as e:
2618 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002619 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002620
2621
tierno7edb6752016-03-21 17:37:52 +01002622def edit_scenario(mydb, tenant_id, scenario_id, data):
2623 data["uuid"] = scenario_id
2624 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002625 c = mydb.edit_scenario( data )
2626 return c
tierno7edb6752016-03-21 17:37:52 +01002627
tiernob3d36742017-03-03 23:51:05 +01002628
tiernob8569aa2018-08-24 11:34:54 +02002629@deprecated("Use create_instance")
tierno7edb6752016-03-21 17:37:52 +01002630def 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 +02002631 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002632 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2633 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002634 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002635 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002636
tierno7edb6752016-03-21 17:37:52 +01002637 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002638 try:
2639 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002640 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002641 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002642 scenarioDict['datacenter_id'] = datacenter_id
2643 #print '================scenarioDict======================='
2644 #print json.dumps(scenarioDict, indent=4)
2645 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002646
tiernoae4a8d12016-07-08 12:30:39 +02002647 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2648 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002649
tiernoae4a8d12016-07-08 12:30:39 +02002650 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2651 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002652
tiernoae4a8d12016-07-08 12:30:39 +02002653 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2654 for sce_net in scenarioDict['nets']:
2655 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002656
tiernoae4a8d12016-07-08 12:30:39 +02002657 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002658 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002659 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002660 myNetDict = {}
2661 myNetDict["name"] = myNetName
2662 myNetDict["type"] = myNetType
2663 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002664 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002665 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002666 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002667 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002668 if not sce_net["external"]:
garciadeblasebd66722019-01-31 16:01:31 +00002669 network_id, _ = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002670 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2671 sce_net['vim_id'] = network_id
2672 auxNetDict['scenario'][sce_net['uuid']] = network_id
2673 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002674 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002675 else:
2676 if sce_net['vim_id'] == None:
2677 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2678 _, message = rollback(mydb, vims, rollbackList)
2679 logger.error("nfvo.start_scenario: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002680 raise NfvoException(error_text, httperrors.Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002681 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2682 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002683
tiernoae4a8d12016-07-08 12:30:39 +02002684 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2685 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002686
tiernoae4a8d12016-07-08 12:30:39 +02002687 for sce_vnf in scenarioDict['vnfs']:
2688 for net in sce_vnf['nets']:
2689 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002690
tiernoae4a8d12016-07-08 12:30:39 +02002691 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2692 myNetName = myNetName[0:255] #limit length
2693 myNetType = net['type']
2694 myNetDict = {}
2695 myNetDict["name"] = myNetName
2696 myNetDict["type"] = myNetType
2697 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002698 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002699 #print myNetDict
2700 #TODO:
2701 #We should use the dictionary as input parameter for new_network
garciadeblasebd66722019-01-31 16:01:31 +00002702 network_id, _ = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002703 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2704 net['vim_id'] = network_id
2705 if sce_vnf['uuid'] not in auxNetDict:
2706 auxNetDict[sce_vnf['uuid']] = {}
2707 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2708 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002709 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002710
tiernoae4a8d12016-07-08 12:30:39 +02002711 #print "auxNetDict:"
2712 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002713
tiernoae4a8d12016-07-08 12:30:39 +02002714 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2715 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2716 i = 0
2717 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002718 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002719 for vm in sce_vnf['vms']:
2720 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002721 if vm_av and vm_av not in vnf_availability_zones:
2722 vnf_availability_zones.append(vm_av)
2723
2724 # check if there is enough availability zones available at vim level.
2725 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2726 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002727 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno5a3273c2017-08-29 11:43:46 +02002728
tiernoae4a8d12016-07-08 12:30:39 +02002729 for vm in sce_vnf['vms']:
2730 i += 1
2731 myVMDict = {}
2732 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002733 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002734 #myVMDict['description'] = vm['description']
2735 myVMDict['description'] = myVMDict['name'][0:99]
2736 if not startvms:
2737 myVMDict['start'] = "no"
2738 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2739 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002740
tiernoae4a8d12016-07-08 12:30:39 +02002741 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002742 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002743 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002744 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002745
tiernoae4a8d12016-07-08 12:30:39 +02002746 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002747 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002748 if flavor_dict['extended']!=None:
2749 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002750 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002751 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002752
2753
tiernoae4a8d12016-07-08 12:30:39 +02002754 myVMDict['imageRef'] = vm['vim_image_id']
2755 myVMDict['flavorRef'] = vm['vim_flavor_id']
2756 myVMDict['networks'] = []
2757 for iface in vm['interfaces']:
2758 netDict = {}
2759 if iface['type']=="data":
2760 netDict['type'] = iface['model']
2761 elif "model" in iface and iface["model"]!=None:
2762 netDict['model']=iface['model']
2763 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2764 #discover type of interface looking at flavor
2765 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2766 for flavor_iface in numa.get('interfaces',[]):
2767 if flavor_iface.get('name') == iface['internal_name']:
2768 if flavor_iface['dedicated'] == 'yes':
2769 netDict['type']="PF" #passthrough
2770 elif flavor_iface['dedicated'] == 'no':
2771 netDict['type']="VF" #siov
2772 elif flavor_iface['dedicated'] == 'yes:sriov':
2773 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2774 netDict["mac_address"] = flavor_iface.get("mac_address")
2775 break;
2776 netDict["use"]=iface['type']
2777 if netDict["use"]=="data" and not netDict.get("type"):
2778 #print "netDict", netDict
2779 #print "iface", iface
2780 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'])
2781 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002782 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002783 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002784 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002785 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002786 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2787 netDict["type"]="virtual"
2788 if "vpci" in iface and iface["vpci"] is not None:
2789 netDict['vpci'] = iface['vpci']
2790 if "mac" in iface and iface["mac"] is not None:
2791 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002792 if "port-security" in iface and iface["port-security"] is not None:
2793 netDict['port_security'] = iface['port-security']
2794 if "floating-ip" in iface and iface["floating-ip"] is not None:
2795 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002796 netDict['name'] = iface['internal_name']
2797 if iface['net_id'] is None:
2798 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002799 #print iface
2800 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002801 if vnf_iface['interface_id']==iface['uuid']:
2802 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2803 break
2804 else:
2805 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2806 #skip bridge ifaces not connected to any net
2807 #if 'net_id' not in netDict or netDict['net_id']==None:
2808 # continue
2809 myVMDict['networks'].append(netDict)
2810 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2811 #print myVMDict['name']
2812 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2813 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2814 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002815
2816 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002817 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002818 else:
tierno5a3273c2017-08-29 11:43:46 +02002819 av_index = None
mirabal29356312017-07-27 12:21:22 +02002820
tierno98e909c2017-10-14 13:27:03 +02002821 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002822 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002823 availability_zone_index=av_index,
2824 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002825 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2826 vm['vim_id'] = vm_id
2827 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2828 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2829 for net in myVMDict['networks']:
2830 if "vim_id" in net:
2831 for iface in vm['interfaces']:
2832 if net["name"]==iface["internal_name"]:
2833 iface["vim_id"]=net["vim_id"]
2834 break
tierno42026a02017-02-10 15:13:40 +01002835
tiernoae4a8d12016-07-08 12:30:39 +02002836 logger.debug("start scenario Deployment done")
2837 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2838 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002839 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2840 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002841
tiernof97fd272016-07-11 14:32:37 +02002842 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002843 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002844 if isinstance(e, db_base_Exception):
2845 error_text = "Exception at database"
2846 else:
2847 error_text = "Exception at VIM"
2848 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2849 #logger.error("start_scenario %s", error_text)
2850 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002851
tierno36c0b172017-01-12 18:32:28 +01002852def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002853 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002854 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002855 None is allowed
2856 """
tierno36c0b172017-01-12 18:32:28 +01002857 if not cloud_config_preserve and not cloud_config:
2858 return None
2859
2860 new_cloud_config = {"key-pairs":[], "users":[]}
2861 # key-pairs
2862 if cloud_config_preserve:
2863 for key in cloud_config_preserve.get("key-pairs", () ):
2864 if key not in new_cloud_config["key-pairs"]:
2865 new_cloud_config["key-pairs"].append(key)
2866 if cloud_config:
2867 for key in cloud_config.get("key-pairs", () ):
2868 if key not in new_cloud_config["key-pairs"]:
2869 new_cloud_config["key-pairs"].append(key)
2870 if not new_cloud_config["key-pairs"]:
2871 del new_cloud_config["key-pairs"]
2872
2873 # users
2874 if cloud_config:
2875 new_cloud_config["users"] += cloud_config.get("users", () )
2876 if cloud_config_preserve:
2877 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002878 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002879 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002880 for index0 in range(0,len(users)):
2881 if index0 in index_to_delete:
2882 continue
2883 for index1 in range(index0+1,len(users)):
2884 if index1 in index_to_delete:
2885 continue
2886 if users[index0]["name"] == users[index1]["name"]:
2887 index_to_delete.append(index1)
2888 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002889 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002890 users[index0]["key-pairs"] = [key]
2891 elif key not in users[index0]["key-pairs"]:
2892 users[index0]["key-pairs"].append(key)
2893 index_to_delete.sort(reverse=True)
2894 for index in index_to_delete:
2895 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002896 if not new_cloud_config["users"]:
2897 del new_cloud_config["users"]
2898
2899 #boot-data-drive
2900 if cloud_config and cloud_config.get("boot-data-drive") != None:
2901 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2902 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2903 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2904
2905 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002906 new_cloud_config["user-data"] = []
2907 if cloud_config and cloud_config.get("user-data"):
2908 if isinstance(cloud_config["user-data"], list):
2909 new_cloud_config["user-data"] += cloud_config["user-data"]
2910 else:
2911 new_cloud_config["user-data"].append(cloud_config["user-data"])
2912 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2913 if isinstance(cloud_config_preserve["user-data"], list):
2914 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2915 else:
2916 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2917 if not new_cloud_config["user-data"]:
2918 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002919
2920 # config files
2921 new_cloud_config["config-files"] = []
2922 if cloud_config and cloud_config.get("config-files") != None:
2923 new_cloud_config["config-files"] += cloud_config["config-files"]
2924 if cloud_config_preserve:
2925 for file in cloud_config_preserve.get("config-files", ()):
2926 for index in range(0, len(new_cloud_config["config-files"])):
2927 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2928 new_cloud_config["config-files"][index] = file
2929 break
2930 else:
2931 new_cloud_config["config-files"].append(file)
2932 if not new_cloud_config["config-files"]:
2933 del new_cloud_config["config-files"]
2934 return new_cloud_config
2935
2936
tierno867ffe92017-03-27 12:50:34 +02002937def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002938 datacenter_id = None
2939 datacenter_name = None
2940 thread = None
tierno867ffe92017-03-27 12:50:34 +02002941 try:
2942 if datacenter_tenant_id:
2943 thread_id = datacenter_tenant_id
2944 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002945 else:
tierno867ffe92017-03-27 12:50:34 +02002946 where_={"td.nfvo_tenant_id": tenant_id}
2947 if datacenter_id_name:
2948 if utils.check_valid_uuid(datacenter_id_name):
2949 datacenter_id = datacenter_id_name
2950 where_["dt.datacenter_id"] = datacenter_id
2951 else:
2952 datacenter_name = datacenter_id_name
2953 where_["d.name"] = datacenter_name
2954 if datacenter_tenant_id:
2955 where_["dt.uuid"] = datacenter_tenant_id
2956 datacenters = mydb.get_rows(
2957 SELECT=("dt.uuid as datacenter_tenant_id",),
2958 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2959 "join datacenters as d on d.uuid=dt.datacenter_id",
2960 WHERE=where_)
2961 if len(datacenters) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002962 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno867ffe92017-03-27 12:50:34 +02002963 elif datacenters:
2964 thread_id = datacenters[0]["datacenter_tenant_id"]
2965 thread = vim_threads["running"].get(thread_id)
2966 if not thread:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002967 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tierno867ffe92017-03-27 12:50:34 +02002968 return thread_id, thread
2969 except db_base_Exception as e:
2970 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002971
tiernof5755962017-07-13 15:44:34 +02002972
tiernoa15c4b92017-10-05 12:41:44 +02002973def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2974 WHERE_dict={}
2975 if utils.check_valid_uuid(datacenter_id_name):
2976 WHERE_dict['d.uuid'] = datacenter_id_name
2977 else:
2978 WHERE_dict['d.name'] = datacenter_id_name
2979
2980 if tenant_id:
2981 WHERE_dict['nfvo_tenant_id'] = tenant_id
2982 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2983 " dt on td.datacenter_tenant_id=dt.uuid"
2984 else:
2985 from_ = 'datacenters as d'
tiernod3750b32018-07-20 15:33:08 +02002986 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid, d.name as name",), WHERE=WHERE_dict )
tiernoa15c4b92017-10-05 12:41:44 +02002987 if len(vimaccounts) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002988 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernoa15c4b92017-10-05 12:41:44 +02002989 elif len(vimaccounts)>1:
2990 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002991 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02002992 return vimaccounts[0]["uuid"], vimaccounts[0]["name"]
tiernoa15c4b92017-10-05 12:41:44 +02002993
2994
tiernoa2793912016-10-04 08:15:08 +00002995def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002996 datacenter_id = None
2997 datacenter_name = None
2998 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002999 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02003000 datacenter_id = datacenter_id_name
3001 else:
3002 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00003003 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02003004 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003005 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernobe41e222016-09-02 15:16:13 +02003006 elif len(vims)>1:
3007 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003008 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernobe41e222016-09-02 15:16:13 +02003009 return vims.keys()[0], vims.values()[0]
3010
tiernob3d36742017-03-03 23:51:05 +01003011
garciadeblas9f8456e2016-09-05 05:02:59 +02003012def update(d, u):
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003013 """Takes dict d and updates it with the values in dict u.
3014 It merges all depth levels"""
garciadeblas9f8456e2016-09-05 05:02:59 +02003015 for k, v in u.iteritems():
3016 if isinstance(v, collections.Mapping):
3017 r = update(d.get(k, {}), v)
3018 d[k] = r
3019 else:
3020 d[k] = u[k]
3021 return d
3022
tierno16e3dd42018-04-24 12:52:40 +02003023
tierno7edb6752016-03-21 17:37:52 +01003024def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01003025 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
3026 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01003027 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01003028
tierno868220c2017-09-26 00:11:05 +02003029 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02003030 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02003031 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01003032 datacenter = instance_dict.get("datacenter")
tiernofc7cfbf2019-03-20 17:23:45 +00003033 default_wim_account = instance_dict.get("wim_account")
tiernobe41e222016-09-02 15:16:13 +02003034 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3035 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02003036 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02003037 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02003038 # myvim_tenant = myvim['tenant_id']
tierno16e3dd42018-04-24 12:52:40 +02003039 rollbackList = []
tierno42026a02017-02-10 15:13:40 +01003040
tierno868220c2017-09-26 00:11:05 +02003041 # print "Checking that the scenario exists and getting the scenario dictionary"
tierno7fe82642018-11-26 14:14:51 +00003042 if isinstance(scenario, str):
3043 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
3044 datacenter_id=default_datacenter_id)
3045 else:
3046 scenarioDict = scenario
3047 scenarioDict["uuid"] = None
tierno42026a02017-02-10 15:13:40 +01003048
tierno868220c2017-09-26 00:11:05 +02003049 # logger.debug(">>>>>> Dictionaries before merging")
3050 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
3051 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01003052
tierno868220c2017-09-26 00:11:05 +02003053 db_instance_vnfs = []
3054 db_instance_vms = []
3055 db_instance_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00003056 db_instance_sfis = []
3057 db_instance_sfs = []
3058 db_instance_classifications = []
3059 db_instance_sfps = []
tierno868220c2017-09-26 00:11:05 +02003060 db_ip_profiles = []
3061 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02003062 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02003063 task_index = 0
tierno8e690322017-08-10 15:58:50 +02003064 instance_name = instance_dict["name"]
3065 instance_uuid = str(uuid4())
3066 uuid_list.append(instance_uuid)
3067 db_instance_scenario = {
3068 "uuid": instance_uuid,
3069 "name": instance_name,
3070 "tenant_id": tenant_id,
3071 "scenario_id": scenarioDict['uuid'],
3072 "datacenter_id": default_datacenter_id,
3073 # filled bellow 'datacenter_tenant_id'
3074 "description": instance_dict.get("description"),
3075 }
tierno8e690322017-08-10 15:58:50 +02003076 if scenarioDict.get("cloud-config"):
3077 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
3078 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003079 instance_action_id = get_task_id()
3080 db_instance_action = {
3081 "uuid": instance_action_id, # same uuid for the instance and the action on create
3082 "tenant_id": tenant_id,
3083 "instance_id": instance_uuid,
3084 "description": "CREATE",
3085 }
garciadeblas9f8456e2016-09-05 05:02:59 +02003086
tierno868220c2017-09-26 00:11:05 +02003087 # Auxiliary dictionaries from x to y
tierno8e690322017-08-10 15:58:50 +02003088 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02003089 net2task_id = {'scenario': {}}
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003090 # Mapping between local networks and WIMs
3091 wim_usage = {}
tierno42026a02017-02-10 15:13:40 +01003092
tierno1df468d2018-07-06 14:25:16 +02003093 def ip_profile_IM2RO(ip_profile_im):
3094 # translate from input format to database format
3095 ip_profile_ro = {}
3096 if 'subnet-address' in ip_profile_im:
3097 ip_profile_ro['subnet_address'] = ip_profile_im['subnet-address']
3098 if 'ip-version' in ip_profile_im:
3099 ip_profile_ro['ip_version'] = ip_profile_im['ip-version']
3100 if 'gateway-address' in ip_profile_im:
3101 ip_profile_ro['gateway_address'] = ip_profile_im['gateway-address']
3102 if 'dns-address' in ip_profile_im:
3103 ip_profile_ro['dns_address'] = ip_profile_im['dns-address']
3104 if isinstance(ip_profile_ro['dns_address'], (list, tuple)):
3105 ip_profile_ro['dns_address'] = ";".join(ip_profile_ro['dns_address'])
3106 if 'dhcp' in ip_profile_im:
3107 ip_profile_ro['dhcp_start_address'] = ip_profile_im['dhcp'].get('start-address')
3108 ip_profile_ro['dhcp_enabled'] = ip_profile_im['dhcp'].get('enabled', True)
3109 ip_profile_ro['dhcp_count'] = ip_profile_im['dhcp'].get('count')
3110 return ip_profile_ro
3111
tierno868220c2017-09-26 00:11:05 +02003112 # logger.debug("Creating instance from scenario-dict:\n%s",
3113 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01003114 try:
tiernob3d36742017-03-03 23:51:05 +01003115 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02003116 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003117 for scenario_net in scenarioDict['nets']:
tierno1df468d2018-07-06 14:25:16 +02003118 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 +01003119 break
tierno1df468d2018-07-06 14:25:16 +02003120 else:
3121 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003122 httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003123 if "sites" not in net_instance_desc:
3124 net_instance_desc["sites"] = [ {} ]
3125 site_without_datacenter_field = False
3126 for site in net_instance_desc["sites"]:
3127 if site.get("datacenter"):
tiernod3750b32018-07-20 15:33:08 +02003128 site["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003129 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02003130 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02003131 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
3132 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003133 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
3134 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02003135 else:
3136 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02003137 raise NfvoException("Found more than one entries without datacenter field at "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003138 "instance:networks:{}:sites".format(net_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003139 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02003140 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01003141
tiernobe41e222016-09-02 15:16:13 +02003142 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003143 for scenario_vnf in scenarioDict['vnfs']:
tierno1df468d2018-07-06 14:25:16 +02003144 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 +01003145 break
tierno1df468d2018-07-06 14:25:16 +02003146 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003147 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003148 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02003149 # Add this datacenter to myvims
tiernod3750b32018-07-20 15:33:08 +02003150 vnf_instance_desc["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003151 if vnf_instance_desc["datacenter"] not in myvims:
3152 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3153 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003154 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00003155 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01003156
tierno1df468d2018-07-06 14:25:16 +02003157 for net_id, net_instance_desc in vnf_instance_desc.get("networks", {}).iteritems():
3158 for scenario_net in scenario_vnf['nets']:
3159 if net_id == scenario_net['osm_id'] or net_id == scenario_net['uuid'] or net_id == scenario_net["name"]:
3160 break
3161 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003162 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003163 if net_instance_desc.get("vim-network-name"):
3164 scenario_net["vim-network-name"] = net_instance_desc["vim-network-name"]
gcalvino0a480542018-12-17 16:19:33 +01003165 if net_instance_desc.get("vim-network-id"):
3166 scenario_net["vim-network-id"] = net_instance_desc["vim-network-id"]
tierno1df468d2018-07-06 14:25:16 +02003167 if net_instance_desc.get("name"):
3168 scenario_net["name"] = net_instance_desc["name"]
3169 if 'ip-profile' in net_instance_desc:
3170 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3171 if 'ip_profile' not in scenario_net:
3172 scenario_net['ip_profile'] = ipprofile_db
3173 else:
3174 update(scenario_net['ip_profile'], ipprofile_db)
3175
3176 for vdu_id, vdu_instance_desc in vnf_instance_desc.get("vdus", {}).iteritems():
3177 for scenario_vm in scenario_vnf['vms']:
3178 if vdu_id == scenario_vm['osm_id'] or vdu_id == scenario_vm["name"]:
3179 break
3180 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003181 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003182 scenario_vm["instance_parameters"] = vdu_instance_desc
3183 for iface_id, iface_instance_desc in vdu_instance_desc.get("interfaces", {}).iteritems():
3184 for scenario_interface in scenario_vm['interfaces']:
3185 if iface_id == scenario_interface['internal_name'] or iface_id == scenario_interface["external_name"]:
3186 scenario_interface.update(iface_instance_desc)
3187 break
3188 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003189 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003190
tierno868220c2017-09-26 00:11:05 +02003191 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01003192 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02003193
tierno868220c2017-09-26 00:11:05 +02003194 # 0.2 merge instance information into scenario
3195 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3196 # However, this is not possible yet.
tierno41a69812018-02-16 14:34:33 +01003197 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
garciadeblas9f8456e2016-09-05 05:02:59 +02003198 for scenario_net in scenarioDict['nets']:
tiernofc7cfbf2019-03-20 17:23:45 +00003199 if net_name == scenario_net.get("name") or net_name == scenario_net.get("osm_id") or net_name == scenario_net.get("uuid"):
3200 if "wim_account" in net_instance_desc and net_instance_desc["wim_account"] is not None:
3201 scenario_net["wim_account"] = net_instance_desc["wim_account"]
garciadeblas9f8456e2016-09-05 05:02:59 +02003202 if 'ip-profile' in net_instance_desc:
tierno1df468d2018-07-06 14:25:16 +02003203 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
garciadeblasedca7b32016-09-29 14:01:52 +00003204 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02003205 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00003206 else:
tierno455612d2017-05-30 16:40:10 +02003207 update(scenario_net['ip_profile'], ipprofile_db)
tierno41a69812018-02-16 14:34:33 +01003208 for interface in net_instance_desc.get('interfaces', ()):
garciadeblas9f8456e2016-09-05 05:02:59 +02003209 if 'ip_address' in interface:
3210 for vnf in scenarioDict['vnfs']:
3211 if interface['vnf'] == vnf['name']:
3212 for vnf_interface in vnf['interfaces']:
3213 if interface['vnf_interface'] == vnf_interface['external_name']:
tierno41a69812018-02-16 14:34:33 +01003214 vnf_interface['ip_address'] = interface['ip_address']
garciadeblas9f8456e2016-09-05 05:02:59 +02003215
tierno868220c2017-09-26 00:11:05 +02003216 # logger.debug(">>>>>>>> Merged dictionary")
3217 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3218 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02003219
tiernob3d36742017-03-03 23:51:05 +01003220 # 1. Creating new nets (sce_nets) in the VIM"
tierno8f79ea12018-05-03 17:37:40 +02003221 number_mgmt_networks = 0
tierno8e690322017-08-10 15:58:50 +02003222 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01003223 for sce_net in scenarioDict['nets']:
tierno7fe82642018-11-26 14:14:51 +00003224 sce_net_uuid = sce_net.get('uuid', sce_net["name"])
tierno1df468d2018-07-06 14:25:16 +02003225 # get involved datacenters where this network need to be created
3226 involved_datacenters = []
tierno7fe82642018-11-26 14:14:51 +00003227 for sce_vnf in scenarioDict.get("vnfs", ()):
tierno1df468d2018-07-06 14:25:16 +02003228 vnf_datacenter = sce_vnf.get("datacenter", default_datacenter_id)
3229 if vnf_datacenter in involved_datacenters:
3230 continue
3231 if sce_vnf.get("interfaces"):
3232 for sce_vnf_ifaces in sce_vnf["interfaces"]:
3233 if sce_vnf_ifaces.get("sce_net_id") == sce_net["uuid"]:
3234 involved_datacenters.append(vnf_datacenter)
3235 break
gcalvinod6fac4d2018-11-05 10:42:06 +01003236 if not involved_datacenters:
3237 involved_datacenters.append(default_datacenter_id)
tierno80391822019-03-21 22:12:14 +00003238 target_wim_account = sce_net.get("wim_account", default_wim_account)
tierno1df468d2018-07-06 14:25:16 +02003239
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003240 # --> WIM
3241 # TODO: use this information during network creation
tierno4070e442019-01-23 10:19:23 +00003242 wim_account_id = wim_account_name = None
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003243 if len(involved_datacenters) > 1 and 'uuid' in sce_net:
tiernofc7cfbf2019-03-20 17:23:45 +00003244 if target_wim_account is None or target_wim_account is True: # automatic selection of WIM
3245 # OBS: sce_net without uuid are used internally to VNFs
3246 # and the assumption is that VNFs will not be split among
3247 # different datacenters
3248 wim_account = wim_engine.find_suitable_wim_account(
3249 involved_datacenters, tenant_id)
3250 wim_account_id = wim_account['uuid']
3251 wim_account_name = wim_account['name']
3252 wim_usage[sce_net['uuid']] = wim_account_id
3253 elif isinstance(target_wim_account, str): # manual selection of WIM
3254 wim_account.persist.get_wim_account_by(target_wim_account, tenant_id)
3255 wim_account_id = wim_account['uuid']
3256 wim_account_name = wim_account['name']
3257 wim_usage[sce_net['uuid']] = wim_account_id
3258 else: # not WIM usage
3259 wim_usage[sce_net['uuid']] = False
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003260 # <-- WIM
3261
tierno1df468d2018-07-06 14:25:16 +02003262 descriptor_net = {}
tierno3c44e7b2019-03-04 17:32:01 +00003263 if instance_dict.get("networks"):
3264 if sce_net.get("uuid") in instance_dict["networks"]:
3265 descriptor_net = instance_dict["networks"][sce_net["uuid"]]
3266 descriptor_net_name = sce_net["uuid"]
3267 elif sce_net.get("osm_id") in instance_dict["networks"]:
3268 descriptor_net = instance_dict["networks"][sce_net["osm_id"]]
3269 descriptor_net_name = sce_net["osm_id"]
3270 elif sce_net["name"] in instance_dict["networks"]:
3271 descriptor_net = instance_dict["networks"][sce_net["name"]]
3272 descriptor_net_name = sce_net["name"]
tiernobe41e222016-09-02 15:16:13 +02003273 net_name = descriptor_net.get("vim-network-name")
tierno7fe82642018-11-26 14:14:51 +00003274 # add datacenters from instantiation parameters
3275 if descriptor_net.get("sites"):
3276 for site in descriptor_net["sites"]:
3277 if site.get("datacenter") and site["datacenter"] not in involved_datacenters:
3278 involved_datacenters.append(site["datacenter"])
3279 sce_net2instance[sce_net_uuid] = {}
3280 net2task_id['scenario'][sce_net_uuid] = {}
tiernobe41e222016-09-02 15:16:13 +02003281
tierno3c44e7b2019-03-04 17:32:01 +00003282 use_network = None
3283 related_network = None
3284 if descriptor_net.get("use-network"):
3285 target_instance_nets = mydb.get_rows(
3286 SELECT="related",
3287 FROM="instance_nets",
3288 WHERE={"instance_scenario_id": descriptor_net["use-network"]["instance_scenario_id"],
3289 "osm_id": descriptor_net["use-network"]["osm_id"]},
3290 )
3291 if not target_instance_nets:
3292 raise NfvoException(
3293 "Cannot find the target network at instance:networks[{}]:use-network".format(descriptor_net_name),
3294 httperrors.Bad_Request)
3295 else:
3296 use_network = target_instance_nets[0]["related"]
3297
tierno1df468d2018-07-06 14:25:16 +02003298 if sce_net["external"]:
3299 number_mgmt_networks += 1
3300
3301 for datacenter_id in involved_datacenters:
3302 netmap_use = None
3303 netmap_create = None
3304 if descriptor_net.get("sites"):
3305 for site in descriptor_net["sites"]:
3306 if site.get("datacenter") == datacenter_id:
3307 netmap_use = site.get("netmap-use")
3308 netmap_create = site.get("netmap-create")
3309 break
3310
3311 vim = myvims[datacenter_id]
3312 myvim_thread_id = myvim_threads_id[datacenter_id]
3313
tiernobe41e222016-09-02 15:16:13 +02003314 net_type = sce_net['type']
tiernob6990792018-11-13 10:37:42 +01003315 net_vim_name = None
tierno868220c2017-09-26 00:11:05 +02003316 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01003317
tiernof1ba57e2017-09-07 12:23:19 +02003318 if not net_name:
3319 if sce_net["external"]:
3320 net_name = sce_net["name"]
3321 else:
tierno1df468d2018-07-06 14:25:16 +02003322 net_name = "{}-{}".format(instance_name, sce_net["name"])
tiernof1ba57e2017-09-07 12:23:19 +02003323 net_name = net_name[:255] # limit length
3324
tierno1df468d2018-07-06 14:25:16 +02003325 if netmap_use or netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003326 create_network = False
3327 lookfor_network = False
tierno1df468d2018-07-06 14:25:16 +02003328 if netmap_use:
tiernof1ba57e2017-09-07 12:23:19 +02003329 lookfor_network = True
tierno1df468d2018-07-06 14:25:16 +02003330 if utils.check_valid_uuid(netmap_use):
3331 lookfor_filter["id"] = netmap_use
tiernof1ba57e2017-09-07 12:23:19 +02003332 else:
tierno1df468d2018-07-06 14:25:16 +02003333 lookfor_filter["name"] = netmap_use
3334 if netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003335 create_network = True
3336 net_vim_name = net_name
tierno1df468d2018-07-06 14:25:16 +02003337 if isinstance(netmap_create, str):
3338 net_vim_name = netmap_create
tierno8f79ea12018-05-03 17:37:40 +02003339 elif sce_net.get("vim_network_name"):
3340 create_network = False
3341 lookfor_network = True
3342 lookfor_filter["name"] = sce_net.get("vim_network_name")
tiernof1ba57e2017-09-07 12:23:19 +02003343 elif sce_net["external"]:
tiernod108c412018-12-18 15:19:27 +00003344 if sce_net.get('vim_id'):
tierno868220c2017-09-26 00:11:05 +02003345 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02003346 create_network = False
3347 lookfor_network = True
3348 lookfor_filter["id"] = sce_net['vim_id']
tierno8f79ea12018-05-03 17:37:40 +02003349 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3350 if number_mgmt_networks > 1:
3351 raise NfvoException("Found several VLD of type mgmt. "
3352 "You must concrete what vim-network must be use for each one",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003353 httperrors.Bad_Request)
tierno8f79ea12018-05-03 17:37:40 +02003354 create_network = False
3355 lookfor_network = True
3356 if vim["config"].get("management_network_id"):
3357 lookfor_filter["id"] = vim["config"]["management_network_id"]
3358 else:
3359 lookfor_filter["name"] = vim["config"]["management_network_name"]
tiernobe41e222016-09-02 15:16:13 +02003360 else:
tierno868220c2017-09-26 00:11:05 +02003361 # 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 +02003362 create_network = True
3363 lookfor_network = True
3364 lookfor_filter["name"] = sce_net["name"]
3365 net_vim_name = sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01003366 else:
tiernobe41e222016-09-02 15:16:13 +02003367 net_vim_name = net_name
3368 create_network = True
3369 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01003370
tiernof1450872017-10-17 23:15:08 +02003371 task_extra = {}
3372 if create_network:
3373 task_action = "CREATE"
tierno4070e442019-01-23 10:19:23 +00003374 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None), wim_account_name)
tiernof1450872017-10-17 23:15:08 +02003375 if lookfor_network:
3376 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02003377 elif lookfor_network:
3378 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02003379 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01003380
tierno8e690322017-08-10 15:58:50 +02003381 # fill database content
3382 net_uuid = str(uuid4())
3383 uuid_list.append(net_uuid)
tierno7fe82642018-11-26 14:14:51 +00003384 sce_net2instance[sce_net_uuid][datacenter_id] = net_uuid
tierno3c44e7b2019-03-04 17:32:01 +00003385 if not related_network: # all db_instance_nets will have same related
3386 related_network = use_network or net_uuid
tierno8e690322017-08-10 15:58:50 +02003387 db_net = {
3388 "uuid": net_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003389 "osm_id": sce_net.get("osm_id") or sce_net["name"],
3390 "related": related_network,
tierno868220c2017-09-26 00:11:05 +02003391 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003392 "vim_name": net_vim_name,
tierno8e690322017-08-10 15:58:50 +02003393 "instance_scenario_id": instance_uuid,
tierno7fe82642018-11-26 14:14:51 +00003394 "sce_net_id": sce_net.get("uuid"),
tierno8e690322017-08-10 15:58:50 +02003395 "created": create_network,
3396 'datacenter_id': datacenter_id,
3397 'datacenter_tenant_id': myvim_thread_id,
tiernod2836fc2018-05-30 15:03:27 +02003398 'status': 'BUILD' # if create_network else "ACTIVE"
tierno8e690322017-08-10 15:58:50 +02003399 }
3400 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003401 db_vim_action = {
3402 "instance_action_id": instance_action_id,
3403 "status": "SCHEDULED",
3404 "task_index": task_index,
3405 "datacenter_vim_id": myvim_thread_id,
3406 "action": task_action,
3407 "item": "instance_nets",
3408 "item_id": net_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003409 "related": related_network,
tiernof1450872017-10-17 23:15:08 +02003410 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003411 }
tierno7fe82642018-11-26 14:14:51 +00003412 net2task_id['scenario'][sce_net_uuid][datacenter_id] = task_index
tierno868220c2017-09-26 00:11:05 +02003413 task_index += 1
3414 db_vim_actions.append(db_vim_action)
3415
tierno8e690322017-08-10 15:58:50 +02003416 if 'ip_profile' in sce_net:
3417 db_ip_profile={
3418 'instance_net_id': net_uuid,
3419 'ip_version': sce_net['ip_profile']['ip_version'],
3420 'subnet_address': sce_net['ip_profile']['subnet_address'],
3421 'gateway_address': sce_net['ip_profile']['gateway_address'],
3422 'dns_address': sce_net['ip_profile']['dns_address'],
3423 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3424 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3425 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3426 }
3427 db_ip_profiles.append(db_ip_profile)
3428
tierno16e3dd42018-04-24 12:52:40 +02003429 # Create VNFs
3430 vnf_params = {
3431 "default_datacenter_id": default_datacenter_id,
3432 "myvim_threads_id": myvim_threads_id,
3433 "instance_uuid": instance_uuid,
3434 "instance_name": instance_name,
3435 "instance_action_id": instance_action_id,
3436 "myvims": myvims,
3437 "cloud_config": cloud_config,
3438 "RO_pub_key": tenant[0].get('RO_pub_key'),
tierno67881db2018-10-24 18:46:03 +02003439 "instance_parameters": instance_dict,
tierno16e3dd42018-04-24 12:52:40 +02003440 }
3441 vnf_params_out = {
3442 "task_index": task_index,
3443 "uuid_list": uuid_list,
3444 "db_instance_nets": db_instance_nets,
3445 "db_vim_actions": db_vim_actions,
3446 "db_ip_profiles": db_ip_profiles,
3447 "db_instance_vnfs": db_instance_vnfs,
3448 "db_instance_vms": db_instance_vms,
3449 "db_instance_interfaces": db_instance_interfaces,
3450 "net2task_id": net2task_id,
3451 "sce_net2instance": sce_net2instance,
3452 }
tierno55d234c2018-07-04 18:29:21 +02003453 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
tierno7fe82642018-11-26 14:14:51 +00003454 for sce_vnf in scenarioDict.get('vnfs', ()): # sce_vnf_list:
tierno16e3dd42018-04-24 12:52:40 +02003455 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3456 task_index = vnf_params_out["task_index"]
3457 uuid_list = vnf_params_out["uuid_list"]
mirabal29356312017-07-27 12:21:22 +02003458
tierno16e3dd42018-04-24 12:52:40 +02003459 # Create VNFFGs
3460 # task_depends_on = []
tierno7fe82642018-11-26 14:14:51 +00003461 for vnffg in scenarioDict.get('vnffgs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003462 for rsp in vnffg['rsps']:
3463 sfs_created = []
3464 for cp in rsp['connection_points']:
3465 count = mydb.get_rows(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003466 SELECT='vms.count',
3467 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h "
3468 "on interfaces.uuid=h.ingress_interface_id",
Igor D.Ccaadc442017-11-06 12:48:48 +00003469 WHERE={'h.uuid': cp['uuid']})[0]['count']
3470 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3471 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3472 dependencies = []
3473 for instance_vm in instance_vms:
3474 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3475 if action:
3476 dependencies.append(action['task_index'])
3477 # TODO: throw exception if count != len(instance_vms)
3478 # TODO: and action shouldn't ever be None
3479 sfis_created = []
3480 for i in range(count):
3481 # create sfis
3482 sfi_uuid = str(uuid4())
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003483 extra_params = {
3484 "ingress_interface_id": cp["ingress_interface_id"],
3485 "egress_interface_id": cp["egress_interface_id"]
3486 }
Igor D.Ccaadc442017-11-06 12:48:48 +00003487 uuid_list.append(sfi_uuid)
3488 db_sfi = {
3489 "uuid": sfi_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003490 "related": sfi_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003491 "instance_scenario_id": instance_uuid,
3492 'sce_rsp_hop_id': cp['uuid'],
3493 'datacenter_id': datacenter_id,
3494 'datacenter_tenant_id': myvim_thread_id,
3495 "vim_sfi_id": None, # vim thread will populate
3496 }
3497 db_instance_sfis.append(db_sfi)
3498 db_vim_action = {
3499 "instance_action_id": instance_action_id,
3500 "task_index": task_index,
3501 "datacenter_vim_id": myvim_thread_id,
3502 "action": "CREATE",
3503 "status": "SCHEDULED",
3504 "item": "instance_sfis",
3505 "item_id": sfi_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003506 "related": sfi_uuid,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003507 "extra": yaml.safe_dump({"params": extra_params, "depends_on": [dependencies[i]]},
Igor D.Ccaadc442017-11-06 12:48:48 +00003508 default_flow_style=True, width=256)
3509 }
3510 sfis_created.append(task_index)
3511 task_index += 1
3512 db_vim_actions.append(db_vim_action)
3513 # create sfs
3514 sf_uuid = str(uuid4())
3515 uuid_list.append(sf_uuid)
3516 db_sf = {
3517 "uuid": sf_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003518 "related": sf_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003519 "instance_scenario_id": instance_uuid,
3520 'sce_rsp_hop_id': cp['uuid'],
3521 'datacenter_id': datacenter_id,
3522 'datacenter_tenant_id': myvim_thread_id,
3523 "vim_sf_id": None, # vim thread will populate
3524 }
3525 db_instance_sfs.append(db_sf)
3526 db_vim_action = {
3527 "instance_action_id": instance_action_id,
3528 "task_index": task_index,
3529 "datacenter_vim_id": myvim_thread_id,
3530 "action": "CREATE",
3531 "status": "SCHEDULED",
3532 "item": "instance_sfs",
3533 "item_id": sf_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003534 "related": sf_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003535 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3536 default_flow_style=True, width=256)
3537 }
3538 sfs_created.append(task_index)
3539 task_index += 1
3540 db_vim_actions.append(db_vim_action)
3541 classifier = rsp['classifier']
3542
3543 # TODO the following ~13 lines can be reused for the sfi case
3544 count = mydb.get_rows(
3545 SELECT=('vms.count'),
3546 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3547 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3548 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3549 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3550 dependencies = []
3551 for instance_vm in instance_vms:
3552 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3553 if action:
3554 dependencies.append(action['task_index'])
3555 # TODO: throw exception if count != len(instance_vms)
3556 # TODO: and action shouldn't ever be None
3557 classifications_created = []
3558 for i in range(count):
3559 for match in classifier['matches']:
3560 # create classifications
3561 classification_uuid = str(uuid4())
3562 uuid_list.append(classification_uuid)
3563 db_classification = {
3564 "uuid": classification_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003565 "related": classification_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003566 "instance_scenario_id": instance_uuid,
3567 'sce_classifier_match_id': match['uuid'],
3568 'datacenter_id': datacenter_id,
3569 'datacenter_tenant_id': myvim_thread_id,
3570 "vim_classification_id": None, # vim thread will populate
3571 }
3572 db_instance_classifications.append(db_classification)
3573 classification_params = {
3574 "ip_proto": match["ip_proto"],
3575 "source_ip": match["source_ip"],
3576 "destination_ip": match["destination_ip"],
3577 "source_port": match["source_port"],
3578 "destination_port": match["destination_port"]
3579 }
3580 db_vim_action = {
3581 "instance_action_id": instance_action_id,
3582 "task_index": task_index,
3583 "datacenter_vim_id": myvim_thread_id,
3584 "action": "CREATE",
3585 "status": "SCHEDULED",
3586 "item": "instance_classifications",
3587 "item_id": classification_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003588 "related": classification_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003589 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3590 default_flow_style=True, width=256)
3591 }
3592 classifications_created.append(task_index)
3593 task_index += 1
3594 db_vim_actions.append(db_vim_action)
3595
3596 # create sfps
3597 sfp_uuid = str(uuid4())
3598 uuid_list.append(sfp_uuid)
3599 db_sfp = {
3600 "uuid": sfp_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003601 "related": sfp_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003602 "instance_scenario_id": instance_uuid,
3603 'sce_rsp_id': rsp['uuid'],
3604 'datacenter_id': datacenter_id,
3605 'datacenter_tenant_id': myvim_thread_id,
3606 "vim_sfp_id": None, # vim thread will populate
3607 }
3608 db_instance_sfps.append(db_sfp)
3609 db_vim_action = {
3610 "instance_action_id": instance_action_id,
3611 "task_index": task_index,
3612 "datacenter_vim_id": myvim_thread_id,
3613 "action": "CREATE",
3614 "status": "SCHEDULED",
3615 "item": "instance_sfps",
3616 "item_id": sfp_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003617 "related": sfp_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00003618 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3619 default_flow_style=True, width=256)
3620 }
3621 task_index += 1
3622 db_vim_actions.append(db_vim_action)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003623 db_instance_action["number_tasks"] = task_index
3624
3625 # --> WIM
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003626 logger.debug('wim_usage:\n%s\n\n', pformat(wim_usage))
3627 wan_links = wim_engine.derive_wan_links(wim_usage, db_instance_nets, tenant_id)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003628 wim_actions = wim_engine.create_actions(wan_links)
3629 wim_actions, db_instance_action = (
3630 wim_engine.incorporate_actions(wim_actions, db_instance_action))
3631 # <-- WIM
Igor D.Ccaadc442017-11-06 12:48:48 +00003632
tierno867ffe92017-03-27 12:50:34 +02003633 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003634
3635 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3636 db_instance_scenario['datacenter_id'] = default_datacenter_id
3637 db_tables=[
3638 {"instance_scenarios": db_instance_scenario},
3639 {"instance_vnfs": db_instance_vnfs},
3640 {"instance_nets": db_instance_nets},
3641 {"ip_profiles": db_ip_profiles},
3642 {"instance_vms": db_instance_vms},
3643 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003644 {"instance_actions": db_instance_action},
Igor D.Ccaadc442017-11-06 12:48:48 +00003645 {"instance_sfis": db_instance_sfis},
3646 {"instance_sfs": db_instance_sfs},
3647 {"instance_classifications": db_instance_classifications},
3648 {"instance_sfps": db_instance_sfps},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003649 {"instance_wim_nets": wan_links},
3650 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno8e690322017-08-10 15:58:50 +02003651 ]
3652
tierno868220c2017-09-26 00:11:05 +02003653 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003654 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3655 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003656 for myvim_thread_id in myvim_threads_id.values():
3657 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003658
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003659 wim_engine.dispatch(wim_actions)
3660
tierno868220c2017-09-26 00:11:05 +02003661 returned_instance = mydb.get_instance_scenario(instance_uuid)
3662 returned_instance["action_id"] = instance_action_id
3663 return returned_instance
tierno4491ba92019-03-25 15:00:02 +00003664 except (NfvoException, vimconn.vimconnException, wimconn.WimConnectorError, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003665 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003666 if isinstance(e, db_base_Exception):
3667 error_text = "database Exception"
3668 elif isinstance(e, vimconn.vimconnException):
3669 error_text = "VIM Exception"
tierno4491ba92019-03-25 15:00:02 +00003670 elif isinstance(e, wimconn.WimConnectorError):
3671 error_text = "WIM Exception"
tiernof97fd272016-07-11 14:32:37 +02003672 else:
3673 error_text = "Exception"
3674 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003675 # logger.error("create_instance: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003676 logger.exception(e)
tiernof97fd272016-07-11 14:32:37 +02003677 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003678
tiernob3d36742017-03-03 23:51:05 +01003679
tierno16e3dd42018-04-24 12:52:40 +02003680def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3681 default_datacenter_id = params["default_datacenter_id"]
3682 myvim_threads_id = params["myvim_threads_id"]
3683 instance_uuid = params["instance_uuid"]
3684 instance_name = params["instance_name"]
3685 instance_action_id = params["instance_action_id"]
3686 myvims = params["myvims"]
3687 cloud_config = params["cloud_config"]
3688 RO_pub_key = params["RO_pub_key"]
3689
3690 task_index = params_out["task_index"]
3691 uuid_list = params_out["uuid_list"]
3692 db_instance_nets = params_out["db_instance_nets"]
3693 db_vim_actions = params_out["db_vim_actions"]
3694 db_ip_profiles = params_out["db_ip_profiles"]
3695 db_instance_vnfs = params_out["db_instance_vnfs"]
3696 db_instance_vms = params_out["db_instance_vms"]
3697 db_instance_interfaces = params_out["db_instance_interfaces"]
3698 net2task_id = params_out["net2task_id"]
3699 sce_net2instance = params_out["sce_net2instance"]
3700
3701 vnf_net2instance = {}
3702
3703 # 2. Creating new nets (vnf internal nets) in the VIM"
3704 # For each vnf net, we create it and we add it to instanceNetlist.
3705 if sce_vnf.get("datacenter"):
3706 datacenter_id = sce_vnf["datacenter"]
3707 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3708 else:
3709 datacenter_id = default_datacenter_id
3710 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3711 for net in sce_vnf['nets']:
3712 # TODO revis
3713 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3714 # net_name = descriptor_net.get("name")
3715 net_name = None
3716 if not net_name:
tierno1df468d2018-07-06 14:25:16 +02003717 net_name = "{}-{}".format(instance_name, net["name"])
tierno16e3dd42018-04-24 12:52:40 +02003718 net_name = net_name[:255] # limit length
3719 net_type = net['type']
3720
3721 if sce_vnf['uuid'] not in vnf_net2instance:
3722 vnf_net2instance[sce_vnf['uuid']] = {}
3723 if sce_vnf['uuid'] not in net2task_id:
3724 net2task_id[sce_vnf['uuid']] = {}
3725 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3726
3727 # fill database content
3728 net_uuid = str(uuid4())
3729 uuid_list.append(net_uuid)
3730 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3731 db_net = {
3732 "uuid": net_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003733 "related": net_uuid,
tierno16e3dd42018-04-24 12:52:40 +02003734 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003735 "vim_name": net_name,
tierno16e3dd42018-04-24 12:52:40 +02003736 "instance_scenario_id": instance_uuid,
3737 "net_id": net["uuid"],
3738 "created": True,
3739 'datacenter_id': datacenter_id,
3740 'datacenter_tenant_id': myvim_thread_id,
3741 }
3742 db_instance_nets.append(db_net)
3743
gcalvino0a480542018-12-17 16:19:33 +01003744 lookfor_filter = {}
tierno1df468d2018-07-06 14:25:16 +02003745 if net.get("vim-network-name"):
gcalvino0a480542018-12-17 16:19:33 +01003746 lookfor_filter["name"] = net["vim-network-name"]
3747 if net.get("vim-network-id"):
3748 lookfor_filter["id"] = net["vim-network-id"]
3749 if lookfor_filter:
tierno1df468d2018-07-06 14:25:16 +02003750 task_action = "FIND"
3751 task_extra = {"params": (lookfor_filter,)}
3752 else:
3753 task_action = "CREATE"
3754 task_extra = {"params": (net_name, net_type, net.get('ip_profile', None))}
3755
tierno16e3dd42018-04-24 12:52:40 +02003756 db_vim_action = {
3757 "instance_action_id": instance_action_id,
3758 "task_index": task_index,
3759 "datacenter_vim_id": myvim_thread_id,
3760 "status": "SCHEDULED",
tierno1df468d2018-07-06 14:25:16 +02003761 "action": task_action,
tierno16e3dd42018-04-24 12:52:40 +02003762 "item": "instance_nets",
3763 "item_id": net_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00003764 "related": net_uuid,
tierno1df468d2018-07-06 14:25:16 +02003765 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno16e3dd42018-04-24 12:52:40 +02003766 }
3767 task_index += 1
3768 db_vim_actions.append(db_vim_action)
3769
3770 if 'ip_profile' in net:
3771 db_ip_profile = {
3772 'instance_net_id': net_uuid,
3773 'ip_version': net['ip_profile']['ip_version'],
3774 'subnet_address': net['ip_profile']['subnet_address'],
3775 'gateway_address': net['ip_profile']['gateway_address'],
3776 'dns_address': net['ip_profile']['dns_address'],
3777 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3778 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3779 'dhcp_count': net['ip_profile']['dhcp_count'],
3780 }
3781 db_ip_profiles.append(db_ip_profile)
3782
3783 # print "vnf_net2instance:"
3784 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3785
3786 # 3. Creating new vm instances in the VIM
3787 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3788 ssh_access = None
3789 if sce_vnf.get('mgmt_access'):
3790 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3791 vnf_availability_zones = []
gcalvinod6fac4d2018-11-05 10:42:06 +01003792 for vm in sce_vnf.get('vms'):
tierno16e3dd42018-04-24 12:52:40 +02003793 vm_av = vm.get('availability_zone')
3794 if vm_av and vm_av not in vnf_availability_zones:
3795 vnf_availability_zones.append(vm_av)
3796
3797 # check if there is enough availability zones available at vim level.
3798 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3799 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003800 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno16e3dd42018-04-24 12:52:40 +02003801
3802 if sce_vnf.get("datacenter"):
3803 vim = myvims[sce_vnf["datacenter"]]
3804 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3805 datacenter_id = sce_vnf["datacenter"]
3806 else:
3807 vim = myvims[default_datacenter_id]
3808 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3809 datacenter_id = default_datacenter_id
3810 sce_vnf["datacenter_id"] = datacenter_id
3811 i = 0
3812
3813 vnf_uuid = str(uuid4())
3814 uuid_list.append(vnf_uuid)
3815 db_instance_vnf = {
3816 'uuid': vnf_uuid,
3817 'instance_scenario_id': instance_uuid,
3818 'vnf_id': sce_vnf['vnf_id'],
3819 'sce_vnf_id': sce_vnf['uuid'],
3820 'datacenter_id': datacenter_id,
3821 'datacenter_tenant_id': myvim_thread_id,
3822 }
3823 db_instance_vnfs.append(db_instance_vnf)
3824
3825 for vm in sce_vnf['vms']:
tiernob6990792018-11-13 10:37:42 +01003826 # skip PDUs
3827 if vm.get("pdu_type"):
3828 continue
3829
tierno16e3dd42018-04-24 12:52:40 +02003830 myVMDict = {}
tierno7f426e92018-06-28 15:21:32 +02003831 sce_vnf_name = sce_vnf['member_vnf_index'] if sce_vnf['member_vnf_index'] else sce_vnf['name']
3832 myVMDict['name'] = "{}-{}-{}".format(instance_name[:64], sce_vnf_name[:64], vm["name"][:64])
tierno16e3dd42018-04-24 12:52:40 +02003833 myVMDict['description'] = myVMDict['name'][0:99]
3834 # if not startvms:
3835 # myVMDict['start'] = "no"
tierno1df468d2018-07-06 14:25:16 +02003836 if vm.get("instance_parameters") and vm["instance_parameters"].get("name"):
3837 myVMDict['name'] = vm["instance_parameters"].get("name")
tierno16e3dd42018-04-24 12:52:40 +02003838 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3839 # create image at vim in case it not exist
3840 image_uuid = vm['image_id']
3841 if vm.get("image_list"):
3842 for alternative_image in vm["image_list"]:
tiernob6434212018-04-26 16:27:47 +02003843 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
tierno16e3dd42018-04-24 12:52:40 +02003844 image_uuid = alternative_image['image_id']
3845 break
3846 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
3847 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
3848 vm['vim_image_id'] = image_id
3849
3850 # create flavor at vim in case it not exist
3851 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
3852 if flavor_dict['extended'] != None:
3853 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
3854 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3855
3856 # Obtain information for additional disks
3857 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
3858 WHERE={'vim_id': flavor_id})
3859 if not extended_flavor_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003860 raise NfvoException("flavor '{}' not found".format(flavor_id), httperrors.Not_Found)
tierno16e3dd42018-04-24 12:52:40 +02003861
3862 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
3863 myVMDict['disks'] = None
3864 extended_info = extended_flavor_dict[0]['extended']
3865 if extended_info != None:
3866 extended_flavor_dict_yaml = yaml.load(extended_info)
3867 if 'disks' in extended_flavor_dict_yaml:
3868 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
tierno1df468d2018-07-06 14:25:16 +02003869 if vm.get("instance_parameters") and vm["instance_parameters"].get("devices"):
3870 for disk in myVMDict['disks']:
3871 if disk.get("name") in vm["instance_parameters"]["devices"]:
3872 disk.update(vm["instance_parameters"]["devices"][disk.get("name")])
tierno16e3dd42018-04-24 12:52:40 +02003873
3874 vm['vim_flavor_id'] = flavor_id
3875 myVMDict['imageRef'] = vm['vim_image_id']
3876 myVMDict['flavorRef'] = vm['vim_flavor_id']
3877 myVMDict['availability_zone'] = vm.get('availability_zone')
3878 myVMDict['networks'] = []
3879 task_depends_on = []
3880 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno67881db2018-10-24 18:46:03 +02003881 is_management_vm = False
tierno16e3dd42018-04-24 12:52:40 +02003882 db_vm_ifaces = []
3883 for iface in vm['interfaces']:
3884 netDict = {}
3885 if iface['type'] == "data":
3886 netDict['type'] = iface['model']
3887 elif "model" in iface and iface["model"] != None:
3888 netDict['model'] = iface['model']
3889 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3890 # is obtained from iterface table model
3891 # discover type of interface looking at flavor
3892 for numa in flavor_dict.get('extended', {}).get('numas', []):
3893 for flavor_iface in numa.get('interfaces', []):
3894 if flavor_iface.get('name') == iface['internal_name']:
3895 if flavor_iface['dedicated'] == 'yes':
3896 netDict['type'] = "PF" # passthrough
3897 elif flavor_iface['dedicated'] == 'no':
3898 netDict['type'] = "VF" # siov
3899 elif flavor_iface['dedicated'] == 'yes:sriov':
3900 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
3901 netDict["mac_address"] = flavor_iface.get("mac_address")
3902 break
3903 netDict["use"] = iface['type']
3904 if netDict["use"] == "data" and not netDict.get("type"):
3905 # print "netDict", netDict
3906 # print "iface", iface
3907 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3908 sce_vnf['name'], vm['name'], iface['internal_name'])
3909 if flavor_dict.get('extended') == None:
3910 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003911 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tierno16e3dd42018-04-24 12:52:40 +02003912 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003913 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tierno67881db2018-10-24 18:46:03 +02003914 if netDict["use"] == "mgmt":
3915 is_management_vm = True
3916 netDict["type"] = "virtual"
3917 if netDict["use"] == "bridge":
tierno16e3dd42018-04-24 12:52:40 +02003918 netDict["type"] = "virtual"
3919 if iface.get("vpci"):
3920 netDict['vpci'] = iface['vpci']
3921 if iface.get("mac"):
3922 netDict['mac_address'] = iface['mac']
tierno6082b7d2018-08-31 11:24:08 +00003923 if iface.get("mac_address"):
3924 netDict['mac_address'] = iface['mac_address']
tierno16e3dd42018-04-24 12:52:40 +02003925 if iface.get("ip_address"):
3926 netDict['ip_address'] = iface['ip_address']
3927 if iface.get("port-security") is not None:
3928 netDict['port_security'] = iface['port-security']
3929 if iface.get("floating-ip") is not None:
3930 netDict['floating_ip'] = iface['floating-ip']
3931 netDict['name'] = iface['internal_name']
3932 if iface['net_id'] is None:
3933 for vnf_iface in sce_vnf["interfaces"]:
3934 # print iface
3935 # print vnf_iface
3936 if vnf_iface['interface_id'] == iface['uuid']:
3937 netDict['net_id'] = "TASK-{}".format(
3938 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3939 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
3940 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3941 break
3942 else:
3943 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
3944 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
3945 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
3946 # skip bridge ifaces not connected to any net
3947 if 'net_id' not in netDict or netDict['net_id'] == None:
3948 continue
3949 myVMDict['networks'].append(netDict)
3950 db_vm_iface = {
3951 # "uuid"
3952 # 'instance_vm_id': instance_vm_uuid,
3953 "instance_net_id": instance_net_id,
3954 'interface_id': iface['uuid'],
3955 # 'vim_interface_id': ,
3956 'type': 'external' if iface['external_name'] is not None else 'internal',
3957 'ip_address': iface.get('ip_address'),
3958 'mac_address': iface.get('mac'),
3959 'floating_ip': int(iface.get('floating-ip', False)),
3960 'port_security': int(iface.get('port-security', True))
3961 }
3962 db_vm_ifaces.append(db_vm_iface)
3963 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3964 # print myVMDict['name']
3965 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3966 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3967 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3968
3969 # We add the RO key to cloud_config if vnf will need ssh access
3970 cloud_config_vm = cloud_config
tierno67881db2018-10-24 18:46:03 +02003971 if is_management_vm and params["instance_parameters"].get("mgmt_keys"):
3972 cloud_config_vm = unify_cloud_config({"key-pairs": params["instance_parameters"]["mgmt_keys"]},
3973 cloud_config_vm)
3974
3975 if vm.get("instance_parameters") and vm["instance_parameters"].get("mgmt_keys"):
3976 cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
3977 cloud_config_vm)
3978 # if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3979 # RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3980 # cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
tierno16e3dd42018-04-24 12:52:40 +02003981 if vm.get("boot_data"):
3982 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3983
3984 if myVMDict.get('availability_zone'):
3985 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
3986 else:
3987 av_index = None
3988 for vm_index in range(0, vm.get('count', 1)):
tiernofc5f80b2018-05-29 16:00:43 +02003989 vm_name = myVMDict['name'] + "-" + str(vm_index+1)
3990 task_params = (vm_name, myVMDict['description'], myVMDict.get('start', None),
tierno16e3dd42018-04-24 12:52:40 +02003991 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3992 myVMDict['disks'], av_index, vnf_availability_zones)
3993 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3994 for net in myVMDict['networks']:
3995 if "vim_id" in net:
3996 for iface in vm['interfaces']:
3997 if net["name"] == iface["internal_name"]:
3998 iface["vim_id"] = net["vim_id"]
3999 break
4000 vm_uuid = str(uuid4())
4001 uuid_list.append(vm_uuid)
4002 db_vm = {
4003 "uuid": vm_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00004004 "related": vm_uuid,
tierno16e3dd42018-04-24 12:52:40 +02004005 'instance_vnf_id': vnf_uuid,
4006 # TODO delete "vim_vm_id": vm_id,
4007 "vm_id": vm["uuid"],
tiernofc5f80b2018-05-29 16:00:43 +02004008 "vim_name": vm_name,
tierno16e3dd42018-04-24 12:52:40 +02004009 # "status":
4010 }
4011 db_instance_vms.append(db_vm)
4012
4013 iface_index = 0
4014 for db_vm_iface in db_vm_ifaces:
4015 iface_uuid = str(uuid4())
4016 uuid_list.append(iface_uuid)
4017 db_vm_iface_instance = {
4018 "uuid": iface_uuid,
4019 "instance_vm_id": vm_uuid
4020 }
4021 db_vm_iface_instance.update(db_vm_iface)
4022 if db_vm_iface_instance.get("ip_address"): # increment ip_address
4023 ip = db_vm_iface_instance.get("ip_address")
4024 i = ip.rfind(".")
4025 if i > 0:
4026 try:
4027 i += 1
4028 ip = ip[i:] + str(int(ip[:i]) + 1)
4029 db_vm_iface_instance["ip_address"] = ip
4030 except:
4031 db_vm_iface_instance["ip_address"] = None
4032 db_instance_interfaces.append(db_vm_iface_instance)
4033 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
4034 iface_index += 1
4035
4036 db_vim_action = {
4037 "instance_action_id": instance_action_id,
4038 "task_index": task_index,
4039 "datacenter_vim_id": myvim_thread_id,
4040 "action": "CREATE",
4041 "status": "SCHEDULED",
4042 "item": "instance_vms",
4043 "item_id": vm_uuid,
tierno3c44e7b2019-03-04 17:32:01 +00004044 "related": vm_uuid,
tierno16e3dd42018-04-24 12:52:40 +02004045 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
4046 default_flow_style=True, width=256)
4047 }
4048 task_index += 1
4049 db_vim_actions.append(db_vim_action)
4050 params_out["task_index"] = task_index
4051 params_out["uuid_list"] = uuid_list
4052
4053
tierno7edb6752016-03-21 17:37:52 +01004054def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02004055 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004056 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02004057 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01004058 tenant_id = instanceDict["tenant_id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004059
4060 # --> WIM
4061 # We need to retrieve the WIM Actions now, before the instance_scenario is
4062 # deleted. The reason for that is that: ON CASCADE rules will delete the
4063 # instance_wim_nets record in the database
4064 wim_actions = wim_engine.delete_actions(instance_scenario_id=instance_id)
4065 # <-- WIM
4066
tierno868220c2017-09-26 00:11:05 +02004067 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno868220c2017-09-26 00:11:05 +02004068 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02004069 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01004070
tierno868220c2017-09-26 00:11:05 +02004071 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00004072 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01004073 myvims = {}
4074 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02004075 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02004076 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01004077
tierno868220c2017-09-26 00:11:05 +02004078 task_index = 0
4079 instance_action_id = get_task_id()
4080 db_vim_actions = []
4081 db_instance_action = {
4082 "uuid": instance_action_id, # same uuid for the instance and the action on create
4083 "tenant_id": tenant_id,
4084 "instance_id": instance_id,
4085 "description": "DELETE",
4086 # "number_tasks": 0 # filled bellow
4087 }
4088
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004089 # 2.1 deleting VNFFGs
tierno69b590e2018-03-13 18:52:23 +01004090 for sfp in instanceDict.get('sfps', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004091 vimthread_affected[sfp["datacenter_tenant_id"]] = None
4092 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
4093 if datacenter_key not in myvims:
4094 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004095 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004096 except NfvoException as e:
4097 logger.error(str(e))
4098 myvim_thread = None
4099 myvim_threads[datacenter_key] = myvim_thread
4100 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
4101 datacenter_tenant_id=sfp["datacenter_tenant_id"])
4102 if len(vims) == 0:
4103 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
4104 myvims[datacenter_key] = None
4105 else:
4106 myvims[datacenter_key] = vims.values()[0]
4107 myvim = myvims[datacenter_key]
4108 myvim_thread = myvim_threads[datacenter_key]
4109
4110 if not myvim:
4111 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
4112 continue
4113 extra = {"params": (sfp['vim_sfp_id'])}
4114 db_vim_action = {
4115 "instance_action_id": instance_action_id,
4116 "task_index": task_index,
4117 "datacenter_vim_id": sfp["datacenter_tenant_id"],
4118 "action": "DELETE",
4119 "status": "SCHEDULED",
4120 "item": "instance_sfps",
4121 "item_id": sfp["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004122 "related": sfp["related"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004123 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4124 }
4125 task_index += 1
4126 db_vim_actions.append(db_vim_action)
4127
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004128 for classification in instanceDict['classifications']:
4129 vimthread_affected[classification["datacenter_tenant_id"]] = None
4130 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
4131 if datacenter_key not in myvims:
4132 try:
4133 _, myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
4134 except NfvoException as e:
4135 logger.error(str(e))
4136 myvim_thread = None
4137 myvim_threads[datacenter_key] = myvim_thread
4138 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
4139 datacenter_tenant_id=classification["datacenter_tenant_id"])
4140 if len(vims) == 0:
4141 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"],
4142 classification["datacenter_tenant_id"]))
4143 myvims[datacenter_key] = None
4144 else:
4145 myvims[datacenter_key] = vims.values()[0]
4146 myvim = myvims[datacenter_key]
4147 myvim_thread = myvim_threads[datacenter_key]
4148
4149 if not myvim:
4150 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'],
4151 classification["datacenter_id"])
4152 continue
4153 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4154 extra = {"params": (classification['vim_classification_id']), "depends_on": depends_on}
4155 db_vim_action = {
4156 "instance_action_id": instance_action_id,
4157 "task_index": task_index,
4158 "datacenter_vim_id": classification["datacenter_tenant_id"],
4159 "action": "DELETE",
4160 "status": "SCHEDULED",
4161 "item": "instance_classifications",
4162 "item_id": classification["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004163 "related": classification["related"],
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004164 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4165 }
4166 task_index += 1
4167 db_vim_actions.append(db_vim_action)
4168
tierno69b590e2018-03-13 18:52:23 +01004169 for sf in instanceDict.get('sfs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004170 vimthread_affected[sf["datacenter_tenant_id"]] = None
4171 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
4172 if datacenter_key not in myvims:
4173 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004174 _, myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004175 except NfvoException as e:
4176 logger.error(str(e))
4177 myvim_thread = None
4178 myvim_threads[datacenter_key] = myvim_thread
4179 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
4180 datacenter_tenant_id=sf["datacenter_tenant_id"])
4181 if len(vims) == 0:
4182 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
4183 myvims[datacenter_key] = None
4184 else:
4185 myvims[datacenter_key] = vims.values()[0]
4186 myvim = myvims[datacenter_key]
4187 myvim_thread = myvim_threads[datacenter_key]
4188
4189 if not myvim:
4190 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
4191 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004192 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4193 extra = {"params": (sf['vim_sf_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004194 db_vim_action = {
4195 "instance_action_id": instance_action_id,
4196 "task_index": task_index,
4197 "datacenter_vim_id": sf["datacenter_tenant_id"],
4198 "action": "DELETE",
4199 "status": "SCHEDULED",
4200 "item": "instance_sfs",
4201 "item_id": sf["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004202 "related": sf["related"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004203 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4204 }
4205 task_index += 1
4206 db_vim_actions.append(db_vim_action)
4207
tierno69b590e2018-03-13 18:52:23 +01004208 for sfi in instanceDict.get('sfis', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004209 vimthread_affected[sfi["datacenter_tenant_id"]] = None
4210 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4211 if datacenter_key not in myvims:
4212 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004213 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004214 except NfvoException as e:
4215 logger.error(str(e))
4216 myvim_thread = None
4217 myvim_threads[datacenter_key] = myvim_thread
4218 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
4219 datacenter_tenant_id=sfi["datacenter_tenant_id"])
4220 if len(vims) == 0:
4221 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
4222 myvims[datacenter_key] = None
4223 else:
4224 myvims[datacenter_key] = vims.values()[0]
4225 myvim = myvims[datacenter_key]
4226 myvim_thread = myvim_threads[datacenter_key]
4227
4228 if not myvim:
4229 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
4230 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004231 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfs"]
4232 extra = {"params": (sfi['vim_sfi_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004233 db_vim_action = {
4234 "instance_action_id": instance_action_id,
4235 "task_index": task_index,
4236 "datacenter_vim_id": sfi["datacenter_tenant_id"],
4237 "action": "DELETE",
4238 "status": "SCHEDULED",
4239 "item": "instance_sfis",
4240 "item_id": sfi["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004241 "related": sfi["related"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004242 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4243 }
4244 task_index += 1
4245 db_vim_actions.append(db_vim_action)
4246
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004247 # 2.2 deleting VMs
4248 # vm_fail_list=[]
gcalvinod6fac4d2018-11-05 10:42:06 +01004249 for sce_vnf in instanceDict.get('vnfs', ()):
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004250 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4251 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
Igor D.Ccaadc442017-11-06 12:48:48 +00004252 if datacenter_key not in myvims:
4253 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004254 _, 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 +00004255 except NfvoException as e:
4256 logger.error(str(e))
4257 myvim_thread = None
4258 myvim_threads[datacenter_key] = myvim_thread
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004259 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
4260 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004261 if len(vims) == 0:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004262 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
4263 sce_vnf["datacenter_tenant_id"]))
4264 myvims[datacenter_key] = None
4265 else:
4266 myvims[datacenter_key] = vims.values()[0]
4267 myvim = myvims[datacenter_key]
4268 myvim_thread = myvim_threads[datacenter_key]
4269
4270 for vm in sce_vnf['vms']:
4271 if not myvim:
4272 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
4273 continue
4274 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4275 db_vim_action = {
4276 "instance_action_id": instance_action_id,
4277 "task_index": task_index,
4278 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
4279 "action": "DELETE",
4280 "status": "SCHEDULED",
4281 "item": "instance_vms",
4282 "item_id": vm["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004283 "related": vm["related"],
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004284 "extra": yaml.safe_dump({"params": vm["interfaces"], "depends_on": sfi_dependencies},
4285 default_flow_style=True, width=256)
4286 }
4287 db_vim_actions.append(db_vim_action)
4288 for interface in vm["interfaces"]:
4289 if not interface.get("instance_net_id"):
4290 continue
4291 if interface["instance_net_id"] not in net2vm_dependencies:
4292 net2vm_dependencies[interface["instance_net_id"]] = []
4293 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
4294 task_index += 1
4295
4296 # 2.3 deleting NETS
4297 # net_fail_list=[]
4298 for net in instanceDict['nets']:
4299 vimthread_affected[net["datacenter_tenant_id"]] = None
4300 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4301 if datacenter_key not in myvims:
4302 try:
gcalvinod6fac4d2018-11-05 10:42:06 +01004303 _,myvim_thread = get_vim_thread(mydb, tenant_id, net["datacenter_id"], net["datacenter_tenant_id"])
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004304 except NfvoException as e:
4305 logger.error(str(e))
4306 myvim_thread = None
4307 myvim_threads[datacenter_key] = myvim_thread
4308 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
4309 datacenter_tenant_id=net["datacenter_tenant_id"])
4310 if len(vims) == 0:
4311 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 +00004312 myvims[datacenter_key] = None
4313 else:
4314 myvims[datacenter_key] = vims.values()[0]
4315 myvim = myvims[datacenter_key]
4316 myvim_thread = myvim_threads[datacenter_key]
4317
4318 if not myvim:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004319 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 +00004320 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004321 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
4322 if net2vm_dependencies.get(net["uuid"]):
4323 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
4324 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4325 if len(sfi_dependencies) > 0:
4326 if "depends_on" in extra:
4327 extra["depends_on"] += sfi_dependencies
4328 else:
4329 extra["depends_on"] = sfi_dependencies
Igor D.Ccaadc442017-11-06 12:48:48 +00004330 db_vim_action = {
4331 "instance_action_id": instance_action_id,
4332 "task_index": task_index,
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004333 "datacenter_vim_id": net["datacenter_tenant_id"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004334 "action": "DELETE",
4335 "status": "SCHEDULED",
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004336 "item": "instance_nets",
4337 "item_id": net["uuid"],
tierno3c44e7b2019-03-04 17:32:01 +00004338 "related": net["related"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004339 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4340 }
4341 task_index += 1
4342 db_vim_actions.append(db_vim_action)
4343
tierno868220c2017-09-26 00:11:05 +02004344 db_instance_action["number_tasks"] = task_index
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004345
4346 # --> WIM
4347 wim_actions, db_instance_action = (
4348 wim_engine.incorporate_actions(wim_actions, db_instance_action))
4349 # <-- WIM
4350
tierno868220c2017-09-26 00:11:05 +02004351 db_tables = [
4352 {"instance_actions": db_instance_action},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004353 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno868220c2017-09-26 00:11:05 +02004354 ]
4355
4356 logger.debug("delete_instance done DB tables: %s",
4357 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4358 mydb.new_rows(db_tables, ())
4359 for myvim_thread_id in vimthread_affected.keys():
4360 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4361
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004362 wim_engine.dispatch(wim_actions)
4363
tiernob3d36742017-03-03 23:51:05 +01004364 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02004365 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4366 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01004367 else:
tierno868220c2017-09-26 00:11:05 +02004368 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01004369
tierno7f426e92018-06-28 15:21:32 +02004370def get_instance_id(mydb, tenant_id, instance_id):
4371 global ovim
4372 #check valid tenant_id
4373 check_tenant(mydb, tenant_id)
4374 #obtain data
4375
4376 instance_dict = mydb.get_instance_scenario(instance_id, tenant_id, verbose=True)
4377 for net in instance_dict["nets"]:
4378 if net.get("sdn_net_id"):
4379 net_sdn = ovim.show_network(net["sdn_net_id"])
4380 net["sdn_info"] = {
4381 "admin_state_up": net_sdn.get("admin_state_up"),
4382 "flows": net_sdn.get("flows"),
4383 "last_error": net_sdn.get("last_error"),
4384 "ports": net_sdn.get("ports"),
4385 "type": net_sdn.get("type"),
4386 "status": net_sdn.get("status"),
4387 "vlan": net_sdn.get("vlan"),
4388 }
4389 return instance_dict
tiernob3d36742017-03-03 23:51:05 +01004390
tiernob8569aa2018-08-24 11:34:54 +02004391@deprecated("Instance is automatically refreshed by vim_threads")
tierno7edb6752016-03-21 17:37:52 +01004392def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4393 '''Refreshes a scenario instance. It modifies instanceDict'''
4394 '''Returns:
4395 - 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
4396 - error_msg
4397 '''
tierno867ffe92017-03-27 12:50:34 +02004398 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4399 # #print "nfvo.refresh_instance begins"
4400 # #print json.dumps(instanceDict, indent=4)
4401 #
4402 # #print "Getting the VIM URL and the VIM tenant_id"
4403 # myvims={}
4404 #
4405 # # 1. Getting VIM vm and net list
4406 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4407 # vms_notupdated=[]
4408 # vm_list = {}
4409 # for sce_vnf in instanceDict['vnfs']:
4410 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4411 # if datacenter_key not in vm_list:
4412 # vm_list[datacenter_key] = []
4413 # if datacenter_key not in myvims:
4414 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4415 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4416 # if len(vims) == 0:
4417 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4418 # myvims[datacenter_key] = None
4419 # else:
4420 # myvims[datacenter_key] = vims.values()[0]
4421 # for vm in sce_vnf['vms']:
4422 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4423 # vms_notupdated.append(vm["uuid"])
4424 #
4425 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4426 # nets_notupdated=[]
4427 # net_list = {}
4428 # for net in instanceDict['nets']:
4429 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4430 # if datacenter_key not in net_list:
4431 # net_list[datacenter_key] = []
4432 # if datacenter_key not in myvims:
4433 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4434 # datacenter_tenant_id=net["datacenter_tenant_id"])
4435 # if len(vims) == 0:
4436 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4437 # myvims[datacenter_key] = None
4438 # else:
4439 # myvims[datacenter_key] = vims.values()[0]
4440 #
4441 # net_list[datacenter_key].append(net['vim_net_id'])
4442 # nets_notupdated.append(net["uuid"])
4443 #
4444 # # 1. Getting the status of all VMs
4445 # vm_dict={}
4446 # for datacenter_key in myvims:
4447 # if not vm_list.get(datacenter_key):
4448 # continue
4449 # failed = True
4450 # failed_message=""
4451 # if not myvims[datacenter_key]:
4452 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4453 # else:
4454 # try:
4455 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4456 # failed = False
4457 # except vimconn.vimconnException as e:
4458 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4459 # failed_message = str(e)
4460 # if failed:
4461 # for vm in vm_list[datacenter_key]:
4462 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4463 #
4464 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4465 # for sce_vnf in instanceDict['vnfs']:
4466 # for vm in sce_vnf['vms']:
4467 # vm_id = vm['vim_vm_id']
4468 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4469 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4470 # has_mgmt_iface = False
4471 # for iface in vm["interfaces"]:
4472 # if iface["type"]=="mgmt":
4473 # has_mgmt_iface = True
4474 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4475 # vm_dict[vm_id]['status'] = "ACTIVE"
4476 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4477 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4478 # 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'):
4479 # vm['status'] = vm_dict[vm_id]['status']
4480 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4481 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4482 # # 2.1. Update in openmano DB the VMs whose status changed
4483 # try:
4484 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4485 # vms_notupdated.remove(vm["uuid"])
4486 # if updates>0:
4487 # vms_updated.append(vm["uuid"])
4488 # except db_base_Exception as e:
4489 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4490 # # 2.2. Update in openmano DB the interface VMs
4491 # for interface in interfaces:
4492 # #translate from vim_net_id to instance_net_id
4493 # network_id_list=[]
4494 # for net in instanceDict['nets']:
4495 # if net["vim_net_id"] == interface["vim_net_id"]:
4496 # network_id_list.append(net["uuid"])
4497 # if not network_id_list:
4498 # continue
4499 # del interface["vim_net_id"]
4500 # try:
4501 # for network_id in network_id_list:
4502 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4503 # except db_base_Exception as e:
4504 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4505 #
4506 # # 3. Getting the status of all nets
4507 # net_dict = {}
4508 # for datacenter_key in myvims:
4509 # if not net_list.get(datacenter_key):
4510 # continue
4511 # failed = True
4512 # failed_message = ""
4513 # if not myvims[datacenter_key]:
4514 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4515 # else:
4516 # try:
4517 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4518 # failed = False
4519 # except vimconn.vimconnException as e:
4520 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4521 # failed_message = str(e)
4522 # if failed:
4523 # for net in net_list[datacenter_key]:
4524 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4525 #
4526 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4527 # # TODO: update nets inside a vnf
4528 # for net in instanceDict['nets']:
4529 # net_id = net['vim_net_id']
4530 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4531 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4532 # 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'):
4533 # net['status'] = net_dict[net_id]['status']
4534 # net['error_msg'] = net_dict[net_id].get('error_msg')
4535 # net['vim_info'] = net_dict[net_id].get('vim_info')
4536 # # 5.1. Update in openmano DB the nets whose status changed
4537 # try:
4538 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4539 # nets_notupdated.remove(net["uuid"])
4540 # if updated>0:
4541 # nets_updated.append(net["uuid"])
4542 # except db_base_Exception as e:
4543 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4544 #
4545 # # Returns appropriate output
4546 # #print "nfvo.refresh_instance finishes"
4547 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4548 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01004549 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02004550 # if len(vms_notupdated)+len(nets_notupdated)>0:
4551 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4552 # 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 +01004553
tiernoae4a8d12016-07-08 12:30:39 +02004554 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01004555
4556def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02004557 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004558 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01004559 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4560
tiernoae4a8d12016-07-08 12:30:39 +02004561 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02004562 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4563 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004564 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004565 myvim = vims.values()[0]
tiernofc5f80b2018-05-29 16:00:43 +02004566 vm_result = {}
4567 vm_error = 0
4568 vm_ok = 0
tierno42026a02017-02-10 15:13:40 +01004569
tiernofc5f80b2018-05-29 16:00:43 +02004570 myvim_threads_id = {}
4571 if action_dict.get("vdu-scaling"):
4572 db_instance_vms = []
4573 db_vim_actions = []
4574 db_instance_interfaces = []
4575 instance_action_id = get_task_id()
4576 db_instance_action = {
4577 "uuid": instance_action_id, # same uuid for the instance and the action on create
4578 "tenant_id": nfvo_tenant,
4579 "instance_id": instance_id,
4580 "description": "SCALE",
4581 }
4582 vm_result["instance_action_id"] = instance_action_id
tierno67881db2018-10-24 18:46:03 +02004583 vm_result["created"] = []
4584 vm_result["deleted"] = []
tiernofc5f80b2018-05-29 16:00:43 +02004585 task_index = 0
4586 for vdu in action_dict["vdu-scaling"]:
tierno868220c2017-09-26 00:11:05 +02004587 vdu_id = vdu.get("vdu-id")
tiernofc5f80b2018-05-29 16:00:43 +02004588 osm_vdu_id = vdu.get("osm_vdu_id")
4589 member_vnf_index = vdu.get("member-vnf-index")
tierno868220c2017-09-26 00:11:05 +02004590 vdu_count = vdu.get("count", 1)
tiernofc5f80b2018-05-29 16:00:43 +02004591 if vdu_id:
tierno67881db2018-10-24 18:46:03 +02004592 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004593 FROM="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4594 WHERE={"vms.uuid": vdu_id},
4595 ORDER_BY="vms.created_at"
4596 )
tierno67881db2018-10-24 18:46:03 +02004597 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004598 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id), httperrors.Not_Found)
tiernofc5f80b2018-05-29 16:00:43 +02004599 else:
4600 if not osm_vdu_id and not member_vnf_index:
tiernoa43bd9e2018-11-26 09:28:58 +00004601 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
tierno67881db2018-10-24 18:46:03 +02004602 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004603 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4604 FROM="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4605 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4606 " join vms on ivms.vm_id=vms.uuid",
tiernoa43bd9e2018-11-26 09:28:58 +00004607 WHERE={"vms.osm_id": osm_vdu_id, "svnfs.member_vnf_index": member_vnf_index,
4608 "ivnfs.instance_scenario_id": instance_id},
tiernofc5f80b2018-05-29 16:00:43 +02004609 ORDER_BY="ivms.created_at"
4610 )
tierno67881db2018-10-24 18:46:03 +02004611 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004612 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 +02004613 vdu_id = target_vms[-1]["uuid"]
4614 target_vm = target_vms[-1]
tiernofc5f80b2018-05-29 16:00:43 +02004615 datacenter = target_vm["datacenter_id"]
4616 myvim_threads_id[datacenter], _ = get_vim_thread(mydb, nfvo_tenant, datacenter)
tiernofc5f80b2018-05-29 16:00:43 +02004617
tierno67881db2018-10-24 18:46:03 +02004618 if vdu["type"] == "delete":
4619 for index in range(0, vdu_count):
4620 target_vm = target_vms[-1-index]
4621 vdu_id = target_vm["uuid"]
4622 # look for nm
4623 vm_interfaces = None
4624 for sce_vnf in instanceDict['vnfs']:
4625 for vm in sce_vnf['vms']:
4626 if vm["uuid"] == vdu_id:
tiernob5091bd2019-05-22 16:45:09 +00004627 # TODO revise this should not be vm["uuid"] instance_vms["vm_id"]
tierno67881db2018-10-24 18:46:03 +02004628 vm_interfaces = vm["interfaces"]
4629 break
4630
4631 db_vim_action = {
4632 "instance_action_id": instance_action_id,
4633 "task_index": task_index,
4634 "datacenter_vim_id": target_vm["datacenter_tenant_id"],
4635 "action": "DELETE",
4636 "status": "SCHEDULED",
4637 "item": "instance_vms",
4638 "item_id": vdu_id,
tiernob5091bd2019-05-22 16:45:09 +00004639 "related": target_vm["related"],
tierno67881db2018-10-24 18:46:03 +02004640 "extra": yaml.safe_dump({"params": vm_interfaces},
4641 default_flow_style=True, width=256)
4642 }
4643 task_index += 1
4644 db_vim_actions.append(db_vim_action)
4645 vm_result["deleted"].append(vdu_id)
4646 # delete from database
4647 db_instance_vms.append({"TO-DELETE": vdu_id})
tiernofc5f80b2018-05-29 16:00:43 +02004648
4649 else: # vdu["type"] == "create":
4650 iface2iface = {}
4651 where = {"item": "instance_vms", "item_id": target_vm["uuid"], "action": "CREATE"}
4652
garciadeblas72cd59f2018-12-05 10:59:40 +01004653 vim_action_to_clone = mydb.get_rows(FROM="vim_wim_actions", WHERE=where)
tiernofc5f80b2018-05-29 16:00:43 +02004654 if not vim_action_to_clone:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004655 raise NfvoException("Cannot find the vim_action at database with {}".format(where), httperrors.Internal_Server_Error)
tiernofc5f80b2018-05-29 16:00:43 +02004656 vim_action_to_clone = vim_action_to_clone[0]
4657 extra = yaml.safe_load(vim_action_to_clone["extra"])
4658
4659 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4660 # TODO do the same for flavor and image when available
4661 task_depends_on = []
4662 task_params = extra["params"]
4663 task_params_networks = deepcopy(task_params[5])
4664 for iface in task_params[5]:
4665 if iface["net_id"].startswith("TASK-"):
4666 if "." not in iface["net_id"]:
4667 task_depends_on.append("{}.{}".format(vim_action_to_clone["instance_action_id"],
4668 iface["net_id"][5:]))
4669 iface["net_id"] = "TASK-{}.{}".format(vim_action_to_clone["instance_action_id"],
4670 iface["net_id"][5:])
4671 else:
4672 task_depends_on.append(iface["net_id"][5:])
4673 if "mac_address" in iface:
4674 del iface["mac_address"]
4675
4676 vm_ifaces_to_clone = mydb.get_rows(FROM="instance_interfaces", WHERE={"instance_vm_id": target_vm["uuid"]})
4677 for index in range(0, vdu_count):
4678 vm_uuid = str(uuid4())
4679 vm_name = target_vm.get('vim_name')
4680 try:
4681 suffix = vm_name.rfind("-")
tierno67881db2018-10-24 18:46:03 +02004682 vm_name = vm_name[:suffix+1] + str(index + 1 + int(vm_name[suffix+1:]))
tiernofc5f80b2018-05-29 16:00:43 +02004683 except Exception:
4684 pass
4685 db_instance_vm = {
4686 "uuid": vm_uuid,
tiernob5091bd2019-05-22 16:45:09 +00004687 'related': vm_uuid,
tiernofc5f80b2018-05-29 16:00:43 +02004688 'instance_vnf_id': target_vm['instance_vnf_id'],
4689 'vm_id': target_vm['vm_id'],
tiernob5091bd2019-05-22 16:45:09 +00004690 'vim_name': vm_name,
tiernofc5f80b2018-05-29 16:00:43 +02004691 }
4692 db_instance_vms.append(db_instance_vm)
4693
4694 for vm_iface in vm_ifaces_to_clone:
4695 iface_uuid = str(uuid4())
4696 iface2iface[vm_iface["uuid"]] = iface_uuid
4697 db_vm_iface = {
4698 "uuid": iface_uuid,
4699 'instance_vm_id': vm_uuid,
4700 "instance_net_id": vm_iface["instance_net_id"],
4701 'interface_id': vm_iface['interface_id'],
4702 'type': vm_iface['type'],
4703 'floating_ip': vm_iface['floating_ip'],
4704 'port_security': vm_iface['port_security']
4705 }
4706 db_instance_interfaces.append(db_vm_iface)
4707 task_params_copy = deepcopy(task_params)
4708 for iface in task_params_copy[5]:
4709 iface["uuid"] = iface2iface[iface["uuid"]]
4710 # increment ip_address
4711 if "ip_address" in iface:
4712 ip = iface.get("ip_address")
4713 i = ip.rfind(".")
4714 if i > 0:
4715 try:
4716 i += 1
4717 ip = ip[i:] + str(int(ip[:i]) + 1)
4718 iface["ip_address"] = ip
4719 except:
4720 iface["ip_address"] = None
4721 if vm_name:
4722 task_params_copy[0] = vm_name
4723 db_vim_action = {
4724 "instance_action_id": instance_action_id,
4725 "task_index": task_index,
4726 "datacenter_vim_id": vim_action_to_clone["datacenter_vim_id"],
4727 "action": "CREATE",
4728 "status": "SCHEDULED",
4729 "item": "instance_vms",
4730 "item_id": vm_uuid,
tiernob5091bd2019-05-22 16:45:09 +00004731 "related": vm_uuid,
tiernofc5f80b2018-05-29 16:00:43 +02004732 # ALF
4733 # ALF
4734 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4735 # ALF
4736 # ALF
4737 "extra": yaml.safe_dump({"params": task_params_copy, "depends_on": task_depends_on}, default_flow_style=True, width=256)
4738 }
4739 task_index += 1
4740 db_vim_actions.append(db_vim_action)
tierno67881db2018-10-24 18:46:03 +02004741 vm_result["created"].append(vm_uuid)
tiernofc5f80b2018-05-29 16:00:43 +02004742
4743 db_instance_action["number_tasks"] = task_index
4744 db_tables = [
4745 {"instance_vms": db_instance_vms},
4746 {"instance_interfaces": db_instance_interfaces},
4747 {"instance_actions": db_instance_action},
4748 # TODO revise sfps
4749 # {"instance_sfis": db_instance_sfis},
4750 # {"instance_sfs": db_instance_sfs},
4751 # {"instance_classifications": db_instance_classifications},
4752 # {"instance_sfps": db_instance_sfps},
garciadeblasaba7a0d2018-12-05 12:42:35 +01004753 {"vim_wim_actions": db_vim_actions}
tiernofc5f80b2018-05-29 16:00:43 +02004754 ]
4755 logger.debug("create_vdu done DB tables: %s",
4756 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4757 mydb.new_rows(db_tables, [])
4758 for myvim_thread in myvim_threads_id.values():
4759 vim_threads["running"][myvim_thread].insert_task(db_vim_actions)
4760
4761 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004762
4763 input_vnfs = action_dict.pop("vnfs", [])
4764 input_vms = action_dict.pop("vms", [])
tierno92c36fd2018-05-04 12:21:10 +02004765 action_over_all = True if not input_vnfs and not input_vms else False
tierno7edb6752016-03-21 17:37:52 +01004766 for sce_vnf in instanceDict['vnfs']:
4767 for vm in sce_vnf['vms']:
tierno92c36fd2018-05-04 12:21:10 +02004768 if not action_over_all and sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4769 sce_vnf['member_vnf_index'] not in input_vnfs and \
4770 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
4771 continue
tiernoae4a8d12016-07-08 12:30:39 +02004772 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004773 if "add_public_key" in action_dict:
4774 mgmt_access = {}
4775 if sce_vnf.get('mgmt_access'):
4776 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4777 ssh_access = mgmt_access['config-access']['ssh-access']
4778 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01004779 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004780 if ssh_access['required'] and ssh_access['default-user']:
4781 if 'ip_address' in vm:
4782 mgmt_ip = vm['ip_address'].split(';')
4783 password = mgmt_access['config-access'].get('password')
4784 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4785 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4786 action_dict['add_public_key'],
4787 password=password, ro_key=priv_RO_key)
4788 else:
4789 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004790 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004791 except KeyError:
4792 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004793 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004794 else:
4795 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004796 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004797 else:
4798 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4799 if "console" in action_dict:
4800 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02004801 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4802 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4803 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02004804 ip = data["server"],
4805 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02004806 suffix = data["suffix"]),
4807 "name":vm['name']
4808 }
4809 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004810 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004811 vm_result[ vm['uuid'] ] = {"vim_result": -httperrors.Unauthorized,
gcalvinoe580c7d2017-09-22 14:09:51 +02004812 "description": "this console is only reachable by local interface",
4813 "name":vm['name']
4814 }
tierno20fc2a22016-08-19 17:02:35 +02004815 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004816 else:
4817 #print "console data", data
4818 try:
4819 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4820 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4821 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4822 protocol=data["protocol"],
4823 ip = global_config["http_console_host"],
4824 port = console_thread.port,
4825 suffix = data["suffix"]),
4826 "name":vm['name']
4827 }
4828 vm_ok +=1
4829 except NfvoException as e:
4830 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4831 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02004832
gcalvinoe580c7d2017-09-22 14:09:51 +02004833 else:
4834 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4835 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02004836 except vimconn.vimconnException as e:
4837 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4838 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01004839
4840 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02004841 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004842 else:
tierno351863c2016-07-23 01:46:03 +02004843 return vm_result
tierno42026a02017-02-10 15:13:40 +01004844
tierno868220c2017-09-26 00:11:05 +02004845def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
tierno16e3dd42018-04-24 12:52:40 +02004846 filter = {}
tierno868220c2017-09-26 00:11:05 +02004847 if nfvo_tenant and nfvo_tenant != "any":
4848 filter["tenant_id"] = nfvo_tenant
4849 if instance_id and instance_id != "any":
4850 filter["instance_id"] = instance_id
4851 if action_id:
4852 filter["uuid"] = action_id
4853 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
tierno16e3dd42018-04-24 12:52:40 +02004854 if action_id:
4855 if not rows:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004856 raise NfvoException("Not found any action with this criteria", httperrors.Not_Found)
4857 vim_wim_actions = mydb.get_rows(FROM="vim_wim_actions", WHERE={"instance_action_id": action_id})
4858 rows[0]["vim_wim_actions"] = vim_wim_actions
tierno31e121f2018-12-03 12:04:48 +00004859 # for backward compatibility set vim_actions = vim_wim_actions
4860 rows[0]["vim_actions"] = vim_wim_actions
tiernofc5f80b2018-05-29 16:00:43 +02004861 return {"actions": rows}
tierno868220c2017-09-26 00:11:05 +02004862
tiernob3d36742017-03-03 23:51:05 +01004863
tierno7edb6752016-03-21 17:37:52 +01004864def create_or_use_console_proxy_thread(console_server, console_port):
4865 #look for a non-used port
4866 console_thread_key = console_server + ":" + str(console_port)
4867 if console_thread_key in global_config["console_thread"]:
4868 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02004869 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01004870
tierno7edb6752016-03-21 17:37:52 +01004871 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02004872 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01004873 if port in global_config["console_ports"]:
4874 continue
4875 try:
4876 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4877 clithread.start()
4878 global_config["console_thread"][console_thread_key] = clithread
4879 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02004880 return clithread
tierno7edb6752016-03-21 17:37:52 +01004881 except cli.ConsoleProxyExceptionPortUsed as e:
4882 #port used, try with onoher
4883 continue
4884 except cli.ConsoleProxyException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004885 raise NfvoException(str(e), httperrors.Bad_Request)
4886 raise NfvoException("Not found any free 'http_console_ports'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004887
tiernob3d36742017-03-03 23:51:05 +01004888
tierno7edb6752016-03-21 17:37:52 +01004889def check_tenant(mydb, tenant_id):
4890 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02004891 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4892 if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004893 raise NfvoException("tenant '{}' not found".format(tenant_id), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02004894 return
tierno7edb6752016-03-21 17:37:52 +01004895
4896def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01004897
gcalvinoe580c7d2017-09-22 14:09:51 +02004898 tenant_uuid = str(uuid4())
4899 tenant_dict['uuid'] = tenant_uuid
4900 try:
4901 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4902 tenant_dict['RO_pub_key'] = pub_key
4903 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02004904 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02004905 except db_base_Exception as e:
tierno9c5c8322018-03-23 15:44:03 +01004906 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
gcalvinoe580c7d2017-09-22 14:09:51 +02004907 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01004908
tierno7edb6752016-03-21 17:37:52 +01004909def delete_tenant(mydb, tenant):
4910 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01004911
tiernof97fd272016-07-11 14:32:37 +02004912 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4913 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4914 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01004915
tiernob3d36742017-03-03 23:51:05 +01004916
tierno7edb6752016-03-21 17:37:52 +01004917def new_datacenter(mydb, datacenter_descriptor):
tierno1c848c02018-05-21 16:40:33 +02004918 sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004919 if "config" in datacenter_descriptor:
tiernoedf3f4f2018-05-17 23:02:47 +02004920 sdn_port_mapping = datacenter_descriptor["config"].pop("sdn-port-mapping", None)
4921 datacenter_descriptor["config"] = yaml.safe_dump(datacenter_descriptor["config"], default_flow_style=True,
4922 width=256)
4923 # Check that datacenter-type is correct
tierno3ae39742016-09-07 12:17:51 +02004924 datacenter_type = datacenter_descriptor.get("type", "openvim");
tiernoedf3f4f2018-05-17 23:02:47 +02004925 # module_info = None
tierno3ae39742016-09-07 12:17:51 +02004926 try:
4927 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02004928 pkg = __import__("osm_ro." + module)
tiernoedf3f4f2018-05-17 23:02:47 +02004929 # vim_conn = getattr(pkg, module)
tierno361275f2017-04-25 16:24:34 +02004930 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02004931 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02004932 # if module_info and module_info[0]:
4933 # file.close(module_info[0])
tiernoedf3f4f2018-05-17 23:02:47 +02004934 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type,
4935 module),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004936 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01004937
gcalvinoc62cfa52017-10-05 18:21:25 +02004938 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernoedf3f4f2018-05-17 23:02:47 +02004939 if sdn_port_mapping:
4940 try:
4941 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, sdn_port_mapping)
4942 except Exception as e:
4943 mydb.delete_row_by_id("datacenters", datacenter_id) # Rollback
4944 raise e
tiernof97fd272016-07-11 14:32:37 +02004945 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004946
tiernob3d36742017-03-03 23:51:05 +01004947
tierno7edb6752016-03-21 17:37:52 +01004948def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02004949 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02004950 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02004951
4952 # edit data
tiernof97fd272016-07-11 14:32:37 +02004953 datacenter_id = datacenter['uuid']
tiernod72182f2018-08-29 10:56:13 +02004954 where = {'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02004955 remove_port_mapping = False
tiernoedf3f4f2018-05-17 23:02:47 +02004956 new_sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004957 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02004958 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01004959 try:
4960 new_config_dict = datacenter_descriptor["config"]
tiernoedf3f4f2018-05-17 23:02:47 +02004961 if "sdn-port-mapping" in new_config_dict:
4962 remove_port_mapping = True
4963 new_sdn_port_mapping = new_config_dict.pop("sdn-port-mapping")
tiernod72182f2018-08-29 10:56:13 +02004964 # delete null fields
4965 to_delete = []
tierno7edb6752016-03-21 17:37:52 +01004966 for k in new_config_dict:
tiernod72182f2018-08-29 10:56:13 +02004967 if new_config_dict[k] is None:
tierno7edb6752016-03-21 17:37:52 +01004968 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02004969 if k == 'sdn-controller':
4970 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01004971
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004972 config_text = datacenter.get("config")
4973 if not config_text:
4974 config_text = '{}'
4975 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01004976 config_dict.update(new_config_dict)
tiernod72182f2018-08-29 10:56:13 +02004977 # delete null fields
tierno7edb6752016-03-21 17:37:52 +01004978 for k in to_delete:
4979 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02004980 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004981 raise NfvoException("Bad format at datacenter:config " + str(e), httperrors.Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02004982 if config_dict:
4983 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4984 else:
4985 datacenter_descriptor["config"] = None
4986 if remove_port_mapping:
4987 try:
4988 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4989 except ovimException as e:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004990 raise NfvoException("Error deleting datacenter-port-mapping " + str(e), httperrors.Conflict)
tierno8fe7a492017-07-11 13:50:04 +02004991
tiernof97fd272016-07-11 14:32:37 +02004992 mydb.update_rows('datacenters', datacenter_descriptor, where)
tiernoedf3f4f2018-05-17 23:02:47 +02004993 if new_sdn_port_mapping:
4994 try:
4995 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, new_sdn_port_mapping)
4996 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004997 # Rollback
4998 mydb.update_rows('datacenters', datacenter, where)
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004999 raise NfvoException("Error adding datacenter-port-mapping " + str(e), httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02005000 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01005001
tiernob3d36742017-03-03 23:51:05 +01005002
tierno7edb6752016-03-21 17:37:52 +01005003def delete_datacenter(mydb, datacenter):
5004 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02005005 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
5006 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02005007 try:
5008 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
5009 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02005010 raise NfvoException("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02005011 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01005012
tiernob3d36742017-03-03 23:51:05 +01005013
tiernod3750b32018-07-20 15:33:08 +02005014def create_vim_account(mydb, nfvo_tenant, datacenter_id, name=None, vim_id=None, vim_tenant=None, vim_tenant_name=None,
5015 vim_username=None, vim_password=None, config=None):
tierno9c22f2d2017-10-09 16:23:55 +02005016 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02005017 try:
tiernod3750b32018-07-20 15:33:08 +02005018 if not datacenter_id:
5019 if not vim_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005020 raise NfvoException("You must provide 'vim_id", http_code=httperrors.Bad_Request)
tiernod3750b32018-07-20 15:33:08 +02005021 datacenter_id = vim_id
5022 datacenter_id, datacenter_name = get_datacenter_uuid(mydb, None, datacenter_id)
tierno7edb6752016-03-21 17:37:52 +01005023
tiernod3750b32018-07-20 15:33:08 +02005024 create_vim_tenant = True if not vim_tenant and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01005025
tierno0ea2a7e2017-10-18 00:06:26 +02005026 # get nfvo_tenant info
5027 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
5028 if vim_tenant_name==None:
5029 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01005030
tierno0ea2a7e2017-10-18 00:06:26 +02005031 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernod3750b32018-07-20 15:33:08 +02005032 # #check that this association does not exist before
5033 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5034 # if len(tenants_datacenters)>0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005035 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01005036
tierno0ea2a7e2017-10-18 00:06:26 +02005037 vim_tenant_id_exist_atdb=False
5038 if not create_vim_tenant:
5039 where_={"datacenter_id": datacenter_id}
tiernod3750b32018-07-20 15:33:08 +02005040 if vim_tenant!=None:
5041 where_["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02005042 if vim_tenant_name!=None:
5043 where_["vim_tenant_name"] = vim_tenant_name
5044 #check if vim_tenant_id is already at database
5045 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
5046 if len(datacenter_tenants_dict)>=1:
5047 datacenter_tenants_dict = datacenter_tenants_dict[0]
5048 vim_tenant_id_exist_atdb=True
5049 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
5050 else: #result=0
5051 datacenter_tenants_dict = {}
5052 #insert at table datacenter_tenants
tiernod3750b32018-07-20 15:33:08 +02005053 else: #if vim_tenant==None:
tierno0ea2a7e2017-10-18 00:06:26 +02005054 #create tenant at VIM if not provided
5055 try:
5056 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
5057 vim_passwd=vim_password)
5058 datacenter_name = myvim["name"]
tiernod3750b32018-07-20 15:33:08 +02005059 vim_tenant = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
tierno0ea2a7e2017-10-18 00:06:26 +02005060 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005061 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 +01005062 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02005063 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01005064
tierno0ea2a7e2017-10-18 00:06:26 +02005065 #fill datacenter_tenants table
5066 if not vim_tenant_id_exist_atdb:
tiernod3750b32018-07-20 15:33:08 +02005067 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02005068 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
5069 datacenter_tenants_dict["user"] = vim_username
5070 datacenter_tenants_dict["passwd"] = vim_password
5071 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernod3750b32018-07-20 15:33:08 +02005072 if name:
5073 datacenter_tenants_dict["name"] = name
5074 else:
5075 datacenter_tenants_dict["name"] = datacenter_name
tierno0ea2a7e2017-10-18 00:06:26 +02005076 if config:
5077 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
5078 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
5079 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01005080
tierno0ea2a7e2017-10-18 00:06:26 +02005081 #fill tenants_datacenters table
5082 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
5083 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
5084 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tiernod3750b32018-07-20 15:33:08 +02005085
tierno0ea2a7e2017-10-18 00:06:26 +02005086 # create thread
tierno0ea2a7e2017-10-18 00:06:26 +02005087 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tiernod3750b32018-07-20 15:33:08 +02005088 new_thread = vim_thread.vim_thread(task_lock, thread_name, datacenter_name, datacenter_tenant_id,
tierno0ea2a7e2017-10-18 00:06:26 +02005089 db=db, db_lock=db_lock, ovim=ovim)
5090 new_thread.start()
5091 thread_id = datacenter_tenants_dict["uuid"]
5092 vim_threads["running"][thread_id] = new_thread
tiernod3750b32018-07-20 15:33:08 +02005093 return thread_id
tierno0ea2a7e2017-10-18 00:06:26 +02005094 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005095 raise NfvoException(str(e), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005096
tierno99314902017-04-26 13:23:09 +02005097
tiernod3750b32018-07-20 15:33:08 +02005098def edit_vim_account(mydb, nfvo_tenant, datacenter_tenant_id, datacenter_id=None, name=None, vim_tenant=None,
5099 vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005100
tiernod3750b32018-07-20 15:33:08 +02005101 # get vim_account; check is valid for this tenant
5102 from_ = "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
5103 where_ = {"td.nfvo_tenant_id": nfvo_tenant}
5104 if datacenter_tenant_id:
5105 where_["dt.uuid"] = datacenter_tenant_id
5106 if datacenter_id:
5107 where_["dt.datacenter_id"] = datacenter_id
5108 vim_accounts = mydb.get_rows(SELECT="dt.uuid as uuid, config", FROM=from_, WHERE=where_)
5109 if not vim_accounts:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005110 raise NfvoException("vim_account not found for this tenant", http_code=httperrors.Not_Found)
tiernod3750b32018-07-20 15:33:08 +02005111 elif len(vim_accounts) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005112 raise NfvoException("found more than one vim_account for this tenant", http_code=httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02005113 datacenter_tenant_id = vim_accounts[0]["uuid"]
5114 original_config = vim_accounts[0]["config"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005115
tiernod3750b32018-07-20 15:33:08 +02005116 update_ = {}
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005117 if config:
tiernod3750b32018-07-20 15:33:08 +02005118 original_config_dict = yaml.load(original_config)
5119 original_config_dict.update(config)
5120 update["config"] = yaml.safe_dump(original_config_dict, default_flow_style=True, width=256)
5121 if name:
5122 update_['name'] = name
5123 if vim_tenant:
5124 update_['vim_tenant_id'] = vim_tenant
5125 if vim_tenant_name:
5126 update_['vim_tenant_name'] = vim_tenant_name
5127 if vim_username:
5128 update_['user'] = vim_username
5129 if vim_password:
5130 update_['passwd'] = vim_password
5131 if update_:
5132 mydb.update_rows("datacenter_tenants", UPDATE=update_, WHERE={"uuid": datacenter_tenant_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005133
tiernod3750b32018-07-20 15:33:08 +02005134 vim_threads["running"][datacenter_tenant_id].insert_task("reload")
5135 return datacenter_tenant_id
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005136
tiernod3750b32018-07-20 15:33:08 +02005137def delete_vim_account(mydb, tenant_id, vim_account_id, datacenter=None):
tierno7edb6752016-03-21 17:37:52 +01005138 #get nfvo_tenant info
5139 if not tenant_id or tenant_id=="any":
5140 tenant_uuid = None
5141 else:
tiernof97fd272016-07-11 14:32:37 +02005142 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01005143 tenant_uuid = tenant_dict['uuid']
5144
5145 #check that this association exist before
tiernod3750b32018-07-20 15:33:08 +02005146 tenants_datacenter_dict = {}
5147 if datacenter:
5148 datacenter_id, _ = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
5149 tenants_datacenter_dict["datacenter_id"] = datacenter_id
5150 elif vim_account_id:
5151 tenants_datacenter_dict["datacenter_tenant_id"] = vim_account_id
tierno7edb6752016-03-21 17:37:52 +01005152 if tenant_uuid:
5153 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02005154 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5155 if len(tenant_datacenter_list)==0 and tenant_uuid:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005156 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005157
5158 #delete this association
tiernof97fd272016-07-11 14:32:37 +02005159 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01005160
5161 #get vim_tenant info and deletes
5162 warning=''
5163 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02005164 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5165 #try to delete vim:tenant
5166 try:
5167 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5168 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01005169 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01005170 try:
tierno0ea2a7e2017-10-18 00:06:26 +02005171 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005172 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
5173 except vimconn.vimconnException as e:
5174 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
5175 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02005176 except db_base_Exception as e:
5177 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01005178 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02005179 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tiernoa3572692018-05-14 13:09:33 +02005180 thread = vim_threads["running"].get(thread_id)
5181 if thread:
5182 thread.insert_task("exit")
5183 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02005184 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01005185
tiernob3d36742017-03-03 23:51:05 +01005186
tierno7edb6752016-03-21 17:37:52 +01005187def datacenter_action(mydb, tenant_id, datacenter, action_dict):
5188 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01005189 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005190 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005191
tierno5509c2e2019-07-04 16:23:20 +00005192 if 'check-connectivity' in action_dict:
5193 try:
5194 myvim.check_vim_connectivity()
5195 except vimconn.vimconnException as e:
5196 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
5197 raise NfvoException(str(e), e.http_code)
5198 elif 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02005199 try:
tiernof97fd272016-07-11 14:32:37 +02005200 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02005201 #print content
5202 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005203 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005204 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01005205 #update nets Change from VIM format to NFVO format
5206 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005207 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01005208 net_nfvo={'datacenter_id': datacenter_id}
5209 net_nfvo['name'] = net['name']
5210 #net_nfvo['description']= net['name']
5211 net_nfvo['vim_net_id'] = net['id']
5212 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5213 net_nfvo['shared'] = net['shared']
5214 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5215 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02005216 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
5217 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
5218 return inserted
tierno7edb6752016-03-21 17:37:52 +01005219 elif 'net-edit' in action_dict:
5220 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02005221 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005222 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01005223 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005224 return result
tierno7edb6752016-03-21 17:37:52 +01005225 elif 'net-delete' in action_dict:
5226 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02005227 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005228 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01005229 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005230 return result
tierno7edb6752016-03-21 17:37:52 +01005231
5232 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005233 raise NfvoException("Unknown action " + str(action_dict), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005234
tiernob3d36742017-03-03 23:51:05 +01005235
tierno7edb6752016-03-21 17:37:52 +01005236def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
5237 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005238 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005239
tierno42fcc3b2016-07-06 17:20:40 +02005240 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01005241 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01005242 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02005243 return result
tierno7edb6752016-03-21 17:37:52 +01005244
tiernob3d36742017-03-03 23:51:05 +01005245
tierno7edb6752016-03-21 17:37:52 +01005246def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
5247 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005248 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005249 filter_dict={}
5250 if action_dict:
5251 action_dict = action_dict["netmap"]
5252 if 'vim_id' in action_dict:
5253 filter_dict["id"] = action_dict['vim_id']
5254 if 'vim_name' in action_dict:
5255 filter_dict["name"] = action_dict['vim_name']
5256 else:
5257 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01005258
tiernoae4a8d12016-07-08 12:30:39 +02005259 try:
tiernof97fd272016-07-11 14:32:37 +02005260 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005261 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005262 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005263 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tiernof97fd272016-07-11 14:32:37 +02005264 if len(vim_nets)>1 and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005265 raise NfvoException("more than two networks found, specify with vim_id", httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02005266 elif len(vim_nets)==0: # and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005267 raise NfvoException("Not found a network at VIM with " + str(filter_dict), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005268 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005269 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01005270 net_nfvo={'datacenter_id': datacenter_id}
5271 if action_dict and "name" in action_dict:
5272 net_nfvo['name'] = action_dict['name']
5273 else:
5274 net_nfvo['name'] = net['name']
5275 #net_nfvo['description']= net['name']
5276 net_nfvo['vim_net_id'] = net['id']
5277 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5278 net_nfvo['shared'] = net['shared']
5279 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02005280 try:
5281 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01005282 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02005283 net_nfvo["uuid"] = net_id
5284 except db_base_Exception as e:
5285 if action_dict:
5286 raise
5287 else:
5288 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01005289 net_list.append(net_nfvo)
5290 return net_list
tierno7edb6752016-03-21 17:37:52 +01005291
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005292def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
5293 # obtain all network data
5294 try:
5295 if utils.check_valid_uuid(network_id):
5296 filter_dict = {"id": network_id}
5297 else:
5298 filter_dict = {"name": network_id}
5299
5300 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5301 network = myvim.get_network_list(filter_dict=filter_dict)
5302 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02005303 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 +02005304
5305 # ensure the network is defined
5306 if len(network) == 0:
5307 raise NfvoException("Network {} is not present in the system".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005308 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005309
5310 # ensure there is only one network with the provided name
5311 if len(network) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005312 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005313
5314 # ensure it is a dataplane network
5315 if network[0]['type'] != 'data':
5316 return None
5317
5318 # ensure we use the id
5319 network_id = network[0]['id']
5320
5321 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5322 # and with instance_scenario_id==NULL
5323 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5324 search_dict = {'vim_net_id': network_id}
5325
5326 try:
5327 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5328 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
5329 except db_base_Exception as e:
5330 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005331 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005332
5333 sdn_net_counter = 0
5334 for net in result:
5335 if net['sdn_net_id'] != None:
5336 sdn_net_counter+=1
5337 sdn_net_id = net['sdn_net_id']
5338
5339 if sdn_net_counter == 0:
5340 return None
5341 elif sdn_net_counter == 1:
5342 return sdn_net_id
5343 else:
5344 raise NfvoException("More than one SDN network is associated to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005345 network_id), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005346
5347def get_sdn_controller_id(mydb, datacenter):
5348 # Obtain sdn controller id
5349 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
5350 if not config:
5351 return None
5352
5353 return yaml.load(config).get('sdn-controller')
5354
5355def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
5356 try:
5357 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5358 if not sdn_network_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005359 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 +02005360
5361 #Obtain sdn controller id
5362 controller_id = get_sdn_controller_id(mydb, datacenter)
5363 if not controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005364 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005365
5366 #Obtain sdn controller info
5367 sdn_controller = ovim.show_of_controller(controller_id)
5368
5369 port_data = {
5370 'name': 'external_port',
5371 'net_id': sdn_network_id,
5372 'ofc_id': controller_id,
5373 'switch_dpid': sdn_controller['dpid'],
5374 'switch_port': descriptor['port']
5375 }
5376
5377 if 'vlan' in descriptor:
5378 port_data['vlan'] = descriptor['vlan']
5379 if 'mac' in descriptor:
5380 port_data['mac'] = descriptor['mac']
5381
5382 result = ovim.new_port(port_data)
5383 except ovimException as e:
5384 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005385 sdn_network_id, network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005386 except db_base_Exception as e:
5387 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005388 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005389
5390 return 'Port uuid: '+ result
5391
5392def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
5393 if port_id:
5394 filter = {'uuid': port_id}
5395 else:
5396 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5397 if not sdn_network_id:
5398 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005399 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005400 #in case no port_id is specified only ports marked as 'external_port' will be detached
5401 filter = {'name': 'external_port', 'net_id': sdn_network_id}
5402
5403 try:
5404 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
5405 except ovimException as e:
5406 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005407 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005408
5409 if len(port_list) == 0:
5410 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005411 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005412
5413 port_uuid_list = []
5414 for port in port_list:
5415 try:
5416 port_uuid_list.append(port['uuid'])
5417 ovim.delete_port(port['uuid'])
5418 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005419 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 +02005420
5421 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01005422
tierno7edb6752016-03-21 17:37:52 +01005423def vim_action_get(mydb, tenant_id, datacenter, item, name):
5424 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005425 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005426 filter_dict={}
5427 if name:
tierno42fcc3b2016-07-06 17:20:40 +02005428 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01005429 filter_dict["id"] = name
5430 else:
5431 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02005432 try:
5433 if item=="networks":
5434 #filter_dict['tenant_id'] = myvim['tenant_id']
5435 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005436
5437 if len(content) == 0:
5438 raise NfvoException("Network {} is not present in the system. ".format(name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005439 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005440
5441 #Update the networks with the attached ports
5442 for net in content:
5443 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
5444 if sdn_network_id != None:
5445 try:
5446 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5447 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
5448 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005449 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 +02005450 #Remove field name and if port name is external_port save it as 'type'
5451 for port in port_list:
5452 if port['name'] == 'external_port':
5453 port['type'] = "External"
5454 del port['name']
5455 net['sdn_network_id'] = sdn_network_id
5456 net['sdn_attached_ports'] = port_list
5457
tiernoae4a8d12016-07-08 12:30:39 +02005458 elif item=="tenants":
5459 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01005460 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005461
tierno4540ea52017-01-18 17:44:32 +01005462 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005463 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005464 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02005465 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02005466 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02005467 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02005468 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02005469 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 +02005470 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005471 else:
tiernof97fd272016-07-11 14:32:37 +02005472 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02005473 except vimconn.vimconnException as e:
5474 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02005475 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01005476
tiernob3d36742017-03-03 23:51:05 +01005477
tierno7edb6752016-03-21 17:37:52 +01005478def vim_action_delete(mydb, tenant_id, datacenter, item, name):
5479 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02005480 if tenant_id == "any":
5481 tenant_id=None
5482
tiernoa2793912016-10-04 08:15:08 +00005483 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02005484 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02005485 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
5486 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02005487 items = content.values()[0]
5488 if type(items)==list and len(items)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005489 raise NfvoException("Not found " + item, httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005490 elif type(items)==list and len(items)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005491 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005492 else: # it is a dict
5493 item_id = items["id"]
5494 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01005495
tiernoae4a8d12016-07-08 12:30:39 +02005496 try:
5497 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005498 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5499 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
5500 if sdn_network_id != None:
5501 #Delete any port attachment to this network
5502 try:
5503 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
5504 except ovimException as e:
5505 raise NfvoException(
5506 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005507 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005508
5509 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5510 for port in port_list:
5511 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
5512
5513 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5514 try:
5515 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
5516 except db_base_Exception as e:
5517 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
tierno9c5c8322018-03-23 15:44:03 +01005518 str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005519
5520 #Delete the SDN network
5521 try:
5522 ovim.delete_network(sdn_network_id)
5523 except ovimException as e:
5524 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
5525 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005526 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005527
tiernoae4a8d12016-07-08 12:30:39 +02005528 content = myvim.delete_network(item_id)
5529 elif item=="tenants":
5530 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01005531 elif item == "images":
5532 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02005533 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005534 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005535 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005536 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5537 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005538
tiernof97fd272016-07-11 14:32:37 +02005539 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01005540
tiernob3d36742017-03-03 23:51:05 +01005541
tierno7edb6752016-03-21 17:37:52 +01005542def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
5543 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005544 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02005545 if tenant_id == "any":
5546 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00005547 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005548 try:
5549 if item=="networks":
5550 net = descriptor["network"]
5551 net_name = net.pop("name")
5552 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02005553 net_public = net.pop("shared", False)
5554 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01005555 net_vlan = net.pop("vlan", None)
garciadeblasebd66722019-01-31 16:01:31 +00005556 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 +02005557
5558 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5559 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
tierno00e3df72017-11-29 17:20:13 +01005560 #obtain datacenter_tenant_id
5561 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
5562 FROM='datacenter_tenants',
5563 WHERE={'datacenter_id': datacenter})[0]['uuid']
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005564 try:
5565 sdn_network = {}
5566 sdn_network['vlan'] = net_vlan
5567 sdn_network['type'] = net_type
5568 sdn_network['name'] = net_name
tierno00e3df72017-11-29 17:20:13 +01005569 sdn_network['region'] = datacenter_tenant_id
garciadeblasebd66722019-01-31 16:01:31 +00005570 ovim_content = ovim.new_network(sdn_network)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005571 except ovimException as e:
tierno00e3df72017-11-29 17:20:13 +01005572 logger.error("ovimException creating SDN network={} ".format(
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005573 sdn_network) + str(e), exc_info=True)
5574 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005575 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005576
5577 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5578 # use instance_scenario_id=None to distinguish from real instaces of nets
tierno00e3df72017-11-29 17:20:13 +01005579 correspondence = {'instance_scenario_id': None,
5580 'sdn_net_id': ovim_content,
5581 'vim_net_id': content,
5582 'datacenter_tenant_id': datacenter_tenant_id
5583 }
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005584 try:
5585 mydb.new_row('instance_nets', correspondence, add_uuid=True)
5586 except db_base_Exception as e:
tierno00e3df72017-11-29 17:20:13 +01005587 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005588 correspondence, e), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005589 elif item=="tenants":
5590 tenant = descriptor["tenant"]
5591 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
5592 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005593 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005594 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005595 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005596
tierno7edb6752016-03-21 17:37:52 +01005597 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005598
5599def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005600 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005601 logger.debug('New SDN controller created with uuid {}'.format(data))
5602 return data
5603
5604def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005605 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005606 msg = 'SDN controller {} updated'.format(data)
5607 logger.debug(msg)
5608 return msg
5609
5610def sdn_controller_list(mydb, tenant_id, controller_id=None):
5611 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005612 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005613 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005614 data = ovim.show_of_controller(controller_id)
5615
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005616 msg = 'SDN controller list:\n {}'.format(data)
5617 logger.debug(msg)
5618 return data
5619
5620def sdn_controller_delete(mydb, tenant_id, controller_id):
5621 select_ = ('uuid', 'config')
5622 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5623 for datacenter in datacenters:
5624 if datacenter['config']:
5625 config = yaml.load(datacenter['config'])
5626 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005627 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), httperrors.Conflict)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005628
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005629 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005630 msg = 'SDN controller {} deleted'.format(data)
5631 logger.debug(msg)
5632 return msg
5633
5634def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5635 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5636 if len(controller) < 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005637 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), httperrors.Not_Found)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005638
5639 try:
5640 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
5641 except:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005642 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005643
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005644 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5645 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005646
5647 maps = list()
5648 for compute_node in sdn_port_mapping:
5649 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5650 element = dict()
5651 element["compute_node"] = compute_node["compute_node"]
5652 for port in compute_node["ports"]:
tierno7f426e92018-06-28 15:21:32 +02005653 pci = port.get("pci")
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005654 element["switch_port"] = port.get("switch_port")
5655 element["switch_mac"] = port.get("switch_mac")
tierno4070e442019-01-23 10:19:23 +00005656 if not element["switch_port"] and not element["switch_mac"]:
5657 raise NfvoException ("The mapping must contain 'switch_port' or 'switch_mac'", httperrors.Bad_Request)
tierno7f426e92018-06-28 15:21:32 +02005658 for pci_expanded in utils.expand_brackets(pci):
5659 element["pci"] = pci_expanded
5660 maps.append(dict(element))
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005661
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005662 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 +01005663
5664def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005665 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005666
5667 result = {
5668 "sdn-controller": None,
5669 "datacenter-id": datacenter_id,
5670 "dpid": None,
5671 "ports_mapping": list()
5672 }
5673
5674 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5675 if datacenter['config']:
5676 config = yaml.load(datacenter['config'])
5677 if 'sdn-controller' in config:
5678 controller_id = config['sdn-controller']
5679 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5680 result["sdn-controller"] = controller_id
5681 result["dpid"] = sdn_controller["dpid"]
5682
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005683 if result["sdn-controller"] == None:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005684 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005685 if result["dpid"] == None:
5686 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005687 httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005688
5689 if len(maps) == 0:
5690 return result
5691
5692 ports_correspondence_dict = dict()
5693 for link in maps:
5694 if result["sdn-controller"] != link["ofc_id"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005695 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005696 if result["dpid"] != link["switch_dpid"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005697 raise NfvoException("The dpid specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005698 element = dict()
5699 element["pci"] = link["pci"]
5700 if link["switch_port"]:
5701 element["switch_port"] = link["switch_port"]
5702 if link["switch_mac"]:
5703 element["switch_mac"] = link["switch_mac"]
5704
5705 if not link["compute_node"] in ports_correspondence_dict:
5706 content = dict()
5707 content["compute_node"] = link["compute_node"]
5708 content["ports"] = list()
5709 ports_correspondence_dict[link["compute_node"]] = content
5710
5711 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5712
5713 for key in sorted(ports_correspondence_dict):
5714 result["ports_mapping"].append(ports_correspondence_dict[key])
5715
5716 return result
5717
5718def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02005719 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02005720
5721def create_RO_keypair(tenant_id):
5722 """
5723 Creates a public / private keys for a RO tenant and returns their values
5724 Params:
5725 tenant_id: ID of the tenant
5726 Return:
5727 public_key: Public key for the RO tenant
5728 private_key: Encrypted private key for RO tenant
5729 """
5730
5731 bits = 2048
5732 key = RSA.generate(bits)
5733 try:
5734 public_key = key.publickey().exportKey('OpenSSH')
5735 if isinstance(public_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005736 raise NfvoException("Unable to create public key: {}".format(public_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005737 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5738 except (ValueError, NameError) as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005739 raise NfvoException("Unable to create private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005740 return public_key, private_key
5741
5742def decrypt_key (key, tenant_id):
5743 """
5744 Decrypts an encrypted RSA key
5745 Params:
5746 key: Private key to be decrypted
5747 tenant_id: ID of the tenant
5748 Return:
5749 unencrypted_key: Unencrypted private key for RO tenant
5750 """
5751 try:
5752 key = RSA.importKey(key,tenant_id)
5753 unencrypted_key = key.exportKey('PEM')
5754 if isinstance(unencrypted_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005755 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005756 except ValueError as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005757 raise NfvoException("Unable to decrypt the private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005758 return unencrypted_key