blob: 4b7ecc415ae12c9139bc90c5dbbd80b95c70bfae [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
tierno92021022018-09-12 16:29:23 +02004# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
tierno7edb6752016-03-21 17:37:52 +01005# This file is part of openmano
6# All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License. You may obtain
10# a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
21# contact with: nfvlabs@tid.es
22##
23
24'''
25NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
26'''
27__author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28__date__ ="$16-sep-2014 22:05:01$"
29
tierno361275f2017-04-25 16:24:34 +020030# import imp
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010031import json
tierno7edb6752016-03-21 17:37:52 +010032import yaml
tierno42fcc3b2016-07-06 17:20:40 +020033import utils
tiernob8569aa2018-08-24 11:34:54 +020034from utils import deprecated
tierno42026a02017-02-10 15:13:40 +010035import vim_thread
tierno7edb6752016-03-21 17:37:52 +010036import console_proxy_thread as cli
tiernoae4a8d12016-07-08 12:30:39 +020037import vimconn
38import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020039import collections
tierno66eba6e2017-11-10 17:09:18 +010040import math
tierno8e690322017-08-10 15:58:50 +020041from uuid import uuid4
tiernof97fd272016-07-11 14:32:37 +020042from db_base import db_base_Exception
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010043
tiernob3d36742017-03-03 23:51:05 +010044import nfvo_db
45from threading import Lock
tierno868220c2017-09-26 00:11:05 +020046import time as t
tierno01b3e172017-04-21 10:52:34 +020047from lib_osm_openvim import ovim as ovim_module
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +020048from lib_osm_openvim.ovim import ovimException
gcalvinoe580c7d2017-09-22 14:09:51 +020049from Crypto.PublicKey import RSA
tierno7edb6752016-03-21 17:37:52 +010050
tiernof1ba57e2017-09-07 12:23:19 +020051import osm_im.vnfd as vnfd_catalog
52import osm_im.nsd as nsd_catalog
tiernof1ba57e2017-09-07 12:23:19 +020053from pyangbind.lib.serialise import pybindJSONDecoder
tiernofc5f80b2018-05-29 16:00:43 +020054from copy import deepcopy
55
tiernof1ba57e2017-09-07 12:23:19 +020056
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010057# WIM
58import wim.wimconn as wimconn
59import wim.wim_thread as wim_thread
60from .http_tools import errors as httperrors
61from .wim.engine import WimEngine
62from .wim.persistence import WimPersistence
63from copy import deepcopy
Anderson Bravalherie2c09f32018-11-30 09:55:29 +000064from pprint import pformat
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010065#
66
tierno7edb6752016-03-21 17:37:52 +010067global global_config
68global vimconn_imported
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010069# WIM
70global wim_engine
71wim_engine = None
72global wimconn_imported
73#
tierno73ad9e42016-09-12 18:11:11 +020074global logger
montesmoreno0c8def02016-12-22 12:16:23 +000075global default_volume_size
76default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010077global ovim
78ovim = None
tiernoc5651792017-03-27 10:50:43 +020079global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020080
tierno42026a02017-02-10 15:13:40 +010081vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
82vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010083vim_persistent_info = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010084# WIM
85wimconn_imported = {} # dictionary with WIM type as key, loaded module as value
86wim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
87wim_persistent_info = {}
88#
89
tierno73ad9e42016-09-12 18:11:11 +020090logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010091task_lock = Lock()
tiernob3d36742017-03-03 23:51:05 +010092last_task_id = 0.0
tierno868220c2017-09-26 00:11:05 +020093db = None
94db_lock = Lock()
tierno7edb6752016-03-21 17:37:52 +010095
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010096
97class NfvoException(httperrors.HttpMappedError):
98 """Common Class for NFVO errors"""
tierno7edb6752016-03-21 17:37:52 +010099
100
tiernob3d36742017-03-03 23:51:05 +0100101def get_task_id():
102 global last_task_id
tierno868220c2017-09-26 00:11:05 +0200103 task_id = t.time()
tiernob3d36742017-03-03 23:51:05 +0100104 if task_id <= last_task_id:
105 task_id = last_task_id + 0.000001
106 last_task_id = task_id
tierno868220c2017-09-26 00:11:05 +0200107 return "ACTION-{:.6f}".format(task_id)
108 # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6))
tiernob3d36742017-03-03 23:51:05 +0100109
110
tierno867ffe92017-03-27 12:50:34 +0200111def new_task(name, params, depends=None):
tierno868220c2017-09-26 00:11:05 +0200112 """Deprected!!!"""
tiernob3d36742017-03-03 23:51:05 +0100113 task_id = get_task_id()
114 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
115 if depends:
116 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +0100117 return task
118
119
120def is_task_id(id):
tierno868220c2017-09-26 00:11:05 +0200121 return True if id[:5] == "TASK-" else False
tiernob3d36742017-03-03 23:51:05 +0100122
123
tierno42026a02017-02-10 15:13:40 +0100124def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
125 name = datacenter_name[:16]
126 if name not in vim_threads["names"]:
127 vim_threads["names"].append(name)
128 return name
tiernob3d36742017-03-03 23:51:05 +0100129 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100130 if name not in vim_threads["names"]:
131 vim_threads["names"].append(name)
132 return name
133 name = datacenter_id + "-" + tenant_id
134 vim_threads["names"].append(name)
135 return name
136
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100137# -- Move
138def get_non_used_wim_name(wim_name, wim_id, tenant_name, tenant_id):
139 name = wim_name[:16]
140 if name not in wim_threads["names"]:
141 wim_threads["names"].append(name)
142 return name
143 name = wim_name[:16] + "." + tenant_name[:16]
144 if name not in wim_threads["names"]:
145 wim_threads["names"].append(name)
146 return name
147 name = wim_id + "-" + tenant_id
148 wim_threads["names"].append(name)
149 return name
tierno42026a02017-02-10 15:13:40 +0100150
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100151
152def start_service(mydb, persistence=None, wim=None):
tiernob3d36742017-03-03 23:51:05 +0100153 global db, global_config
154 db = nfvo_db.nfvo_db()
155 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 +0100156 global ovim
157
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100158 if persistence:
159 persistence.lock = db_lock
160 else:
161 persistence = WimPersistence(db, lock=db_lock)
162
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100163 # Initialize openvim for SDN control
164 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
165 # TODO: review ovim.py to delete not needed configuration
166 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200167 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100168 'network_vlan_range_start': 1000,
169 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200170 'db_name': global_config["db_ovim_name"],
171 'db_host': global_config["db_ovim_host"],
172 'db_user': global_config["db_ovim_user"],
173 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100174 'bridge_ifaces': {},
175 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100176 'network_type': 'bridge',
177 #TODO: log_level_of should not be needed. To be modified in ovim
178 'log_level_of': 'DEBUG'
179 }
tierno42026a02017-02-10 15:13:40 +0100180 try:
tierno3fcfdb72017-10-24 07:48:24 +0200181 # starts ovim library
tierno46df9672017-05-26 13:12:21 +0200182 ovim = ovim_module.ovim(ovim_configuration)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100183
184 global wim_engine
185 wim_engine = wim or WimEngine(persistence)
186 wim_engine.ovim = ovim
187
tierno46df9672017-05-26 13:12:21 +0200188 ovim.start_service()
189
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100190 #delete old unneeded vim_wim_actions
tierno3fcfdb72017-10-24 07:48:24 +0200191 clean_db(mydb)
192
193 # starts vim_threads
tierno46df9672017-05-26 13:12:21 +0200194 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
195 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
196 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
197 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
198 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
199 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100200 vims = mydb.get_rows(FROM=from_, SELECT=select_)
201 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200202 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
203 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100204 if vim["config"]:
205 extra.update(yaml.load(vim["config"]))
206 if vim.get('dt_config'):
207 extra.update(yaml.load(vim["dt_config"]))
208 if vim["type"] not in vimconn_imported:
209 module_info=None
210 try:
211 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200212 pkg = __import__("osm_ro." + module)
213 vim_conn = getattr(pkg, module)
214 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
215 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100216 vimconn_imported[vim["type"]] = vim_conn
217 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200218 # if module_info and module_info[0]:
219 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200220 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100221 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100222
tierno867ffe92017-03-27 12:50:34 +0200223 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100224 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100225 try:
226 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100227 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tierno42026a02017-02-10 15:13:40 +0100228 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100229 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
230 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
231 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
232 user=vim['user'], passwd=vim['passwd'],
233 config=extra, persistent_info=vim_persistent_info[thread_id]
234 )
tierno9c22f2d2017-10-09 16:23:55 +0200235 except vimconn.vimconnException as e:
236 myvim = e
237 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
238 vim['datacenter_id'], e))
tierno42026a02017-02-10 15:13:40 +0100239 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200240 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100241 httperrors.Internal_Server_Error)
tierno46df9672017-05-26 13:12:21 +0200242 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
243 vim['vim_tenant_id'])
tiernod3750b32018-07-20 15:33:08 +0200244 new_thread = vim_thread.vim_thread(task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200245 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100246 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100247 vim_threads["running"][thread_id] = new_thread
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100248
249 wim_engine.start_threads()
tierno42026a02017-02-10 15:13:40 +0100250 except db_base_Exception as e:
251 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200252 except ovim_module.ovimException as e:
253 message = str(e)
254 if message[:22] == "DATABASE wrong version":
255 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
256 "at host {dbhost}".format(
257 msg=message[22:-3], dbname=global_config["db_ovim_name"],
258 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
259 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100260 raise NfvoException(message, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100261
tierno867ffe92017-03-27 12:50:34 +0200262
tierno42026a02017-02-10 15:13:40 +0100263def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200264 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100265 if ovim:
266 ovim.stop_service()
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100267 for thread_id, thread in vim_threads["running"].items():
tierno868220c2017-09-26 00:11:05 +0200268 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +0100269 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100270 vim_threads["running"] = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100271
272 if wim_engine:
273 wim_engine.stop_threads()
274
tiernoc5651792017-03-27 10:50:43 +0200275 if global_config and global_config.get("console_thread"):
276 for thread in global_config["console_thread"]:
277 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100278
tierno6ddeded2017-05-16 15:40:26 +0200279def get_version():
280 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
281 global_config["version_date"] ))
282
tierno3fcfdb72017-10-24 07:48:24 +0200283def clean_db(mydb):
284 """
285 Clean unused or old entries at database to avoid unlimited growing
286 :param mydb: database connector
287 :return: None
288 """
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100289 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
tierno3fcfdb72017-10-24 07:48:24 +0200290 now = t.time()-3600*24*7
291 instance_action_id = None
292 nb_deleted = 0
293 while True:
294 actions_to_delete = mydb.get_rows(
295 SELECT=("item", "item_id", "instance_action_id"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100296 FROM="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
tierno3fcfdb72017-10-24 07:48:24 +0200297 "left join instance_scenarios as i on ia.instance_id=i.uuid",
298 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
299 "va.status": ("DONE", "SUPERSEDED")},
300 LIMIT=100
301 )
302 for to_delete in actions_to_delete:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100303 mydb.delete_row(FROM="vim_wim_actions", WHERE=to_delete)
tierno3fcfdb72017-10-24 07:48:24 +0200304 if instance_action_id != to_delete["instance_action_id"]:
305 instance_action_id = to_delete["instance_action_id"]
306 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
307 nb_deleted += len(actions_to_delete)
308 if len(actions_to_delete) < 100:
309 break
310 if nb_deleted:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100311 logger.debug("Removed {} unused vim_wim_actions".format(nb_deleted))
tierno3fcfdb72017-10-24 07:48:24 +0200312
tierno42026a02017-02-10 15:13:40 +0100313
tierno7edb6752016-03-21 17:37:52 +0100314def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
315 '''Obtain flavorList
316 return result, content:
317 <0, error_text upon error
318 nb_records, flavor_list on success
319 '''
320 WHERE_dict={}
321 WHERE_dict['vnf_id'] = vnf_id
322 if nfvo_tenant is not None:
323 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100324
tierno7edb6752016-03-21 17:37:52 +0100325 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
326 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200327 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
328 #print "get_flavor_list result:", result
329 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100330 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200331 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100332 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200333 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100334
tiernob3d36742017-03-03 23:51:05 +0100335
tierno7edb6752016-03-21 17:37:52 +0100336def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
tierno16e3dd42018-04-24 12:52:40 +0200337 """
338 Get used images of all vms belonging to this VNFD
339 :param mydb: database conector
340 :param vnf_id: vnfd uuid
341 :param nfvo_tenant: tenant, not used
342 :return: The list of image uuid used
343 """
344 image_list = []
345 vms = mydb.get_rows(SELECT=('image_id','image_list'), FROM='vms', WHERE={'vnf_id': vnf_id})
346 for vm in vms:
tierno89aada42018-12-19 16:00:25 +0000347 if vm["image_id"] and vm["image_id"] not in image_list:
tierno16e3dd42018-04-24 12:52:40 +0200348 image_list.append(vm["image_id"])
349 if vm["image_list"]:
350 vm_image_list = yaml.load(vm["image_list"])
351 for image_dict in vm_image_list:
352 if image_dict["image_id"] not in image_list:
353 image_list.append(image_dict["image_id"])
354 return image_list
tierno7edb6752016-03-21 17:37:52 +0100355
tiernob3d36742017-03-03 23:51:05 +0100356
tiernoa2793912016-10-04 08:15:08 +0000357def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
tiernocbb52052018-05-31 18:57:30 +0200358 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None, ignore_errors=False):
tierno7edb6752016-03-21 17:37:52 +0100359 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100360 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100361 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200362 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100363 '''
364 WHERE_dict={}
365 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
366 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000367 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100368 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
369 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000370 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
371 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100372 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 +0000373 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 +0100374 '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 +0000375 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100376 else:
377 from_ = 'datacenters as d'
378 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200379 try:
380 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
381 vim_dict={}
382 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200383 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
tierno16e3dd42018-04-24 12:52:40 +0200384 'datacenter_id': vim.get('datacenter_id'),
tiernob6434212018-04-26 16:27:47 +0200385 '_vim_type_internal': vim.get('type')}
tierno8008c3a2016-10-13 15:34:28 +0000386 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200387 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000388 if vim.get('dt_config'):
389 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200390 if vim["type"] not in vimconn_imported:
391 module_info=None
392 try:
393 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200394 pkg = __import__("osm_ro." + module)
395 vim_conn = getattr(pkg, module)
396 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
397 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200398 vimconn_imported[vim["type"]] = vim_conn
399 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200400 # if module_info and module_info[0]:
401 # file.close(module_info[0])
tiernocbb52052018-05-31 18:57:30 +0200402 if ignore_errors:
403 logger.error("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
404 vim["type"], module, type(e).__name__, str(e)))
405 continue
tiernof97fd272016-07-11 14:32:37 +0200406 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100407 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100408
tierno7edb6752016-03-21 17:37:52 +0100409 try:
tierno867ffe92017-03-27 12:50:34 +0200410 if 'datacenter_tenant_id' in vim:
411 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100412 if thread_id not in vim_persistent_info:
413 vim_persistent_info[thread_id] = {}
414 persistent_info = vim_persistent_info[thread_id]
415 else:
416 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200417 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100418 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tiernof97fd272016-07-11 14:32:37 +0200419 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
420 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100421 tenant_id=vim.get('vim_tenant_id',vim_tenant),
422 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100423 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200424 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100425 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200426 )
427 except Exception as e:
tiernocbb52052018-05-31 18:57:30 +0200428 if ignore_errors:
429 logger.error("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)))
430 continue
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100431 http_code = httperrors.Internal_Server_Error
tiernoa3572692018-05-14 13:09:33 +0200432 if isinstance(e, vimconn.vimconnException):
433 http_code = e.http_code
434 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), http_code)
tiernof97fd272016-07-11 14:32:37 +0200435 return vim_dict
436 except db_base_Exception as e:
437 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100438
tiernob3d36742017-03-03 23:51:05 +0100439
tierno7edb6752016-03-21 17:37:52 +0100440def rollback(mydb, vims, rollback_list):
441 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100442 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100443 for i in range(len(rollback_list)-1, -1, -1):
444 item = rollback_list[i]
445 if item["where"]=="vim":
446 if item["vim_id"] not in vims:
447 continue
tierno56d73d22017-08-02 13:53:02 +0200448 if is_task_id(item["uuid"]):
449 continue
450 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200451 try:
452 if item["what"]=="image":
453 vim.delete_image(item["uuid"])
tierno868220c2017-09-26 00:11:05 +0200454 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200455 elif item["what"]=="flavor":
456 vim.delete_flavor(item["uuid"])
tiernoad6bdd42018-01-10 10:43:46 +0100457 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200458 elif item["what"]=="network":
459 vim.delete_network(item["uuid"])
460 elif item["what"]=="vm":
461 vim.delete_vminstance(item["uuid"])
462 except vimconn.vimconnException as e:
463 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
464 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200465 except db_base_Exception as e:
466 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 +0100467
tierno7edb6752016-03-21 17:37:52 +0100468 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200469 try:
470 if item["what"]=="image":
471 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
472 elif item["what"]=="flavor":
473 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
474 except db_base_Exception as e:
475 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
476 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100477 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100478 return True," Rollback successful."
479 else:
480 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100481
tiernob3d36742017-03-03 23:51:05 +0100482
tiernoafed5f12017-01-26 17:57:43 +0100483def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100484 global global_config
tierno42026a02017-02-10 15:13:40 +0100485 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100486 vnfc_interfaces={}
487 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100488 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100489 #dataplane interfaces
490 for numa in vnfc.get("numas",() ):
491 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100492 if interface["name"] in name_dict:
493 raise NfvoException(
494 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
495 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100496 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100497 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100498 #bridge interfaces
499 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100500 if interface["name"] in name_dict:
501 raise NfvoException(
502 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
503 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100504 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100505 name_dict[ interface["name"] ] = "overlay"
506 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100507 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200508 # if "boot-data" in vnfc:
509 # # check that user-data is incompatible with users and config-files
510 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
511 # raise NfvoException(
512 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100513 # httperrors.Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100514
tierno7edb6752016-03-21 17:37:52 +0100515 #check if the info in external_connections matches with the one in the vnfcs
516 name_list=[]
517 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
518 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100519 raise NfvoException(
520 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
521 external_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100522 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100523 name_list.append(external_connection["name"])
524 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100525 raise NfvoException(
526 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
527 external_connection["name"], external_connection["VNFC"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100528 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100529
tierno7edb6752016-03-21 17:37:52 +0100530 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100531 raise NfvoException(
532 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
533 external_connection["name"],
534 external_connection["local_iface_name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100535 httperrors.Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100536
tierno7edb6752016-03-21 17:37:52 +0100537 #check if the info in internal_connections matches with the one in the vnfcs
538 name_list=[]
539 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
540 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100541 raise NfvoException(
542 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
543 internal_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100544 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100545 name_list.append(internal_connection["name"])
546 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100547
548 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
549 raise NfvoException(
550 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
551 internal_connection["name"],
552 'ptp' if vnf_descriptor_version==1 else 'e-line',
553 'data' if vnf_descriptor_version==1 else "e-lan"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100554 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100555 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100556 vnf = port["VNFC"]
557 iface = port["local_iface_name"]
558 if vnf not in vnfc_interfaces:
559 raise NfvoException(
560 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
561 internal_connection["name"], vnf),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100562 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100563 if iface not in vnfc_interfaces[ vnf ]:
564 raise NfvoException(
565 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
566 internal_connection["name"], iface),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100567 httperrors.Bad_Request)
568 return -httperrors.Bad_Request,
tiernoafed5f12017-01-26 17:57:43 +0100569 if vnf_descriptor_version==1 and "type" not in internal_connection:
570 if vnfc_interfaces[vnf][iface] == "overlay":
571 internal_connection["type"] = "bridge"
572 else:
573 internal_connection["type"] = "data"
574 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
575 if vnfc_interfaces[vnf][iface] == "overlay":
576 internal_connection["implementation"] = "overlay"
577 else:
578 internal_connection["implementation"] = "underlay"
579 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
580 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
581 raise NfvoException(
582 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
583 internal_connection["name"],
584 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
585 'data' if vnf_descriptor_version==1 else 'underlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100586 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100587 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
588 vnfc_interfaces[vnf][iface] == "underlay":
589 raise NfvoException(
590 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
591 internal_connection["name"], iface,
592 'data' if vnf_descriptor_version==1 else 'underlay',
593 'bridge' if vnf_descriptor_version==1 else 'overlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100594 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100595
tierno7edb6752016-03-21 17:37:52 +0100596
tierno56d73d22017-08-02 13:53:02 +0200597def 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 +0100598 #look if image exist
599 if only_create_at_vim:
600 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000601 if return_on_error == None:
602 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100603 else:
garciadeblas14480452017-01-10 13:08:07 +0100604 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200605 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
606 else:
607 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200608 if len(images)>=1:
609 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100610 else:
garciadeblas14480452017-01-10 13:08:07 +0100611 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100612 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200613 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
614 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100615 }
garciadeblas14480452017-01-10 13:08:07 +0100616 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200617 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
618 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100619 #create image at every vim
620 for vim_id,vim in vims.iteritems():
tierno868220c2017-09-26 00:11:05 +0200621 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100622 image_created="false"
623 #look at database
tierno868220c2017-09-26 00:11:05 +0200624 image_db = mydb.get_rows(FROM="datacenters_images",
625 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100626 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200627 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200628 if image_dict['location'] is not None:
629 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
630 else:
garciadeblas30833382017-01-09 09:46:31 +0100631 filter_dict = {}
632 filter_dict['name'] = image_dict['universal_name']
633 if image_dict.get('checksum') != None:
634 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000635 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200636 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100637 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200638 if len(vim_images) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100639 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), httperrors.Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000640 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100641 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200642 else:
garciadeblas14480452017-01-10 13:08:07 +0100643 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
644 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200645
tiernoae4a8d12016-07-08 12:30:39 +0200646 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100647 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100648 try:
garciadeblas14480452017-01-10 13:08:07 +0100649 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
650 if image_dict['location']:
651 image_vim_id = vim.new_image(image_dict)
652 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
653 image_created="true"
654 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100655 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
656 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200657 except vimconn.vimconnException as e:
658 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100659 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200660 raise
tierno5e91eb82016-10-04 09:39:07 +0000661 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100662 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200663 continue
664 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000665 if return_on_error:
666 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
667 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200668 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000669 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100670 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200671 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200672 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100673 #add new vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200674 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
675 'image_id':image_mano_id,
676 'vim_id': image_vim_id,
677 'created':image_created})
tierno7edb6752016-03-21 17:37:52 +0100678 elif image_db[0]["vim_id"]!=image_vim_id:
679 #modify existing vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200680 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 +0100681
tiernof97fd272016-07-11 14:32:37 +0200682 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100683
tiernob3d36742017-03-03 23:51:05 +0100684
tierno5e91eb82016-10-04 09:39:07 +0000685def 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 +0100686 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
tierno7edb6752016-03-21 17:37:52 +0100687 'ram':flavor_dict.get('ram'),
688 'vcpus':flavor_dict.get('vcpus'),
689 }
690 if 'extended' in flavor_dict and flavor_dict['extended']==None:
691 del flavor_dict['extended']
692 if 'extended' in flavor_dict:
693 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
694
695 #look if flavor exist
696 if only_create_at_vim:
697 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000698 if return_on_error == None:
699 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100700 else:
tiernof97fd272016-07-11 14:32:37 +0200701 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
702 if len(flavors)>=1:
703 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100704 else:
705 #create flavor
706 #create one by one the images of aditional disks
707 dev_image_list=[] #list of images
708 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
709 dev_nb=0
710 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200711 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100712 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200713 image_dict={}
714 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
715 image_dict['universal_name']=device.get('image name')
716 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
717 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100718 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200719 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100720 image_metadata_dict = device.get('image metadata', None)
721 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100722 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100723 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
724 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200725 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
726 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100727 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100728 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100729 temp_flavor_dict['name'] = flavor_dict['name']
730 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200731 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
732 flavor_mano_id= content
733 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100734 #create flavor at every vim
735 if 'uuid' in flavor_dict:
736 del flavor_dict['uuid']
737 flavor_vim_id=None
738 for vim_id,vim in vims.items():
tierno868220c2017-09-26 00:11:05 +0200739 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100740 flavor_created="false"
741 #look at database
tierno868220c2017-09-26 00:11:05 +0200742 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
743 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100744 #look at VIM if this flavor exist SKIPPED
745 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
746 #if res_vim < 0:
747 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
748 # continue
749 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100750
tiernof1ba57e2017-09-07 12:23:19 +0200751 # Create the flavor in VIM
752 # Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000753 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100754 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
tiernof1ba57e2017-09-07 12:23:19 +0200755 # make a copy of original devices
tierno7edb6752016-03-21 17:37:52 +0100756 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000757
tierno7edb6752016-03-21 17:37:52 +0100758 for device in flavor_dict["extended"].get("devices",[]):
759 dev={}
760 dev.update(device)
761 devices_original.append(dev)
762 if 'image' in device:
763 del device['image']
764 if 'image metadata' in device:
765 del device['image metadata']
tiernof1ba57e2017-09-07 12:23:19 +0200766 if 'image checksum' in device:
767 del device['image checksum']
768 dev_nb = 0
tierno7edb6752016-03-21 17:37:52 +0100769 for index in range(0,len(devices_original)) :
770 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000771 if "image" not in device and "image name" not in device:
tiernoecc68392018-09-06 13:47:11 +0200772 # if 'size' in device:
773 disk_list.append({'size': device.get('size', default_volume_size), 'name': device.get('name')})
tierno7edb6752016-03-21 17:37:52 +0100774 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200775 image_dict={}
776 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
777 image_dict['universal_name']=device.get('image name')
778 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
779 image_dict['location']=device.get('image')
tiernof1ba57e2017-09-07 12:23:19 +0200780 # image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200781 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100782 image_metadata_dict = device.get('image metadata', None)
783 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100784 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100785 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
786 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200787 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 +0100788 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200789 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 +0000790
791 #save disk information (image must be based on and size
792 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
793
tierno7edb6752016-03-21 17:37:52 +0100794 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
795 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200796 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100797 #check that this vim_id exist in VIM, if not create
798 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200799 try:
800 vim.get_flavor(flavor_vim_id)
801 continue #flavor exist
802 except vimconn.vimconnException:
803 pass
tierno7edb6752016-03-21 17:37:52 +0100804 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200805 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
806 try:
tiernocf157a82017-01-30 14:07:06 +0100807 flavor_vim_id = None
808 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
809 flavor_create="false"
810 except vimconn.vimconnException as e:
811 pass
812 try:
813 if not flavor_vim_id:
814 flavor_vim_id = vim.new_flavor(flavor_dict)
815 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
816 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200817 except vimconn.vimconnException as e:
818 if return_on_error:
819 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200820 raise
tiernoae4a8d12016-07-08 12:30:39 +0200821 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000822 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200823 continue
tierno7edb6752016-03-21 17:37:52 +0100824 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200825 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100826 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000827 extended_devices_yaml = None
828 if len(disk_list) > 0:
829 extended_devices = dict()
830 extended_devices['disks'] = disk_list
831 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
832 mydb.new_row('datacenters_flavors',
tierno868220c2017-09-26 00:11:05 +0200833 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
834 'created': flavor_created, 'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100835 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
836 #modify existing vim_id at datacenters_flavors
tierno868220c2017-09-26 00:11:05 +0200837 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
838 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100839
tiernof97fd272016-07-11 14:32:37 +0200840 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100841
tiernob3d36742017-03-03 23:51:05 +0100842
tiernof1ba57e2017-09-07 12:23:19 +0200843def get_str(obj, field, length):
844 """
845 Obtain the str value,
846 :param obj:
847 :param length:
848 :return:
849 """
850 value = obj.get(field)
851 if value is not None:
852 value = str(value)[:length]
853 return value
854
855def _lookfor_or_create_image(db_image, mydb, descriptor):
856 """
857 fill image content at db_image dictionary. Check if the image with this image and checksum exist
858 :param db_image: dictionary to insert data
859 :param mydb: database connector
860 :param descriptor: yang descriptor
861 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
862 """
863
864 db_image["name"] = get_str(descriptor, "image", 255)
865 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
866 if not db_image["checksum"]: # Ensure that if empty string, None is stored
867 db_image["checksum"] = None
868 if db_image["name"].startswith("/"):
869 db_image["location"] = db_image["name"]
870 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
871 else:
872 db_image["universal_name"] = db_image["name"]
873 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
874 'checksum': db_image['checksum']})
875 if existing_images:
876 return existing_images[0]["uuid"]
877 else:
878 image_uuid = str(uuid4())
879 db_image["uuid"] = image_uuid
880 return None
881
882def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
883 """
884 Parses an OSM IM vnfd_catalog and insert at DB
885 :param mydb:
886 :param tenant_id:
887 :param vnf_descriptor:
888 :return: The list of cretated vnf ids
889 """
890 try:
891 myvnfd = vnfd_catalog.vnfd()
tiernoa9550202017-09-22 13:31:35 +0200892 try:
tiernoad6bdd42018-01-10 10:43:46 +0100893 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True)
tiernoa9550202017-09-22 13:31:35 +0200894 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100895 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200896 db_vnfs = []
897 db_nets = []
898 db_vms = []
899 db_vms_index = 0
900 db_interfaces = []
901 db_images = []
902 db_flavors = []
tierno41a69812018-02-16 14:34:33 +0100903 db_ip_profiles_index = 0
904 db_ip_profiles = []
tiernof1ba57e2017-09-07 12:23:19 +0200905 uuid_list = []
906 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200907 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
908 if not vnfd_catalog_descriptor:
909 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
910 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
911 if not vnfd_descriptor_list:
912 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200913 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
914 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200915
916 # table vnf
917 vnf_uuid = str(uuid4())
918 uuid_list.append(vnf_uuid)
919 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100920 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200921 db_vnf = {
922 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100923 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200924 "name": get_str(vnfd, "name", 255),
925 "description": get_str(vnfd, "description", 255),
926 "tenant_id": tenant_id,
927 "vendor": get_str(vnfd, "vendor", 255),
928 "short_name": get_str(vnfd, "short-name", 255),
929 "descriptor": str(vnf_descriptor)[:60000]
930 }
931
tiernoe18ba432017-10-12 10:22:45 +0200932 for vnfd_descriptor in vnfd_descriptor_list:
933 if vnfd_descriptor["id"] == str(vnfd["id"]):
934 break
935
tierno41a69812018-02-16 14:34:33 +0100936 # table ip_profiles (ip-profiles)
937 ip_profile_name2db_table_index = {}
938 for ip_profile in vnfd.get("ip-profiles").itervalues():
939 db_ip_profile = {
940 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
941 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
942 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
943 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
944 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
945 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
946 }
947 dns_list = []
948 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
949 dns_list.append(str(dns.get("address")))
950 db_ip_profile["dns_address"] = ";".join(dns_list)
951 if ip_profile["ip-profile-params"].get('security-group'):
952 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
953 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
954 db_ip_profiles_index += 1
955 db_ip_profiles.append(db_ip_profile)
956
tiernof1ba57e2017-09-07 12:23:19 +0200957 # table nets (internal-vld)
958 net_id2uuid = {} # for mapping interface with network
959 for vld in vnfd.get("internal-vld").itervalues():
960 net_uuid = str(uuid4())
961 uuid_list.append(net_uuid)
962 db_net = {
963 "name": get_str(vld, "name", 255),
964 "vnf_id": vnf_uuid,
965 "uuid": net_uuid,
966 "description": get_str(vld, "description", 255),
tierno1df468d2018-07-06 14:25:16 +0200967 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +0200968 "type": "bridge", # TODO adjust depending on connection point type
969 }
970 net_id2uuid[vld.get("id")] = net_uuid
971 db_nets.append(db_net)
tierno41a69812018-02-16 14:34:33 +0100972 # ip-profile, link db_ip_profile with db_sce_net
973 if vld.get("ip-profile-ref"):
974 ip_profile_name = vld.get("ip-profile-ref")
975 if ip_profile_name not in ip_profile_name2db_table_index:
976 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
977 "'{}'. Reference to a non-existing 'ip_profiles'".format(
978 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100979 httperrors.Bad_Request)
tierno41a69812018-02-16 14:34:33 +0100980 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
981 else: #check no ip-address has been defined
tierno45140f52018-03-26 12:11:46 +0200982 for icp in vld.get("internal-connection-point").itervalues():
tierno41a69812018-02-16 14:34:33 +0100983 if icp.get("ip-address"):
984 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
985 "contains an ip-address but no ip-profile has been defined at VLD".format(
986 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100987 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200988
tiernocf596692017-11-20 15:47:51 +0100989 # connection points vaiable declaration
990 cp_name2iface_uuid = {}
991 cp_name2vm_uuid = {}
992 cp_name2db_interface = {}
tiernob6990792018-11-13 10:37:42 +0100993 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
tiernocf596692017-11-20 15:47:51 +0100994
tiernof1ba57e2017-09-07 12:23:19 +0200995 # table vms (vdus)
996 vdu_id2uuid = {}
997 vdu_id2db_table_index = {}
998 for vdu in vnfd.get("vdu").itervalues():
tierno41a69812018-02-16 14:34:33 +0100999
1000 for vdu_descriptor in vnfd_descriptor["vdu"]:
1001 if vdu_descriptor["id"] == str(vdu["id"]):
1002 break
tiernof1ba57e2017-09-07 12:23:19 +02001003 vm_uuid = str(uuid4())
1004 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +01001005 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +02001006 db_vm = {
1007 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +01001008 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +02001009 "name": get_str(vdu, "name", 255),
1010 "description": get_str(vdu, "description", 255),
tiernob6990792018-11-13 10:37:42 +01001011 "pdu_type": get_str(vdu, "pdu-type", 255),
tiernof1ba57e2017-09-07 12:23:19 +02001012 "vnf_id": vnf_uuid,
1013 }
1014 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
1015 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
1016 if vdu.get("count"):
1017 db_vm["count"] = int(vdu["count"])
1018
1019 # table image
1020 image_present = False
1021 if vdu.get("image"):
1022 image_present = True
1023 db_image = {}
1024 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
1025 if not image_uuid:
1026 image_uuid = db_image["uuid"]
1027 db_images.append(db_image)
1028 db_vm["image_id"] = image_uuid
tierno16e3dd42018-04-24 12:52:40 +02001029 if vdu.get("alternative-images"):
1030 vm_alternative_images = []
1031 for alt_image in vdu.get("alternative-images").itervalues():
1032 db_image = {}
1033 image_uuid = _lookfor_or_create_image(db_image, mydb, alt_image)
1034 if not image_uuid:
1035 image_uuid = db_image["uuid"]
1036 db_images.append(db_image)
1037 vm_alternative_images.append({
1038 "image_id": image_uuid,
1039 "vim_type": str(alt_image["vim-type"]),
1040 # "universal_name": str(alt_image["image"]),
1041 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1042 })
1043
1044 db_vm["image_list"] = yaml.safe_dump(vm_alternative_images, default_flow_style=True, width=256)
tiernof1ba57e2017-09-07 12:23:19 +02001045
1046 # volumes
1047 devices = []
1048 if vdu.get("volumes"):
tierno1df468d2018-07-06 14:25:16 +02001049 for volume_key in vdu["volumes"]:
tiernof1ba57e2017-09-07 12:23:19 +02001050 volume = vdu["volumes"][volume_key]
1051 if not image_present:
1052 # Convert the first volume to vnfc.image
1053 image_present = True
1054 db_image = {}
1055 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
1056 if not image_uuid:
1057 image_uuid = db_image["uuid"]
1058 db_images.append(db_image)
1059 db_vm["image_id"] = image_uuid
1060 else:
1061 # Add Openmano devices
tierno1df468d2018-07-06 14:25:16 +02001062 device = {"name": str(volume.get("name"))}
tiernof1ba57e2017-09-07 12:23:19 +02001063 device["type"] = str(volume.get("device-type"))
1064 if volume.get("size"):
1065 device["size"] = int(volume["size"])
1066 if volume.get("image"):
1067 device["image name"] = str(volume["image"])
1068 if volume.get("image-checksum"):
1069 device["image checksum"] = str(volume["image-checksum"])
tierno1df468d2018-07-06 14:25:16 +02001070
tiernof1ba57e2017-09-07 12:23:19 +02001071 devices.append(device)
1072
tierno89aada42018-12-19 16:00:25 +00001073 if not db_vm.get("image_id"):
1074 if not db_vm["pdu_type"]:
1075 raise NfvoException("Not defined image for VDU")
1076 # create a fake image
1077
tierno66eba6e2017-11-10 17:09:18 +01001078 # cloud-init
1079 boot_data = {}
1080 if vdu.get("cloud-init"):
1081 boot_data["user-data"] = str(vdu["cloud-init"])
1082 elif vdu.get("cloud-init-file"):
1083 # TODO Where this file content is present???
1084 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1085 boot_data["user-data"] = str(vdu["cloud-init-file"])
1086
1087 if vdu.get("supplemental-boot-data"):
1088 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1089 boot_data['boot-data-drive'] = True
1090 if vdu["supplemental-boot-data"].get('config-file'):
1091 om_cfgfile_list = list()
1092 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
1093 # TODO Where this file content is present???
1094 cfg_source = str(custom_config_file["source"])
1095 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1096 "content": cfg_source})
1097 boot_data['config-files'] = om_cfgfile_list
1098 if boot_data:
1099 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1100
1101 db_vms.append(db_vm)
1102 db_vms_index += 1
1103
1104 # table interfaces (internal/external interfaces)
1105 flavor_epa_interfaces = []
tierno66eba6e2017-11-10 17:09:18 +01001106 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
1107 for iface in vdu.get("interface").itervalues():
1108 flavor_epa_interface = {}
1109 iface_uuid = str(uuid4())
1110 uuid_list.append(iface_uuid)
1111 db_interface = {
1112 "uuid": iface_uuid,
1113 "internal_name": get_str(iface, "name", 255),
1114 "vm_id": vm_uuid,
1115 }
1116 flavor_epa_interface["name"] = db_interface["internal_name"]
1117 if iface.get("virtual-interface").get("vpci"):
1118 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1119 flavor_epa_interface["vpci"] = db_interface["vpci"]
1120
1121 if iface.get("virtual-interface").get("bandwidth"):
1122 bps = int(iface.get("virtual-interface").get("bandwidth"))
1123 db_interface["bw"] = int(math.ceil(bps/1000000.0))
1124 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1125
1126 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1127 db_interface["type"] = "mgmt"
garciadeblas31e141b2018-10-25 18:33:19 +02001128 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno66eba6e2017-11-10 17:09:18 +01001129 db_interface["type"] = "bridge"
1130 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1131 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1132 db_interface["type"] = "data"
1133 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1134 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1135 else "yes"
1136 flavor_epa_interfaces.append(flavor_epa_interface)
1137 else:
1138 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1139 "-interface':'type':'{}'. Interface type is not supported".format(
1140 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001141 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001142
tiernoe72710b2018-07-23 16:16:00 +02001143 if iface.get("mgmt-interface"):
1144 db_interface["type"] = "mgmt"
1145
tierno66eba6e2017-11-10 17:09:18 +01001146 if iface.get("external-connection-point-ref"):
1147 try:
1148 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1149 db_interface["external_name"] = get_str(cp, "name", 255)
1150 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1151 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1152 cp_name2db_interface[db_interface["external_name"]] = db_interface
1153 for cp_descriptor in vnfd_descriptor["connection-point"]:
1154 if cp_descriptor["name"] == db_interface["external_name"]:
1155 break
1156 else:
1157 raise KeyError()
1158
1159 if vdu_id in vdu_id2cp_name:
1160 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1161 else:
1162 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1163
1164 # port security
1165 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1166 db_interface["port_security"] = 0
1167 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1168 db_interface["port_security"] = 1
1169 except KeyError:
1170 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1171 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1172 " at connection-point".format(
1173 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1174 cp=iface.get("vnfd-connection-point-ref")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001175 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001176 elif iface.get("internal-connection-point-ref"):
1177 try:
tierno41a69812018-02-16 14:34:33 +01001178 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1179 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1180 break
1181 else:
1182 raise KeyError("does not exist at vdu:internal-connection-point")
1183 icp = None
1184 icp_vld = None
tierno66eba6e2017-11-10 17:09:18 +01001185 for vld in vnfd.get("internal-vld").itervalues():
1186 for cp in vld.get("internal-connection-point").itervalues():
1187 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
tierno41a69812018-02-16 14:34:33 +01001188 if icp:
1189 raise KeyError("is referenced by more than one 'internal-vld'")
1190 icp = cp
1191 icp_vld = vld
1192 if not icp:
1193 raise KeyError("is not referenced by any 'internal-vld'")
1194
1195 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1196 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1197 db_interface["port_security"] = 0
1198 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1199 db_interface["port_security"] = 1
1200 if icp.get("ip-address"):
1201 if not icp_vld.get("ip-profile-ref"):
1202 raise NfvoException
1203 db_interface["ip_address"] = str(icp.get("ip-address"))
1204 except KeyError as e:
tierno66eba6e2017-11-10 17:09:18 +01001205 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
tierno41a69812018-02-16 14:34:33 +01001206 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1207 " {msg}".format(
tierno66eba6e2017-11-10 17:09:18 +01001208 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
tierno41a69812018-02-16 14:34:33 +01001209 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001210 httperrors.Bad_Request)
tierno55d234c2018-07-04 18:29:21 +02001211 if iface.get("position"):
1212 db_interface["created_at"] = int(iface.get("position")) * 50
tierno41a69812018-02-16 14:34:33 +01001213 if iface.get("mac-address"):
1214 db_interface["mac"] = str(iface.get("mac-address"))
tierno66eba6e2017-11-10 17:09:18 +01001215 db_interfaces.append(db_interface)
1216
tiernof1ba57e2017-09-07 12:23:19 +02001217 # table flavors
1218 db_flavor = {
1219 "name": get_str(vdu, "name", 250) + "-flv",
1220 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1221 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
garciadeblas79d1a1a2017-12-11 16:07:07 +01001222 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
tiernof1ba57e2017-09-07 12:23:19 +02001223 }
tiernocf596692017-11-20 15:47:51 +01001224 # TODO revise the case of several numa-node-policy node
tiernof1ba57e2017-09-07 12:23:19 +02001225 extended = {}
1226 numa = {}
1227 if devices:
1228 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001229 if flavor_epa_interfaces:
1230 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001231 if vdu.get("guest-epa"): # TODO or dedicated_int:
1232 epa_vcpu_set = False
1233 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1234 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1235 if numa_node_policy.get("node"):
tiernocf596692017-11-20 15:47:51 +01001236 numa_node = numa_node_policy["node"].values()[0]
tiernof1ba57e2017-09-07 12:23:19 +02001237 if numa_node.get("num-cores"):
1238 numa["cores"] = numa_node["num-cores"]
1239 epa_vcpu_set = True
1240 if numa_node.get("paired-threads"):
1241 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001242 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001243 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001244 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001245 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001246 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001247 numa["paired-threads-id"].append(
1248 (str(pair["thread-a"]), str(pair["thread-b"]))
1249 )
1250 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001251 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001252 epa_vcpu_set = True
1253 if numa_node.get("memory-mb"):
1254 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1255 if vdu["guest-epa"].get("mempage-size"):
1256 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1257 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1258 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1259 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1260 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1261 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1262 numa["cores"] = max(db_flavor["vcpus"], 1)
1263 else:
1264 numa["threads"] = max(db_flavor["vcpus"], 1)
1265 if numa:
1266 extended["numas"] = [numa]
1267 if extended:
1268 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1269 db_flavor["extended"] = extended_text
1270 # look if flavor exist
garciadeblas79d1a1a2017-12-11 16:07:07 +01001271 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
tiernof1ba57e2017-09-07 12:23:19 +02001272 'ram': db_flavor.get('ram'),
1273 'vcpus': db_flavor.get('vcpus'),
1274 'extended': db_flavor.get('extended')
1275 }
1276 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1277 if existing_flavors:
1278 flavor_uuid = existing_flavors[0]["uuid"]
1279 else:
1280 flavor_uuid = str(uuid4())
1281 uuid_list.append(flavor_uuid)
1282 db_flavor["uuid"] = flavor_uuid
1283 db_flavors.append(db_flavor)
1284 db_vm["flavor_id"] = flavor_uuid
1285
tiernof1ba57e2017-09-07 12:23:19 +02001286 # VNF affinity and antiaffinity
1287 for pg in vnfd.get("placement-groups").itervalues():
1288 pg_name = get_str(pg, "name", 255)
1289 for vdu in pg.get("member-vdus").itervalues():
1290 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1291 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001292 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1293 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001294 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001295 httperrors.Bad_Request)
tiernob6990792018-11-13 10:37:42 +01001296 if vdu_id2db_table_index[vdu_id]:
1297 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
tiernof1ba57e2017-09-07 12:23:19 +02001298 # TODO consider the case of isolation and not colocation
1299 # if pg.get("strategy") == "ISOLATION":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001300
tiernof1ba57e2017-09-07 12:23:19 +02001301 # VNF mgmt configuration
1302 mgmt_access = {}
1303 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001304 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1305 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001306 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1307 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001308 vnf=vnfd_id, vdu=mgmt_vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001309 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001310 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001311 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1312 if vdu_id2cp_name.get(mgmt_vdu_id):
tiernob6990792018-11-13 10:37:42 +01001313 if cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]:
1314 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
tierno66eba6e2017-11-10 17:09:18 +01001315
tiernof1ba57e2017-09-07 12:23:19 +02001316 if vnfd["mgmt-interface"].get("ip-address"):
1317 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1318 if vnfd["mgmt-interface"].get("cp"):
1319 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob6990792018-11-13 10:37:42 +01001320 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
tiernob2880eb2017-10-04 15:04:53 +02001321 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001322 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001323 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001324 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1325 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001326 # mark this interface as of type mgmt
tiernob6990792018-11-13 10:37:42 +01001327 if cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]:
1328 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
tiernoe2ff1ce2017-11-02 17:01:10 +01001329
tiernoa9550202017-09-22 13:31:35 +02001330 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001331 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001332
tiernof1ba57e2017-09-07 12:23:19 +02001333 if default_user:
1334 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001335 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1336 "required", 6)
1337 if required:
1338 mgmt_access["required"] = required
1339
tiernof1ba57e2017-09-07 12:23:19 +02001340 if mgmt_access:
1341 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1342
1343 db_vnfs.append(db_vnf)
1344 db_tables=[
1345 {"vnfs": db_vnfs},
1346 {"nets": db_nets},
1347 {"images": db_images},
1348 {"flavors": db_flavors},
tierno41a69812018-02-16 14:34:33 +01001349 {"ip_profiles": db_ip_profiles},
tiernof1ba57e2017-09-07 12:23:19 +02001350 {"vms": db_vms},
1351 {"interfaces": db_interfaces},
1352 ]
1353
1354 logger.debug("create_vnf Deployment done vnfDict: %s",
1355 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1356 mydb.new_rows(db_tables, uuid_list)
1357 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001358 except NfvoException:
1359 raise
tiernof1ba57e2017-09-07 12:23:19 +02001360 except Exception as e:
1361 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001362 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001363
1364
tiernob8569aa2018-08-24 11:34:54 +02001365@deprecated("Use new_vnfd_v3")
tierno7edb6752016-03-21 17:37:52 +01001366def new_vnf(mydb, tenant_id, vnf_descriptor):
1367 global global_config
tierno42026a02017-02-10 15:13:40 +01001368
tierno7edb6752016-03-21 17:37:52 +01001369 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001370 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001371 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001372 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001373 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001374 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001375 if "tenant_id" in vnf_descriptor["vnf"]:
1376 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001377 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 +01001378 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001379 else:
1380 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1381 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001382 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001383 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001384
1385 # Step 4. Review the descriptor and add missing fields
1386 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001387 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001388 vnf_name = vnf_descriptor['vnf']['name']
1389 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1390 if "physical" in vnf_descriptor['vnf']:
1391 del vnf_descriptor['vnf']['physical']
1392 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001393
tierno42026a02017-02-10 15:13:40 +01001394 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001395 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1396 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001397
tierno7edb6752016-03-21 17:37:52 +01001398 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1399 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1400 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001401 try:
tiernof97fd272016-07-11 14:32:37 +02001402 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001403 for vnfc in vnf_descriptor['vnf']['VNFC']:
1404 VNFCitem={}
1405 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001406 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001407 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001408
tiernof97fd272016-07-11 14:32:37 +02001409 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001410
tierno7edb6752016-03-21 17:37:52 +01001411 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001412 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 +01001413 myflavorDict["description"] = VNFCitem["description"]
1414 myflavorDict["ram"] = vnfc.get("ram", 0)
1415 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001416 myflavorDict["disk"] = vnfc.get("disk", 0)
tierno7edb6752016-03-21 17:37:52 +01001417 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001418
tierno7edb6752016-03-21 17:37:52 +01001419 devices = vnfc.get("devices")
1420 if devices != None:
1421 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001422
tierno7edb6752016-03-21 17:37:52 +01001423 # TODO:
1424 # 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 +01001425 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1426
tierno7edb6752016-03-21 17:37:52 +01001427 # Previous code has been commented
1428 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1429 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1430 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1431 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1432 #else:
1433 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1434 # if result2:
1435 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001436 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
tierno7edb6752016-03-21 17:37:52 +01001437 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001438 # 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 +01001439 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001440
tierno7edb6752016-03-21 17:37:52 +01001441 if 'numas' in vnfc and len(vnfc['numas'])>0:
1442 myflavorDict['extended']['numas'] = vnfc['numas']
1443
1444 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001445
tierno7edb6752016-03-21 17:37:52 +01001446 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001447 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001448
tiernof97fd272016-07-11 14:32:37 +02001449 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001450 VNFCitem["flavor_id"] = flavor_id
1451 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001452
tiernof97fd272016-07-11 14:32:37 +02001453 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001454 # Step 6.3 New images are created in the VIM
1455 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001456 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001457 #In case this integration is made, the VNFCDict might become a VNFClist.
1458 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001459 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001460 image_dict={}
1461 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1462 image_dict['universal_name']=vnfc.get('image name')
1463 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1464 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001465 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001466 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001467 image_metadata_dict = vnfc.get('image metadata', None)
1468 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001469 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001470 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1471 image_dict['metadata']=image_metadata_str
1472 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001473 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1474 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001475 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001476 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001477 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001478 if vnfc.get("boot-data"):
1479 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001480
tierno42026a02017-02-10 15:13:40 +01001481
tiernof97fd272016-07-11 14:32:37 +02001482 # Step 7. Storing the VNF descriptor in the repository
1483 if "descriptor" not in vnf_descriptor["vnf"]:
1484 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001485
tiernof97fd272016-07-11 14:32:37 +02001486 # Step 8. Adding the VNF to the NFVO DB
1487 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1488 return vnf_id
1489 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001490 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001491 if isinstance(e, db_base_Exception):
1492 error_text = "Exception at database"
1493 elif isinstance(e, KeyError):
1494 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001495 e.http_code = httperrors.Internal_Server_Error
tiernof97fd272016-07-11 14:32:37 +02001496 else:
1497 error_text = "Exception at VIM"
1498 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1499 #logger.error("start_scenario %s", error_text)
1500 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001501
tiernob3d36742017-03-03 23:51:05 +01001502
tiernob8569aa2018-08-24 11:34:54 +02001503@deprecated("Use new_vnfd_v3")
garciadeblas9f8456e2016-09-05 05:02:59 +02001504def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1505 global global_config
tierno42026a02017-02-10 15:13:40 +01001506
garciadeblas9f8456e2016-09-05 05:02:59 +02001507 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001508 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001509 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001510 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001511 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001512 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001513 if "tenant_id" in vnf_descriptor["vnf"]:
1514 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1515 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 +01001516 httperrors.Unauthorized)
garciadeblas9f8456e2016-09-05 05:02:59 +02001517 else:
1518 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1519 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001520 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001521 vims = get_vim(mydb, tenant_id, ignore_errors=True)
garciadeblas9f8456e2016-09-05 05:02:59 +02001522
1523 # Step 4. Review the descriptor and add missing fields
1524 #print vnf_descriptor
1525 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1526 vnf_name = vnf_descriptor['vnf']['name']
1527 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1528 if "physical" in vnf_descriptor['vnf']:
1529 del vnf_descriptor['vnf']['physical']
1530 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001531
tierno42026a02017-02-10 15:13:40 +01001532 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001533 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1534 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001535
garciadeblas9f8456e2016-09-05 05:02:59 +02001536 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1537 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1538 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1539 try:
1540 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1541 for vnfc in vnf_descriptor['vnf']['VNFC']:
1542 VNFCitem={}
1543 VNFCitem["name"] = vnfc['name']
1544 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001545
garciadeblas9f8456e2016-09-05 05:02:59 +02001546 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001547
garciadeblas9f8456e2016-09-05 05:02:59 +02001548 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001549 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 +02001550 myflavorDict["description"] = VNFCitem["description"]
1551 myflavorDict["ram"] = vnfc.get("ram", 0)
1552 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001553 myflavorDict["disk"] = vnfc.get("disk", 0)
garciadeblas9f8456e2016-09-05 05:02:59 +02001554 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001555
garciadeblas9f8456e2016-09-05 05:02:59 +02001556 devices = vnfc.get("devices")
1557 if devices != None:
1558 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001559
garciadeblas9f8456e2016-09-05 05:02:59 +02001560 # TODO:
1561 # 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 +01001562 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1563
garciadeblas9f8456e2016-09-05 05:02:59 +02001564 # Previous code has been commented
1565 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1566 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1567 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1568 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1569 #else:
1570 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1571 # if result2:
1572 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001573 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
garciadeblas9f8456e2016-09-05 05:02:59 +02001574 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001575 # 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 +02001576 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001577
garciadeblas9f8456e2016-09-05 05:02:59 +02001578 if 'numas' in vnfc and len(vnfc['numas'])>0:
1579 myflavorDict['extended']['numas'] = vnfc['numas']
1580
1581 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001582
garciadeblas9f8456e2016-09-05 05:02:59 +02001583 # Step 6.2 New flavors are created in the VIM
1584 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1585
1586 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1587 VNFCitem["flavor_id"] = flavor_id
1588 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001589
garciadeblas9f8456e2016-09-05 05:02:59 +02001590 logger.debug("Creating new images in the VIM for each VNFC")
1591 # Step 6.3 New images are created in the VIM
1592 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001593 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001594 #In case this integration is made, the VNFCDict might become a VNFClist.
1595 for vnfc in vnf_descriptor['vnf']['VNFC']:
1596 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001597 image_dict={}
1598 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1599 image_dict['universal_name']=vnfc.get('image name')
1600 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1601 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001602 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001603 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001604 image_metadata_dict = vnfc.get('image metadata', None)
1605 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001606 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001607 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1608 image_dict['metadata']=image_metadata_str
1609 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1610 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1611 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1612 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001613 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001614 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001615 if vnfc.get("boot-data"):
1616 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001617
garciadeblas9f8456e2016-09-05 05:02:59 +02001618 # Step 7. Storing the VNF descriptor in the repository
1619 if "descriptor" not in vnf_descriptor["vnf"]:
1620 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001621
garciadeblas9f8456e2016-09-05 05:02:59 +02001622 # Step 8. Adding the VNF to the NFVO DB
1623 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1624 return vnf_id
1625 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1626 _, message = rollback(mydb, vims, rollback_list)
1627 if isinstance(e, db_base_Exception):
1628 error_text = "Exception at database"
1629 elif isinstance(e, KeyError):
1630 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001631 e.http_code = httperrors.Internal_Server_Error
garciadeblas9f8456e2016-09-05 05:02:59 +02001632 else:
1633 error_text = "Exception at VIM"
1634 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1635 #logger.error("start_scenario %s", error_text)
1636 raise NfvoException(error_text, e.http_code)
1637
tiernob3d36742017-03-03 23:51:05 +01001638
tierno7edb6752016-03-21 17:37:52 +01001639def get_vnf_id(mydb, tenant_id, vnf_id):
1640 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001641 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001642 #obtain data
1643 where_or = {}
1644 if tenant_id != "any":
1645 where_or["tenant_id"] = tenant_id
1646 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001647 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1648
tiernof1ba57e2017-09-07 12:23:19 +02001649 vnf_id = vnf["uuid"]
1650 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001651 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001652 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1653 data={'vnf' : filtered_content}
1654 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001655 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001656 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1657 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001658 WHERE={'vnfs.uuid': vnf_id} )
gcalvinobfa2fd92018-11-13 18:47:28 +01001659 if len(content) != 0:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00001660 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001661 # change boot_data into boot-data
gcalvino319b8a52018-11-05 15:33:23 +01001662 for vm in content:
1663 if vm.get("boot_data"):
1664 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1665 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001666
gcalvinobfa2fd92018-11-13 18:47:28 +01001667 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001668 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001669
tierno7edb6752016-03-21 17:37:52 +01001670 #GET NET
tierno42026a02017-02-10 15:13:40 +01001671 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001672 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1673 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001674 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001675
1676 #GET ip-profile for each net
1677 for net in data['vnf']['nets']:
1678 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1679 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1680 WHERE={'net_id': net["uuid"]} )
1681 if len(ipprofiles)==1:
1682 net["ip_profile"] = ipprofiles[0]
1683 elif len(ipprofiles)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001684 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 +01001685
1686
garciadeblas9f8456e2016-09-05 05:02:59 +02001687 #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 +01001688
garciadeblas9f8456e2016-09-05 05:02:59 +02001689 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001690 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 +01001691 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1692 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001693 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001694 #print content
tiernof97fd272016-07-11 14:32:37 +02001695 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001696
tiernof97fd272016-07-11 14:32:37 +02001697 return data
tierno7edb6752016-03-21 17:37:52 +01001698
1699
1700def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1701 # Check tenant exist
1702 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001703 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001704 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernocbb52052018-05-31 18:57:30 +02001705 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001706 else:
1707 vims={}
1708
1709 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1710 where_or = {}
1711 if tenant_id != "any":
1712 where_or["tenant_id"] = tenant_id
1713 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001714 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 +02001715 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001716
tierno7edb6752016-03-21 17:37:52 +01001717 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001718 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001719 if len(flavorList)==0:
1720 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001721
tiernof97fd272016-07-11 14:32:37 +02001722 imageList = get_imagelist(mydb, vnf_id)
1723 if len(imageList)==0:
1724 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001725
tiernof97fd272016-07-11 14:32:37 +02001726 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1727 if deleted == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001728 raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno42026a02017-02-10 15:13:40 +01001729
tierno7edb6752016-03-21 17:37:52 +01001730 undeletedItems = []
1731 for flavor in flavorList:
1732 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001733 try:
1734 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1735 if len(c) > 0:
1736 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1737 continue
1738 #flavor not used, must be deleted
1739 #delelte at VIM
tierno96ebf002017-12-13 10:55:38 +01001740 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
tierno7edb6752016-03-21 17:37:52 +01001741 for flavor_vim in c:
tierno96ebf002017-12-13 10:55:38 +01001742 if not flavor_vim['created']: # skip this flavor because not created by openmano
tierno7edb6752016-03-21 17:37:52 +01001743 continue
tierno96ebf002017-12-13 10:55:38 +01001744 # look for vim
1745 myvim = None
1746 for vim in vims.values():
1747 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1748 myvim = vim
1749 break
1750 if not myvim:
tierno7edb6752016-03-21 17:37:52 +01001751 continue
tiernoae4a8d12016-07-08 12:30:39 +02001752 try:
1753 myvim.delete_flavor(flavor_vim["vim_id"])
tierno96ebf002017-12-13 10:55:38 +01001754 except vimconn.vimconnNotFoundException:
1755 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1756 flavor_vim["datacenter_vim_id"] )
tiernoae4a8d12016-07-08 12:30:39 +02001757 except vimconn.vimconnException as e:
1758 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
tierno96ebf002017-12-13 10:55:38 +01001759 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1760 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1761 flavor_vim["datacenter_vim_id"]))
1762 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
tiernof97fd272016-07-11 14:32:37 +02001763 mydb.delete_row_by_id('flavors', flavor)
1764 except db_base_Exception as e:
1765 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno96ebf002017-12-13 10:55:38 +01001766 undeletedItems.append("flavor {}".format(flavor))
tiernof97fd272016-07-11 14:32:37 +02001767
tierno42026a02017-02-10 15:13:40 +01001768
tierno7edb6752016-03-21 17:37:52 +01001769 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001770 try:
1771 #check if image is used by other vnf
tierno16e3dd42018-04-24 12:52:40 +02001772 c = mydb.get_rows(FROM='vms', WHERE=[{'image_id': image}, {'image_list LIKE ': '%' + image + '%'}])
tiernof97fd272016-07-11 14:32:37 +02001773 if len(c) > 0:
1774 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1775 continue
1776 #image not used, must be deleted
1777 #delelte at VIM
1778 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001779 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001780 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001781 continue
1782 if image_vim['created']=='false': #skip this image because not created by openmano
1783 continue
1784 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001785 try:
1786 myvim.delete_image(image_vim["vim_id"])
1787 except vimconn.vimconnNotFoundException as e:
1788 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1789 except vimconn.vimconnException as e:
1790 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1791 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1792 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001793 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1794 mydb.delete_row_by_id('images', image)
1795 except db_base_Exception as e:
1796 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001797 undeletedItems.append("image %s" % image)
1798
tiernof97fd272016-07-11 14:32:37 +02001799 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001800 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001801 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001802
tiernob3d36742017-03-03 23:51:05 +01001803
tiernob8569aa2018-08-24 11:34:54 +02001804@deprecated("Not used")
tierno7edb6752016-03-21 17:37:52 +01001805def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1806 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1807 if result < 0:
1808 return result, vims
1809 elif result == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001810 return -httperrors.Not_Found, "datacenter '%s' not found" % datacenter_name
tierno7edb6752016-03-21 17:37:52 +01001811 myvim = vims.values()[0]
1812 result,servers = myvim.get_hosts_info()
1813 if result < 0:
1814 return result, servers
1815 topology = {'name':myvim['name'] , 'servers': servers}
1816 return result, topology
1817
tiernob3d36742017-03-03 23:51:05 +01001818
tierno7edb6752016-03-21 17:37:52 +01001819def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001820 vims = get_vim(mydb, nfvo_tenant_id)
1821 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001822 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001823 elif len(vims)>1:
1824 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001825 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001826 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001827 try:
1828 hosts = myvim.get_hosts()
1829 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001830
tiernof97fd272016-07-11 14:32:37 +02001831 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1832 for host in hosts:
1833 server={'name':host['name'], 'vms':[]}
1834 for vm in host['instances']:
1835 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001836 try:
tiernof97fd272016-07-11 14:32:37 +02001837 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1838 WHERE={'vim_vm_id':vm['id']} )
1839 if len(c) == 0:
1840 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1841 continue
1842 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001843
tiernof97fd272016-07-11 14:32:37 +02001844 except db_base_Exception as e:
1845 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1846 datacenter['Datacenters'][0]['servers'].append(server)
1847 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001848
tiernof97fd272016-07-11 14:32:37 +02001849 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1850 return datacenter
1851 except vimconn.vimconnException as e:
1852 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001853
tiernob3d36742017-03-03 23:51:05 +01001854
tiernob8569aa2018-08-24 11:34:54 +02001855@deprecated("Use new_nsd_v3")
tierno7edb6752016-03-21 17:37:52 +01001856def new_scenario(mydb, tenant_id, topo):
1857
1858# result, vims = get_vim(mydb, tenant_id)
1859# if result < 0:
1860# return result, vims
1861#1: parse input
1862 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001863 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001864 if "tenant_id" in topo:
1865 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001866 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 +01001867 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001868 else:
1869 tenant_id=None
1870
tierno42026a02017-02-10 15:13:40 +01001871#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001872 vnfs={}
1873 other_nets={} #external_networks, bridge_networks and data_networkds
1874 nodes = topo['topology']['nodes']
1875 for k in nodes.keys():
1876 if nodes[k]['type'] == 'VNF':
1877 vnfs[k] = nodes[k]
1878 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001879 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001880 other_nets[k] = nodes[k]
1881 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001882 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001883 other_nets[k] = nodes[k]
1884 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001885
tierno7edb6752016-03-21 17:37:52 +01001886
1887#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1888 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001889 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001890 error_text = ""
1891 error_pos = "'topology':'nodes':'" + name + "'"
1892 if 'vnf_id' in vnf:
1893 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001894 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001895 if 'VNF model' in vnf:
1896 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001897 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001898 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001899 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001900
tiernocea279c2016-07-18 12:36:49 +02001901 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1902 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001903 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001904 if len(vnf_db)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001905 raise NfvoException("unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001906 elif len(vnf_db)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001907 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001908 vnf['uuid']=vnf_db[0]['uuid']
1909 vnf['description']=vnf_db[0]['description']
1910 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001911 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1912 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 +02001913 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001914 for ext_iface in ext_ifaces:
1915 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1916
1917#1.4 get list of connections
1918 conections = topo['topology']['connections']
1919 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001920 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001921 for k in conections.keys():
1922 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1923 ifaces_list = conections[k]['nodes'].items()
1924 elif type(conections[k]['nodes'])==list: #list with dictionary
1925 ifaces_list=[]
1926 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1927 for k2 in conection_pair_list:
1928 ifaces_list += k2
1929
1930 con_type = conections[k].get("type", "link")
1931 if con_type != "link":
1932 if k in other_nets:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001933 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001934 other_nets[k] = {'external': False}
1935 if conections[k].get("graph"):
1936 other_nets[k]["graph"] = conections[k]["graph"]
1937 ifaces_list.append( (k, None) )
1938
tierno42026a02017-02-10 15:13:40 +01001939
tierno7edb6752016-03-21 17:37:52 +01001940 if con_type == "external_network":
1941 other_nets[k]['external'] = True
1942 if conections[k].get("model"):
1943 other_nets[k]["model"] = conections[k]["model"]
1944 else:
1945 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001946 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001947 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001948
tiernoefd80c92016-09-16 14:17:46 +02001949 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001950 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)
1951 #print set(ifaces_list)
1952 #check valid VNF and iface names
1953 for iface in ifaces_list:
1954 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001955 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001956 str(k), iface[0]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001957 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001958 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001959 str(k), iface[0], iface[1]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001960
1961#1.5 unify connections from the pair list to a consolidated list
1962 index=0
1963 while index < len(conections_list):
1964 index2 = index+1
1965 while index2 < len(conections_list):
1966 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1967 conections_list[index] |= conections_list[index2]
1968 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001969 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001970 else:
1971 index2 += 1
1972 conections_list[index] = list(conections_list[index]) # from set to list again
1973 index += 1
1974 #for k in conections_list:
1975 # print k
tierno42026a02017-02-10 15:13:40 +01001976
tierno7edb6752016-03-21 17:37:52 +01001977
1978
1979#1.6 Delete non external nets
1980# for k in other_nets.keys():
1981# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1982# for con in conections_list:
1983# delete_indexes=[]
1984# for index in range(0,len(con)):
1985# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1986# for index in delete_indexes:
1987# del con[index]
1988# del other_nets[k]
1989#1.7: Check external_ports are present at database table datacenter_nets
1990 for k,net in other_nets.items():
1991 error_pos = "'topology':'nodes':'" + k + "'"
1992 if net['external']==False:
1993 if 'name' not in net:
1994 net['name']=k
1995 if 'model' not in net:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001996 raise NfvoException("needed a 'model' at " + error_pos, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001997 if net['model']=='bridge_net':
1998 net['type']='bridge';
1999 elif net['model']=='dataplane_net':
2000 net['type']='data';
2001 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002002 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002003 else: #external
2004#IF we do not want to check that external network exist at datacenter
2005 pass
tierno42026a02017-02-10 15:13:40 +01002006#ELSE
tierno7edb6752016-03-21 17:37:52 +01002007# error_text = ""
2008# WHERE_={}
2009# if 'net_id' in net:
2010# error_text += " 'net_id' " + net['net_id']
2011# WHERE_['uuid'] = net['net_id']
2012# if 'model' in net:
2013# error_text += " 'model' " + net['model']
2014# WHERE_['name'] = net['model']
2015# if len(WHERE_) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002016# return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002017# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2018# FROM='datacenter_nets', WHERE=WHERE_ )
2019# if r<0:
2020# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2021# elif r==0:
2022# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002023# return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002024# elif r>1:
tierno42026a02017-02-10 15:13:40 +01002025# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002026# 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 +01002027# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01002028#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002029 net_list={}
2030 net_nb=0 #Number of nets
2031 for con in conections_list:
2032 #check if this is connected to a external net
2033 other_net_index=-1
2034 #print
2035 #print "con", con
2036 for index in range(0,len(con)):
2037 #check if this is connected to a external net
2038 for net_key in other_nets.keys():
2039 if con[index][0]==net_key:
2040 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01002041 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 +02002042 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002043 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002044 else:
2045 other_net_index = index
2046 net_target = net_key
2047 break
2048 #print "other_net_index", other_net_index
2049 try:
2050 if other_net_index>=0:
2051 del con[other_net_index]
2052#IF we do not want to check that external network exist at datacenter
2053 if other_nets[net_target]['external'] :
2054 if "name" not in other_nets[net_target]:
2055 other_nets[net_target]['name'] = other_nets[net_target]['model']
2056 if other_nets[net_target]["type"] == "external_network":
2057 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
2058 other_nets[net_target]["type"] = "data"
2059 else:
2060 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01002061#ELSE
tierno7edb6752016-03-21 17:37:52 +01002062# if other_nets[net_target]['external'] :
2063# 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
2064# if type_=='data' and other_nets[net_target]['type']=="ptp":
2065# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2066# print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002067# return -httperrors.Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01002068#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002069 for iface in con:
2070 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2071 else:
2072 #create a net
2073 net_type_bridge=False
2074 net_type_data=False
2075 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01002076 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02002077 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01002078 'external':False}
tierno7edb6752016-03-21 17:37:52 +01002079 for iface in con:
2080 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2081 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
2082 if iface_type=='mgmt' or iface_type=='bridge':
2083 net_type_bridge = True
2084 else:
2085 net_type_data = True
2086 if net_type_bridge and net_type_data:
2087 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 +02002088 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002089 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002090 elif net_type_bridge:
2091 type_='bridge'
2092 else:
2093 type_='data' if len(con)>2 else 'ptp'
2094 net_list[net_target]['type'] = type_
2095 net_nb+=1
2096 except Exception:
2097 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02002098 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01002099 #raise e
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002100 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002101
2102#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01002103 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02002104 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01002105 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01002106 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02002107 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01002108 add_mgmt_net = False
2109 for vnf in vnfs.values():
2110 for iface in vnf['ifaces'].values():
2111 if iface['type']=='mgmt' and 'net_key' not in iface:
2112 #iface not connected
2113 iface['net_key'] = 'mgmt'
2114 add_mgmt_net = True
2115 if add_mgmt_net and 'mgmt' not in net_list:
2116 net_list['mgmt']=mgmt_net[0]
2117 net_list['mgmt']['external']=True
2118 net_list['mgmt']['graph']={'visible':False}
2119
2120 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02002121 #print
2122 #print 'net_list', net_list
2123 #print
2124 #print 'vnfs', vnfs
2125 #print
tierno7edb6752016-03-21 17:37:52 +01002126
2127#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02002128 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02002129 'tenant_id':tenant_id, 'name':topo['name'],
2130 'description':topo.get('description',topo['name']),
2131 'public': topo.get('public', False)
2132 })
tierno42026a02017-02-10 15:13:40 +01002133
tiernof97fd272016-07-11 14:32:37 +02002134 return c
tierno7edb6752016-03-21 17:37:52 +01002135
tiernob3d36742017-03-03 23:51:05 +01002136
tiernob8569aa2018-08-24 11:34:54 +02002137@deprecated("Use new_nsd_v3")
tierno5bb59dc2017-02-13 14:53:54 +01002138def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2139 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02002140 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01002141 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01002142 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002143 if "tenant_id" in scenario:
2144 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01002145 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02002146 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002147 scenario["tenant_id"], tenant_id), httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01002148 else:
2149 tenant_id=None
2150
tierno5bb59dc2017-02-13 14:53:54 +01002151 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01002152 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02002153 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01002154 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02002155 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01002156 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002157 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02002158 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02002159 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002160 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02002161 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02002162 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002163 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002164 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002165 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002166 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002167 if len(vnf_db) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002168 raise NfvoException("Unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002169 elif len(vnf_db) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002170 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002171 vnf['uuid'] = vnf_db[0]['uuid']
2172 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002173 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002174 # get external interfaces
2175 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2176 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 +02002177 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002178 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002179 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2180 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002181
tierno5bb59dc2017-02-13 14:53:54 +01002182 # 2: Insert net_key and ip_address at every vnf interface
2183 for net_name, net in scenario["networks"].items():
2184 net_type_bridge = False
2185 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002186 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002187 if version == "0.2":
2188 temp_dict = iface_dict
2189 ip_address = None
2190 elif version == "0.3":
2191 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2192 ip_address = iface_dict.get('ip_address', None)
2193 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002194 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002195 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2196 net_name, vnf)
2197 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002198 raise NfvoException(error_text, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002199 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002200 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2201 .format(net_name, iface)
2202 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002203 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002204 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002205 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2206 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2207 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002208 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002209 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002210 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002211 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002212 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002213 net_type_bridge = True
2214 else:
2215 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002216
tierno7edb6752016-03-21 17:37:52 +01002217 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002218 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2219 .format(net_name)
2220 # logger.debug("nfvo.new_scenario " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002221 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002222 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002223 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002224 else:
tierno5bb59dc2017-02-13 14:53:54 +01002225 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2226
2227 if net.get("implementation"): # for v0.3
2228 if type_ == "bridge" and net["implementation"] == "underlay":
2229 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2230 "'network':'{}'".format(net_name)
2231 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002232 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002233 elif type_ != "bridge" and net["implementation"] == "overlay":
2234 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2235 "'network':'{}'".format(net_name)
2236 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002237 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002238 net.pop("implementation")
2239 if "type" in net and version == "0.3": # for v0.3
2240 if type_ == "data" and net["type"] == "e-line":
2241 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2242 "'e-line' at 'network':'{}'".format(net_name)
2243 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002244 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002245 elif type_ == "ptp" and net["type"] == "e-lan":
2246 type_ = "data"
2247
tierno7edb6752016-03-21 17:37:52 +01002248 net['type'] = type_
2249 net['name'] = net_name
2250 net['external'] = net.get('external', False)
2251
tierno5bb59dc2017-02-13 14:53:54 +01002252 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002253 scenario["nets"] = scenario["networks"]
2254 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002255 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002256 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002257
tiernob3d36742017-03-03 23:51:05 +01002258
tiernof1ba57e2017-09-07 12:23:19 +02002259def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2260 """
2261 Parses an OSM IM nsd_catalog and insert at DB
2262 :param mydb:
2263 :param tenant_id:
2264 :param nsd_descriptor:
Igor D.Ccaadc442017-11-06 12:48:48 +00002265 :return: The list of created NSD ids
tiernof1ba57e2017-09-07 12:23:19 +02002266 """
2267 try:
2268 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002269 try:
2270 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd)
2271 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002272 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002273 db_scenarios = []
2274 db_sce_nets = []
2275 db_sce_vnfs = []
2276 db_sce_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002277 db_sce_vnffgs = []
2278 db_sce_rsps = []
2279 db_sce_rsp_hops = []
2280 db_sce_classifiers = []
2281 db_sce_classifier_matches = []
tiernof1ba57e2017-09-07 12:23:19 +02002282 db_ip_profiles = []
2283 db_ip_profiles_index = 0
2284 uuid_list = []
2285 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002286 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2287 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002288
Igor D.Ccaadc442017-11-06 12:48:48 +00002289 # table scenarios
tiernof1ba57e2017-09-07 12:23:19 +02002290 scenario_uuid = str(uuid4())
2291 uuid_list.append(scenario_uuid)
2292 nsd_uuid_list.append(scenario_uuid)
2293 db_scenario = {
2294 "uuid": scenario_uuid,
2295 "osm_id": get_str(nsd, "id", 255),
2296 "name": get_str(nsd, "name", 255),
2297 "description": get_str(nsd, "description", 255),
2298 "tenant_id": tenant_id,
2299 "vendor": get_str(nsd, "vendor", 255),
2300 "short_name": get_str(nsd, "short-name", 255),
2301 "descriptor": str(nsd_descriptor)[:60000],
2302 }
2303 db_scenarios.append(db_scenario)
2304
2305 # table sce_vnfs (constituent-vnfd)
2306 vnf_index2scevnf_uuid = {}
2307 vnf_index2vnf_uuid = {}
2308 for vnf in nsd.get("constituent-vnfd").itervalues():
2309 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2310 'tenant_id': tenant_id})
2311 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002312 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2313 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2314 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002315 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002316 sce_vnf_uuid = str(uuid4())
2317 uuid_list.append(sce_vnf_uuid)
2318 db_sce_vnf = {
2319 "uuid": sce_vnf_uuid,
2320 "scenario_id": scenario_uuid,
tierno92c36fd2018-05-04 12:21:10 +02002321 # "name": get_str(vnf, "member-vnf-index", 255),
2322 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 50),
tiernof1ba57e2017-09-07 12:23:19 +02002323 "vnf_id": existing_vnf[0]["uuid"],
tierno16e3dd42018-04-24 12:52:40 +02002324 "member_vnf_index": str(vnf["member-vnf-index"]),
tiernof1ba57e2017-09-07 12:23:19 +02002325 # TODO 'start-by-default': True
2326 }
tierno16e3dd42018-04-24 12:52:40 +02002327 vnf_index2scevnf_uuid[str(vnf['member-vnf-index'])] = sce_vnf_uuid
2328 vnf_index2vnf_uuid[str(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
tiernof1ba57e2017-09-07 12:23:19 +02002329 db_sce_vnfs.append(db_sce_vnf)
2330
2331 # table ip_profiles (ip-profiles)
2332 ip_profile_name2db_table_index = {}
2333 for ip_profile in nsd.get("ip-profiles").itervalues():
2334 db_ip_profile = {
2335 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2336 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2337 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2338 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2339 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2340 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2341 }
2342 dns_list = []
2343 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2344 dns_list.append(str(dns.get("address")))
2345 db_ip_profile["dns_address"] = ";".join(dns_list)
2346 if ip_profile["ip-profile-params"].get('security-group'):
2347 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2348 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2349 db_ip_profiles_index += 1
2350 db_ip_profiles.append(db_ip_profile)
2351
2352 # table sce_nets (internal-vld)
2353 for vld in nsd.get("vld").itervalues():
2354 sce_net_uuid = str(uuid4())
2355 uuid_list.append(sce_net_uuid)
2356 db_sce_net = {
2357 "uuid": sce_net_uuid,
2358 "name": get_str(vld, "name", 255),
2359 "scenario_id": scenario_uuid,
2360 # "type": #TODO
2361 "multipoint": not vld.get("type") == "ELINE",
tierno1df468d2018-07-06 14:25:16 +02002362 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +02002363 # "external": #TODO
2364 "description": get_str(vld, "description", 255),
2365 }
2366 # guess type of network
2367 if vld.get("mgmt-network"):
2368 db_sce_net["type"] = "bridge"
2369 db_sce_net["external"] = True
2370 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2371 db_sce_net["type"] = "data"
2372 else:
tierno66eba6e2017-11-10 17:09:18 +01002373 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2374 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002375 db_sce_nets.append(db_sce_net)
2376
2377 # ip-profile, link db_ip_profile with db_sce_net
2378 if vld.get("ip-profile-ref"):
2379 ip_profile_name = vld.get("ip-profile-ref")
2380 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002381 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2382 " Reference to a non-existing 'ip_profiles'".format(
2383 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002384 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002385 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
tierno8f79ea12018-05-03 17:37:40 +02002386 elif vld.get("vim-network-name"):
2387 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
tiernof1ba57e2017-09-07 12:23:19 +02002388
2389 # table sce_interfaces (vld:vnfd-connection-point-ref)
2390 for iface in vld.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002391 vnf_index = str(iface['member-vnf-index-ref'])
tiernof1ba57e2017-09-07 12:23:19 +02002392 # check correct parameters
2393 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002394 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2395 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2396 "'nsd':'constituent-vnfd'".format(
2397 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002398 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002399
tierno66eba6e2017-11-10 17:09:18 +01002400 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002401 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2402 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2403 'external_name': get_str(iface, "vnfd-connection-point-ref",
2404 255)})
2405 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002406 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2407 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2408 "connection-point name at VNFD '{}'".format(
2409 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2410 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002411 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002412 interface_uuid = existing_ifaces[0]["uuid"]
tierno66eba6e2017-11-10 17:09:18 +01002413 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2414 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002415 sce_interface_uuid = str(uuid4())
2416 uuid_list.append(sce_net_uuid)
tierno41a69812018-02-16 14:34:33 +01002417 iface_ip_address = None
2418 if iface.get("ip-address"):
2419 iface_ip_address = str(iface.get("ip-address"))
tiernof1ba57e2017-09-07 12:23:19 +02002420 db_sce_interface = {
2421 "uuid": sce_interface_uuid,
2422 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2423 "sce_net_id": sce_net_uuid,
2424 "interface_id": interface_uuid,
tierno41a69812018-02-16 14:34:33 +01002425 "ip_address": iface_ip_address,
tiernof1ba57e2017-09-07 12:23:19 +02002426 }
2427 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002428 if not db_sce_net["type"]:
2429 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002430
Igor D.Ccaadc442017-11-06 12:48:48 +00002431 # table sce_vnffgs (vnffgd)
2432 for vnffg in nsd.get("vnffgd").itervalues():
2433 sce_vnffg_uuid = str(uuid4())
2434 uuid_list.append(sce_vnffg_uuid)
2435 db_sce_vnffg = {
2436 "uuid": sce_vnffg_uuid,
2437 "name": get_str(vnffg, "name", 255),
2438 "scenario_id": scenario_uuid,
2439 "vendor": get_str(vnffg, "vendor", 255),
2440 "description": get_str(vld, "description", 255),
2441 }
2442 db_sce_vnffgs.append(db_sce_vnffg)
2443
2444 # deal with rsps
2445 db_sce_rsps = []
2446 for rsp in vnffg.get("rsp").itervalues():
2447 sce_rsp_uuid = str(uuid4())
2448 uuid_list.append(sce_rsp_uuid)
2449 db_sce_rsp = {
2450 "uuid": sce_rsp_uuid,
2451 "name": get_str(rsp, "name", 255),
2452 "sce_vnffg_id": sce_vnffg_uuid,
2453 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2454 }
2455 db_sce_rsps.append(db_sce_rsp)
2456 db_sce_rsp_hops = []
2457 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002458 vnf_index = str(iface['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002459 if_order = int(iface['order'])
2460 # check correct parameters
2461 if vnf_index not in vnf_index2vnf_uuid:
2462 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2463 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2464 "'nsd':'constituent-vnfd'".format(
2465 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002466 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002467
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002468 ingress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2469 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2470 WHERE={
2471 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2472 'external_name': get_str(iface, "vnfd-ingress-connection-point-ref",
2473 255)})
2474 if not ingress_existing_ifaces:
Igor D.Ccaadc442017-11-06 12:48:48 +00002475 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002476 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
Igor D.Ccaadc442017-11-06 12:48:48 +00002477 "connection-point name at VNFD '{}'".format(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002478 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-ingress-connection-point-ref"]),
2479 str(iface.get("vnfd-id-ref"))[:255]), httperrors.Bad_Request)
2480
2481 egress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2482 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2483 WHERE={
2484 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2485 'external_name': get_str(iface, "vnfd-egress-connection-point-ref",
2486 255)})
2487 if not egress_existing_ifaces:
2488 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2489 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2490 "connection-point name at VNFD '{}'".format(
2491 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-egress-connection-point-ref"]),
2492 str(iface.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request)
2493
2494 ingress_interface_uuid = ingress_existing_ifaces[0]["uuid"]
2495 egress_interface_uuid = egress_existing_ifaces[0]["uuid"]
Igor D.Ccaadc442017-11-06 12:48:48 +00002496 sce_rsp_hop_uuid = str(uuid4())
2497 uuid_list.append(sce_rsp_hop_uuid)
2498 db_sce_rsp_hop = {
2499 "uuid": sce_rsp_hop_uuid,
2500 "if_order": if_order,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002501 "ingress_interface_id": ingress_interface_uuid,
2502 "egress_interface_id": egress_interface_uuid,
Igor D.Ccaadc442017-11-06 12:48:48 +00002503 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2504 "sce_rsp_id": sce_rsp_uuid,
2505 }
2506 db_sce_rsp_hops.append(db_sce_rsp_hop)
2507
2508 # deal with classifiers
2509 db_sce_classifiers = []
2510 for classifier in vnffg.get("classifier").itervalues():
2511 sce_classifier_uuid = str(uuid4())
2512 uuid_list.append(sce_classifier_uuid)
2513
2514 # source VNF
tierno16e3dd42018-04-24 12:52:40 +02002515 vnf_index = str(classifier['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002516 if vnf_index not in vnf_index2vnf_uuid:
2517 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2518 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2519 "'nsd':'constituent-vnfd'".format(
2520 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002521 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002522 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2523 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2524 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2525 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2526 255)})
2527 if not existing_ifaces:
2528 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2529 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2530 "connection-point name at VNFD '{}'".format(
2531 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2532 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002533 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002534 interface_uuid = existing_ifaces[0]["uuid"]
2535
2536 db_sce_classifier = {
2537 "uuid": sce_classifier_uuid,
2538 "name": get_str(classifier, "name", 255),
2539 "sce_vnffg_id": sce_vnffg_uuid,
2540 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2541 "interface_id": interface_uuid,
2542 }
2543 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2544 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2545 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2546 db_sce_classifiers.append(db_sce_classifier)
2547
2548 db_sce_classifier_matches = []
2549 for match in classifier.get("match-attributes").itervalues():
2550 sce_classifier_match_uuid = str(uuid4())
2551 uuid_list.append(sce_classifier_match_uuid)
2552 db_sce_classifier_match = {
2553 "uuid": sce_classifier_match_uuid,
2554 "ip_proto": get_str(match, "ip-proto", 2),
2555 "source_ip": get_str(match, "source-ip-address", 16),
2556 "destination_ip": get_str(match, "destination-ip-address", 16),
2557 "source_port": get_str(match, "source-port", 5),
2558 "destination_port": get_str(match, "destination-port", 5),
2559 "sce_classifier_id": sce_classifier_uuid,
2560 }
2561 db_sce_classifier_matches.append(db_sce_classifier_match)
2562 # TODO: vnf/cp keys
2563
2564 # remove unneeded id's in sce_rsps
2565 for rsp in db_sce_rsps:
2566 rsp.pop('id')
2567
tiernof1ba57e2017-09-07 12:23:19 +02002568 db_tables = [
2569 {"scenarios": db_scenarios},
2570 {"sce_nets": db_sce_nets},
2571 {"ip_profiles": db_ip_profiles},
2572 {"sce_vnfs": db_sce_vnfs},
2573 {"sce_interfaces": db_sce_interfaces},
Igor D.Ccaadc442017-11-06 12:48:48 +00002574 {"sce_vnffgs": db_sce_vnffgs},
2575 {"sce_rsps": db_sce_rsps},
2576 {"sce_rsp_hops": db_sce_rsp_hops},
2577 {"sce_classifiers": db_sce_classifiers},
2578 {"sce_classifier_matches": db_sce_classifier_matches},
tiernof1ba57e2017-09-07 12:23:19 +02002579 ]
2580
Igor D.Ccaadc442017-11-06 12:48:48 +00002581 logger.debug("new_nsd_v3 done: %s",
tiernof1ba57e2017-09-07 12:23:19 +02002582 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2583 mydb.new_rows(db_tables, uuid_list)
2584 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002585 except NfvoException:
2586 raise
tiernof1ba57e2017-09-07 12:23:19 +02002587 except Exception as e:
2588 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002589 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002590
2591
tierno7edb6752016-03-21 17:37:52 +01002592def edit_scenario(mydb, tenant_id, scenario_id, data):
2593 data["uuid"] = scenario_id
2594 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002595 c = mydb.edit_scenario( data )
2596 return c
tierno7edb6752016-03-21 17:37:52 +01002597
tiernob3d36742017-03-03 23:51:05 +01002598
tiernob8569aa2018-08-24 11:34:54 +02002599@deprecated("Use create_instance")
tierno7edb6752016-03-21 17:37:52 +01002600def 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 +02002601 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002602 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2603 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002604 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002605 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002606
tierno7edb6752016-03-21 17:37:52 +01002607 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002608 try:
2609 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002610 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002611 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002612 scenarioDict['datacenter_id'] = datacenter_id
2613 #print '================scenarioDict======================='
2614 #print json.dumps(scenarioDict, indent=4)
2615 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002616
tiernoae4a8d12016-07-08 12:30:39 +02002617 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2618 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002619
tiernoae4a8d12016-07-08 12:30:39 +02002620 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2621 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002622
tiernoae4a8d12016-07-08 12:30:39 +02002623 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2624 for sce_net in scenarioDict['nets']:
2625 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002626
tiernoae4a8d12016-07-08 12:30:39 +02002627 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002628 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002629 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002630 myNetDict = {}
2631 myNetDict["name"] = myNetName
2632 myNetDict["type"] = myNetType
2633 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002634 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002635 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002636 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002637 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002638 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02002639 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002640 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2641 sce_net['vim_id'] = network_id
2642 auxNetDict['scenario'][sce_net['uuid']] = network_id
2643 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002644 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002645 else:
2646 if sce_net['vim_id'] == None:
2647 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2648 _, message = rollback(mydb, vims, rollbackList)
2649 logger.error("nfvo.start_scenario: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002650 raise NfvoException(error_text, httperrors.Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002651 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2652 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002653
tiernoae4a8d12016-07-08 12:30:39 +02002654 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2655 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002656
tiernoae4a8d12016-07-08 12:30:39 +02002657 for sce_vnf in scenarioDict['vnfs']:
2658 for net in sce_vnf['nets']:
2659 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002660
tiernoae4a8d12016-07-08 12:30:39 +02002661 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2662 myNetName = myNetName[0:255] #limit length
2663 myNetType = net['type']
2664 myNetDict = {}
2665 myNetDict["name"] = myNetName
2666 myNetDict["type"] = myNetType
2667 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002668 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002669 #print myNetDict
2670 #TODO:
2671 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02002672 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002673 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2674 net['vim_id'] = network_id
2675 if sce_vnf['uuid'] not in auxNetDict:
2676 auxNetDict[sce_vnf['uuid']] = {}
2677 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2678 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002679 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002680
tiernoae4a8d12016-07-08 12:30:39 +02002681 #print "auxNetDict:"
2682 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002683
tiernoae4a8d12016-07-08 12:30:39 +02002684 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2685 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2686 i = 0
2687 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002688 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002689 for vm in sce_vnf['vms']:
2690 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002691 if vm_av and vm_av not in vnf_availability_zones:
2692 vnf_availability_zones.append(vm_av)
2693
2694 # check if there is enough availability zones available at vim level.
2695 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2696 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002697 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno5a3273c2017-08-29 11:43:46 +02002698
tiernoae4a8d12016-07-08 12:30:39 +02002699 for vm in sce_vnf['vms']:
2700 i += 1
2701 myVMDict = {}
2702 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002703 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002704 #myVMDict['description'] = vm['description']
2705 myVMDict['description'] = myVMDict['name'][0:99]
2706 if not startvms:
2707 myVMDict['start'] = "no"
2708 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2709 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002710
tiernoae4a8d12016-07-08 12:30:39 +02002711 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002712 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002713 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002714 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002715
tiernoae4a8d12016-07-08 12:30:39 +02002716 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002717 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002718 if flavor_dict['extended']!=None:
2719 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002720 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002721 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002722
2723
tiernoae4a8d12016-07-08 12:30:39 +02002724 myVMDict['imageRef'] = vm['vim_image_id']
2725 myVMDict['flavorRef'] = vm['vim_flavor_id']
2726 myVMDict['networks'] = []
2727 for iface in vm['interfaces']:
2728 netDict = {}
2729 if iface['type']=="data":
2730 netDict['type'] = iface['model']
2731 elif "model" in iface and iface["model"]!=None:
2732 netDict['model']=iface['model']
2733 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2734 #discover type of interface looking at flavor
2735 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2736 for flavor_iface in numa.get('interfaces',[]):
2737 if flavor_iface.get('name') == iface['internal_name']:
2738 if flavor_iface['dedicated'] == 'yes':
2739 netDict['type']="PF" #passthrough
2740 elif flavor_iface['dedicated'] == 'no':
2741 netDict['type']="VF" #siov
2742 elif flavor_iface['dedicated'] == 'yes:sriov':
2743 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2744 netDict["mac_address"] = flavor_iface.get("mac_address")
2745 break;
2746 netDict["use"]=iface['type']
2747 if netDict["use"]=="data" and not netDict.get("type"):
2748 #print "netDict", netDict
2749 #print "iface", iface
2750 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'])
2751 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002752 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002753 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002754 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002755 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002756 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2757 netDict["type"]="virtual"
2758 if "vpci" in iface and iface["vpci"] is not None:
2759 netDict['vpci'] = iface['vpci']
2760 if "mac" in iface and iface["mac"] is not None:
2761 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002762 if "port-security" in iface and iface["port-security"] is not None:
2763 netDict['port_security'] = iface['port-security']
2764 if "floating-ip" in iface and iface["floating-ip"] is not None:
2765 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002766 netDict['name'] = iface['internal_name']
2767 if iface['net_id'] is None:
2768 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002769 #print iface
2770 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002771 if vnf_iface['interface_id']==iface['uuid']:
2772 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2773 break
2774 else:
2775 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2776 #skip bridge ifaces not connected to any net
2777 #if 'net_id' not in netDict or netDict['net_id']==None:
2778 # continue
2779 myVMDict['networks'].append(netDict)
2780 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2781 #print myVMDict['name']
2782 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2783 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2784 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002785
2786 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002787 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002788 else:
tierno5a3273c2017-08-29 11:43:46 +02002789 av_index = None
mirabal29356312017-07-27 12:21:22 +02002790
tierno98e909c2017-10-14 13:27:03 +02002791 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002792 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002793 availability_zone_index=av_index,
2794 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002795 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2796 vm['vim_id'] = vm_id
2797 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2798 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2799 for net in myVMDict['networks']:
2800 if "vim_id" in net:
2801 for iface in vm['interfaces']:
2802 if net["name"]==iface["internal_name"]:
2803 iface["vim_id"]=net["vim_id"]
2804 break
tierno42026a02017-02-10 15:13:40 +01002805
tiernoae4a8d12016-07-08 12:30:39 +02002806 logger.debug("start scenario Deployment done")
2807 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2808 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002809 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2810 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002811
tiernof97fd272016-07-11 14:32:37 +02002812 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002813 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002814 if isinstance(e, db_base_Exception):
2815 error_text = "Exception at database"
2816 else:
2817 error_text = "Exception at VIM"
2818 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2819 #logger.error("start_scenario %s", error_text)
2820 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002821
tierno36c0b172017-01-12 18:32:28 +01002822def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002823 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002824 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002825 None is allowed
2826 """
tierno36c0b172017-01-12 18:32:28 +01002827 if not cloud_config_preserve and not cloud_config:
2828 return None
2829
2830 new_cloud_config = {"key-pairs":[], "users":[]}
2831 # key-pairs
2832 if cloud_config_preserve:
2833 for key in cloud_config_preserve.get("key-pairs", () ):
2834 if key not in new_cloud_config["key-pairs"]:
2835 new_cloud_config["key-pairs"].append(key)
2836 if cloud_config:
2837 for key in cloud_config.get("key-pairs", () ):
2838 if key not in new_cloud_config["key-pairs"]:
2839 new_cloud_config["key-pairs"].append(key)
2840 if not new_cloud_config["key-pairs"]:
2841 del new_cloud_config["key-pairs"]
2842
2843 # users
2844 if cloud_config:
2845 new_cloud_config["users"] += cloud_config.get("users", () )
2846 if cloud_config_preserve:
2847 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002848 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002849 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002850 for index0 in range(0,len(users)):
2851 if index0 in index_to_delete:
2852 continue
2853 for index1 in range(index0+1,len(users)):
2854 if index1 in index_to_delete:
2855 continue
2856 if users[index0]["name"] == users[index1]["name"]:
2857 index_to_delete.append(index1)
2858 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002859 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002860 users[index0]["key-pairs"] = [key]
2861 elif key not in users[index0]["key-pairs"]:
2862 users[index0]["key-pairs"].append(key)
2863 index_to_delete.sort(reverse=True)
2864 for index in index_to_delete:
2865 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002866 if not new_cloud_config["users"]:
2867 del new_cloud_config["users"]
2868
2869 #boot-data-drive
2870 if cloud_config and cloud_config.get("boot-data-drive") != None:
2871 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2872 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2873 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2874
2875 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002876 new_cloud_config["user-data"] = []
2877 if cloud_config and cloud_config.get("user-data"):
2878 if isinstance(cloud_config["user-data"], list):
2879 new_cloud_config["user-data"] += cloud_config["user-data"]
2880 else:
2881 new_cloud_config["user-data"].append(cloud_config["user-data"])
2882 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2883 if isinstance(cloud_config_preserve["user-data"], list):
2884 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2885 else:
2886 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2887 if not new_cloud_config["user-data"]:
2888 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002889
2890 # config files
2891 new_cloud_config["config-files"] = []
2892 if cloud_config and cloud_config.get("config-files") != None:
2893 new_cloud_config["config-files"] += cloud_config["config-files"]
2894 if cloud_config_preserve:
2895 for file in cloud_config_preserve.get("config-files", ()):
2896 for index in range(0, len(new_cloud_config["config-files"])):
2897 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2898 new_cloud_config["config-files"][index] = file
2899 break
2900 else:
2901 new_cloud_config["config-files"].append(file)
2902 if not new_cloud_config["config-files"]:
2903 del new_cloud_config["config-files"]
2904 return new_cloud_config
2905
2906
tierno867ffe92017-03-27 12:50:34 +02002907def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002908 datacenter_id = None
2909 datacenter_name = None
2910 thread = None
tierno867ffe92017-03-27 12:50:34 +02002911 try:
2912 if datacenter_tenant_id:
2913 thread_id = datacenter_tenant_id
2914 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002915 else:
tierno867ffe92017-03-27 12:50:34 +02002916 where_={"td.nfvo_tenant_id": tenant_id}
2917 if datacenter_id_name:
2918 if utils.check_valid_uuid(datacenter_id_name):
2919 datacenter_id = datacenter_id_name
2920 where_["dt.datacenter_id"] = datacenter_id
2921 else:
2922 datacenter_name = datacenter_id_name
2923 where_["d.name"] = datacenter_name
2924 if datacenter_tenant_id:
2925 where_["dt.uuid"] = datacenter_tenant_id
2926 datacenters = mydb.get_rows(
2927 SELECT=("dt.uuid as datacenter_tenant_id",),
2928 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2929 "join datacenters as d on d.uuid=dt.datacenter_id",
2930 WHERE=where_)
2931 if len(datacenters) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002932 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno867ffe92017-03-27 12:50:34 +02002933 elif datacenters:
2934 thread_id = datacenters[0]["datacenter_tenant_id"]
2935 thread = vim_threads["running"].get(thread_id)
2936 if not thread:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002937 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tierno867ffe92017-03-27 12:50:34 +02002938 return thread_id, thread
2939 except db_base_Exception as e:
2940 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002941
tiernof5755962017-07-13 15:44:34 +02002942
tiernoa15c4b92017-10-05 12:41:44 +02002943def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2944 WHERE_dict={}
2945 if utils.check_valid_uuid(datacenter_id_name):
2946 WHERE_dict['d.uuid'] = datacenter_id_name
2947 else:
2948 WHERE_dict['d.name'] = datacenter_id_name
2949
2950 if tenant_id:
2951 WHERE_dict['nfvo_tenant_id'] = tenant_id
2952 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2953 " dt on td.datacenter_tenant_id=dt.uuid"
2954 else:
2955 from_ = 'datacenters as d'
tiernod3750b32018-07-20 15:33:08 +02002956 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid, d.name as name",), WHERE=WHERE_dict )
tiernoa15c4b92017-10-05 12:41:44 +02002957 if len(vimaccounts) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002958 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernoa15c4b92017-10-05 12:41:44 +02002959 elif len(vimaccounts)>1:
2960 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002961 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02002962 return vimaccounts[0]["uuid"], vimaccounts[0]["name"]
tiernoa15c4b92017-10-05 12:41:44 +02002963
2964
tiernoa2793912016-10-04 08:15:08 +00002965def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002966 datacenter_id = None
2967 datacenter_name = None
2968 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002969 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02002970 datacenter_id = datacenter_id_name
2971 else:
2972 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00002973 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02002974 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002975 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernobe41e222016-09-02 15:16:13 +02002976 elif len(vims)>1:
2977 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002978 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernobe41e222016-09-02 15:16:13 +02002979 return vims.keys()[0], vims.values()[0]
2980
tiernob3d36742017-03-03 23:51:05 +01002981
garciadeblas9f8456e2016-09-05 05:02:59 +02002982def update(d, u):
Eduardo Sousa16cfd562018-11-30 15:33:35 +00002983 """Takes dict d and updates it with the values in dict u.
2984 It merges all depth levels"""
garciadeblas9f8456e2016-09-05 05:02:59 +02002985 for k, v in u.iteritems():
2986 if isinstance(v, collections.Mapping):
2987 r = update(d.get(k, {}), v)
2988 d[k] = r
2989 else:
2990 d[k] = u[k]
2991 return d
2992
tierno16e3dd42018-04-24 12:52:40 +02002993
tierno7edb6752016-03-21 17:37:52 +01002994def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01002995 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2996 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01002997 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01002998
tierno868220c2017-09-26 00:11:05 +02002999 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02003000 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02003001 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01003002 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02003003 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3004 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02003005 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02003006 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02003007 # myvim_tenant = myvim['tenant_id']
tierno16e3dd42018-04-24 12:52:40 +02003008 rollbackList = []
tierno42026a02017-02-10 15:13:40 +01003009
tierno868220c2017-09-26 00:11:05 +02003010 # print "Checking that the scenario exists and getting the scenario dictionary"
tierno7fe82642018-11-26 14:14:51 +00003011 if isinstance(scenario, str):
3012 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
3013 datacenter_id=default_datacenter_id)
3014 else:
3015 scenarioDict = scenario
3016 scenarioDict["uuid"] = None
tierno42026a02017-02-10 15:13:40 +01003017
tierno868220c2017-09-26 00:11:05 +02003018 # logger.debug(">>>>>> Dictionaries before merging")
3019 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
3020 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01003021
tierno868220c2017-09-26 00:11:05 +02003022 db_instance_vnfs = []
3023 db_instance_vms = []
3024 db_instance_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00003025 db_instance_sfis = []
3026 db_instance_sfs = []
3027 db_instance_classifications = []
3028 db_instance_sfps = []
tierno868220c2017-09-26 00:11:05 +02003029 db_ip_profiles = []
3030 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02003031 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02003032 task_index = 0
tierno8e690322017-08-10 15:58:50 +02003033 instance_name = instance_dict["name"]
3034 instance_uuid = str(uuid4())
3035 uuid_list.append(instance_uuid)
3036 db_instance_scenario = {
3037 "uuid": instance_uuid,
3038 "name": instance_name,
3039 "tenant_id": tenant_id,
3040 "scenario_id": scenarioDict['uuid'],
3041 "datacenter_id": default_datacenter_id,
3042 # filled bellow 'datacenter_tenant_id'
3043 "description": instance_dict.get("description"),
3044 }
tierno8e690322017-08-10 15:58:50 +02003045 if scenarioDict.get("cloud-config"):
3046 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
3047 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003048 instance_action_id = get_task_id()
3049 db_instance_action = {
3050 "uuid": instance_action_id, # same uuid for the instance and the action on create
3051 "tenant_id": tenant_id,
3052 "instance_id": instance_uuid,
3053 "description": "CREATE",
3054 }
garciadeblas9f8456e2016-09-05 05:02:59 +02003055
tierno868220c2017-09-26 00:11:05 +02003056 # Auxiliary dictionaries from x to y
tierno8e690322017-08-10 15:58:50 +02003057 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02003058 net2task_id = {'scenario': {}}
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003059 # Mapping between local networks and WIMs
3060 wim_usage = {}
tierno42026a02017-02-10 15:13:40 +01003061
tierno1df468d2018-07-06 14:25:16 +02003062 def ip_profile_IM2RO(ip_profile_im):
3063 # translate from input format to database format
3064 ip_profile_ro = {}
3065 if 'subnet-address' in ip_profile_im:
3066 ip_profile_ro['subnet_address'] = ip_profile_im['subnet-address']
3067 if 'ip-version' in ip_profile_im:
3068 ip_profile_ro['ip_version'] = ip_profile_im['ip-version']
3069 if 'gateway-address' in ip_profile_im:
3070 ip_profile_ro['gateway_address'] = ip_profile_im['gateway-address']
3071 if 'dns-address' in ip_profile_im:
3072 ip_profile_ro['dns_address'] = ip_profile_im['dns-address']
3073 if isinstance(ip_profile_ro['dns_address'], (list, tuple)):
3074 ip_profile_ro['dns_address'] = ";".join(ip_profile_ro['dns_address'])
3075 if 'dhcp' in ip_profile_im:
3076 ip_profile_ro['dhcp_start_address'] = ip_profile_im['dhcp'].get('start-address')
3077 ip_profile_ro['dhcp_enabled'] = ip_profile_im['dhcp'].get('enabled', True)
3078 ip_profile_ro['dhcp_count'] = ip_profile_im['dhcp'].get('count')
3079 return ip_profile_ro
3080
tierno868220c2017-09-26 00:11:05 +02003081 # logger.debug("Creating instance from scenario-dict:\n%s",
3082 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01003083 try:
tiernob3d36742017-03-03 23:51:05 +01003084 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02003085 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003086 for scenario_net in scenarioDict['nets']:
tierno1df468d2018-07-06 14:25:16 +02003087 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 +01003088 break
tierno1df468d2018-07-06 14:25:16 +02003089 else:
3090 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003091 httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003092 if "sites" not in net_instance_desc:
3093 net_instance_desc["sites"] = [ {} ]
3094 site_without_datacenter_field = False
3095 for site in net_instance_desc["sites"]:
3096 if site.get("datacenter"):
tiernod3750b32018-07-20 15:33:08 +02003097 site["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003098 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02003099 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02003100 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
3101 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003102 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
3103 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02003104 else:
3105 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02003106 raise NfvoException("Found more than one entries without datacenter field at "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003107 "instance:networks:{}:sites".format(net_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003108 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02003109 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01003110
tiernobe41e222016-09-02 15:16:13 +02003111 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003112 for scenario_vnf in scenarioDict['vnfs']:
tierno1df468d2018-07-06 14:25:16 +02003113 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 +01003114 break
tierno1df468d2018-07-06 14:25:16 +02003115 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003116 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003117 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02003118 # Add this datacenter to myvims
tiernod3750b32018-07-20 15:33:08 +02003119 vnf_instance_desc["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003120 if vnf_instance_desc["datacenter"] not in myvims:
3121 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3122 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003123 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00003124 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01003125
tierno1df468d2018-07-06 14:25:16 +02003126 for net_id, net_instance_desc in vnf_instance_desc.get("networks", {}).iteritems():
3127 for scenario_net in scenario_vnf['nets']:
3128 if net_id == scenario_net['osm_id'] or net_id == scenario_net['uuid'] or net_id == scenario_net["name"]:
3129 break
3130 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003131 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003132 if net_instance_desc.get("vim-network-name"):
3133 scenario_net["vim-network-name"] = net_instance_desc["vim-network-name"]
gcalvino0a480542018-12-17 16:19:33 +01003134 if net_instance_desc.get("vim-network-id"):
3135 scenario_net["vim-network-id"] = net_instance_desc["vim-network-id"]
tierno1df468d2018-07-06 14:25:16 +02003136 if net_instance_desc.get("name"):
3137 scenario_net["name"] = net_instance_desc["name"]
3138 if 'ip-profile' in net_instance_desc:
3139 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3140 if 'ip_profile' not in scenario_net:
3141 scenario_net['ip_profile'] = ipprofile_db
3142 else:
3143 update(scenario_net['ip_profile'], ipprofile_db)
3144
3145 for vdu_id, vdu_instance_desc in vnf_instance_desc.get("vdus", {}).iteritems():
3146 for scenario_vm in scenario_vnf['vms']:
3147 if vdu_id == scenario_vm['osm_id'] or vdu_id == scenario_vm["name"]:
3148 break
3149 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003150 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003151 scenario_vm["instance_parameters"] = vdu_instance_desc
3152 for iface_id, iface_instance_desc in vdu_instance_desc.get("interfaces", {}).iteritems():
3153 for scenario_interface in scenario_vm['interfaces']:
3154 if iface_id == scenario_interface['internal_name'] or iface_id == scenario_interface["external_name"]:
3155 scenario_interface.update(iface_instance_desc)
3156 break
3157 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003158 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003159
tierno868220c2017-09-26 00:11:05 +02003160 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01003161 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02003162
tierno868220c2017-09-26 00:11:05 +02003163 # 0.2 merge instance information into scenario
3164 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3165 # However, this is not possible yet.
tierno41a69812018-02-16 14:34:33 +01003166 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
garciadeblas9f8456e2016-09-05 05:02:59 +02003167 for scenario_net in scenarioDict['nets']:
3168 if net_name == scenario_net["name"]:
3169 if 'ip-profile' in net_instance_desc:
tierno1df468d2018-07-06 14:25:16 +02003170 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
garciadeblasedca7b32016-09-29 14:01:52 +00003171 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02003172 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00003173 else:
tierno455612d2017-05-30 16:40:10 +02003174 update(scenario_net['ip_profile'], ipprofile_db)
tierno41a69812018-02-16 14:34:33 +01003175 for interface in net_instance_desc.get('interfaces', ()):
garciadeblas9f8456e2016-09-05 05:02:59 +02003176 if 'ip_address' in interface:
3177 for vnf in scenarioDict['vnfs']:
3178 if interface['vnf'] == vnf['name']:
3179 for vnf_interface in vnf['interfaces']:
3180 if interface['vnf_interface'] == vnf_interface['external_name']:
tierno41a69812018-02-16 14:34:33 +01003181 vnf_interface['ip_address'] = interface['ip_address']
garciadeblas9f8456e2016-09-05 05:02:59 +02003182
tierno868220c2017-09-26 00:11:05 +02003183 # logger.debug(">>>>>>>> Merged dictionary")
3184 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3185 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02003186
tiernob3d36742017-03-03 23:51:05 +01003187 # 1. Creating new nets (sce_nets) in the VIM"
tierno8f79ea12018-05-03 17:37:40 +02003188 number_mgmt_networks = 0
tierno8e690322017-08-10 15:58:50 +02003189 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01003190 for sce_net in scenarioDict['nets']:
tierno7fe82642018-11-26 14:14:51 +00003191 sce_net_uuid = sce_net.get('uuid', sce_net["name"])
tierno1df468d2018-07-06 14:25:16 +02003192 # get involved datacenters where this network need to be created
3193 involved_datacenters = []
tierno7fe82642018-11-26 14:14:51 +00003194 for sce_vnf in scenarioDict.get("vnfs", ()):
tierno1df468d2018-07-06 14:25:16 +02003195 vnf_datacenter = sce_vnf.get("datacenter", default_datacenter_id)
3196 if vnf_datacenter in involved_datacenters:
3197 continue
3198 if sce_vnf.get("interfaces"):
3199 for sce_vnf_ifaces in sce_vnf["interfaces"]:
3200 if sce_vnf_ifaces.get("sce_net_id") == sce_net["uuid"]:
3201 involved_datacenters.append(vnf_datacenter)
3202 break
gcalvinod6fac4d2018-11-05 10:42:06 +01003203 if not involved_datacenters:
3204 involved_datacenters.append(default_datacenter_id)
tierno1df468d2018-07-06 14:25:16 +02003205
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003206 # --> WIM
3207 # TODO: use this information during network creation
tierno4070e442019-01-23 10:19:23 +00003208 wim_account_id = wim_account_name = None
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003209 if len(involved_datacenters) > 1 and 'uuid' in sce_net:
3210 # OBS: sce_net without uuid are used internally to VNFs
3211 # and the assumption is that VNFs will not be split among
3212 # different datacenters
tierno4070e442019-01-23 10:19:23 +00003213 wim_account = wim_engine.find_suitable_wim_account(
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003214 involved_datacenters, tenant_id)
tierno4070e442019-01-23 10:19:23 +00003215 wim_account_id = wim_account['uuid']
3216 wim_account_name = wim_account['name']
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003217 wim_usage[sce_net['uuid']] = wim_account_id
3218 # <-- WIM
3219
tierno1df468d2018-07-06 14:25:16 +02003220 descriptor_net = {}
3221 if instance_dict.get("networks") and instance_dict["networks"].get(sce_net["name"]):
3222 descriptor_net = instance_dict["networks"][sce_net["name"]]
tiernobe41e222016-09-02 15:16:13 +02003223 net_name = descriptor_net.get("vim-network-name")
tierno7fe82642018-11-26 14:14:51 +00003224 # add datacenters from instantiation parameters
3225 if descriptor_net.get("sites"):
3226 for site in descriptor_net["sites"]:
3227 if site.get("datacenter") and site["datacenter"] not in involved_datacenters:
3228 involved_datacenters.append(site["datacenter"])
3229 sce_net2instance[sce_net_uuid] = {}
3230 net2task_id['scenario'][sce_net_uuid] = {}
tiernobe41e222016-09-02 15:16:13 +02003231
tierno1df468d2018-07-06 14:25:16 +02003232 if sce_net["external"]:
3233 number_mgmt_networks += 1
3234
3235 for datacenter_id in involved_datacenters:
3236 netmap_use = None
3237 netmap_create = None
3238 if descriptor_net.get("sites"):
3239 for site in descriptor_net["sites"]:
3240 if site.get("datacenter") == datacenter_id:
3241 netmap_use = site.get("netmap-use")
3242 netmap_create = site.get("netmap-create")
3243 break
3244
3245 vim = myvims[datacenter_id]
3246 myvim_thread_id = myvim_threads_id[datacenter_id]
3247
tiernobe41e222016-09-02 15:16:13 +02003248 net_type = sce_net['type']
tiernob6990792018-11-13 10:37:42 +01003249 net_vim_name = None
tierno868220c2017-09-26 00:11:05 +02003250 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01003251
tiernof1ba57e2017-09-07 12:23:19 +02003252 if not net_name:
3253 if sce_net["external"]:
3254 net_name = sce_net["name"]
3255 else:
tierno1df468d2018-07-06 14:25:16 +02003256 net_name = "{}-{}".format(instance_name, sce_net["name"])
tiernof1ba57e2017-09-07 12:23:19 +02003257 net_name = net_name[:255] # limit length
3258
tierno1df468d2018-07-06 14:25:16 +02003259 if netmap_use or netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003260 create_network = False
3261 lookfor_network = False
tierno1df468d2018-07-06 14:25:16 +02003262 if netmap_use:
tiernof1ba57e2017-09-07 12:23:19 +02003263 lookfor_network = True
tierno1df468d2018-07-06 14:25:16 +02003264 if utils.check_valid_uuid(netmap_use):
3265 lookfor_filter["id"] = netmap_use
tiernof1ba57e2017-09-07 12:23:19 +02003266 else:
tierno1df468d2018-07-06 14:25:16 +02003267 lookfor_filter["name"] = netmap_use
3268 if netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003269 create_network = True
3270 net_vim_name = net_name
tierno1df468d2018-07-06 14:25:16 +02003271 if isinstance(netmap_create, str):
3272 net_vim_name = netmap_create
tierno8f79ea12018-05-03 17:37:40 +02003273 elif sce_net.get("vim_network_name"):
3274 create_network = False
3275 lookfor_network = True
3276 lookfor_filter["name"] = sce_net.get("vim_network_name")
tiernof1ba57e2017-09-07 12:23:19 +02003277 elif sce_net["external"]:
tiernod108c412018-12-18 15:19:27 +00003278 if sce_net.get('vim_id'):
tierno868220c2017-09-26 00:11:05 +02003279 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02003280 create_network = False
3281 lookfor_network = True
3282 lookfor_filter["id"] = sce_net['vim_id']
tierno8f79ea12018-05-03 17:37:40 +02003283 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3284 if number_mgmt_networks > 1:
3285 raise NfvoException("Found several VLD of type mgmt. "
3286 "You must concrete what vim-network must be use for each one",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003287 httperrors.Bad_Request)
tierno8f79ea12018-05-03 17:37:40 +02003288 create_network = False
3289 lookfor_network = True
3290 if vim["config"].get("management_network_id"):
3291 lookfor_filter["id"] = vim["config"]["management_network_id"]
3292 else:
3293 lookfor_filter["name"] = vim["config"]["management_network_name"]
tiernobe41e222016-09-02 15:16:13 +02003294 else:
tierno868220c2017-09-26 00:11:05 +02003295 # 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 +02003296 create_network = True
3297 lookfor_network = True
3298 lookfor_filter["name"] = sce_net["name"]
3299 net_vim_name = sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01003300 else:
tiernobe41e222016-09-02 15:16:13 +02003301 net_vim_name = net_name
3302 create_network = True
3303 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01003304
tiernof1450872017-10-17 23:15:08 +02003305 task_extra = {}
3306 if create_network:
3307 task_action = "CREATE"
tierno4070e442019-01-23 10:19:23 +00003308 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None), wim_account_name)
tiernof1450872017-10-17 23:15:08 +02003309 if lookfor_network:
3310 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02003311 elif lookfor_network:
3312 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02003313 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01003314
tierno8e690322017-08-10 15:58:50 +02003315 # fill database content
3316 net_uuid = str(uuid4())
3317 uuid_list.append(net_uuid)
tierno7fe82642018-11-26 14:14:51 +00003318 sce_net2instance[sce_net_uuid][datacenter_id] = net_uuid
tierno8e690322017-08-10 15:58:50 +02003319 db_net = {
3320 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02003321 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003322 "vim_name": net_vim_name,
tierno8e690322017-08-10 15:58:50 +02003323 "instance_scenario_id": instance_uuid,
tierno7fe82642018-11-26 14:14:51 +00003324 "sce_net_id": sce_net.get("uuid"),
tierno8e690322017-08-10 15:58:50 +02003325 "created": create_network,
3326 'datacenter_id': datacenter_id,
3327 'datacenter_tenant_id': myvim_thread_id,
tiernod2836fc2018-05-30 15:03:27 +02003328 'status': 'BUILD' # if create_network else "ACTIVE"
tierno8e690322017-08-10 15:58:50 +02003329 }
3330 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003331 db_vim_action = {
3332 "instance_action_id": instance_action_id,
3333 "status": "SCHEDULED",
3334 "task_index": task_index,
3335 "datacenter_vim_id": myvim_thread_id,
3336 "action": task_action,
3337 "item": "instance_nets",
3338 "item_id": net_uuid,
tiernof1450872017-10-17 23:15:08 +02003339 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003340 }
tierno7fe82642018-11-26 14:14:51 +00003341 net2task_id['scenario'][sce_net_uuid][datacenter_id] = task_index
tierno868220c2017-09-26 00:11:05 +02003342 task_index += 1
3343 db_vim_actions.append(db_vim_action)
3344
tierno8e690322017-08-10 15:58:50 +02003345 if 'ip_profile' in sce_net:
3346 db_ip_profile={
3347 'instance_net_id': net_uuid,
3348 'ip_version': sce_net['ip_profile']['ip_version'],
3349 'subnet_address': sce_net['ip_profile']['subnet_address'],
3350 'gateway_address': sce_net['ip_profile']['gateway_address'],
3351 'dns_address': sce_net['ip_profile']['dns_address'],
3352 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3353 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3354 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3355 }
3356 db_ip_profiles.append(db_ip_profile)
3357
tierno16e3dd42018-04-24 12:52:40 +02003358 # Create VNFs
3359 vnf_params = {
3360 "default_datacenter_id": default_datacenter_id,
3361 "myvim_threads_id": myvim_threads_id,
3362 "instance_uuid": instance_uuid,
3363 "instance_name": instance_name,
3364 "instance_action_id": instance_action_id,
3365 "myvims": myvims,
3366 "cloud_config": cloud_config,
3367 "RO_pub_key": tenant[0].get('RO_pub_key'),
tierno67881db2018-10-24 18:46:03 +02003368 "instance_parameters": instance_dict,
tierno16e3dd42018-04-24 12:52:40 +02003369 }
3370 vnf_params_out = {
3371 "task_index": task_index,
3372 "uuid_list": uuid_list,
3373 "db_instance_nets": db_instance_nets,
3374 "db_vim_actions": db_vim_actions,
3375 "db_ip_profiles": db_ip_profiles,
3376 "db_instance_vnfs": db_instance_vnfs,
3377 "db_instance_vms": db_instance_vms,
3378 "db_instance_interfaces": db_instance_interfaces,
3379 "net2task_id": net2task_id,
3380 "sce_net2instance": sce_net2instance,
3381 }
tierno55d234c2018-07-04 18:29:21 +02003382 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
tierno7fe82642018-11-26 14:14:51 +00003383 for sce_vnf in scenarioDict.get('vnfs', ()): # sce_vnf_list:
tierno16e3dd42018-04-24 12:52:40 +02003384 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3385 task_index = vnf_params_out["task_index"]
3386 uuid_list = vnf_params_out["uuid_list"]
mirabal29356312017-07-27 12:21:22 +02003387
tierno16e3dd42018-04-24 12:52:40 +02003388 # Create VNFFGs
3389 # task_depends_on = []
tierno7fe82642018-11-26 14:14:51 +00003390 for vnffg in scenarioDict.get('vnffgs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003391 for rsp in vnffg['rsps']:
3392 sfs_created = []
3393 for cp in rsp['connection_points']:
3394 count = mydb.get_rows(
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003395 SELECT='vms.count',
3396 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h "
3397 "on interfaces.uuid=h.ingress_interface_id",
Igor D.Ccaadc442017-11-06 12:48:48 +00003398 WHERE={'h.uuid': cp['uuid']})[0]['count']
3399 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3400 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3401 dependencies = []
3402 for instance_vm in instance_vms:
3403 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3404 if action:
3405 dependencies.append(action['task_index'])
3406 # TODO: throw exception if count != len(instance_vms)
3407 # TODO: and action shouldn't ever be None
3408 sfis_created = []
3409 for i in range(count):
3410 # create sfis
3411 sfi_uuid = str(uuid4())
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003412 extra_params = {
3413 "ingress_interface_id": cp["ingress_interface_id"],
3414 "egress_interface_id": cp["egress_interface_id"]
3415 }
Igor D.Ccaadc442017-11-06 12:48:48 +00003416 uuid_list.append(sfi_uuid)
3417 db_sfi = {
3418 "uuid": sfi_uuid,
3419 "instance_scenario_id": instance_uuid,
3420 'sce_rsp_hop_id': cp['uuid'],
3421 'datacenter_id': datacenter_id,
3422 'datacenter_tenant_id': myvim_thread_id,
3423 "vim_sfi_id": None, # vim thread will populate
3424 }
3425 db_instance_sfis.append(db_sfi)
3426 db_vim_action = {
3427 "instance_action_id": instance_action_id,
3428 "task_index": task_index,
3429 "datacenter_vim_id": myvim_thread_id,
3430 "action": "CREATE",
3431 "status": "SCHEDULED",
3432 "item": "instance_sfis",
3433 "item_id": sfi_uuid,
Eduardo Sousa16cfd562018-11-30 15:33:35 +00003434 "extra": yaml.safe_dump({"params": extra_params, "depends_on": [dependencies[i]]},
Igor D.Ccaadc442017-11-06 12:48:48 +00003435 default_flow_style=True, width=256)
3436 }
3437 sfis_created.append(task_index)
3438 task_index += 1
3439 db_vim_actions.append(db_vim_action)
3440 # create sfs
3441 sf_uuid = str(uuid4())
3442 uuid_list.append(sf_uuid)
3443 db_sf = {
3444 "uuid": sf_uuid,
3445 "instance_scenario_id": instance_uuid,
3446 'sce_rsp_hop_id': cp['uuid'],
3447 'datacenter_id': datacenter_id,
3448 'datacenter_tenant_id': myvim_thread_id,
3449 "vim_sf_id": None, # vim thread will populate
3450 }
3451 db_instance_sfs.append(db_sf)
3452 db_vim_action = {
3453 "instance_action_id": instance_action_id,
3454 "task_index": task_index,
3455 "datacenter_vim_id": myvim_thread_id,
3456 "action": "CREATE",
3457 "status": "SCHEDULED",
3458 "item": "instance_sfs",
3459 "item_id": sf_uuid,
3460 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3461 default_flow_style=True, width=256)
3462 }
3463 sfs_created.append(task_index)
3464 task_index += 1
3465 db_vim_actions.append(db_vim_action)
3466 classifier = rsp['classifier']
3467
3468 # TODO the following ~13 lines can be reused for the sfi case
3469 count = mydb.get_rows(
3470 SELECT=('vms.count'),
3471 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3472 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3473 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3474 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3475 dependencies = []
3476 for instance_vm in instance_vms:
3477 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3478 if action:
3479 dependencies.append(action['task_index'])
3480 # TODO: throw exception if count != len(instance_vms)
3481 # TODO: and action shouldn't ever be None
3482 classifications_created = []
3483 for i in range(count):
3484 for match in classifier['matches']:
3485 # create classifications
3486 classification_uuid = str(uuid4())
3487 uuid_list.append(classification_uuid)
3488 db_classification = {
3489 "uuid": classification_uuid,
3490 "instance_scenario_id": instance_uuid,
3491 'sce_classifier_match_id': match['uuid'],
3492 'datacenter_id': datacenter_id,
3493 'datacenter_tenant_id': myvim_thread_id,
3494 "vim_classification_id": None, # vim thread will populate
3495 }
3496 db_instance_classifications.append(db_classification)
3497 classification_params = {
3498 "ip_proto": match["ip_proto"],
3499 "source_ip": match["source_ip"],
3500 "destination_ip": match["destination_ip"],
3501 "source_port": match["source_port"],
3502 "destination_port": match["destination_port"]
3503 }
3504 db_vim_action = {
3505 "instance_action_id": instance_action_id,
3506 "task_index": task_index,
3507 "datacenter_vim_id": myvim_thread_id,
3508 "action": "CREATE",
3509 "status": "SCHEDULED",
3510 "item": "instance_classifications",
3511 "item_id": classification_uuid,
3512 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3513 default_flow_style=True, width=256)
3514 }
3515 classifications_created.append(task_index)
3516 task_index += 1
3517 db_vim_actions.append(db_vim_action)
3518
3519 # create sfps
3520 sfp_uuid = str(uuid4())
3521 uuid_list.append(sfp_uuid)
3522 db_sfp = {
3523 "uuid": sfp_uuid,
3524 "instance_scenario_id": instance_uuid,
3525 'sce_rsp_id': rsp['uuid'],
3526 'datacenter_id': datacenter_id,
3527 'datacenter_tenant_id': myvim_thread_id,
3528 "vim_sfp_id": None, # vim thread will populate
3529 }
3530 db_instance_sfps.append(db_sfp)
3531 db_vim_action = {
3532 "instance_action_id": instance_action_id,
3533 "task_index": task_index,
3534 "datacenter_vim_id": myvim_thread_id,
3535 "action": "CREATE",
3536 "status": "SCHEDULED",
3537 "item": "instance_sfps",
3538 "item_id": sfp_uuid,
3539 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3540 default_flow_style=True, width=256)
3541 }
3542 task_index += 1
3543 db_vim_actions.append(db_vim_action)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003544 db_instance_action["number_tasks"] = task_index
3545
3546 # --> WIM
Anderson Bravalherie2c09f32018-11-30 09:55:29 +00003547 logger.debug('wim_usage:\n%s\n\n', pformat(wim_usage))
3548 wan_links = wim_engine.derive_wan_links(wim_usage, db_instance_nets, tenant_id)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003549 wim_actions = wim_engine.create_actions(wan_links)
3550 wim_actions, db_instance_action = (
3551 wim_engine.incorporate_actions(wim_actions, db_instance_action))
3552 # <-- WIM
Igor D.Ccaadc442017-11-06 12:48:48 +00003553
tierno867ffe92017-03-27 12:50:34 +02003554 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003555
3556 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3557 db_instance_scenario['datacenter_id'] = default_datacenter_id
3558 db_tables=[
3559 {"instance_scenarios": db_instance_scenario},
3560 {"instance_vnfs": db_instance_vnfs},
3561 {"instance_nets": db_instance_nets},
3562 {"ip_profiles": db_ip_profiles},
3563 {"instance_vms": db_instance_vms},
3564 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003565 {"instance_actions": db_instance_action},
Igor D.Ccaadc442017-11-06 12:48:48 +00003566 {"instance_sfis": db_instance_sfis},
3567 {"instance_sfs": db_instance_sfs},
3568 {"instance_classifications": db_instance_classifications},
3569 {"instance_sfps": db_instance_sfps},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003570 {"instance_wim_nets": wan_links},
3571 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno8e690322017-08-10 15:58:50 +02003572 ]
3573
tierno868220c2017-09-26 00:11:05 +02003574 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003575 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3576 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003577 for myvim_thread_id in myvim_threads_id.values():
3578 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003579
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003580 wim_engine.dispatch(wim_actions)
3581
tierno868220c2017-09-26 00:11:05 +02003582 returned_instance = mydb.get_instance_scenario(instance_uuid)
3583 returned_instance["action_id"] = instance_action_id
3584 return returned_instance
3585 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003586 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003587 if isinstance(e, db_base_Exception):
3588 error_text = "database Exception"
3589 elif isinstance(e, vimconn.vimconnException):
3590 error_text = "VIM Exception"
3591 else:
3592 error_text = "Exception"
3593 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003594 # logger.error("create_instance: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003595 logger.exception(e)
tiernof97fd272016-07-11 14:32:37 +02003596 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003597
tiernob3d36742017-03-03 23:51:05 +01003598
tierno16e3dd42018-04-24 12:52:40 +02003599def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3600 default_datacenter_id = params["default_datacenter_id"]
3601 myvim_threads_id = params["myvim_threads_id"]
3602 instance_uuid = params["instance_uuid"]
3603 instance_name = params["instance_name"]
3604 instance_action_id = params["instance_action_id"]
3605 myvims = params["myvims"]
3606 cloud_config = params["cloud_config"]
3607 RO_pub_key = params["RO_pub_key"]
3608
3609 task_index = params_out["task_index"]
3610 uuid_list = params_out["uuid_list"]
3611 db_instance_nets = params_out["db_instance_nets"]
3612 db_vim_actions = params_out["db_vim_actions"]
3613 db_ip_profiles = params_out["db_ip_profiles"]
3614 db_instance_vnfs = params_out["db_instance_vnfs"]
3615 db_instance_vms = params_out["db_instance_vms"]
3616 db_instance_interfaces = params_out["db_instance_interfaces"]
3617 net2task_id = params_out["net2task_id"]
3618 sce_net2instance = params_out["sce_net2instance"]
3619
3620 vnf_net2instance = {}
3621
3622 # 2. Creating new nets (vnf internal nets) in the VIM"
3623 # For each vnf net, we create it and we add it to instanceNetlist.
3624 if sce_vnf.get("datacenter"):
3625 datacenter_id = sce_vnf["datacenter"]
3626 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3627 else:
3628 datacenter_id = default_datacenter_id
3629 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3630 for net in sce_vnf['nets']:
3631 # TODO revis
3632 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3633 # net_name = descriptor_net.get("name")
3634 net_name = None
3635 if not net_name:
tierno1df468d2018-07-06 14:25:16 +02003636 net_name = "{}-{}".format(instance_name, net["name"])
tierno16e3dd42018-04-24 12:52:40 +02003637 net_name = net_name[:255] # limit length
3638 net_type = net['type']
3639
3640 if sce_vnf['uuid'] not in vnf_net2instance:
3641 vnf_net2instance[sce_vnf['uuid']] = {}
3642 if sce_vnf['uuid'] not in net2task_id:
3643 net2task_id[sce_vnf['uuid']] = {}
3644 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3645
3646 # fill database content
3647 net_uuid = str(uuid4())
3648 uuid_list.append(net_uuid)
3649 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3650 db_net = {
3651 "uuid": net_uuid,
3652 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003653 "vim_name": net_name,
tierno16e3dd42018-04-24 12:52:40 +02003654 "instance_scenario_id": instance_uuid,
3655 "net_id": net["uuid"],
3656 "created": True,
3657 'datacenter_id': datacenter_id,
3658 'datacenter_tenant_id': myvim_thread_id,
3659 }
3660 db_instance_nets.append(db_net)
3661
gcalvino0a480542018-12-17 16:19:33 +01003662 lookfor_filter = {}
tierno1df468d2018-07-06 14:25:16 +02003663 if net.get("vim-network-name"):
gcalvino0a480542018-12-17 16:19:33 +01003664 lookfor_filter["name"] = net["vim-network-name"]
3665 if net.get("vim-network-id"):
3666 lookfor_filter["id"] = net["vim-network-id"]
3667 if lookfor_filter:
tierno1df468d2018-07-06 14:25:16 +02003668 task_action = "FIND"
3669 task_extra = {"params": (lookfor_filter,)}
3670 else:
3671 task_action = "CREATE"
3672 task_extra = {"params": (net_name, net_type, net.get('ip_profile', None))}
3673
tierno16e3dd42018-04-24 12:52:40 +02003674 db_vim_action = {
3675 "instance_action_id": instance_action_id,
3676 "task_index": task_index,
3677 "datacenter_vim_id": myvim_thread_id,
3678 "status": "SCHEDULED",
tierno1df468d2018-07-06 14:25:16 +02003679 "action": task_action,
tierno16e3dd42018-04-24 12:52:40 +02003680 "item": "instance_nets",
3681 "item_id": net_uuid,
tierno1df468d2018-07-06 14:25:16 +02003682 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno16e3dd42018-04-24 12:52:40 +02003683 }
3684 task_index += 1
3685 db_vim_actions.append(db_vim_action)
3686
3687 if 'ip_profile' in net:
3688 db_ip_profile = {
3689 'instance_net_id': net_uuid,
3690 'ip_version': net['ip_profile']['ip_version'],
3691 'subnet_address': net['ip_profile']['subnet_address'],
3692 'gateway_address': net['ip_profile']['gateway_address'],
3693 'dns_address': net['ip_profile']['dns_address'],
3694 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3695 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3696 'dhcp_count': net['ip_profile']['dhcp_count'],
3697 }
3698 db_ip_profiles.append(db_ip_profile)
3699
3700 # print "vnf_net2instance:"
3701 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3702
3703 # 3. Creating new vm instances in the VIM
3704 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3705 ssh_access = None
3706 if sce_vnf.get('mgmt_access'):
3707 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3708 vnf_availability_zones = []
gcalvinod6fac4d2018-11-05 10:42:06 +01003709 for vm in sce_vnf.get('vms'):
tierno16e3dd42018-04-24 12:52:40 +02003710 vm_av = vm.get('availability_zone')
3711 if vm_av and vm_av not in vnf_availability_zones:
3712 vnf_availability_zones.append(vm_av)
3713
3714 # check if there is enough availability zones available at vim level.
3715 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3716 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003717 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno16e3dd42018-04-24 12:52:40 +02003718
3719 if sce_vnf.get("datacenter"):
3720 vim = myvims[sce_vnf["datacenter"]]
3721 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3722 datacenter_id = sce_vnf["datacenter"]
3723 else:
3724 vim = myvims[default_datacenter_id]
3725 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3726 datacenter_id = default_datacenter_id
3727 sce_vnf["datacenter_id"] = datacenter_id
3728 i = 0
3729
3730 vnf_uuid = str(uuid4())
3731 uuid_list.append(vnf_uuid)
3732 db_instance_vnf = {
3733 'uuid': vnf_uuid,
3734 'instance_scenario_id': instance_uuid,
3735 'vnf_id': sce_vnf['vnf_id'],
3736 'sce_vnf_id': sce_vnf['uuid'],
3737 'datacenter_id': datacenter_id,
3738 'datacenter_tenant_id': myvim_thread_id,
3739 }
3740 db_instance_vnfs.append(db_instance_vnf)
3741
3742 for vm in sce_vnf['vms']:
tiernob6990792018-11-13 10:37:42 +01003743 # skip PDUs
3744 if vm.get("pdu_type"):
3745 continue
3746
tierno16e3dd42018-04-24 12:52:40 +02003747 myVMDict = {}
tierno7f426e92018-06-28 15:21:32 +02003748 sce_vnf_name = sce_vnf['member_vnf_index'] if sce_vnf['member_vnf_index'] else sce_vnf['name']
3749 myVMDict['name'] = "{}-{}-{}".format(instance_name[:64], sce_vnf_name[:64], vm["name"][:64])
tierno16e3dd42018-04-24 12:52:40 +02003750 myVMDict['description'] = myVMDict['name'][0:99]
3751 # if not startvms:
3752 # myVMDict['start'] = "no"
tierno1df468d2018-07-06 14:25:16 +02003753 if vm.get("instance_parameters") and vm["instance_parameters"].get("name"):
3754 myVMDict['name'] = vm["instance_parameters"].get("name")
tierno16e3dd42018-04-24 12:52:40 +02003755 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3756 # create image at vim in case it not exist
3757 image_uuid = vm['image_id']
3758 if vm.get("image_list"):
3759 for alternative_image in vm["image_list"]:
tiernob6434212018-04-26 16:27:47 +02003760 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
tierno16e3dd42018-04-24 12:52:40 +02003761 image_uuid = alternative_image['image_id']
3762 break
3763 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
3764 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
3765 vm['vim_image_id'] = image_id
3766
3767 # create flavor at vim in case it not exist
3768 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
3769 if flavor_dict['extended'] != None:
3770 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
3771 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3772
3773 # Obtain information for additional disks
3774 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
3775 WHERE={'vim_id': flavor_id})
3776 if not extended_flavor_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003777 raise NfvoException("flavor '{}' not found".format(flavor_id), httperrors.Not_Found)
tierno16e3dd42018-04-24 12:52:40 +02003778
3779 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
3780 myVMDict['disks'] = None
3781 extended_info = extended_flavor_dict[0]['extended']
3782 if extended_info != None:
3783 extended_flavor_dict_yaml = yaml.load(extended_info)
3784 if 'disks' in extended_flavor_dict_yaml:
3785 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
tierno1df468d2018-07-06 14:25:16 +02003786 if vm.get("instance_parameters") and vm["instance_parameters"].get("devices"):
3787 for disk in myVMDict['disks']:
3788 if disk.get("name") in vm["instance_parameters"]["devices"]:
3789 disk.update(vm["instance_parameters"]["devices"][disk.get("name")])
tierno16e3dd42018-04-24 12:52:40 +02003790
3791 vm['vim_flavor_id'] = flavor_id
3792 myVMDict['imageRef'] = vm['vim_image_id']
3793 myVMDict['flavorRef'] = vm['vim_flavor_id']
3794 myVMDict['availability_zone'] = vm.get('availability_zone')
3795 myVMDict['networks'] = []
3796 task_depends_on = []
3797 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno67881db2018-10-24 18:46:03 +02003798 is_management_vm = False
tierno16e3dd42018-04-24 12:52:40 +02003799 db_vm_ifaces = []
3800 for iface in vm['interfaces']:
3801 netDict = {}
3802 if iface['type'] == "data":
3803 netDict['type'] = iface['model']
3804 elif "model" in iface and iface["model"] != None:
3805 netDict['model'] = iface['model']
3806 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3807 # is obtained from iterface table model
3808 # discover type of interface looking at flavor
3809 for numa in flavor_dict.get('extended', {}).get('numas', []):
3810 for flavor_iface in numa.get('interfaces', []):
3811 if flavor_iface.get('name') == iface['internal_name']:
3812 if flavor_iface['dedicated'] == 'yes':
3813 netDict['type'] = "PF" # passthrough
3814 elif flavor_iface['dedicated'] == 'no':
3815 netDict['type'] = "VF" # siov
3816 elif flavor_iface['dedicated'] == 'yes:sriov':
3817 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
3818 netDict["mac_address"] = flavor_iface.get("mac_address")
3819 break
3820 netDict["use"] = iface['type']
3821 if netDict["use"] == "data" and not netDict.get("type"):
3822 # print "netDict", netDict
3823 # print "iface", iface
3824 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3825 sce_vnf['name'], vm['name'], iface['internal_name'])
3826 if flavor_dict.get('extended') == None:
3827 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003828 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tierno16e3dd42018-04-24 12:52:40 +02003829 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003830 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tierno67881db2018-10-24 18:46:03 +02003831 if netDict["use"] == "mgmt":
3832 is_management_vm = True
3833 netDict["type"] = "virtual"
3834 if netDict["use"] == "bridge":
tierno16e3dd42018-04-24 12:52:40 +02003835 netDict["type"] = "virtual"
3836 if iface.get("vpci"):
3837 netDict['vpci'] = iface['vpci']
3838 if iface.get("mac"):
3839 netDict['mac_address'] = iface['mac']
tierno6082b7d2018-08-31 11:24:08 +00003840 if iface.get("mac_address"):
3841 netDict['mac_address'] = iface['mac_address']
tierno16e3dd42018-04-24 12:52:40 +02003842 if iface.get("ip_address"):
3843 netDict['ip_address'] = iface['ip_address']
3844 if iface.get("port-security") is not None:
3845 netDict['port_security'] = iface['port-security']
3846 if iface.get("floating-ip") is not None:
3847 netDict['floating_ip'] = iface['floating-ip']
3848 netDict['name'] = iface['internal_name']
3849 if iface['net_id'] is None:
3850 for vnf_iface in sce_vnf["interfaces"]:
3851 # print iface
3852 # print vnf_iface
3853 if vnf_iface['interface_id'] == iface['uuid']:
3854 netDict['net_id'] = "TASK-{}".format(
3855 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3856 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
3857 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3858 break
3859 else:
3860 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
3861 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
3862 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
3863 # skip bridge ifaces not connected to any net
3864 if 'net_id' not in netDict or netDict['net_id'] == None:
3865 continue
3866 myVMDict['networks'].append(netDict)
3867 db_vm_iface = {
3868 # "uuid"
3869 # 'instance_vm_id': instance_vm_uuid,
3870 "instance_net_id": instance_net_id,
3871 'interface_id': iface['uuid'],
3872 # 'vim_interface_id': ,
3873 'type': 'external' if iface['external_name'] is not None else 'internal',
3874 'ip_address': iface.get('ip_address'),
3875 'mac_address': iface.get('mac'),
3876 'floating_ip': int(iface.get('floating-ip', False)),
3877 'port_security': int(iface.get('port-security', True))
3878 }
3879 db_vm_ifaces.append(db_vm_iface)
3880 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3881 # print myVMDict['name']
3882 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3883 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3884 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3885
3886 # We add the RO key to cloud_config if vnf will need ssh access
3887 cloud_config_vm = cloud_config
tierno67881db2018-10-24 18:46:03 +02003888 if is_management_vm and params["instance_parameters"].get("mgmt_keys"):
3889 cloud_config_vm = unify_cloud_config({"key-pairs": params["instance_parameters"]["mgmt_keys"]},
3890 cloud_config_vm)
3891
3892 if vm.get("instance_parameters") and vm["instance_parameters"].get("mgmt_keys"):
3893 cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
3894 cloud_config_vm)
3895 # if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3896 # RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3897 # cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
tierno16e3dd42018-04-24 12:52:40 +02003898 if vm.get("boot_data"):
3899 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3900
3901 if myVMDict.get('availability_zone'):
3902 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
3903 else:
3904 av_index = None
3905 for vm_index in range(0, vm.get('count', 1)):
tiernofc5f80b2018-05-29 16:00:43 +02003906 vm_name = myVMDict['name'] + "-" + str(vm_index+1)
3907 task_params = (vm_name, myVMDict['description'], myVMDict.get('start', None),
tierno16e3dd42018-04-24 12:52:40 +02003908 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3909 myVMDict['disks'], av_index, vnf_availability_zones)
3910 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3911 for net in myVMDict['networks']:
3912 if "vim_id" in net:
3913 for iface in vm['interfaces']:
3914 if net["name"] == iface["internal_name"]:
3915 iface["vim_id"] = net["vim_id"]
3916 break
3917 vm_uuid = str(uuid4())
3918 uuid_list.append(vm_uuid)
3919 db_vm = {
3920 "uuid": vm_uuid,
3921 'instance_vnf_id': vnf_uuid,
3922 # TODO delete "vim_vm_id": vm_id,
3923 "vm_id": vm["uuid"],
tiernofc5f80b2018-05-29 16:00:43 +02003924 "vim_name": vm_name,
tierno16e3dd42018-04-24 12:52:40 +02003925 # "status":
3926 }
3927 db_instance_vms.append(db_vm)
3928
3929 iface_index = 0
3930 for db_vm_iface in db_vm_ifaces:
3931 iface_uuid = str(uuid4())
3932 uuid_list.append(iface_uuid)
3933 db_vm_iface_instance = {
3934 "uuid": iface_uuid,
3935 "instance_vm_id": vm_uuid
3936 }
3937 db_vm_iface_instance.update(db_vm_iface)
3938 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3939 ip = db_vm_iface_instance.get("ip_address")
3940 i = ip.rfind(".")
3941 if i > 0:
3942 try:
3943 i += 1
3944 ip = ip[i:] + str(int(ip[:i]) + 1)
3945 db_vm_iface_instance["ip_address"] = ip
3946 except:
3947 db_vm_iface_instance["ip_address"] = None
3948 db_instance_interfaces.append(db_vm_iface_instance)
3949 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3950 iface_index += 1
3951
3952 db_vim_action = {
3953 "instance_action_id": instance_action_id,
3954 "task_index": task_index,
3955 "datacenter_vim_id": myvim_thread_id,
3956 "action": "CREATE",
3957 "status": "SCHEDULED",
3958 "item": "instance_vms",
3959 "item_id": vm_uuid,
3960 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3961 default_flow_style=True, width=256)
3962 }
3963 task_index += 1
3964 db_vim_actions.append(db_vim_action)
3965 params_out["task_index"] = task_index
3966 params_out["uuid_list"] = uuid_list
3967
3968
tierno7edb6752016-03-21 17:37:52 +01003969def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02003970 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003971 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02003972 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01003973 tenant_id = instanceDict["tenant_id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003974
3975 # --> WIM
3976 # We need to retrieve the WIM Actions now, before the instance_scenario is
3977 # deleted. The reason for that is that: ON CASCADE rules will delete the
3978 # instance_wim_nets record in the database
3979 wim_actions = wim_engine.delete_actions(instance_scenario_id=instance_id)
3980 # <-- WIM
3981
tierno868220c2017-09-26 00:11:05 +02003982 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno868220c2017-09-26 00:11:05 +02003983 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02003984 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003985
tierno868220c2017-09-26 00:11:05 +02003986 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00003987 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01003988 myvims = {}
3989 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02003990 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02003991 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01003992
tierno868220c2017-09-26 00:11:05 +02003993 task_index = 0
3994 instance_action_id = get_task_id()
3995 db_vim_actions = []
3996 db_instance_action = {
3997 "uuid": instance_action_id, # same uuid for the instance and the action on create
3998 "tenant_id": tenant_id,
3999 "instance_id": instance_id,
4000 "description": "DELETE",
4001 # "number_tasks": 0 # filled bellow
4002 }
4003
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004004 # 2.1 deleting VNFFGs
tierno69b590e2018-03-13 18:52:23 +01004005 for sfp in instanceDict.get('sfps', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004006 vimthread_affected[sfp["datacenter_tenant_id"]] = None
4007 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
4008 if datacenter_key not in myvims:
4009 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004010 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004011 except NfvoException as e:
4012 logger.error(str(e))
4013 myvim_thread = None
4014 myvim_threads[datacenter_key] = myvim_thread
4015 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
4016 datacenter_tenant_id=sfp["datacenter_tenant_id"])
4017 if len(vims) == 0:
4018 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
4019 myvims[datacenter_key] = None
4020 else:
4021 myvims[datacenter_key] = vims.values()[0]
4022 myvim = myvims[datacenter_key]
4023 myvim_thread = myvim_threads[datacenter_key]
4024
4025 if not myvim:
4026 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
4027 continue
4028 extra = {"params": (sfp['vim_sfp_id'])}
4029 db_vim_action = {
4030 "instance_action_id": instance_action_id,
4031 "task_index": task_index,
4032 "datacenter_vim_id": sfp["datacenter_tenant_id"],
4033 "action": "DELETE",
4034 "status": "SCHEDULED",
4035 "item": "instance_sfps",
4036 "item_id": sfp["uuid"],
4037 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4038 }
4039 task_index += 1
4040 db_vim_actions.append(db_vim_action)
4041
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004042 for classification in instanceDict['classifications']:
4043 vimthread_affected[classification["datacenter_tenant_id"]] = None
4044 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
4045 if datacenter_key not in myvims:
4046 try:
4047 _, myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
4048 except NfvoException as e:
4049 logger.error(str(e))
4050 myvim_thread = None
4051 myvim_threads[datacenter_key] = myvim_thread
4052 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
4053 datacenter_tenant_id=classification["datacenter_tenant_id"])
4054 if len(vims) == 0:
4055 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"],
4056 classification["datacenter_tenant_id"]))
4057 myvims[datacenter_key] = None
4058 else:
4059 myvims[datacenter_key] = vims.values()[0]
4060 myvim = myvims[datacenter_key]
4061 myvim_thread = myvim_threads[datacenter_key]
4062
4063 if not myvim:
4064 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'],
4065 classification["datacenter_id"])
4066 continue
4067 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4068 extra = {"params": (classification['vim_classification_id']), "depends_on": depends_on}
4069 db_vim_action = {
4070 "instance_action_id": instance_action_id,
4071 "task_index": task_index,
4072 "datacenter_vim_id": classification["datacenter_tenant_id"],
4073 "action": "DELETE",
4074 "status": "SCHEDULED",
4075 "item": "instance_classifications",
4076 "item_id": classification["uuid"],
4077 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4078 }
4079 task_index += 1
4080 db_vim_actions.append(db_vim_action)
4081
tierno69b590e2018-03-13 18:52:23 +01004082 for sf in instanceDict.get('sfs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004083 vimthread_affected[sf["datacenter_tenant_id"]] = None
4084 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
4085 if datacenter_key not in myvims:
4086 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004087 _, myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004088 except NfvoException as e:
4089 logger.error(str(e))
4090 myvim_thread = None
4091 myvim_threads[datacenter_key] = myvim_thread
4092 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
4093 datacenter_tenant_id=sf["datacenter_tenant_id"])
4094 if len(vims) == 0:
4095 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
4096 myvims[datacenter_key] = None
4097 else:
4098 myvims[datacenter_key] = vims.values()[0]
4099 myvim = myvims[datacenter_key]
4100 myvim_thread = myvim_threads[datacenter_key]
4101
4102 if not myvim:
4103 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
4104 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004105 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4106 extra = {"params": (sf['vim_sf_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004107 db_vim_action = {
4108 "instance_action_id": instance_action_id,
4109 "task_index": task_index,
4110 "datacenter_vim_id": sf["datacenter_tenant_id"],
4111 "action": "DELETE",
4112 "status": "SCHEDULED",
4113 "item": "instance_sfs",
4114 "item_id": sf["uuid"],
4115 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4116 }
4117 task_index += 1
4118 db_vim_actions.append(db_vim_action)
4119
tierno69b590e2018-03-13 18:52:23 +01004120 for sfi in instanceDict.get('sfis', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004121 vimthread_affected[sfi["datacenter_tenant_id"]] = None
4122 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4123 if datacenter_key not in myvims:
4124 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004125 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004126 except NfvoException as e:
4127 logger.error(str(e))
4128 myvim_thread = None
4129 myvim_threads[datacenter_key] = myvim_thread
4130 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
4131 datacenter_tenant_id=sfi["datacenter_tenant_id"])
4132 if len(vims) == 0:
4133 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
4134 myvims[datacenter_key] = None
4135 else:
4136 myvims[datacenter_key] = vims.values()[0]
4137 myvim = myvims[datacenter_key]
4138 myvim_thread = myvim_threads[datacenter_key]
4139
4140 if not myvim:
4141 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
4142 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004143 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfs"]
4144 extra = {"params": (sfi['vim_sfi_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004145 db_vim_action = {
4146 "instance_action_id": instance_action_id,
4147 "task_index": task_index,
4148 "datacenter_vim_id": sfi["datacenter_tenant_id"],
4149 "action": "DELETE",
4150 "status": "SCHEDULED",
4151 "item": "instance_sfis",
4152 "item_id": sfi["uuid"],
4153 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4154 }
4155 task_index += 1
4156 db_vim_actions.append(db_vim_action)
4157
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004158 # 2.2 deleting VMs
4159 # vm_fail_list=[]
gcalvinod6fac4d2018-11-05 10:42:06 +01004160 for sce_vnf in instanceDict.get('vnfs', ()):
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004161 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4162 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
Igor D.Ccaadc442017-11-06 12:48:48 +00004163 if datacenter_key not in myvims:
4164 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004165 _, 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 +00004166 except NfvoException as e:
4167 logger.error(str(e))
4168 myvim_thread = None
4169 myvim_threads[datacenter_key] = myvim_thread
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004170 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
4171 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004172 if len(vims) == 0:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004173 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
4174 sce_vnf["datacenter_tenant_id"]))
4175 myvims[datacenter_key] = None
4176 else:
4177 myvims[datacenter_key] = vims.values()[0]
4178 myvim = myvims[datacenter_key]
4179 myvim_thread = myvim_threads[datacenter_key]
4180
4181 for vm in sce_vnf['vms']:
4182 if not myvim:
4183 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
4184 continue
4185 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4186 db_vim_action = {
4187 "instance_action_id": instance_action_id,
4188 "task_index": task_index,
4189 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
4190 "action": "DELETE",
4191 "status": "SCHEDULED",
4192 "item": "instance_vms",
4193 "item_id": vm["uuid"],
4194 "extra": yaml.safe_dump({"params": vm["interfaces"], "depends_on": sfi_dependencies},
4195 default_flow_style=True, width=256)
4196 }
4197 db_vim_actions.append(db_vim_action)
4198 for interface in vm["interfaces"]:
4199 if not interface.get("instance_net_id"):
4200 continue
4201 if interface["instance_net_id"] not in net2vm_dependencies:
4202 net2vm_dependencies[interface["instance_net_id"]] = []
4203 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
4204 task_index += 1
4205
4206 # 2.3 deleting NETS
4207 # net_fail_list=[]
4208 for net in instanceDict['nets']:
4209 vimthread_affected[net["datacenter_tenant_id"]] = None
4210 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4211 if datacenter_key not in myvims:
4212 try:
gcalvinod6fac4d2018-11-05 10:42:06 +01004213 _,myvim_thread = get_vim_thread(mydb, tenant_id, net["datacenter_id"], net["datacenter_tenant_id"])
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004214 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=net["datacenter_id"],
4219 datacenter_tenant_id=net["datacenter_tenant_id"])
4220 if len(vims) == 0:
4221 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 +00004222 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:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004229 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 +00004230 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004231 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
4232 if net2vm_dependencies.get(net["uuid"]):
4233 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
4234 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4235 if len(sfi_dependencies) > 0:
4236 if "depends_on" in extra:
4237 extra["depends_on"] += sfi_dependencies
4238 else:
4239 extra["depends_on"] = sfi_dependencies
Igor D.Ccaadc442017-11-06 12:48:48 +00004240 db_vim_action = {
4241 "instance_action_id": instance_action_id,
4242 "task_index": task_index,
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004243 "datacenter_vim_id": net["datacenter_tenant_id"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004244 "action": "DELETE",
4245 "status": "SCHEDULED",
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004246 "item": "instance_nets",
4247 "item_id": net["uuid"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004248 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4249 }
4250 task_index += 1
4251 db_vim_actions.append(db_vim_action)
4252
tierno868220c2017-09-26 00:11:05 +02004253 db_instance_action["number_tasks"] = task_index
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004254
4255 # --> WIM
4256 wim_actions, db_instance_action = (
4257 wim_engine.incorporate_actions(wim_actions, db_instance_action))
4258 # <-- WIM
4259
tierno868220c2017-09-26 00:11:05 +02004260 db_tables = [
4261 {"instance_actions": db_instance_action},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004262 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno868220c2017-09-26 00:11:05 +02004263 ]
4264
4265 logger.debug("delete_instance done DB tables: %s",
4266 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4267 mydb.new_rows(db_tables, ())
4268 for myvim_thread_id in vimthread_affected.keys():
4269 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4270
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004271 wim_engine.dispatch(wim_actions)
4272
tiernob3d36742017-03-03 23:51:05 +01004273 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02004274 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4275 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01004276 else:
tierno868220c2017-09-26 00:11:05 +02004277 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01004278
tierno7f426e92018-06-28 15:21:32 +02004279def get_instance_id(mydb, tenant_id, instance_id):
4280 global ovim
4281 #check valid tenant_id
4282 check_tenant(mydb, tenant_id)
4283 #obtain data
4284
4285 instance_dict = mydb.get_instance_scenario(instance_id, tenant_id, verbose=True)
4286 for net in instance_dict["nets"]:
4287 if net.get("sdn_net_id"):
4288 net_sdn = ovim.show_network(net["sdn_net_id"])
4289 net["sdn_info"] = {
4290 "admin_state_up": net_sdn.get("admin_state_up"),
4291 "flows": net_sdn.get("flows"),
4292 "last_error": net_sdn.get("last_error"),
4293 "ports": net_sdn.get("ports"),
4294 "type": net_sdn.get("type"),
4295 "status": net_sdn.get("status"),
4296 "vlan": net_sdn.get("vlan"),
4297 }
4298 return instance_dict
tiernob3d36742017-03-03 23:51:05 +01004299
tiernob8569aa2018-08-24 11:34:54 +02004300@deprecated("Instance is automatically refreshed by vim_threads")
tierno7edb6752016-03-21 17:37:52 +01004301def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4302 '''Refreshes a scenario instance. It modifies instanceDict'''
4303 '''Returns:
4304 - 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
4305 - error_msg
4306 '''
tierno867ffe92017-03-27 12:50:34 +02004307 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4308 # #print "nfvo.refresh_instance begins"
4309 # #print json.dumps(instanceDict, indent=4)
4310 #
4311 # #print "Getting the VIM URL and the VIM tenant_id"
4312 # myvims={}
4313 #
4314 # # 1. Getting VIM vm and net list
4315 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4316 # vms_notupdated=[]
4317 # vm_list = {}
4318 # for sce_vnf in instanceDict['vnfs']:
4319 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4320 # if datacenter_key not in vm_list:
4321 # vm_list[datacenter_key] = []
4322 # if datacenter_key not in myvims:
4323 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4324 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4325 # if len(vims) == 0:
4326 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4327 # myvims[datacenter_key] = None
4328 # else:
4329 # myvims[datacenter_key] = vims.values()[0]
4330 # for vm in sce_vnf['vms']:
4331 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4332 # vms_notupdated.append(vm["uuid"])
4333 #
4334 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4335 # nets_notupdated=[]
4336 # net_list = {}
4337 # for net in instanceDict['nets']:
4338 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4339 # if datacenter_key not in net_list:
4340 # net_list[datacenter_key] = []
4341 # if datacenter_key not in myvims:
4342 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4343 # datacenter_tenant_id=net["datacenter_tenant_id"])
4344 # if len(vims) == 0:
4345 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4346 # myvims[datacenter_key] = None
4347 # else:
4348 # myvims[datacenter_key] = vims.values()[0]
4349 #
4350 # net_list[datacenter_key].append(net['vim_net_id'])
4351 # nets_notupdated.append(net["uuid"])
4352 #
4353 # # 1. Getting the status of all VMs
4354 # vm_dict={}
4355 # for datacenter_key in myvims:
4356 # if not vm_list.get(datacenter_key):
4357 # continue
4358 # failed = True
4359 # failed_message=""
4360 # if not myvims[datacenter_key]:
4361 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4362 # else:
4363 # try:
4364 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4365 # failed = False
4366 # except vimconn.vimconnException as e:
4367 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4368 # failed_message = str(e)
4369 # if failed:
4370 # for vm in vm_list[datacenter_key]:
4371 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4372 #
4373 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4374 # for sce_vnf in instanceDict['vnfs']:
4375 # for vm in sce_vnf['vms']:
4376 # vm_id = vm['vim_vm_id']
4377 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4378 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4379 # has_mgmt_iface = False
4380 # for iface in vm["interfaces"]:
4381 # if iface["type"]=="mgmt":
4382 # has_mgmt_iface = True
4383 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4384 # vm_dict[vm_id]['status'] = "ACTIVE"
4385 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4386 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4387 # 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'):
4388 # vm['status'] = vm_dict[vm_id]['status']
4389 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4390 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4391 # # 2.1. Update in openmano DB the VMs whose status changed
4392 # try:
4393 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4394 # vms_notupdated.remove(vm["uuid"])
4395 # if updates>0:
4396 # vms_updated.append(vm["uuid"])
4397 # except db_base_Exception as e:
4398 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4399 # # 2.2. Update in openmano DB the interface VMs
4400 # for interface in interfaces:
4401 # #translate from vim_net_id to instance_net_id
4402 # network_id_list=[]
4403 # for net in instanceDict['nets']:
4404 # if net["vim_net_id"] == interface["vim_net_id"]:
4405 # network_id_list.append(net["uuid"])
4406 # if not network_id_list:
4407 # continue
4408 # del interface["vim_net_id"]
4409 # try:
4410 # for network_id in network_id_list:
4411 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4412 # except db_base_Exception as e:
4413 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4414 #
4415 # # 3. Getting the status of all nets
4416 # net_dict = {}
4417 # for datacenter_key in myvims:
4418 # if not net_list.get(datacenter_key):
4419 # continue
4420 # failed = True
4421 # failed_message = ""
4422 # if not myvims[datacenter_key]:
4423 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4424 # else:
4425 # try:
4426 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4427 # failed = False
4428 # except vimconn.vimconnException as e:
4429 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4430 # failed_message = str(e)
4431 # if failed:
4432 # for net in net_list[datacenter_key]:
4433 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4434 #
4435 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4436 # # TODO: update nets inside a vnf
4437 # for net in instanceDict['nets']:
4438 # net_id = net['vim_net_id']
4439 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4440 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4441 # 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'):
4442 # net['status'] = net_dict[net_id]['status']
4443 # net['error_msg'] = net_dict[net_id].get('error_msg')
4444 # net['vim_info'] = net_dict[net_id].get('vim_info')
4445 # # 5.1. Update in openmano DB the nets whose status changed
4446 # try:
4447 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4448 # nets_notupdated.remove(net["uuid"])
4449 # if updated>0:
4450 # nets_updated.append(net["uuid"])
4451 # except db_base_Exception as e:
4452 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4453 #
4454 # # Returns appropriate output
4455 # #print "nfvo.refresh_instance finishes"
4456 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4457 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01004458 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02004459 # if len(vms_notupdated)+len(nets_notupdated)>0:
4460 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4461 # 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 +01004462
tiernoae4a8d12016-07-08 12:30:39 +02004463 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01004464
4465def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02004466 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004467 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01004468 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4469
tiernoae4a8d12016-07-08 12:30:39 +02004470 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02004471 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4472 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004473 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004474 myvim = vims.values()[0]
tiernofc5f80b2018-05-29 16:00:43 +02004475 vm_result = {}
4476 vm_error = 0
4477 vm_ok = 0
tierno42026a02017-02-10 15:13:40 +01004478
tiernofc5f80b2018-05-29 16:00:43 +02004479 myvim_threads_id = {}
4480 if action_dict.get("vdu-scaling"):
4481 db_instance_vms = []
4482 db_vim_actions = []
4483 db_instance_interfaces = []
4484 instance_action_id = get_task_id()
4485 db_instance_action = {
4486 "uuid": instance_action_id, # same uuid for the instance and the action on create
4487 "tenant_id": nfvo_tenant,
4488 "instance_id": instance_id,
4489 "description": "SCALE",
4490 }
4491 vm_result["instance_action_id"] = instance_action_id
tierno67881db2018-10-24 18:46:03 +02004492 vm_result["created"] = []
4493 vm_result["deleted"] = []
tiernofc5f80b2018-05-29 16:00:43 +02004494 task_index = 0
4495 for vdu in action_dict["vdu-scaling"]:
tierno868220c2017-09-26 00:11:05 +02004496 vdu_id = vdu.get("vdu-id")
tiernofc5f80b2018-05-29 16:00:43 +02004497 osm_vdu_id = vdu.get("osm_vdu_id")
4498 member_vnf_index = vdu.get("member-vnf-index")
tierno868220c2017-09-26 00:11:05 +02004499 vdu_count = vdu.get("count", 1)
tiernofc5f80b2018-05-29 16:00:43 +02004500 if vdu_id:
tierno67881db2018-10-24 18:46:03 +02004501 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004502 FROM="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4503 WHERE={"vms.uuid": vdu_id},
4504 ORDER_BY="vms.created_at"
4505 )
tierno67881db2018-10-24 18:46:03 +02004506 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004507 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id), httperrors.Not_Found)
tiernofc5f80b2018-05-29 16:00:43 +02004508 else:
4509 if not osm_vdu_id and not member_vnf_index:
tiernoa43bd9e2018-11-26 09:28:58 +00004510 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
tierno67881db2018-10-24 18:46:03 +02004511 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004512 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4513 FROM="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4514 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4515 " join vms on ivms.vm_id=vms.uuid",
tiernoa43bd9e2018-11-26 09:28:58 +00004516 WHERE={"vms.osm_id": osm_vdu_id, "svnfs.member_vnf_index": member_vnf_index,
4517 "ivnfs.instance_scenario_id": instance_id},
tiernofc5f80b2018-05-29 16:00:43 +02004518 ORDER_BY="ivms.created_at"
4519 )
tierno67881db2018-10-24 18:46:03 +02004520 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004521 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 +02004522 vdu_id = target_vms[-1]["uuid"]
4523 target_vm = target_vms[-1]
tiernofc5f80b2018-05-29 16:00:43 +02004524 datacenter = target_vm["datacenter_id"]
4525 myvim_threads_id[datacenter], _ = get_vim_thread(mydb, nfvo_tenant, datacenter)
tiernofc5f80b2018-05-29 16:00:43 +02004526
tierno67881db2018-10-24 18:46:03 +02004527 if vdu["type"] == "delete":
4528 for index in range(0, vdu_count):
4529 target_vm = target_vms[-1-index]
4530 vdu_id = target_vm["uuid"]
4531 # look for nm
4532 vm_interfaces = None
4533 for sce_vnf in instanceDict['vnfs']:
4534 for vm in sce_vnf['vms']:
4535 if vm["uuid"] == vdu_id:
4536 vm_interfaces = vm["interfaces"]
4537 break
4538
4539 db_vim_action = {
4540 "instance_action_id": instance_action_id,
4541 "task_index": task_index,
4542 "datacenter_vim_id": target_vm["datacenter_tenant_id"],
4543 "action": "DELETE",
4544 "status": "SCHEDULED",
4545 "item": "instance_vms",
4546 "item_id": vdu_id,
4547 "extra": yaml.safe_dump({"params": vm_interfaces},
4548 default_flow_style=True, width=256)
4549 }
4550 task_index += 1
4551 db_vim_actions.append(db_vim_action)
4552 vm_result["deleted"].append(vdu_id)
4553 # delete from database
4554 db_instance_vms.append({"TO-DELETE": vdu_id})
tiernofc5f80b2018-05-29 16:00:43 +02004555
4556 else: # vdu["type"] == "create":
4557 iface2iface = {}
4558 where = {"item": "instance_vms", "item_id": target_vm["uuid"], "action": "CREATE"}
4559
garciadeblas72cd59f2018-12-05 10:59:40 +01004560 vim_action_to_clone = mydb.get_rows(FROM="vim_wim_actions", WHERE=where)
tiernofc5f80b2018-05-29 16:00:43 +02004561 if not vim_action_to_clone:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004562 raise NfvoException("Cannot find the vim_action at database with {}".format(where), httperrors.Internal_Server_Error)
tiernofc5f80b2018-05-29 16:00:43 +02004563 vim_action_to_clone = vim_action_to_clone[0]
4564 extra = yaml.safe_load(vim_action_to_clone["extra"])
4565
4566 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4567 # TODO do the same for flavor and image when available
4568 task_depends_on = []
4569 task_params = extra["params"]
4570 task_params_networks = deepcopy(task_params[5])
4571 for iface in task_params[5]:
4572 if iface["net_id"].startswith("TASK-"):
4573 if "." not in iface["net_id"]:
4574 task_depends_on.append("{}.{}".format(vim_action_to_clone["instance_action_id"],
4575 iface["net_id"][5:]))
4576 iface["net_id"] = "TASK-{}.{}".format(vim_action_to_clone["instance_action_id"],
4577 iface["net_id"][5:])
4578 else:
4579 task_depends_on.append(iface["net_id"][5:])
4580 if "mac_address" in iface:
4581 del iface["mac_address"]
4582
4583 vm_ifaces_to_clone = mydb.get_rows(FROM="instance_interfaces", WHERE={"instance_vm_id": target_vm["uuid"]})
4584 for index in range(0, vdu_count):
4585 vm_uuid = str(uuid4())
4586 vm_name = target_vm.get('vim_name')
4587 try:
4588 suffix = vm_name.rfind("-")
tierno67881db2018-10-24 18:46:03 +02004589 vm_name = vm_name[:suffix+1] + str(index + 1 + int(vm_name[suffix+1:]))
tiernofc5f80b2018-05-29 16:00:43 +02004590 except Exception:
4591 pass
4592 db_instance_vm = {
4593 "uuid": vm_uuid,
4594 'instance_vnf_id': target_vm['instance_vnf_id'],
4595 'vm_id': target_vm['vm_id'],
4596 'vim_name': vm_name
4597 }
4598 db_instance_vms.append(db_instance_vm)
4599
4600 for vm_iface in vm_ifaces_to_clone:
4601 iface_uuid = str(uuid4())
4602 iface2iface[vm_iface["uuid"]] = iface_uuid
4603 db_vm_iface = {
4604 "uuid": iface_uuid,
4605 'instance_vm_id': vm_uuid,
4606 "instance_net_id": vm_iface["instance_net_id"],
4607 'interface_id': vm_iface['interface_id'],
4608 'type': vm_iface['type'],
4609 'floating_ip': vm_iface['floating_ip'],
4610 'port_security': vm_iface['port_security']
4611 }
4612 db_instance_interfaces.append(db_vm_iface)
4613 task_params_copy = deepcopy(task_params)
4614 for iface in task_params_copy[5]:
4615 iface["uuid"] = iface2iface[iface["uuid"]]
4616 # increment ip_address
4617 if "ip_address" in iface:
4618 ip = iface.get("ip_address")
4619 i = ip.rfind(".")
4620 if i > 0:
4621 try:
4622 i += 1
4623 ip = ip[i:] + str(int(ip[:i]) + 1)
4624 iface["ip_address"] = ip
4625 except:
4626 iface["ip_address"] = None
4627 if vm_name:
4628 task_params_copy[0] = vm_name
4629 db_vim_action = {
4630 "instance_action_id": instance_action_id,
4631 "task_index": task_index,
4632 "datacenter_vim_id": vim_action_to_clone["datacenter_vim_id"],
4633 "action": "CREATE",
4634 "status": "SCHEDULED",
4635 "item": "instance_vms",
4636 "item_id": vm_uuid,
4637 # ALF
4638 # ALF
4639 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4640 # ALF
4641 # ALF
4642 "extra": yaml.safe_dump({"params": task_params_copy, "depends_on": task_depends_on}, default_flow_style=True, width=256)
4643 }
4644 task_index += 1
4645 db_vim_actions.append(db_vim_action)
tierno67881db2018-10-24 18:46:03 +02004646 vm_result["created"].append(vm_uuid)
tiernofc5f80b2018-05-29 16:00:43 +02004647
4648 db_instance_action["number_tasks"] = task_index
4649 db_tables = [
4650 {"instance_vms": db_instance_vms},
4651 {"instance_interfaces": db_instance_interfaces},
4652 {"instance_actions": db_instance_action},
4653 # TODO revise sfps
4654 # {"instance_sfis": db_instance_sfis},
4655 # {"instance_sfs": db_instance_sfs},
4656 # {"instance_classifications": db_instance_classifications},
4657 # {"instance_sfps": db_instance_sfps},
garciadeblasaba7a0d2018-12-05 12:42:35 +01004658 {"vim_wim_actions": db_vim_actions}
tiernofc5f80b2018-05-29 16:00:43 +02004659 ]
4660 logger.debug("create_vdu done DB tables: %s",
4661 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4662 mydb.new_rows(db_tables, [])
4663 for myvim_thread in myvim_threads_id.values():
4664 vim_threads["running"][myvim_thread].insert_task(db_vim_actions)
4665
4666 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004667
4668 input_vnfs = action_dict.pop("vnfs", [])
4669 input_vms = action_dict.pop("vms", [])
tierno92c36fd2018-05-04 12:21:10 +02004670 action_over_all = True if not input_vnfs and not input_vms else False
tierno7edb6752016-03-21 17:37:52 +01004671 for sce_vnf in instanceDict['vnfs']:
4672 for vm in sce_vnf['vms']:
tierno92c36fd2018-05-04 12:21:10 +02004673 if not action_over_all and sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4674 sce_vnf['member_vnf_index'] not in input_vnfs and \
4675 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
4676 continue
tiernoae4a8d12016-07-08 12:30:39 +02004677 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004678 if "add_public_key" in action_dict:
4679 mgmt_access = {}
4680 if sce_vnf.get('mgmt_access'):
4681 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4682 ssh_access = mgmt_access['config-access']['ssh-access']
4683 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01004684 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004685 if ssh_access['required'] and ssh_access['default-user']:
4686 if 'ip_address' in vm:
4687 mgmt_ip = vm['ip_address'].split(';')
4688 password = mgmt_access['config-access'].get('password')
4689 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4690 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4691 action_dict['add_public_key'],
4692 password=password, ro_key=priv_RO_key)
4693 else:
4694 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004695 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004696 except KeyError:
4697 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004698 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004699 else:
4700 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004701 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004702 else:
4703 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4704 if "console" in action_dict:
4705 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02004706 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4707 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4708 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02004709 ip = data["server"],
4710 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02004711 suffix = data["suffix"]),
4712 "name":vm['name']
4713 }
4714 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004715 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004716 vm_result[ vm['uuid'] ] = {"vim_result": -httperrors.Unauthorized,
gcalvinoe580c7d2017-09-22 14:09:51 +02004717 "description": "this console is only reachable by local interface",
4718 "name":vm['name']
4719 }
tierno20fc2a22016-08-19 17:02:35 +02004720 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004721 else:
4722 #print "console data", data
4723 try:
4724 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4725 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4726 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4727 protocol=data["protocol"],
4728 ip = global_config["http_console_host"],
4729 port = console_thread.port,
4730 suffix = data["suffix"]),
4731 "name":vm['name']
4732 }
4733 vm_ok +=1
4734 except NfvoException as e:
4735 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4736 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02004737
gcalvinoe580c7d2017-09-22 14:09:51 +02004738 else:
4739 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4740 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02004741 except vimconn.vimconnException as e:
4742 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4743 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01004744
4745 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02004746 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004747 else:
tierno351863c2016-07-23 01:46:03 +02004748 return vm_result
tierno42026a02017-02-10 15:13:40 +01004749
tierno868220c2017-09-26 00:11:05 +02004750def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
tierno16e3dd42018-04-24 12:52:40 +02004751 filter = {}
tierno868220c2017-09-26 00:11:05 +02004752 if nfvo_tenant and nfvo_tenant != "any":
4753 filter["tenant_id"] = nfvo_tenant
4754 if instance_id and instance_id != "any":
4755 filter["instance_id"] = instance_id
4756 if action_id:
4757 filter["uuid"] = action_id
4758 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
tierno16e3dd42018-04-24 12:52:40 +02004759 if action_id:
4760 if not rows:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004761 raise NfvoException("Not found any action with this criteria", httperrors.Not_Found)
4762 vim_wim_actions = mydb.get_rows(FROM="vim_wim_actions", WHERE={"instance_action_id": action_id})
4763 rows[0]["vim_wim_actions"] = vim_wim_actions
tierno31e121f2018-12-03 12:04:48 +00004764 # for backward compatibility set vim_actions = vim_wim_actions
4765 rows[0]["vim_actions"] = vim_wim_actions
tiernofc5f80b2018-05-29 16:00:43 +02004766 return {"actions": rows}
tierno868220c2017-09-26 00:11:05 +02004767
tiernob3d36742017-03-03 23:51:05 +01004768
tierno7edb6752016-03-21 17:37:52 +01004769def create_or_use_console_proxy_thread(console_server, console_port):
4770 #look for a non-used port
4771 console_thread_key = console_server + ":" + str(console_port)
4772 if console_thread_key in global_config["console_thread"]:
4773 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02004774 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01004775
tierno7edb6752016-03-21 17:37:52 +01004776 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02004777 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01004778 if port in global_config["console_ports"]:
4779 continue
4780 try:
4781 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4782 clithread.start()
4783 global_config["console_thread"][console_thread_key] = clithread
4784 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02004785 return clithread
tierno7edb6752016-03-21 17:37:52 +01004786 except cli.ConsoleProxyExceptionPortUsed as e:
4787 #port used, try with onoher
4788 continue
4789 except cli.ConsoleProxyException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004790 raise NfvoException(str(e), httperrors.Bad_Request)
4791 raise NfvoException("Not found any free 'http_console_ports'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004792
tiernob3d36742017-03-03 23:51:05 +01004793
tierno7edb6752016-03-21 17:37:52 +01004794def check_tenant(mydb, tenant_id):
4795 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02004796 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4797 if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004798 raise NfvoException("tenant '{}' not found".format(tenant_id), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02004799 return
tierno7edb6752016-03-21 17:37:52 +01004800
4801def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01004802
gcalvinoe580c7d2017-09-22 14:09:51 +02004803 tenant_uuid = str(uuid4())
4804 tenant_dict['uuid'] = tenant_uuid
4805 try:
4806 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4807 tenant_dict['RO_pub_key'] = pub_key
4808 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02004809 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02004810 except db_base_Exception as e:
tierno9c5c8322018-03-23 15:44:03 +01004811 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
gcalvinoe580c7d2017-09-22 14:09:51 +02004812 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01004813
tierno7edb6752016-03-21 17:37:52 +01004814def delete_tenant(mydb, tenant):
4815 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01004816
tiernof97fd272016-07-11 14:32:37 +02004817 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4818 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4819 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01004820
tiernob3d36742017-03-03 23:51:05 +01004821
tierno7edb6752016-03-21 17:37:52 +01004822def new_datacenter(mydb, datacenter_descriptor):
tierno1c848c02018-05-21 16:40:33 +02004823 sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004824 if "config" in datacenter_descriptor:
tiernoedf3f4f2018-05-17 23:02:47 +02004825 sdn_port_mapping = datacenter_descriptor["config"].pop("sdn-port-mapping", None)
4826 datacenter_descriptor["config"] = yaml.safe_dump(datacenter_descriptor["config"], default_flow_style=True,
4827 width=256)
4828 # Check that datacenter-type is correct
tierno3ae39742016-09-07 12:17:51 +02004829 datacenter_type = datacenter_descriptor.get("type", "openvim");
tiernoedf3f4f2018-05-17 23:02:47 +02004830 # module_info = None
tierno3ae39742016-09-07 12:17:51 +02004831 try:
4832 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02004833 pkg = __import__("osm_ro." + module)
tiernoedf3f4f2018-05-17 23:02:47 +02004834 # vim_conn = getattr(pkg, module)
tierno361275f2017-04-25 16:24:34 +02004835 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02004836 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02004837 # if module_info and module_info[0]:
4838 # file.close(module_info[0])
tiernoedf3f4f2018-05-17 23:02:47 +02004839 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type,
4840 module),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004841 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01004842
gcalvinoc62cfa52017-10-05 18:21:25 +02004843 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernoedf3f4f2018-05-17 23:02:47 +02004844 if sdn_port_mapping:
4845 try:
4846 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, sdn_port_mapping)
4847 except Exception as e:
4848 mydb.delete_row_by_id("datacenters", datacenter_id) # Rollback
4849 raise e
tiernof97fd272016-07-11 14:32:37 +02004850 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004851
tiernob3d36742017-03-03 23:51:05 +01004852
tierno7edb6752016-03-21 17:37:52 +01004853def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02004854 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02004855 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02004856
4857 # edit data
tiernof97fd272016-07-11 14:32:37 +02004858 datacenter_id = datacenter['uuid']
tiernod72182f2018-08-29 10:56:13 +02004859 where = {'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02004860 remove_port_mapping = False
tiernoedf3f4f2018-05-17 23:02:47 +02004861 new_sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004862 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02004863 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01004864 try:
4865 new_config_dict = datacenter_descriptor["config"]
tiernoedf3f4f2018-05-17 23:02:47 +02004866 if "sdn-port-mapping" in new_config_dict:
4867 remove_port_mapping = True
4868 new_sdn_port_mapping = new_config_dict.pop("sdn-port-mapping")
tiernod72182f2018-08-29 10:56:13 +02004869 # delete null fields
4870 to_delete = []
tierno7edb6752016-03-21 17:37:52 +01004871 for k in new_config_dict:
tiernod72182f2018-08-29 10:56:13 +02004872 if new_config_dict[k] is None:
tierno7edb6752016-03-21 17:37:52 +01004873 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02004874 if k == 'sdn-controller':
4875 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01004876
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004877 config_text = datacenter.get("config")
4878 if not config_text:
4879 config_text = '{}'
4880 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01004881 config_dict.update(new_config_dict)
tiernod72182f2018-08-29 10:56:13 +02004882 # delete null fields
tierno7edb6752016-03-21 17:37:52 +01004883 for k in to_delete:
4884 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02004885 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004886 raise NfvoException("Bad format at datacenter:config " + str(e), httperrors.Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02004887 if config_dict:
4888 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4889 else:
4890 datacenter_descriptor["config"] = None
4891 if remove_port_mapping:
4892 try:
4893 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4894 except ovimException as e:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004895 raise NfvoException("Error deleting datacenter-port-mapping " + str(e), httperrors.Conflict)
tierno8fe7a492017-07-11 13:50:04 +02004896
tiernof97fd272016-07-11 14:32:37 +02004897 mydb.update_rows('datacenters', datacenter_descriptor, where)
tiernoedf3f4f2018-05-17 23:02:47 +02004898 if new_sdn_port_mapping:
4899 try:
4900 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, new_sdn_port_mapping)
4901 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004902 # Rollback
4903 mydb.update_rows('datacenters', datacenter, where)
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004904 raise NfvoException("Error adding datacenter-port-mapping " + str(e), httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02004905 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004906
tiernob3d36742017-03-03 23:51:05 +01004907
tierno7edb6752016-03-21 17:37:52 +01004908def delete_datacenter(mydb, datacenter):
4909 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02004910 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
4911 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02004912 try:
4913 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
4914 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004915 raise NfvoException("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02004916 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01004917
tiernob3d36742017-03-03 23:51:05 +01004918
tiernod3750b32018-07-20 15:33:08 +02004919def create_vim_account(mydb, nfvo_tenant, datacenter_id, name=None, vim_id=None, vim_tenant=None, vim_tenant_name=None,
4920 vim_username=None, vim_password=None, config=None):
tierno9c22f2d2017-10-09 16:23:55 +02004921 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02004922 try:
tiernod3750b32018-07-20 15:33:08 +02004923 if not datacenter_id:
4924 if not vim_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004925 raise NfvoException("You must provide 'vim_id", http_code=httperrors.Bad_Request)
tiernod3750b32018-07-20 15:33:08 +02004926 datacenter_id = vim_id
4927 datacenter_id, datacenter_name = get_datacenter_uuid(mydb, None, datacenter_id)
tierno7edb6752016-03-21 17:37:52 +01004928
tiernod3750b32018-07-20 15:33:08 +02004929 create_vim_tenant = True if not vim_tenant and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01004930
tierno0ea2a7e2017-10-18 00:06:26 +02004931 # get nfvo_tenant info
4932 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
4933 if vim_tenant_name==None:
4934 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01004935
tierno0ea2a7e2017-10-18 00:06:26 +02004936 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernod3750b32018-07-20 15:33:08 +02004937 # #check that this association does not exist before
4938 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4939 # if len(tenants_datacenters)>0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004940 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004941
tierno0ea2a7e2017-10-18 00:06:26 +02004942 vim_tenant_id_exist_atdb=False
4943 if not create_vim_tenant:
4944 where_={"datacenter_id": datacenter_id}
tiernod3750b32018-07-20 15:33:08 +02004945 if vim_tenant!=None:
4946 where_["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004947 if vim_tenant_name!=None:
4948 where_["vim_tenant_name"] = vim_tenant_name
4949 #check if vim_tenant_id is already at database
4950 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
4951 if len(datacenter_tenants_dict)>=1:
4952 datacenter_tenants_dict = datacenter_tenants_dict[0]
4953 vim_tenant_id_exist_atdb=True
4954 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
4955 else: #result=0
4956 datacenter_tenants_dict = {}
4957 #insert at table datacenter_tenants
tiernod3750b32018-07-20 15:33:08 +02004958 else: #if vim_tenant==None:
tierno0ea2a7e2017-10-18 00:06:26 +02004959 #create tenant at VIM if not provided
4960 try:
4961 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
4962 vim_passwd=vim_password)
4963 datacenter_name = myvim["name"]
tiernod3750b32018-07-20 15:33:08 +02004964 vim_tenant = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
tierno0ea2a7e2017-10-18 00:06:26 +02004965 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004966 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 +01004967 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02004968 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01004969
tierno0ea2a7e2017-10-18 00:06:26 +02004970 #fill datacenter_tenants table
4971 if not vim_tenant_id_exist_atdb:
tiernod3750b32018-07-20 15:33:08 +02004972 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004973 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
4974 datacenter_tenants_dict["user"] = vim_username
4975 datacenter_tenants_dict["passwd"] = vim_password
4976 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernod3750b32018-07-20 15:33:08 +02004977 if name:
4978 datacenter_tenants_dict["name"] = name
4979 else:
4980 datacenter_tenants_dict["name"] = datacenter_name
tierno0ea2a7e2017-10-18 00:06:26 +02004981 if config:
4982 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
4983 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
4984 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01004985
tierno0ea2a7e2017-10-18 00:06:26 +02004986 #fill tenants_datacenters table
4987 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
4988 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
4989 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tiernod3750b32018-07-20 15:33:08 +02004990
tierno0ea2a7e2017-10-18 00:06:26 +02004991 # create thread
tierno0ea2a7e2017-10-18 00:06:26 +02004992 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tiernod3750b32018-07-20 15:33:08 +02004993 new_thread = vim_thread.vim_thread(task_lock, thread_name, datacenter_name, datacenter_tenant_id,
tierno0ea2a7e2017-10-18 00:06:26 +02004994 db=db, db_lock=db_lock, ovim=ovim)
4995 new_thread.start()
4996 thread_id = datacenter_tenants_dict["uuid"]
4997 vim_threads["running"][thread_id] = new_thread
tiernod3750b32018-07-20 15:33:08 +02004998 return thread_id
tierno0ea2a7e2017-10-18 00:06:26 +02004999 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005000 raise NfvoException(str(e), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005001
tierno99314902017-04-26 13:23:09 +02005002
tiernod3750b32018-07-20 15:33:08 +02005003def edit_vim_account(mydb, nfvo_tenant, datacenter_tenant_id, datacenter_id=None, name=None, vim_tenant=None,
5004 vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005005
tiernod3750b32018-07-20 15:33:08 +02005006 # get vim_account; check is valid for this tenant
5007 from_ = "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
5008 where_ = {"td.nfvo_tenant_id": nfvo_tenant}
5009 if datacenter_tenant_id:
5010 where_["dt.uuid"] = datacenter_tenant_id
5011 if datacenter_id:
5012 where_["dt.datacenter_id"] = datacenter_id
5013 vim_accounts = mydb.get_rows(SELECT="dt.uuid as uuid, config", FROM=from_, WHERE=where_)
5014 if not vim_accounts:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005015 raise NfvoException("vim_account not found for this tenant", http_code=httperrors.Not_Found)
tiernod3750b32018-07-20 15:33:08 +02005016 elif len(vim_accounts) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005017 raise NfvoException("found more than one vim_account for this tenant", http_code=httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02005018 datacenter_tenant_id = vim_accounts[0]["uuid"]
5019 original_config = vim_accounts[0]["config"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005020
tiernod3750b32018-07-20 15:33:08 +02005021 update_ = {}
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005022 if config:
tiernod3750b32018-07-20 15:33:08 +02005023 original_config_dict = yaml.load(original_config)
5024 original_config_dict.update(config)
5025 update["config"] = yaml.safe_dump(original_config_dict, default_flow_style=True, width=256)
5026 if name:
5027 update_['name'] = name
5028 if vim_tenant:
5029 update_['vim_tenant_id'] = vim_tenant
5030 if vim_tenant_name:
5031 update_['vim_tenant_name'] = vim_tenant_name
5032 if vim_username:
5033 update_['user'] = vim_username
5034 if vim_password:
5035 update_['passwd'] = vim_password
5036 if update_:
5037 mydb.update_rows("datacenter_tenants", UPDATE=update_, WHERE={"uuid": datacenter_tenant_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005038
tiernod3750b32018-07-20 15:33:08 +02005039 vim_threads["running"][datacenter_tenant_id].insert_task("reload")
5040 return datacenter_tenant_id
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005041
tiernod3750b32018-07-20 15:33:08 +02005042def delete_vim_account(mydb, tenant_id, vim_account_id, datacenter=None):
tierno7edb6752016-03-21 17:37:52 +01005043 #get nfvo_tenant info
5044 if not tenant_id or tenant_id=="any":
5045 tenant_uuid = None
5046 else:
tiernof97fd272016-07-11 14:32:37 +02005047 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01005048 tenant_uuid = tenant_dict['uuid']
5049
5050 #check that this association exist before
tiernod3750b32018-07-20 15:33:08 +02005051 tenants_datacenter_dict = {}
5052 if datacenter:
5053 datacenter_id, _ = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
5054 tenants_datacenter_dict["datacenter_id"] = datacenter_id
5055 elif vim_account_id:
5056 tenants_datacenter_dict["datacenter_tenant_id"] = vim_account_id
tierno7edb6752016-03-21 17:37:52 +01005057 if tenant_uuid:
5058 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02005059 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5060 if len(tenant_datacenter_list)==0 and tenant_uuid:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005061 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005062
5063 #delete this association
tiernof97fd272016-07-11 14:32:37 +02005064 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01005065
5066 #get vim_tenant info and deletes
5067 warning=''
5068 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02005069 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5070 #try to delete vim:tenant
5071 try:
5072 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5073 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01005074 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01005075 try:
tierno0ea2a7e2017-10-18 00:06:26 +02005076 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005077 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
5078 except vimconn.vimconnException as e:
5079 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
5080 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02005081 except db_base_Exception as e:
5082 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01005083 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02005084 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tiernoa3572692018-05-14 13:09:33 +02005085 thread = vim_threads["running"].get(thread_id)
5086 if thread:
5087 thread.insert_task("exit")
5088 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02005089 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01005090
tiernob3d36742017-03-03 23:51:05 +01005091
tierno7edb6752016-03-21 17:37:52 +01005092def datacenter_action(mydb, tenant_id, datacenter, action_dict):
5093 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01005094 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005095 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005096
5097 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02005098 try:
tiernof97fd272016-07-11 14:32:37 +02005099 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02005100 #print content
5101 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005102 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005103 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01005104 #update nets Change from VIM format to NFVO format
5105 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005106 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01005107 net_nfvo={'datacenter_id': datacenter_id}
5108 net_nfvo['name'] = net['name']
5109 #net_nfvo['description']= net['name']
5110 net_nfvo['vim_net_id'] = net['id']
5111 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5112 net_nfvo['shared'] = net['shared']
5113 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5114 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02005115 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
5116 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
5117 return inserted
tierno7edb6752016-03-21 17:37:52 +01005118 elif 'net-edit' in action_dict:
5119 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02005120 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005121 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01005122 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005123 return result
tierno7edb6752016-03-21 17:37:52 +01005124 elif 'net-delete' in action_dict:
5125 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02005126 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005127 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01005128 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005129 return result
tierno7edb6752016-03-21 17:37:52 +01005130
5131 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005132 raise NfvoException("Unknown action " + str(action_dict), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005133
tiernob3d36742017-03-03 23:51:05 +01005134
tierno7edb6752016-03-21 17:37:52 +01005135def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
5136 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005137 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005138
tierno42fcc3b2016-07-06 17:20:40 +02005139 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01005140 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01005141 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02005142 return result
tierno7edb6752016-03-21 17:37:52 +01005143
tiernob3d36742017-03-03 23:51:05 +01005144
tierno7edb6752016-03-21 17:37:52 +01005145def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
5146 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005147 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005148 filter_dict={}
5149 if action_dict:
5150 action_dict = action_dict["netmap"]
5151 if 'vim_id' in action_dict:
5152 filter_dict["id"] = action_dict['vim_id']
5153 if 'vim_name' in action_dict:
5154 filter_dict["name"] = action_dict['vim_name']
5155 else:
5156 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01005157
tiernoae4a8d12016-07-08 12:30:39 +02005158 try:
tiernof97fd272016-07-11 14:32:37 +02005159 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005160 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005161 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005162 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tiernof97fd272016-07-11 14:32:37 +02005163 if len(vim_nets)>1 and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005164 raise NfvoException("more than two networks found, specify with vim_id", httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02005165 elif len(vim_nets)==0: # and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005166 raise NfvoException("Not found a network at VIM with " + str(filter_dict), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005167 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005168 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01005169 net_nfvo={'datacenter_id': datacenter_id}
5170 if action_dict and "name" in action_dict:
5171 net_nfvo['name'] = action_dict['name']
5172 else:
5173 net_nfvo['name'] = net['name']
5174 #net_nfvo['description']= net['name']
5175 net_nfvo['vim_net_id'] = net['id']
5176 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5177 net_nfvo['shared'] = net['shared']
5178 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02005179 try:
5180 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01005181 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02005182 net_nfvo["uuid"] = net_id
5183 except db_base_Exception as e:
5184 if action_dict:
5185 raise
5186 else:
5187 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01005188 net_list.append(net_nfvo)
5189 return net_list
tierno7edb6752016-03-21 17:37:52 +01005190
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005191def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
5192 # obtain all network data
5193 try:
5194 if utils.check_valid_uuid(network_id):
5195 filter_dict = {"id": network_id}
5196 else:
5197 filter_dict = {"name": network_id}
5198
5199 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5200 network = myvim.get_network_list(filter_dict=filter_dict)
5201 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02005202 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 +02005203
5204 # ensure the network is defined
5205 if len(network) == 0:
5206 raise NfvoException("Network {} is not present in the system".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005207 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005208
5209 # ensure there is only one network with the provided name
5210 if len(network) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005211 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005212
5213 # ensure it is a dataplane network
5214 if network[0]['type'] != 'data':
5215 return None
5216
5217 # ensure we use the id
5218 network_id = network[0]['id']
5219
5220 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5221 # and with instance_scenario_id==NULL
5222 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5223 search_dict = {'vim_net_id': network_id}
5224
5225 try:
5226 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5227 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
5228 except db_base_Exception as e:
5229 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005230 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005231
5232 sdn_net_counter = 0
5233 for net in result:
5234 if net['sdn_net_id'] != None:
5235 sdn_net_counter+=1
5236 sdn_net_id = net['sdn_net_id']
5237
5238 if sdn_net_counter == 0:
5239 return None
5240 elif sdn_net_counter == 1:
5241 return sdn_net_id
5242 else:
5243 raise NfvoException("More than one SDN network is associated to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005244 network_id), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005245
5246def get_sdn_controller_id(mydb, datacenter):
5247 # Obtain sdn controller id
5248 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
5249 if not config:
5250 return None
5251
5252 return yaml.load(config).get('sdn-controller')
5253
5254def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
5255 try:
5256 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5257 if not sdn_network_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005258 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 +02005259
5260 #Obtain sdn controller id
5261 controller_id = get_sdn_controller_id(mydb, datacenter)
5262 if not controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005263 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005264
5265 #Obtain sdn controller info
5266 sdn_controller = ovim.show_of_controller(controller_id)
5267
5268 port_data = {
5269 'name': 'external_port',
5270 'net_id': sdn_network_id,
5271 'ofc_id': controller_id,
5272 'switch_dpid': sdn_controller['dpid'],
5273 'switch_port': descriptor['port']
5274 }
5275
5276 if 'vlan' in descriptor:
5277 port_data['vlan'] = descriptor['vlan']
5278 if 'mac' in descriptor:
5279 port_data['mac'] = descriptor['mac']
5280
5281 result = ovim.new_port(port_data)
5282 except ovimException as e:
5283 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005284 sdn_network_id, network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005285 except db_base_Exception as e:
5286 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005287 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005288
5289 return 'Port uuid: '+ result
5290
5291def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
5292 if port_id:
5293 filter = {'uuid': port_id}
5294 else:
5295 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5296 if not sdn_network_id:
5297 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005298 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005299 #in case no port_id is specified only ports marked as 'external_port' will be detached
5300 filter = {'name': 'external_port', 'net_id': sdn_network_id}
5301
5302 try:
5303 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
5304 except ovimException as e:
5305 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005306 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005307
5308 if len(port_list) == 0:
5309 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005310 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005311
5312 port_uuid_list = []
5313 for port in port_list:
5314 try:
5315 port_uuid_list.append(port['uuid'])
5316 ovim.delete_port(port['uuid'])
5317 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005318 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 +02005319
5320 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01005321
tierno7edb6752016-03-21 17:37:52 +01005322def vim_action_get(mydb, tenant_id, datacenter, item, name):
5323 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005324 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005325 filter_dict={}
5326 if name:
tierno42fcc3b2016-07-06 17:20:40 +02005327 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01005328 filter_dict["id"] = name
5329 else:
5330 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02005331 try:
5332 if item=="networks":
5333 #filter_dict['tenant_id'] = myvim['tenant_id']
5334 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005335
5336 if len(content) == 0:
5337 raise NfvoException("Network {} is not present in the system. ".format(name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005338 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005339
5340 #Update the networks with the attached ports
5341 for net in content:
5342 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
5343 if sdn_network_id != None:
5344 try:
5345 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5346 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
5347 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005348 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 +02005349 #Remove field name and if port name is external_port save it as 'type'
5350 for port in port_list:
5351 if port['name'] == 'external_port':
5352 port['type'] = "External"
5353 del port['name']
5354 net['sdn_network_id'] = sdn_network_id
5355 net['sdn_attached_ports'] = port_list
5356
tiernoae4a8d12016-07-08 12:30:39 +02005357 elif item=="tenants":
5358 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01005359 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005360
tierno4540ea52017-01-18 17:44:32 +01005361 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005362 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005363 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02005364 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02005365 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02005366 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02005367 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02005368 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 +02005369 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005370 else:
tiernof97fd272016-07-11 14:32:37 +02005371 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02005372 except vimconn.vimconnException as e:
5373 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02005374 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01005375
tiernob3d36742017-03-03 23:51:05 +01005376
tierno7edb6752016-03-21 17:37:52 +01005377def vim_action_delete(mydb, tenant_id, datacenter, item, name):
5378 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02005379 if tenant_id == "any":
5380 tenant_id=None
5381
tiernoa2793912016-10-04 08:15:08 +00005382 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02005383 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02005384 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
5385 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02005386 items = content.values()[0]
5387 if type(items)==list and len(items)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005388 raise NfvoException("Not found " + item, httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005389 elif type(items)==list and len(items)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005390 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005391 else: # it is a dict
5392 item_id = items["id"]
5393 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01005394
tiernoae4a8d12016-07-08 12:30:39 +02005395 try:
5396 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005397 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5398 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
5399 if sdn_network_id != None:
5400 #Delete any port attachment to this network
5401 try:
5402 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
5403 except ovimException as e:
5404 raise NfvoException(
5405 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005406 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005407
5408 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5409 for port in port_list:
5410 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
5411
5412 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5413 try:
5414 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
5415 except db_base_Exception as e:
5416 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
tierno9c5c8322018-03-23 15:44:03 +01005417 str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005418
5419 #Delete the SDN network
5420 try:
5421 ovim.delete_network(sdn_network_id)
5422 except ovimException as e:
5423 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
5424 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005425 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005426
tiernoae4a8d12016-07-08 12:30:39 +02005427 content = myvim.delete_network(item_id)
5428 elif item=="tenants":
5429 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01005430 elif item == "images":
5431 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02005432 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005433 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005434 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005435 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5436 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005437
tiernof97fd272016-07-11 14:32:37 +02005438 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01005439
tiernob3d36742017-03-03 23:51:05 +01005440
tierno7edb6752016-03-21 17:37:52 +01005441def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
5442 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005443 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02005444 if tenant_id == "any":
5445 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00005446 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005447 try:
5448 if item=="networks":
5449 net = descriptor["network"]
5450 net_name = net.pop("name")
5451 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02005452 net_public = net.pop("shared", False)
5453 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01005454 net_vlan = net.pop("vlan", None)
5455 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 +02005456
5457 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5458 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
tierno00e3df72017-11-29 17:20:13 +01005459 #obtain datacenter_tenant_id
5460 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
5461 FROM='datacenter_tenants',
5462 WHERE={'datacenter_id': datacenter})[0]['uuid']
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005463 try:
5464 sdn_network = {}
5465 sdn_network['vlan'] = net_vlan
5466 sdn_network['type'] = net_type
5467 sdn_network['name'] = net_name
tierno00e3df72017-11-29 17:20:13 +01005468 sdn_network['region'] = datacenter_tenant_id
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005469 ovim_content = ovim.new_network(sdn_network)
5470 except ovimException as e:
tierno00e3df72017-11-29 17:20:13 +01005471 logger.error("ovimException creating SDN network={} ".format(
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005472 sdn_network) + str(e), exc_info=True)
5473 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005474 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005475
5476 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5477 # use instance_scenario_id=None to distinguish from real instaces of nets
tierno00e3df72017-11-29 17:20:13 +01005478 correspondence = {'instance_scenario_id': None,
5479 'sdn_net_id': ovim_content,
5480 'vim_net_id': content,
5481 'datacenter_tenant_id': datacenter_tenant_id
5482 }
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005483 try:
5484 mydb.new_row('instance_nets', correspondence, add_uuid=True)
5485 except db_base_Exception as e:
tierno00e3df72017-11-29 17:20:13 +01005486 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005487 correspondence, e), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005488 elif item=="tenants":
5489 tenant = descriptor["tenant"]
5490 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
5491 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005492 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005493 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005494 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005495
tierno7edb6752016-03-21 17:37:52 +01005496 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005497
5498def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005499 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005500 logger.debug('New SDN controller created with uuid {}'.format(data))
5501 return data
5502
5503def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005504 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005505 msg = 'SDN controller {} updated'.format(data)
5506 logger.debug(msg)
5507 return msg
5508
5509def sdn_controller_list(mydb, tenant_id, controller_id=None):
5510 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005511 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005512 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005513 data = ovim.show_of_controller(controller_id)
5514
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005515 msg = 'SDN controller list:\n {}'.format(data)
5516 logger.debug(msg)
5517 return data
5518
5519def sdn_controller_delete(mydb, tenant_id, controller_id):
5520 select_ = ('uuid', 'config')
5521 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5522 for datacenter in datacenters:
5523 if datacenter['config']:
5524 config = yaml.load(datacenter['config'])
5525 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005526 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), httperrors.Conflict)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005527
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005528 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005529 msg = 'SDN controller {} deleted'.format(data)
5530 logger.debug(msg)
5531 return msg
5532
5533def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5534 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5535 if len(controller) < 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005536 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), httperrors.Not_Found)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005537
5538 try:
5539 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
5540 except:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005541 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005542
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005543 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5544 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005545
5546 maps = list()
5547 for compute_node in sdn_port_mapping:
5548 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5549 element = dict()
5550 element["compute_node"] = compute_node["compute_node"]
5551 for port in compute_node["ports"]:
tierno7f426e92018-06-28 15:21:32 +02005552 pci = port.get("pci")
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005553 element["switch_port"] = port.get("switch_port")
5554 element["switch_mac"] = port.get("switch_mac")
tierno4070e442019-01-23 10:19:23 +00005555 if not element["switch_port"] and not element["switch_mac"]:
5556 raise NfvoException ("The mapping must contain 'switch_port' or 'switch_mac'", httperrors.Bad_Request)
tierno7f426e92018-06-28 15:21:32 +02005557 for pci_expanded in utils.expand_brackets(pci):
5558 element["pci"] = pci_expanded
5559 maps.append(dict(element))
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005560
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005561 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 +01005562
5563def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005564 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005565
5566 result = {
5567 "sdn-controller": None,
5568 "datacenter-id": datacenter_id,
5569 "dpid": None,
5570 "ports_mapping": list()
5571 }
5572
5573 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5574 if datacenter['config']:
5575 config = yaml.load(datacenter['config'])
5576 if 'sdn-controller' in config:
5577 controller_id = config['sdn-controller']
5578 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5579 result["sdn-controller"] = controller_id
5580 result["dpid"] = sdn_controller["dpid"]
5581
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005582 if result["sdn-controller"] == None:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005583 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005584 if result["dpid"] == None:
5585 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005586 httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005587
5588 if len(maps) == 0:
5589 return result
5590
5591 ports_correspondence_dict = dict()
5592 for link in maps:
5593 if result["sdn-controller"] != link["ofc_id"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005594 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005595 if result["dpid"] != link["switch_dpid"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005596 raise NfvoException("The dpid specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005597 element = dict()
5598 element["pci"] = link["pci"]
5599 if link["switch_port"]:
5600 element["switch_port"] = link["switch_port"]
5601 if link["switch_mac"]:
5602 element["switch_mac"] = link["switch_mac"]
5603
5604 if not link["compute_node"] in ports_correspondence_dict:
5605 content = dict()
5606 content["compute_node"] = link["compute_node"]
5607 content["ports"] = list()
5608 ports_correspondence_dict[link["compute_node"]] = content
5609
5610 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5611
5612 for key in sorted(ports_correspondence_dict):
5613 result["ports_mapping"].append(ports_correspondence_dict[key])
5614
5615 return result
5616
5617def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02005618 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02005619
5620def create_RO_keypair(tenant_id):
5621 """
5622 Creates a public / private keys for a RO tenant and returns their values
5623 Params:
5624 tenant_id: ID of the tenant
5625 Return:
5626 public_key: Public key for the RO tenant
5627 private_key: Encrypted private key for RO tenant
5628 """
5629
5630 bits = 2048
5631 key = RSA.generate(bits)
5632 try:
5633 public_key = key.publickey().exportKey('OpenSSH')
5634 if isinstance(public_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005635 raise NfvoException("Unable to create public key: {}".format(public_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005636 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5637 except (ValueError, NameError) as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005638 raise NfvoException("Unable to create private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005639 return public_key, private_key
5640
5641def decrypt_key (key, tenant_id):
5642 """
5643 Decrypts an encrypted RSA key
5644 Params:
5645 key: Private key to be decrypted
5646 tenant_id: ID of the tenant
5647 Return:
5648 unencrypted_key: Unencrypted private key for RO tenant
5649 """
5650 try:
5651 key = RSA.importKey(key,tenant_id)
5652 unencrypted_key = key.exportKey('PEM')
5653 if isinstance(unencrypted_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005654 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005655 except ValueError as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005656 raise NfvoException("Unable to decrypt the private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005657 return unencrypted_key