blob: 19c8b7d3bd2719219d0d664ff43a46b4cb8693a0 [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
64#
65
tierno7edb6752016-03-21 17:37:52 +010066global global_config
67global vimconn_imported
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010068# WIM
69global wim_engine
70wim_engine = None
71global wimconn_imported
72#
tierno73ad9e42016-09-12 18:11:11 +020073global logger
montesmoreno0c8def02016-12-22 12:16:23 +000074global default_volume_size
75default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010076global ovim
77ovim = None
tiernoc5651792017-03-27 10:50:43 +020078global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020079
tierno42026a02017-02-10 15:13:40 +010080vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
81vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010082vim_persistent_info = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010083# WIM
84wimconn_imported = {} # dictionary with WIM type as key, loaded module as value
85wim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
86wim_persistent_info = {}
87#
88
tierno73ad9e42016-09-12 18:11:11 +020089logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010090task_lock = Lock()
tiernob3d36742017-03-03 23:51:05 +010091last_task_id = 0.0
tierno868220c2017-09-26 00:11:05 +020092db = None
93db_lock = Lock()
tierno7edb6752016-03-21 17:37:52 +010094
Anderson Bravalheri0446cd52018-08-17 15:26:19 +010095
96class NfvoException(httperrors.HttpMappedError):
97 """Common Class for NFVO errors"""
tierno7edb6752016-03-21 17:37:52 +010098
99
tiernob3d36742017-03-03 23:51:05 +0100100def get_task_id():
101 global last_task_id
tierno868220c2017-09-26 00:11:05 +0200102 task_id = t.time()
tiernob3d36742017-03-03 23:51:05 +0100103 if task_id <= last_task_id:
104 task_id = last_task_id + 0.000001
105 last_task_id = task_id
tierno868220c2017-09-26 00:11:05 +0200106 return "ACTION-{:.6f}".format(task_id)
107 # 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 +0100108
109
tierno867ffe92017-03-27 12:50:34 +0200110def new_task(name, params, depends=None):
tierno868220c2017-09-26 00:11:05 +0200111 """Deprected!!!"""
tiernob3d36742017-03-03 23:51:05 +0100112 task_id = get_task_id()
113 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
114 if depends:
115 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +0100116 return task
117
118
119def is_task_id(id):
tierno868220c2017-09-26 00:11:05 +0200120 return True if id[:5] == "TASK-" else False
tiernob3d36742017-03-03 23:51:05 +0100121
122
tierno42026a02017-02-10 15:13:40 +0100123def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
124 name = datacenter_name[:16]
125 if name not in vim_threads["names"]:
126 vim_threads["names"].append(name)
127 return name
tiernob3d36742017-03-03 23:51:05 +0100128 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100129 if name not in vim_threads["names"]:
130 vim_threads["names"].append(name)
131 return name
132 name = datacenter_id + "-" + tenant_id
133 vim_threads["names"].append(name)
134 return name
135
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100136# -- Move
137def get_non_used_wim_name(wim_name, wim_id, tenant_name, tenant_id):
138 name = wim_name[:16]
139 if name not in wim_threads["names"]:
140 wim_threads["names"].append(name)
141 return name
142 name = wim_name[:16] + "." + tenant_name[:16]
143 if name not in wim_threads["names"]:
144 wim_threads["names"].append(name)
145 return name
146 name = wim_id + "-" + tenant_id
147 wim_threads["names"].append(name)
148 return name
tierno42026a02017-02-10 15:13:40 +0100149
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100150
151def start_service(mydb, persistence=None, wim=None):
tiernob3d36742017-03-03 23:51:05 +0100152 global db, global_config
153 db = nfvo_db.nfvo_db()
154 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 +0100155 global ovim
156
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100157 if persistence:
158 persistence.lock = db_lock
159 else:
160 persistence = WimPersistence(db, lock=db_lock)
161
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100162 # Initialize openvim for SDN control
163 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
164 # TODO: review ovim.py to delete not needed configuration
165 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200166 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100167 'network_vlan_range_start': 1000,
168 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200169 'db_name': global_config["db_ovim_name"],
170 'db_host': global_config["db_ovim_host"],
171 'db_user': global_config["db_ovim_user"],
172 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100173 'bridge_ifaces': {},
174 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100175 'network_type': 'bridge',
176 #TODO: log_level_of should not be needed. To be modified in ovim
177 'log_level_of': 'DEBUG'
178 }
tierno42026a02017-02-10 15:13:40 +0100179 try:
tierno3fcfdb72017-10-24 07:48:24 +0200180 # starts ovim library
tierno46df9672017-05-26 13:12:21 +0200181 ovim = ovim_module.ovim(ovim_configuration)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100182
183 global wim_engine
184 wim_engine = wim or WimEngine(persistence)
185 wim_engine.ovim = ovim
186
tierno46df9672017-05-26 13:12:21 +0200187 ovim.start_service()
188
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100189 #delete old unneeded vim_wim_actions
tierno3fcfdb72017-10-24 07:48:24 +0200190 clean_db(mydb)
191
192 # starts vim_threads
tierno46df9672017-05-26 13:12:21 +0200193 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
194 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
195 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
196 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
197 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
198 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100199 vims = mydb.get_rows(FROM=from_, SELECT=select_)
200 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200201 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
202 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100203 if vim["config"]:
204 extra.update(yaml.load(vim["config"]))
205 if vim.get('dt_config'):
206 extra.update(yaml.load(vim["dt_config"]))
207 if vim["type"] not in vimconn_imported:
208 module_info=None
209 try:
210 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200211 pkg = __import__("osm_ro." + module)
212 vim_conn = getattr(pkg, module)
213 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
214 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100215 vimconn_imported[vim["type"]] = vim_conn
216 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200217 # if module_info and module_info[0]:
218 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200219 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100220 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100221
tierno867ffe92017-03-27 12:50:34 +0200222 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100223 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100224 try:
225 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100226 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tierno42026a02017-02-10 15:13:40 +0100227 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100228 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
229 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
230 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
231 user=vim['user'], passwd=vim['passwd'],
232 config=extra, persistent_info=vim_persistent_info[thread_id]
233 )
tierno9c22f2d2017-10-09 16:23:55 +0200234 except vimconn.vimconnException as e:
235 myvim = e
236 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
237 vim['datacenter_id'], e))
tierno42026a02017-02-10 15:13:40 +0100238 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200239 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100240 httperrors.Internal_Server_Error)
tierno46df9672017-05-26 13:12:21 +0200241 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
242 vim['vim_tenant_id'])
tiernod3750b32018-07-20 15:33:08 +0200243 new_thread = vim_thread.vim_thread(task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200244 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100245 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100246 vim_threads["running"][thread_id] = new_thread
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100247
248 wim_engine.start_threads()
tierno42026a02017-02-10 15:13:40 +0100249 except db_base_Exception as e:
250 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200251 except ovim_module.ovimException as e:
252 message = str(e)
253 if message[:22] == "DATABASE wrong version":
254 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
255 "at host {dbhost}".format(
256 msg=message[22:-3], dbname=global_config["db_ovim_name"],
257 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
258 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100259 raise NfvoException(message, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100260
tierno867ffe92017-03-27 12:50:34 +0200261
tierno42026a02017-02-10 15:13:40 +0100262def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200263 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100264 if ovim:
265 ovim.stop_service()
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100266 for thread_id, thread in vim_threads["running"].items():
tierno868220c2017-09-26 00:11:05 +0200267 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +0100268 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100269 vim_threads["running"] = {}
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100270
271 if wim_engine:
272 wim_engine.stop_threads()
273
tiernoc5651792017-03-27 10:50:43 +0200274 if global_config and global_config.get("console_thread"):
275 for thread in global_config["console_thread"]:
276 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100277
tierno6ddeded2017-05-16 15:40:26 +0200278def get_version():
279 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
280 global_config["version_date"] ))
281
tierno3fcfdb72017-10-24 07:48:24 +0200282def clean_db(mydb):
283 """
284 Clean unused or old entries at database to avoid unlimited growing
285 :param mydb: database connector
286 :return: None
287 """
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100288 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
tierno3fcfdb72017-10-24 07:48:24 +0200289 now = t.time()-3600*24*7
290 instance_action_id = None
291 nb_deleted = 0
292 while True:
293 actions_to_delete = mydb.get_rows(
294 SELECT=("item", "item_id", "instance_action_id"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100295 FROM="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
tierno3fcfdb72017-10-24 07:48:24 +0200296 "left join instance_scenarios as i on ia.instance_id=i.uuid",
297 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
298 "va.status": ("DONE", "SUPERSEDED")},
299 LIMIT=100
300 )
301 for to_delete in actions_to_delete:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100302 mydb.delete_row(FROM="vim_wim_actions", WHERE=to_delete)
tierno3fcfdb72017-10-24 07:48:24 +0200303 if instance_action_id != to_delete["instance_action_id"]:
304 instance_action_id = to_delete["instance_action_id"]
305 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
306 nb_deleted += len(actions_to_delete)
307 if len(actions_to_delete) < 100:
308 break
309 if nb_deleted:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100310 logger.debug("Removed {} unused vim_wim_actions".format(nb_deleted))
tierno3fcfdb72017-10-24 07:48:24 +0200311
tierno42026a02017-02-10 15:13:40 +0100312
tierno7edb6752016-03-21 17:37:52 +0100313def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
314 '''Obtain flavorList
315 return result, content:
316 <0, error_text upon error
317 nb_records, flavor_list on success
318 '''
319 WHERE_dict={}
320 WHERE_dict['vnf_id'] = vnf_id
321 if nfvo_tenant is not None:
322 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100323
tierno7edb6752016-03-21 17:37:52 +0100324 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
325 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200326 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
327 #print "get_flavor_list result:", result
328 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100329 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200330 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100331 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200332 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100333
tiernob3d36742017-03-03 23:51:05 +0100334
tierno7edb6752016-03-21 17:37:52 +0100335def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
tierno16e3dd42018-04-24 12:52:40 +0200336 """
337 Get used images of all vms belonging to this VNFD
338 :param mydb: database conector
339 :param vnf_id: vnfd uuid
340 :param nfvo_tenant: tenant, not used
341 :return: The list of image uuid used
342 """
343 image_list = []
344 vms = mydb.get_rows(SELECT=('image_id','image_list'), FROM='vms', WHERE={'vnf_id': vnf_id})
345 for vm in vms:
346 if vm["image_id"] not in image_list:
347 image_list.append(vm["image_id"])
348 if vm["image_list"]:
349 vm_image_list = yaml.load(vm["image_list"])
350 for image_dict in vm_image_list:
351 if image_dict["image_id"] not in image_list:
352 image_list.append(image_dict["image_id"])
353 return image_list
tierno7edb6752016-03-21 17:37:52 +0100354
tiernob3d36742017-03-03 23:51:05 +0100355
tiernoa2793912016-10-04 08:15:08 +0000356def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
tiernocbb52052018-05-31 18:57:30 +0200357 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None, ignore_errors=False):
tierno7edb6752016-03-21 17:37:52 +0100358 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100359 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100360 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200361 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100362 '''
363 WHERE_dict={}
364 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
365 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000366 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100367 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
368 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000369 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
370 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100371 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 +0000372 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 +0100373 '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 +0000374 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100375 else:
376 from_ = 'datacenters as d'
377 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200378 try:
379 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
380 vim_dict={}
381 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200382 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
tierno16e3dd42018-04-24 12:52:40 +0200383 'datacenter_id': vim.get('datacenter_id'),
tiernob6434212018-04-26 16:27:47 +0200384 '_vim_type_internal': vim.get('type')}
tierno8008c3a2016-10-13 15:34:28 +0000385 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200386 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000387 if vim.get('dt_config'):
388 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200389 if vim["type"] not in vimconn_imported:
390 module_info=None
391 try:
392 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200393 pkg = __import__("osm_ro." + module)
394 vim_conn = getattr(pkg, module)
395 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
396 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200397 vimconn_imported[vim["type"]] = vim_conn
398 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200399 # if module_info and module_info[0]:
400 # file.close(module_info[0])
tiernocbb52052018-05-31 18:57:30 +0200401 if ignore_errors:
402 logger.error("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
403 vim["type"], module, type(e).__name__, str(e)))
404 continue
tiernof97fd272016-07-11 14:32:37 +0200405 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100406 vim["type"], module, type(e).__name__, str(e)), httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100407
tierno7edb6752016-03-21 17:37:52 +0100408 try:
tierno867ffe92017-03-27 12:50:34 +0200409 if 'datacenter_tenant_id' in vim:
410 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100411 if thread_id not in vim_persistent_info:
412 vim_persistent_info[thread_id] = {}
413 persistent_info = vim_persistent_info[thread_id]
414 else:
415 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200416 #if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100417 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
tiernof97fd272016-07-11 14:32:37 +0200418 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
419 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100420 tenant_id=vim.get('vim_tenant_id',vim_tenant),
421 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100422 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200423 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100424 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200425 )
426 except Exception as e:
tiernocbb52052018-05-31 18:57:30 +0200427 if ignore_errors:
428 logger.error("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)))
429 continue
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100430 http_code = httperrors.Internal_Server_Error
tiernoa3572692018-05-14 13:09:33 +0200431 if isinstance(e, vimconn.vimconnException):
432 http_code = e.http_code
433 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), http_code)
tiernof97fd272016-07-11 14:32:37 +0200434 return vim_dict
435 except db_base_Exception as e:
436 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100437
tiernob3d36742017-03-03 23:51:05 +0100438
tierno7edb6752016-03-21 17:37:52 +0100439def rollback(mydb, vims, rollback_list):
440 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100441 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100442 for i in range(len(rollback_list)-1, -1, -1):
443 item = rollback_list[i]
444 if item["where"]=="vim":
445 if item["vim_id"] not in vims:
446 continue
tierno56d73d22017-08-02 13:53:02 +0200447 if is_task_id(item["uuid"]):
448 continue
449 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200450 try:
451 if item["what"]=="image":
452 vim.delete_image(item["uuid"])
tierno868220c2017-09-26 00:11:05 +0200453 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200454 elif item["what"]=="flavor":
455 vim.delete_flavor(item["uuid"])
tiernoad6bdd42018-01-10 10:43:46 +0100456 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200457 elif item["what"]=="network":
458 vim.delete_network(item["uuid"])
459 elif item["what"]=="vm":
460 vim.delete_vminstance(item["uuid"])
461 except vimconn.vimconnException as e:
462 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
463 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200464 except db_base_Exception as e:
465 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 +0100466
tierno7edb6752016-03-21 17:37:52 +0100467 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200468 try:
469 if item["what"]=="image":
470 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
471 elif item["what"]=="flavor":
472 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
473 except db_base_Exception as e:
474 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
475 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100476 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100477 return True," Rollback successful."
478 else:
479 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100480
tiernob3d36742017-03-03 23:51:05 +0100481
tiernoafed5f12017-01-26 17:57:43 +0100482def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100483 global global_config
tierno42026a02017-02-10 15:13:40 +0100484 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100485 vnfc_interfaces={}
486 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100487 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100488 #dataplane interfaces
489 for numa in vnfc.get("numas",() ):
490 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100491 if interface["name"] in name_dict:
492 raise NfvoException(
493 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
494 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100495 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100496 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100497 #bridge interfaces
498 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100499 if interface["name"] in name_dict:
500 raise NfvoException(
501 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
502 vnfc["name"], interface["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100503 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100504 name_dict[ interface["name"] ] = "overlay"
505 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100506 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200507 # if "boot-data" in vnfc:
508 # # check that user-data is incompatible with users and config-files
509 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
510 # raise NfvoException(
511 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100512 # httperrors.Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100513
tierno7edb6752016-03-21 17:37:52 +0100514 #check if the info in external_connections matches with the one in the vnfcs
515 name_list=[]
516 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
517 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100518 raise NfvoException(
519 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
520 external_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100521 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100522 name_list.append(external_connection["name"])
523 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100524 raise NfvoException(
525 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
526 external_connection["name"], external_connection["VNFC"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100527 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100528
tierno7edb6752016-03-21 17:37:52 +0100529 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100530 raise NfvoException(
531 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
532 external_connection["name"],
533 external_connection["local_iface_name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100534 httperrors.Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100535
tierno7edb6752016-03-21 17:37:52 +0100536 #check if the info in internal_connections matches with the one in the vnfcs
537 name_list=[]
538 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
539 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100540 raise NfvoException(
541 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
542 internal_connection["name"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100543 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100544 name_list.append(internal_connection["name"])
545 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100546
547 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
548 raise NfvoException(
549 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
550 internal_connection["name"],
551 'ptp' if vnf_descriptor_version==1 else 'e-line',
552 'data' if vnf_descriptor_version==1 else "e-lan"),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100553 httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100554 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100555 vnf = port["VNFC"]
556 iface = port["local_iface_name"]
557 if vnf not in vnfc_interfaces:
558 raise NfvoException(
559 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
560 internal_connection["name"], vnf),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100561 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100562 if iface not in vnfc_interfaces[ vnf ]:
563 raise NfvoException(
564 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
565 internal_connection["name"], iface),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100566 httperrors.Bad_Request)
567 return -httperrors.Bad_Request,
tiernoafed5f12017-01-26 17:57:43 +0100568 if vnf_descriptor_version==1 and "type" not in internal_connection:
569 if vnfc_interfaces[vnf][iface] == "overlay":
570 internal_connection["type"] = "bridge"
571 else:
572 internal_connection["type"] = "data"
573 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
574 if vnfc_interfaces[vnf][iface] == "overlay":
575 internal_connection["implementation"] = "overlay"
576 else:
577 internal_connection["implementation"] = "underlay"
578 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
579 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
580 raise NfvoException(
581 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
582 internal_connection["name"],
583 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
584 'data' if vnf_descriptor_version==1 else 'underlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100585 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100586 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
587 vnfc_interfaces[vnf][iface] == "underlay":
588 raise NfvoException(
589 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
590 internal_connection["name"], iface,
591 'data' if vnf_descriptor_version==1 else 'underlay',
592 'bridge' if vnf_descriptor_version==1 else 'overlay'),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100593 httperrors.Bad_Request)
tiernoafed5f12017-01-26 17:57:43 +0100594
tierno7edb6752016-03-21 17:37:52 +0100595
tierno56d73d22017-08-02 13:53:02 +0200596def 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 +0100597 #look if image exist
598 if only_create_at_vim:
599 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000600 if return_on_error == None:
601 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100602 else:
garciadeblas14480452017-01-10 13:08:07 +0100603 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200604 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
605 else:
606 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200607 if len(images)>=1:
608 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100609 else:
garciadeblas14480452017-01-10 13:08:07 +0100610 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100611 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200612 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
613 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100614 }
garciadeblas14480452017-01-10 13:08:07 +0100615 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200616 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
617 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100618 #create image at every vim
619 for vim_id,vim in vims.iteritems():
tierno868220c2017-09-26 00:11:05 +0200620 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100621 image_created="false"
622 #look at database
tierno868220c2017-09-26 00:11:05 +0200623 image_db = mydb.get_rows(FROM="datacenters_images",
624 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100625 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200626 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200627 if image_dict['location'] is not None:
628 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
629 else:
garciadeblas30833382017-01-09 09:46:31 +0100630 filter_dict = {}
631 filter_dict['name'] = image_dict['universal_name']
632 if image_dict.get('checksum') != None:
633 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000634 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200635 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100636 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200637 if len(vim_images) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100638 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), httperrors.Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000639 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100640 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200641 else:
garciadeblas14480452017-01-10 13:08:07 +0100642 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
643 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200644
tiernoae4a8d12016-07-08 12:30:39 +0200645 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100646 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100647 try:
garciadeblas14480452017-01-10 13:08:07 +0100648 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
649 if image_dict['location']:
650 image_vim_id = vim.new_image(image_dict)
651 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
652 image_created="true"
653 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100654 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
655 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200656 except vimconn.vimconnException as e:
657 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100658 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200659 raise
tierno5e91eb82016-10-04 09:39:07 +0000660 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100661 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200662 continue
663 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000664 if return_on_error:
665 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
666 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200667 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000668 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100669 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200670 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200671 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100672 #add new vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200673 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
674 'image_id':image_mano_id,
675 'vim_id': image_vim_id,
676 'created':image_created})
tierno7edb6752016-03-21 17:37:52 +0100677 elif image_db[0]["vim_id"]!=image_vim_id:
678 #modify existing vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200679 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 +0100680
tiernof97fd272016-07-11 14:32:37 +0200681 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100682
tiernob3d36742017-03-03 23:51:05 +0100683
tierno5e91eb82016-10-04 09:39:07 +0000684def 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 +0100685 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
tierno7edb6752016-03-21 17:37:52 +0100686 'ram':flavor_dict.get('ram'),
687 'vcpus':flavor_dict.get('vcpus'),
688 }
689 if 'extended' in flavor_dict and flavor_dict['extended']==None:
690 del flavor_dict['extended']
691 if 'extended' in flavor_dict:
692 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
693
694 #look if flavor exist
695 if only_create_at_vim:
696 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000697 if return_on_error == None:
698 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100699 else:
tiernof97fd272016-07-11 14:32:37 +0200700 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
701 if len(flavors)>=1:
702 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100703 else:
704 #create flavor
705 #create one by one the images of aditional disks
706 dev_image_list=[] #list of images
707 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
708 dev_nb=0
709 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200710 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100711 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200712 image_dict={}
713 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
714 image_dict['universal_name']=device.get('image name')
715 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
716 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100717 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200718 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100719 image_metadata_dict = device.get('image metadata', None)
720 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100721 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100722 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
723 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200724 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
725 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100726 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100727 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100728 temp_flavor_dict['name'] = flavor_dict['name']
729 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200730 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
731 flavor_mano_id= content
732 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100733 #create flavor at every vim
734 if 'uuid' in flavor_dict:
735 del flavor_dict['uuid']
736 flavor_vim_id=None
737 for vim_id,vim in vims.items():
tierno868220c2017-09-26 00:11:05 +0200738 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100739 flavor_created="false"
740 #look at database
tierno868220c2017-09-26 00:11:05 +0200741 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
742 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100743 #look at VIM if this flavor exist SKIPPED
744 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
745 #if res_vim < 0:
746 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
747 # continue
748 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100749
tiernof1ba57e2017-09-07 12:23:19 +0200750 # Create the flavor in VIM
751 # Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000752 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100753 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
tiernof1ba57e2017-09-07 12:23:19 +0200754 # make a copy of original devices
tierno7edb6752016-03-21 17:37:52 +0100755 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000756
tierno7edb6752016-03-21 17:37:52 +0100757 for device in flavor_dict["extended"].get("devices",[]):
758 dev={}
759 dev.update(device)
760 devices_original.append(dev)
761 if 'image' in device:
762 del device['image']
763 if 'image metadata' in device:
764 del device['image metadata']
tiernof1ba57e2017-09-07 12:23:19 +0200765 if 'image checksum' in device:
766 del device['image checksum']
767 dev_nb = 0
tierno7edb6752016-03-21 17:37:52 +0100768 for index in range(0,len(devices_original)) :
769 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000770 if "image" not in device and "image name" not in device:
tiernoecc68392018-09-06 13:47:11 +0200771 # if 'size' in device:
772 disk_list.append({'size': device.get('size', default_volume_size), 'name': device.get('name')})
tierno7edb6752016-03-21 17:37:52 +0100773 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200774 image_dict={}
775 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
776 image_dict['universal_name']=device.get('image name')
777 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
778 image_dict['location']=device.get('image')
tiernof1ba57e2017-09-07 12:23:19 +0200779 # image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200780 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100781 image_metadata_dict = device.get('image metadata', None)
782 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100783 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100784 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
785 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200786 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 +0100787 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200788 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 +0000789
790 #save disk information (image must be based on and size
791 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
792
tierno7edb6752016-03-21 17:37:52 +0100793 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
794 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200795 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100796 #check that this vim_id exist in VIM, if not create
797 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200798 try:
799 vim.get_flavor(flavor_vim_id)
800 continue #flavor exist
801 except vimconn.vimconnException:
802 pass
tierno7edb6752016-03-21 17:37:52 +0100803 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200804 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
805 try:
tiernocf157a82017-01-30 14:07:06 +0100806 flavor_vim_id = None
807 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
808 flavor_create="false"
809 except vimconn.vimconnException as e:
810 pass
811 try:
812 if not flavor_vim_id:
813 flavor_vim_id = vim.new_flavor(flavor_dict)
814 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
815 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200816 except vimconn.vimconnException as e:
817 if return_on_error:
818 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200819 raise
tiernoae4a8d12016-07-08 12:30:39 +0200820 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000821 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200822 continue
tierno7edb6752016-03-21 17:37:52 +0100823 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200824 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100825 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000826 extended_devices_yaml = None
827 if len(disk_list) > 0:
828 extended_devices = dict()
829 extended_devices['disks'] = disk_list
830 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
831 mydb.new_row('datacenters_flavors',
tierno868220c2017-09-26 00:11:05 +0200832 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
833 'created': flavor_created, 'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100834 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
835 #modify existing vim_id at datacenters_flavors
tierno868220c2017-09-26 00:11:05 +0200836 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
837 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100838
tiernof97fd272016-07-11 14:32:37 +0200839 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100840
tiernob3d36742017-03-03 23:51:05 +0100841
tiernof1ba57e2017-09-07 12:23:19 +0200842def get_str(obj, field, length):
843 """
844 Obtain the str value,
845 :param obj:
846 :param length:
847 :return:
848 """
849 value = obj.get(field)
850 if value is not None:
851 value = str(value)[:length]
852 return value
853
854def _lookfor_or_create_image(db_image, mydb, descriptor):
855 """
856 fill image content at db_image dictionary. Check if the image with this image and checksum exist
857 :param db_image: dictionary to insert data
858 :param mydb: database connector
859 :param descriptor: yang descriptor
860 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
861 """
862
863 db_image["name"] = get_str(descriptor, "image", 255)
864 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
865 if not db_image["checksum"]: # Ensure that if empty string, None is stored
866 db_image["checksum"] = None
867 if db_image["name"].startswith("/"):
868 db_image["location"] = db_image["name"]
869 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
870 else:
871 db_image["universal_name"] = db_image["name"]
872 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
873 'checksum': db_image['checksum']})
874 if existing_images:
875 return existing_images[0]["uuid"]
876 else:
877 image_uuid = str(uuid4())
878 db_image["uuid"] = image_uuid
879 return None
880
881def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
882 """
883 Parses an OSM IM vnfd_catalog and insert at DB
884 :param mydb:
885 :param tenant_id:
886 :param vnf_descriptor:
887 :return: The list of cretated vnf ids
888 """
889 try:
890 myvnfd = vnfd_catalog.vnfd()
tiernoa9550202017-09-22 13:31:35 +0200891 try:
tiernoad6bdd42018-01-10 10:43:46 +0100892 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True)
tiernoa9550202017-09-22 13:31:35 +0200893 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100894 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200895 db_vnfs = []
896 db_nets = []
897 db_vms = []
898 db_vms_index = 0
899 db_interfaces = []
900 db_images = []
901 db_flavors = []
tierno41a69812018-02-16 14:34:33 +0100902 db_ip_profiles_index = 0
903 db_ip_profiles = []
tiernof1ba57e2017-09-07 12:23:19 +0200904 uuid_list = []
905 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200906 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
907 if not vnfd_catalog_descriptor:
908 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
909 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
910 if not vnfd_descriptor_list:
911 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200912 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
913 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200914
915 # table vnf
916 vnf_uuid = str(uuid4())
917 uuid_list.append(vnf_uuid)
918 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100919 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200920 db_vnf = {
921 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100922 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200923 "name": get_str(vnfd, "name", 255),
924 "description": get_str(vnfd, "description", 255),
925 "tenant_id": tenant_id,
926 "vendor": get_str(vnfd, "vendor", 255),
927 "short_name": get_str(vnfd, "short-name", 255),
928 "descriptor": str(vnf_descriptor)[:60000]
929 }
930
tiernoe18ba432017-10-12 10:22:45 +0200931 for vnfd_descriptor in vnfd_descriptor_list:
932 if vnfd_descriptor["id"] == str(vnfd["id"]):
933 break
934
tierno41a69812018-02-16 14:34:33 +0100935 # table ip_profiles (ip-profiles)
936 ip_profile_name2db_table_index = {}
937 for ip_profile in vnfd.get("ip-profiles").itervalues():
938 db_ip_profile = {
939 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
940 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
941 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
942 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
943 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
944 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
945 }
946 dns_list = []
947 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
948 dns_list.append(str(dns.get("address")))
949 db_ip_profile["dns_address"] = ";".join(dns_list)
950 if ip_profile["ip-profile-params"].get('security-group'):
951 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
952 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
953 db_ip_profiles_index += 1
954 db_ip_profiles.append(db_ip_profile)
955
tiernof1ba57e2017-09-07 12:23:19 +0200956 # table nets (internal-vld)
957 net_id2uuid = {} # for mapping interface with network
958 for vld in vnfd.get("internal-vld").itervalues():
959 net_uuid = str(uuid4())
960 uuid_list.append(net_uuid)
961 db_net = {
962 "name": get_str(vld, "name", 255),
963 "vnf_id": vnf_uuid,
964 "uuid": net_uuid,
965 "description": get_str(vld, "description", 255),
tierno1df468d2018-07-06 14:25:16 +0200966 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +0200967 "type": "bridge", # TODO adjust depending on connection point type
968 }
969 net_id2uuid[vld.get("id")] = net_uuid
970 db_nets.append(db_net)
tierno41a69812018-02-16 14:34:33 +0100971 # ip-profile, link db_ip_profile with db_sce_net
972 if vld.get("ip-profile-ref"):
973 ip_profile_name = vld.get("ip-profile-ref")
974 if ip_profile_name not in ip_profile_name2db_table_index:
975 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
976 "'{}'. Reference to a non-existing 'ip_profiles'".format(
977 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100978 httperrors.Bad_Request)
tierno41a69812018-02-16 14:34:33 +0100979 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
980 else: #check no ip-address has been defined
tierno45140f52018-03-26 12:11:46 +0200981 for icp in vld.get("internal-connection-point").itervalues():
tierno41a69812018-02-16 14:34:33 +0100982 if icp.get("ip-address"):
983 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
984 "contains an ip-address but no ip-profile has been defined at VLD".format(
985 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +0100986 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200987
tiernocf596692017-11-20 15:47:51 +0100988 # connection points vaiable declaration
989 cp_name2iface_uuid = {}
990 cp_name2vm_uuid = {}
991 cp_name2db_interface = {}
tiernob6990792018-11-13 10:37:42 +0100992 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
tiernocf596692017-11-20 15:47:51 +0100993
tiernof1ba57e2017-09-07 12:23:19 +0200994 # table vms (vdus)
995 vdu_id2uuid = {}
996 vdu_id2db_table_index = {}
997 for vdu in vnfd.get("vdu").itervalues():
tierno41a69812018-02-16 14:34:33 +0100998
999 for vdu_descriptor in vnfd_descriptor["vdu"]:
1000 if vdu_descriptor["id"] == str(vdu["id"]):
1001 break
tiernof1ba57e2017-09-07 12:23:19 +02001002 vm_uuid = str(uuid4())
1003 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +01001004 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +02001005 db_vm = {
1006 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +01001007 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +02001008 "name": get_str(vdu, "name", 255),
1009 "description": get_str(vdu, "description", 255),
tiernob6990792018-11-13 10:37:42 +01001010 "pdu_type": get_str(vdu, "pdu-type", 255),
tiernof1ba57e2017-09-07 12:23:19 +02001011 "vnf_id": vnf_uuid,
1012 }
1013 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
1014 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
1015 if vdu.get("count"):
1016 db_vm["count"] = int(vdu["count"])
1017
1018 # table image
1019 image_present = False
1020 if vdu.get("image"):
1021 image_present = True
1022 db_image = {}
1023 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
1024 if not image_uuid:
1025 image_uuid = db_image["uuid"]
1026 db_images.append(db_image)
1027 db_vm["image_id"] = image_uuid
tierno16e3dd42018-04-24 12:52:40 +02001028 if vdu.get("alternative-images"):
1029 vm_alternative_images = []
1030 for alt_image in vdu.get("alternative-images").itervalues():
1031 db_image = {}
1032 image_uuid = _lookfor_or_create_image(db_image, mydb, alt_image)
1033 if not image_uuid:
1034 image_uuid = db_image["uuid"]
1035 db_images.append(db_image)
1036 vm_alternative_images.append({
1037 "image_id": image_uuid,
1038 "vim_type": str(alt_image["vim-type"]),
1039 # "universal_name": str(alt_image["image"]),
1040 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1041 })
1042
1043 db_vm["image_list"] = yaml.safe_dump(vm_alternative_images, default_flow_style=True, width=256)
tiernof1ba57e2017-09-07 12:23:19 +02001044
1045 # volumes
1046 devices = []
1047 if vdu.get("volumes"):
tierno1df468d2018-07-06 14:25:16 +02001048 for volume_key in vdu["volumes"]:
tiernof1ba57e2017-09-07 12:23:19 +02001049 volume = vdu["volumes"][volume_key]
1050 if not image_present:
1051 # Convert the first volume to vnfc.image
1052 image_present = True
1053 db_image = {}
1054 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
1055 if not image_uuid:
1056 image_uuid = db_image["uuid"]
1057 db_images.append(db_image)
1058 db_vm["image_id"] = image_uuid
1059 else:
1060 # Add Openmano devices
tierno1df468d2018-07-06 14:25:16 +02001061 device = {"name": str(volume.get("name"))}
tiernof1ba57e2017-09-07 12:23:19 +02001062 device["type"] = str(volume.get("device-type"))
1063 if volume.get("size"):
1064 device["size"] = int(volume["size"])
1065 if volume.get("image"):
1066 device["image name"] = str(volume["image"])
1067 if volume.get("image-checksum"):
1068 device["image checksum"] = str(volume["image-checksum"])
tierno1df468d2018-07-06 14:25:16 +02001069
tiernof1ba57e2017-09-07 12:23:19 +02001070 devices.append(device)
1071
tierno66eba6e2017-11-10 17:09:18 +01001072 # cloud-init
1073 boot_data = {}
1074 if vdu.get("cloud-init"):
1075 boot_data["user-data"] = str(vdu["cloud-init"])
1076 elif vdu.get("cloud-init-file"):
1077 # TODO Where this file content is present???
1078 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1079 boot_data["user-data"] = str(vdu["cloud-init-file"])
1080
1081 if vdu.get("supplemental-boot-data"):
1082 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1083 boot_data['boot-data-drive'] = True
1084 if vdu["supplemental-boot-data"].get('config-file'):
1085 om_cfgfile_list = list()
1086 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
1087 # TODO Where this file content is present???
1088 cfg_source = str(custom_config_file["source"])
1089 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1090 "content": cfg_source})
1091 boot_data['config-files'] = om_cfgfile_list
1092 if boot_data:
1093 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1094
1095 db_vms.append(db_vm)
1096 db_vms_index += 1
1097
1098 # table interfaces (internal/external interfaces)
1099 flavor_epa_interfaces = []
tierno66eba6e2017-11-10 17:09:18 +01001100 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
1101 for iface in vdu.get("interface").itervalues():
1102 flavor_epa_interface = {}
1103 iface_uuid = str(uuid4())
1104 uuid_list.append(iface_uuid)
1105 db_interface = {
1106 "uuid": iface_uuid,
1107 "internal_name": get_str(iface, "name", 255),
1108 "vm_id": vm_uuid,
1109 }
1110 flavor_epa_interface["name"] = db_interface["internal_name"]
1111 if iface.get("virtual-interface").get("vpci"):
1112 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1113 flavor_epa_interface["vpci"] = db_interface["vpci"]
1114
1115 if iface.get("virtual-interface").get("bandwidth"):
1116 bps = int(iface.get("virtual-interface").get("bandwidth"))
1117 db_interface["bw"] = int(math.ceil(bps/1000000.0))
1118 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1119
1120 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1121 db_interface["type"] = "mgmt"
garciadeblas31e141b2018-10-25 18:33:19 +02001122 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
tierno66eba6e2017-11-10 17:09:18 +01001123 db_interface["type"] = "bridge"
1124 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1125 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1126 db_interface["type"] = "data"
1127 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1128 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1129 else "yes"
1130 flavor_epa_interfaces.append(flavor_epa_interface)
1131 else:
1132 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1133 "-interface':'type':'{}'. Interface type is not supported".format(
1134 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001135 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001136
tiernoe72710b2018-07-23 16:16:00 +02001137 if iface.get("mgmt-interface"):
1138 db_interface["type"] = "mgmt"
1139
tierno66eba6e2017-11-10 17:09:18 +01001140 if iface.get("external-connection-point-ref"):
1141 try:
1142 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1143 db_interface["external_name"] = get_str(cp, "name", 255)
1144 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1145 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1146 cp_name2db_interface[db_interface["external_name"]] = db_interface
1147 for cp_descriptor in vnfd_descriptor["connection-point"]:
1148 if cp_descriptor["name"] == db_interface["external_name"]:
1149 break
1150 else:
1151 raise KeyError()
1152
1153 if vdu_id in vdu_id2cp_name:
1154 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1155 else:
1156 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1157
1158 # port security
1159 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1160 db_interface["port_security"] = 0
1161 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1162 db_interface["port_security"] = 1
1163 except KeyError:
1164 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1165 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1166 " at connection-point".format(
1167 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1168 cp=iface.get("vnfd-connection-point-ref")),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001169 httperrors.Bad_Request)
tierno66eba6e2017-11-10 17:09:18 +01001170 elif iface.get("internal-connection-point-ref"):
1171 try:
tierno41a69812018-02-16 14:34:33 +01001172 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1173 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1174 break
1175 else:
1176 raise KeyError("does not exist at vdu:internal-connection-point")
1177 icp = None
1178 icp_vld = None
tierno66eba6e2017-11-10 17:09:18 +01001179 for vld in vnfd.get("internal-vld").itervalues():
1180 for cp in vld.get("internal-connection-point").itervalues():
1181 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
tierno41a69812018-02-16 14:34:33 +01001182 if icp:
1183 raise KeyError("is referenced by more than one 'internal-vld'")
1184 icp = cp
1185 icp_vld = vld
1186 if not icp:
1187 raise KeyError("is not referenced by any 'internal-vld'")
1188
1189 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1190 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1191 db_interface["port_security"] = 0
1192 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1193 db_interface["port_security"] = 1
1194 if icp.get("ip-address"):
1195 if not icp_vld.get("ip-profile-ref"):
1196 raise NfvoException
1197 db_interface["ip_address"] = str(icp.get("ip-address"))
1198 except KeyError as e:
tierno66eba6e2017-11-10 17:09:18 +01001199 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
tierno41a69812018-02-16 14:34:33 +01001200 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1201 " {msg}".format(
tierno66eba6e2017-11-10 17:09:18 +01001202 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
tierno41a69812018-02-16 14:34:33 +01001203 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001204 httperrors.Bad_Request)
tierno55d234c2018-07-04 18:29:21 +02001205 if iface.get("position"):
1206 db_interface["created_at"] = int(iface.get("position")) * 50
tierno41a69812018-02-16 14:34:33 +01001207 if iface.get("mac-address"):
1208 db_interface["mac"] = str(iface.get("mac-address"))
tierno66eba6e2017-11-10 17:09:18 +01001209 db_interfaces.append(db_interface)
1210
tiernof1ba57e2017-09-07 12:23:19 +02001211 # table flavors
1212 db_flavor = {
1213 "name": get_str(vdu, "name", 250) + "-flv",
1214 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1215 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
garciadeblas79d1a1a2017-12-11 16:07:07 +01001216 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
tiernof1ba57e2017-09-07 12:23:19 +02001217 }
tiernocf596692017-11-20 15:47:51 +01001218 # TODO revise the case of several numa-node-policy node
tiernof1ba57e2017-09-07 12:23:19 +02001219 extended = {}
1220 numa = {}
1221 if devices:
1222 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001223 if flavor_epa_interfaces:
1224 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001225 if vdu.get("guest-epa"): # TODO or dedicated_int:
1226 epa_vcpu_set = False
1227 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1228 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1229 if numa_node_policy.get("node"):
tiernocf596692017-11-20 15:47:51 +01001230 numa_node = numa_node_policy["node"].values()[0]
tiernof1ba57e2017-09-07 12:23:19 +02001231 if numa_node.get("num-cores"):
1232 numa["cores"] = numa_node["num-cores"]
1233 epa_vcpu_set = True
1234 if numa_node.get("paired-threads"):
1235 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001236 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001237 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001238 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001239 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001240 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001241 numa["paired-threads-id"].append(
1242 (str(pair["thread-a"]), str(pair["thread-b"]))
1243 )
1244 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001245 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001246 epa_vcpu_set = True
1247 if numa_node.get("memory-mb"):
1248 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1249 if vdu["guest-epa"].get("mempage-size"):
1250 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1251 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1252 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1253 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1254 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1255 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1256 numa["cores"] = max(db_flavor["vcpus"], 1)
1257 else:
1258 numa["threads"] = max(db_flavor["vcpus"], 1)
1259 if numa:
1260 extended["numas"] = [numa]
1261 if extended:
1262 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1263 db_flavor["extended"] = extended_text
1264 # look if flavor exist
garciadeblas79d1a1a2017-12-11 16:07:07 +01001265 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
tiernof1ba57e2017-09-07 12:23:19 +02001266 'ram': db_flavor.get('ram'),
1267 'vcpus': db_flavor.get('vcpus'),
1268 'extended': db_flavor.get('extended')
1269 }
1270 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1271 if existing_flavors:
1272 flavor_uuid = existing_flavors[0]["uuid"]
1273 else:
1274 flavor_uuid = str(uuid4())
1275 uuid_list.append(flavor_uuid)
1276 db_flavor["uuid"] = flavor_uuid
1277 db_flavors.append(db_flavor)
1278 db_vm["flavor_id"] = flavor_uuid
1279
tiernof1ba57e2017-09-07 12:23:19 +02001280 # VNF affinity and antiaffinity
1281 for pg in vnfd.get("placement-groups").itervalues():
1282 pg_name = get_str(pg, "name", 255)
1283 for vdu in pg.get("member-vdus").itervalues():
1284 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1285 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001286 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1287 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001288 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001289 httperrors.Bad_Request)
tiernob6990792018-11-13 10:37:42 +01001290 if vdu_id2db_table_index[vdu_id]:
1291 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
tiernof1ba57e2017-09-07 12:23:19 +02001292 # TODO consider the case of isolation and not colocation
1293 # if pg.get("strategy") == "ISOLATION":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001294
tiernof1ba57e2017-09-07 12:23:19 +02001295 # VNF mgmt configuration
1296 mgmt_access = {}
1297 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001298 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1299 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001300 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1301 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001302 vnf=vnfd_id, vdu=mgmt_vdu_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001303 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001304 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001305 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1306 if vdu_id2cp_name.get(mgmt_vdu_id):
tiernob6990792018-11-13 10:37:42 +01001307 if cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]:
1308 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
tierno66eba6e2017-11-10 17:09:18 +01001309
tiernof1ba57e2017-09-07 12:23:19 +02001310 if vnfd["mgmt-interface"].get("ip-address"):
1311 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1312 if vnfd["mgmt-interface"].get("cp"):
1313 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob6990792018-11-13 10:37:42 +01001314 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
tiernob2880eb2017-10-04 15:04:53 +02001315 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001316 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001317 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001318 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1319 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001320 # mark this interface as of type mgmt
tiernob6990792018-11-13 10:37:42 +01001321 if cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]:
1322 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
tiernoe2ff1ce2017-11-02 17:01:10 +01001323
tiernoa9550202017-09-22 13:31:35 +02001324 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001325 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001326
tiernof1ba57e2017-09-07 12:23:19 +02001327 if default_user:
1328 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001329 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1330 "required", 6)
1331 if required:
1332 mgmt_access["required"] = required
1333
tiernof1ba57e2017-09-07 12:23:19 +02001334 if mgmt_access:
1335 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1336
1337 db_vnfs.append(db_vnf)
1338 db_tables=[
1339 {"vnfs": db_vnfs},
1340 {"nets": db_nets},
1341 {"images": db_images},
1342 {"flavors": db_flavors},
tierno41a69812018-02-16 14:34:33 +01001343 {"ip_profiles": db_ip_profiles},
tiernof1ba57e2017-09-07 12:23:19 +02001344 {"vms": db_vms},
1345 {"interfaces": db_interfaces},
1346 ]
1347
1348 logger.debug("create_vnf Deployment done vnfDict: %s",
1349 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1350 mydb.new_rows(db_tables, uuid_list)
1351 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001352 except NfvoException:
1353 raise
tiernof1ba57e2017-09-07 12:23:19 +02001354 except Exception as e:
1355 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001356 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001357
1358
tiernob8569aa2018-08-24 11:34:54 +02001359@deprecated("Use new_vnfd_v3")
tierno7edb6752016-03-21 17:37:52 +01001360def new_vnf(mydb, tenant_id, vnf_descriptor):
1361 global global_config
tierno42026a02017-02-10 15:13:40 +01001362
tierno7edb6752016-03-21 17:37:52 +01001363 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001364 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001365 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001366 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001367 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001368 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001369 if "tenant_id" in vnf_descriptor["vnf"]:
1370 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001371 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 +01001372 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001373 else:
1374 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1375 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001376 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001377 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001378
1379 # Step 4. Review the descriptor and add missing fields
1380 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001381 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001382 vnf_name = vnf_descriptor['vnf']['name']
1383 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1384 if "physical" in vnf_descriptor['vnf']:
1385 del vnf_descriptor['vnf']['physical']
1386 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001387
tierno42026a02017-02-10 15:13:40 +01001388 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001389 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1390 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001391
tierno7edb6752016-03-21 17:37:52 +01001392 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1393 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1394 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001395 try:
tiernof97fd272016-07-11 14:32:37 +02001396 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001397 for vnfc in vnf_descriptor['vnf']['VNFC']:
1398 VNFCitem={}
1399 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001400 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001401 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001402
tiernof97fd272016-07-11 14:32:37 +02001403 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001404
tierno7edb6752016-03-21 17:37:52 +01001405 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001406 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 +01001407 myflavorDict["description"] = VNFCitem["description"]
1408 myflavorDict["ram"] = vnfc.get("ram", 0)
1409 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001410 myflavorDict["disk"] = vnfc.get("disk", 0)
tierno7edb6752016-03-21 17:37:52 +01001411 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001412
tierno7edb6752016-03-21 17:37:52 +01001413 devices = vnfc.get("devices")
1414 if devices != None:
1415 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001416
tierno7edb6752016-03-21 17:37:52 +01001417 # TODO:
1418 # 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 +01001419 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1420
tierno7edb6752016-03-21 17:37:52 +01001421 # Previous code has been commented
1422 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1423 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1424 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1425 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1426 #else:
1427 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1428 # if result2:
1429 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001430 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
tierno7edb6752016-03-21 17:37:52 +01001431 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001432 # 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 +01001433 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001434
tierno7edb6752016-03-21 17:37:52 +01001435 if 'numas' in vnfc and len(vnfc['numas'])>0:
1436 myflavorDict['extended']['numas'] = vnfc['numas']
1437
1438 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001439
tierno7edb6752016-03-21 17:37:52 +01001440 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001441 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001442
tiernof97fd272016-07-11 14:32:37 +02001443 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001444 VNFCitem["flavor_id"] = flavor_id
1445 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001446
tiernof97fd272016-07-11 14:32:37 +02001447 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001448 # Step 6.3 New images are created in the VIM
1449 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001450 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001451 #In case this integration is made, the VNFCDict might become a VNFClist.
1452 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001453 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001454 image_dict={}
1455 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1456 image_dict['universal_name']=vnfc.get('image name')
1457 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1458 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001459 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001460 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001461 image_metadata_dict = vnfc.get('image metadata', None)
1462 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001463 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001464 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1465 image_dict['metadata']=image_metadata_str
1466 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001467 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1468 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001469 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001470 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001471 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001472 if vnfc.get("boot-data"):
1473 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001474
tierno42026a02017-02-10 15:13:40 +01001475
tiernof97fd272016-07-11 14:32:37 +02001476 # Step 7. Storing the VNF descriptor in the repository
1477 if "descriptor" not in vnf_descriptor["vnf"]:
1478 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001479
tiernof97fd272016-07-11 14:32:37 +02001480 # Step 8. Adding the VNF to the NFVO DB
1481 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1482 return vnf_id
1483 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001484 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001485 if isinstance(e, db_base_Exception):
1486 error_text = "Exception at database"
1487 elif isinstance(e, KeyError):
1488 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001489 e.http_code = httperrors.Internal_Server_Error
tiernof97fd272016-07-11 14:32:37 +02001490 else:
1491 error_text = "Exception at VIM"
1492 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1493 #logger.error("start_scenario %s", error_text)
1494 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001495
tiernob3d36742017-03-03 23:51:05 +01001496
tiernob8569aa2018-08-24 11:34:54 +02001497@deprecated("Use new_vnfd_v3")
garciadeblas9f8456e2016-09-05 05:02:59 +02001498def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1499 global global_config
tierno42026a02017-02-10 15:13:40 +01001500
garciadeblas9f8456e2016-09-05 05:02:59 +02001501 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001502 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001503 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001504 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001505 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001506 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001507 if "tenant_id" in vnf_descriptor["vnf"]:
1508 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1509 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 +01001510 httperrors.Unauthorized)
garciadeblas9f8456e2016-09-05 05:02:59 +02001511 else:
1512 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1513 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001514 if global_config["auto_push_VNF_to_VIMs"]:
tiernocbb52052018-05-31 18:57:30 +02001515 vims = get_vim(mydb, tenant_id, ignore_errors=True)
garciadeblas9f8456e2016-09-05 05:02:59 +02001516
1517 # Step 4. Review the descriptor and add missing fields
1518 #print vnf_descriptor
1519 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1520 vnf_name = vnf_descriptor['vnf']['name']
1521 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1522 if "physical" in vnf_descriptor['vnf']:
1523 del vnf_descriptor['vnf']['physical']
1524 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001525
tierno42026a02017-02-10 15:13:40 +01001526 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001527 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1528 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001529
garciadeblas9f8456e2016-09-05 05:02:59 +02001530 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1531 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1532 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1533 try:
1534 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1535 for vnfc in vnf_descriptor['vnf']['VNFC']:
1536 VNFCitem={}
1537 VNFCitem["name"] = vnfc['name']
1538 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001539
garciadeblas9f8456e2016-09-05 05:02:59 +02001540 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001541
garciadeblas9f8456e2016-09-05 05:02:59 +02001542 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001543 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 +02001544 myflavorDict["description"] = VNFCitem["description"]
1545 myflavorDict["ram"] = vnfc.get("ram", 0)
1546 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001547 myflavorDict["disk"] = vnfc.get("disk", 0)
garciadeblas9f8456e2016-09-05 05:02:59 +02001548 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001549
garciadeblas9f8456e2016-09-05 05:02:59 +02001550 devices = vnfc.get("devices")
1551 if devices != None:
1552 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001553
garciadeblas9f8456e2016-09-05 05:02:59 +02001554 # TODO:
1555 # 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 +01001556 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1557
garciadeblas9f8456e2016-09-05 05:02:59 +02001558 # Previous code has been commented
1559 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1560 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1561 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1562 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1563 #else:
1564 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1565 # if result2:
1566 # print "Error creating flavor: unknown processor model. Rollback successful."
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001567 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
garciadeblas9f8456e2016-09-05 05:02:59 +02001568 # else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001569 # 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 +02001570 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001571
garciadeblas9f8456e2016-09-05 05:02:59 +02001572 if 'numas' in vnfc and len(vnfc['numas'])>0:
1573 myflavorDict['extended']['numas'] = vnfc['numas']
1574
1575 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001576
garciadeblas9f8456e2016-09-05 05:02:59 +02001577 # Step 6.2 New flavors are created in the VIM
1578 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1579
1580 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1581 VNFCitem["flavor_id"] = flavor_id
1582 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001583
garciadeblas9f8456e2016-09-05 05:02:59 +02001584 logger.debug("Creating new images in the VIM for each VNFC")
1585 # Step 6.3 New images are created in the VIM
1586 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001587 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001588 #In case this integration is made, the VNFCDict might become a VNFClist.
1589 for vnfc in vnf_descriptor['vnf']['VNFC']:
1590 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001591 image_dict={}
1592 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1593 image_dict['universal_name']=vnfc.get('image name')
1594 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1595 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001596 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001597 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001598 image_metadata_dict = vnfc.get('image metadata', None)
1599 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001600 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001601 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1602 image_dict['metadata']=image_metadata_str
1603 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1604 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1605 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1606 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001607 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001608 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001609 if vnfc.get("boot-data"):
1610 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001611
garciadeblas9f8456e2016-09-05 05:02:59 +02001612 # Step 7. Storing the VNF descriptor in the repository
1613 if "descriptor" not in vnf_descriptor["vnf"]:
1614 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001615
garciadeblas9f8456e2016-09-05 05:02:59 +02001616 # Step 8. Adding the VNF to the NFVO DB
1617 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1618 return vnf_id
1619 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1620 _, message = rollback(mydb, vims, rollback_list)
1621 if isinstance(e, db_base_Exception):
1622 error_text = "Exception at database"
1623 elif isinstance(e, KeyError):
1624 error_text = "KeyError exception "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001625 e.http_code = httperrors.Internal_Server_Error
garciadeblas9f8456e2016-09-05 05:02:59 +02001626 else:
1627 error_text = "Exception at VIM"
1628 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1629 #logger.error("start_scenario %s", error_text)
1630 raise NfvoException(error_text, e.http_code)
1631
tiernob3d36742017-03-03 23:51:05 +01001632
tierno7edb6752016-03-21 17:37:52 +01001633def get_vnf_id(mydb, tenant_id, vnf_id):
1634 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001635 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001636 #obtain data
1637 where_or = {}
1638 if tenant_id != "any":
1639 where_or["tenant_id"] = tenant_id
1640 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001641 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1642
tiernof1ba57e2017-09-07 12:23:19 +02001643 vnf_id = vnf["uuid"]
1644 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001645 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001646 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1647 data={'vnf' : filtered_content}
1648 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001649 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001650 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1651 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001652 WHERE={'vnfs.uuid': vnf_id} )
gcalvinobfa2fd92018-11-13 18:47:28 +01001653 if len(content) != 0:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00001654 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001655 # change boot_data into boot-data
gcalvino319b8a52018-11-05 15:33:23 +01001656 for vm in content:
1657 if vm.get("boot_data"):
1658 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1659 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001660
gcalvinobfa2fd92018-11-13 18:47:28 +01001661 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001662 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001663
tierno7edb6752016-03-21 17:37:52 +01001664 #GET NET
tierno42026a02017-02-10 15:13:40 +01001665 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001666 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1667 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001668 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001669
1670 #GET ip-profile for each net
1671 for net in data['vnf']['nets']:
1672 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1673 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1674 WHERE={'net_id': net["uuid"]} )
1675 if len(ipprofiles)==1:
1676 net["ip_profile"] = ipprofiles[0]
1677 elif len(ipprofiles)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001678 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 +01001679
1680
garciadeblas9f8456e2016-09-05 05:02:59 +02001681 #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 +01001682
garciadeblas9f8456e2016-09-05 05:02:59 +02001683 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001684 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 +01001685 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1686 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001687 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001688 #print content
tiernof97fd272016-07-11 14:32:37 +02001689 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001690
tiernof97fd272016-07-11 14:32:37 +02001691 return data
tierno7edb6752016-03-21 17:37:52 +01001692
1693
1694def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1695 # Check tenant exist
1696 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001697 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001698 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernocbb52052018-05-31 18:57:30 +02001699 vims = get_vim(mydb, tenant_id, ignore_errors=True)
tierno7edb6752016-03-21 17:37:52 +01001700 else:
1701 vims={}
1702
1703 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1704 where_or = {}
1705 if tenant_id != "any":
1706 where_or["tenant_id"] = tenant_id
1707 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001708 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 +02001709 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001710
tierno7edb6752016-03-21 17:37:52 +01001711 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001712 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001713 if len(flavorList)==0:
1714 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001715
tiernof97fd272016-07-11 14:32:37 +02001716 imageList = get_imagelist(mydb, vnf_id)
1717 if len(imageList)==0:
1718 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001719
tiernof97fd272016-07-11 14:32:37 +02001720 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1721 if deleted == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001722 raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
tierno42026a02017-02-10 15:13:40 +01001723
tierno7edb6752016-03-21 17:37:52 +01001724 undeletedItems = []
1725 for flavor in flavorList:
1726 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001727 try:
1728 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1729 if len(c) > 0:
1730 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1731 continue
1732 #flavor not used, must be deleted
1733 #delelte at VIM
tierno96ebf002017-12-13 10:55:38 +01001734 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
tierno7edb6752016-03-21 17:37:52 +01001735 for flavor_vim in c:
tierno96ebf002017-12-13 10:55:38 +01001736 if not flavor_vim['created']: # skip this flavor because not created by openmano
tierno7edb6752016-03-21 17:37:52 +01001737 continue
tierno96ebf002017-12-13 10:55:38 +01001738 # look for vim
1739 myvim = None
1740 for vim in vims.values():
1741 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1742 myvim = vim
1743 break
1744 if not myvim:
tierno7edb6752016-03-21 17:37:52 +01001745 continue
tiernoae4a8d12016-07-08 12:30:39 +02001746 try:
1747 myvim.delete_flavor(flavor_vim["vim_id"])
tierno96ebf002017-12-13 10:55:38 +01001748 except vimconn.vimconnNotFoundException:
1749 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1750 flavor_vim["datacenter_vim_id"] )
tiernoae4a8d12016-07-08 12:30:39 +02001751 except vimconn.vimconnException as e:
1752 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
tierno96ebf002017-12-13 10:55:38 +01001753 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1754 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1755 flavor_vim["datacenter_vim_id"]))
1756 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
tiernof97fd272016-07-11 14:32:37 +02001757 mydb.delete_row_by_id('flavors', flavor)
1758 except db_base_Exception as e:
1759 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno96ebf002017-12-13 10:55:38 +01001760 undeletedItems.append("flavor {}".format(flavor))
tiernof97fd272016-07-11 14:32:37 +02001761
tierno42026a02017-02-10 15:13:40 +01001762
tierno7edb6752016-03-21 17:37:52 +01001763 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001764 try:
1765 #check if image is used by other vnf
tierno16e3dd42018-04-24 12:52:40 +02001766 c = mydb.get_rows(FROM='vms', WHERE=[{'image_id': image}, {'image_list LIKE ': '%' + image + '%'}])
tiernof97fd272016-07-11 14:32:37 +02001767 if len(c) > 0:
1768 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1769 continue
1770 #image not used, must be deleted
1771 #delelte at VIM
1772 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001773 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001774 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001775 continue
1776 if image_vim['created']=='false': #skip this image because not created by openmano
1777 continue
1778 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001779 try:
1780 myvim.delete_image(image_vim["vim_id"])
1781 except vimconn.vimconnNotFoundException as e:
1782 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1783 except vimconn.vimconnException as e:
1784 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1785 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1786 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001787 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1788 mydb.delete_row_by_id('images', image)
1789 except db_base_Exception as e:
1790 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001791 undeletedItems.append("image %s" % image)
1792
tiernof97fd272016-07-11 14:32:37 +02001793 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001794 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001795 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001796
tiernob3d36742017-03-03 23:51:05 +01001797
tiernob8569aa2018-08-24 11:34:54 +02001798@deprecated("Not used")
tierno7edb6752016-03-21 17:37:52 +01001799def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1800 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1801 if result < 0:
1802 return result, vims
1803 elif result == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001804 return -httperrors.Not_Found, "datacenter '%s' not found" % datacenter_name
tierno7edb6752016-03-21 17:37:52 +01001805 myvim = vims.values()[0]
1806 result,servers = myvim.get_hosts_info()
1807 if result < 0:
1808 return result, servers
1809 topology = {'name':myvim['name'] , 'servers': servers}
1810 return result, topology
1811
tiernob3d36742017-03-03 23:51:05 +01001812
tierno7edb6752016-03-21 17:37:52 +01001813def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001814 vims = get_vim(mydb, nfvo_tenant_id)
1815 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001816 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001817 elif len(vims)>1:
1818 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001819 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001820 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001821 try:
1822 hosts = myvim.get_hosts()
1823 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001824
tiernof97fd272016-07-11 14:32:37 +02001825 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1826 for host in hosts:
1827 server={'name':host['name'], 'vms':[]}
1828 for vm in host['instances']:
1829 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001830 try:
tiernof97fd272016-07-11 14:32:37 +02001831 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1832 WHERE={'vim_vm_id':vm['id']} )
1833 if len(c) == 0:
1834 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1835 continue
1836 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001837
tiernof97fd272016-07-11 14:32:37 +02001838 except db_base_Exception as e:
1839 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1840 datacenter['Datacenters'][0]['servers'].append(server)
1841 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001842
tiernof97fd272016-07-11 14:32:37 +02001843 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1844 return datacenter
1845 except vimconn.vimconnException as e:
1846 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001847
tiernob3d36742017-03-03 23:51:05 +01001848
tiernob8569aa2018-08-24 11:34:54 +02001849@deprecated("Use new_nsd_v3")
tierno7edb6752016-03-21 17:37:52 +01001850def new_scenario(mydb, tenant_id, topo):
1851
1852# result, vims = get_vim(mydb, tenant_id)
1853# if result < 0:
1854# return result, vims
1855#1: parse input
1856 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001857 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001858 if "tenant_id" in topo:
1859 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001860 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 +01001861 httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001862 else:
1863 tenant_id=None
1864
tierno42026a02017-02-10 15:13:40 +01001865#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001866 vnfs={}
1867 other_nets={} #external_networks, bridge_networks and data_networkds
1868 nodes = topo['topology']['nodes']
1869 for k in nodes.keys():
1870 if nodes[k]['type'] == 'VNF':
1871 vnfs[k] = nodes[k]
1872 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001873 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001874 other_nets[k] = nodes[k]
1875 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001876 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001877 other_nets[k] = nodes[k]
1878 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001879
tierno7edb6752016-03-21 17:37:52 +01001880
1881#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1882 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001883 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001884 error_text = ""
1885 error_pos = "'topology':'nodes':'" + name + "'"
1886 if 'vnf_id' in vnf:
1887 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001888 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001889 if 'VNF model' in vnf:
1890 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001891 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001892 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001893 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001894
tiernocea279c2016-07-18 12:36:49 +02001895 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1896 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001897 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001898 if len(vnf_db)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001899 raise NfvoException("unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02001900 elif len(vnf_db)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001901 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01001902 vnf['uuid']=vnf_db[0]['uuid']
1903 vnf['description']=vnf_db[0]['description']
1904 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001905 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1906 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 +02001907 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001908 for ext_iface in ext_ifaces:
1909 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1910
1911#1.4 get list of connections
1912 conections = topo['topology']['connections']
1913 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001914 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001915 for k in conections.keys():
1916 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1917 ifaces_list = conections[k]['nodes'].items()
1918 elif type(conections[k]['nodes'])==list: #list with dictionary
1919 ifaces_list=[]
1920 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1921 for k2 in conection_pair_list:
1922 ifaces_list += k2
1923
1924 con_type = conections[k].get("type", "link")
1925 if con_type != "link":
1926 if k in other_nets:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001927 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001928 other_nets[k] = {'external': False}
1929 if conections[k].get("graph"):
1930 other_nets[k]["graph"] = conections[k]["graph"]
1931 ifaces_list.append( (k, None) )
1932
tierno42026a02017-02-10 15:13:40 +01001933
tierno7edb6752016-03-21 17:37:52 +01001934 if con_type == "external_network":
1935 other_nets[k]['external'] = True
1936 if conections[k].get("model"):
1937 other_nets[k]["model"] = conections[k]["model"]
1938 else:
1939 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001940 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001941 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001942
tiernoefd80c92016-09-16 14:17:46 +02001943 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001944 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)
1945 #print set(ifaces_list)
1946 #check valid VNF and iface names
1947 for iface in ifaces_list:
1948 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001949 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001950 str(k), iface[0]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001951 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001952 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001953 str(k), iface[0], iface[1]), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001954
1955#1.5 unify connections from the pair list to a consolidated list
1956 index=0
1957 while index < len(conections_list):
1958 index2 = index+1
1959 while index2 < len(conections_list):
1960 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1961 conections_list[index] |= conections_list[index2]
1962 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001963 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001964 else:
1965 index2 += 1
1966 conections_list[index] = list(conections_list[index]) # from set to list again
1967 index += 1
1968 #for k in conections_list:
1969 # print k
tierno42026a02017-02-10 15:13:40 +01001970
tierno7edb6752016-03-21 17:37:52 +01001971
1972
1973#1.6 Delete non external nets
1974# for k in other_nets.keys():
1975# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1976# for con in conections_list:
1977# delete_indexes=[]
1978# for index in range(0,len(con)):
1979# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1980# for index in delete_indexes:
1981# del con[index]
1982# del other_nets[k]
1983#1.7: Check external_ports are present at database table datacenter_nets
1984 for k,net in other_nets.items():
1985 error_pos = "'topology':'nodes':'" + k + "'"
1986 if net['external']==False:
1987 if 'name' not in net:
1988 net['name']=k
1989 if 'model' not in net:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001990 raise NfvoException("needed a 'model' at " + error_pos, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001991 if net['model']=='bridge_net':
1992 net['type']='bridge';
1993 elif net['model']=='dataplane_net':
1994 net['type']='data';
1995 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01001996 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001997 else: #external
1998#IF we do not want to check that external network exist at datacenter
1999 pass
tierno42026a02017-02-10 15:13:40 +01002000#ELSE
tierno7edb6752016-03-21 17:37:52 +01002001# error_text = ""
2002# WHERE_={}
2003# if 'net_id' in net:
2004# error_text += " 'net_id' " + net['net_id']
2005# WHERE_['uuid'] = net['net_id']
2006# if 'model' in net:
2007# error_text += " 'model' " + net['model']
2008# WHERE_['name'] = net['model']
2009# if len(WHERE_) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002010# return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002011# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2012# FROM='datacenter_nets', WHERE=WHERE_ )
2013# if r<0:
2014# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2015# elif r==0:
2016# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002017# return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
tierno7edb6752016-03-21 17:37:52 +01002018# elif r>1:
tierno42026a02017-02-10 15:13:40 +01002019# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002020# 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 +01002021# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01002022#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002023 net_list={}
2024 net_nb=0 #Number of nets
2025 for con in conections_list:
2026 #check if this is connected to a external net
2027 other_net_index=-1
2028 #print
2029 #print "con", con
2030 for index in range(0,len(con)):
2031 #check if this is connected to a external net
2032 for net_key in other_nets.keys():
2033 if con[index][0]==net_key:
2034 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01002035 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 +02002036 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002037 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002038 else:
2039 other_net_index = index
2040 net_target = net_key
2041 break
2042 #print "other_net_index", other_net_index
2043 try:
2044 if other_net_index>=0:
2045 del con[other_net_index]
2046#IF we do not want to check that external network exist at datacenter
2047 if other_nets[net_target]['external'] :
2048 if "name" not in other_nets[net_target]:
2049 other_nets[net_target]['name'] = other_nets[net_target]['model']
2050 if other_nets[net_target]["type"] == "external_network":
2051 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
2052 other_nets[net_target]["type"] = "data"
2053 else:
2054 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01002055#ELSE
tierno7edb6752016-03-21 17:37:52 +01002056# if other_nets[net_target]['external'] :
2057# 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
2058# if type_=='data' and other_nets[net_target]['type']=="ptp":
2059# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2060# print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002061# return -httperrors.Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01002062#ENDIF
tierno7edb6752016-03-21 17:37:52 +01002063 for iface in con:
2064 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2065 else:
2066 #create a net
2067 net_type_bridge=False
2068 net_type_data=False
2069 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01002070 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02002071 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01002072 'external':False}
tierno7edb6752016-03-21 17:37:52 +01002073 for iface in con:
2074 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2075 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
2076 if iface_type=='mgmt' or iface_type=='bridge':
2077 net_type_bridge = True
2078 else:
2079 net_type_data = True
2080 if net_type_bridge and net_type_data:
2081 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 +02002082 #print "nfvo.new_scenario " + error_text
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002083 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002084 elif net_type_bridge:
2085 type_='bridge'
2086 else:
2087 type_='data' if len(con)>2 else 'ptp'
2088 net_list[net_target]['type'] = type_
2089 net_nb+=1
2090 except Exception:
2091 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02002092 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01002093 #raise e
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002094 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002095
2096#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01002097 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02002098 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01002099 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01002100 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02002101 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01002102 add_mgmt_net = False
2103 for vnf in vnfs.values():
2104 for iface in vnf['ifaces'].values():
2105 if iface['type']=='mgmt' and 'net_key' not in iface:
2106 #iface not connected
2107 iface['net_key'] = 'mgmt'
2108 add_mgmt_net = True
2109 if add_mgmt_net and 'mgmt' not in net_list:
2110 net_list['mgmt']=mgmt_net[0]
2111 net_list['mgmt']['external']=True
2112 net_list['mgmt']['graph']={'visible':False}
2113
2114 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02002115 #print
2116 #print 'net_list', net_list
2117 #print
2118 #print 'vnfs', vnfs
2119 #print
tierno7edb6752016-03-21 17:37:52 +01002120
2121#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02002122 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02002123 'tenant_id':tenant_id, 'name':topo['name'],
2124 'description':topo.get('description',topo['name']),
2125 'public': topo.get('public', False)
2126 })
tierno42026a02017-02-10 15:13:40 +01002127
tiernof97fd272016-07-11 14:32:37 +02002128 return c
tierno7edb6752016-03-21 17:37:52 +01002129
tiernob3d36742017-03-03 23:51:05 +01002130
tiernob8569aa2018-08-24 11:34:54 +02002131@deprecated("Use new_nsd_v3")
tierno5bb59dc2017-02-13 14:53:54 +01002132def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2133 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02002134 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01002135 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01002136 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002137 if "tenant_id" in scenario:
2138 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01002139 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02002140 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002141 scenario["tenant_id"], tenant_id), httperrors.Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01002142 else:
2143 tenant_id=None
2144
tierno5bb59dc2017-02-13 14:53:54 +01002145 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01002146 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02002147 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01002148 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02002149 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01002150 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002151 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02002152 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02002153 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002154 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02002155 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02002156 if len(where) == 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002157 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002158 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002159 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002160 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002161 if len(vnf_db) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002162 raise NfvoException("Unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002163 elif len(vnf_db) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002164 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002165 vnf['uuid'] = vnf_db[0]['uuid']
2166 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002167 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002168 # get external interfaces
2169 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2170 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 +02002171 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002172 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002173 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2174 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002175
tierno5bb59dc2017-02-13 14:53:54 +01002176 # 2: Insert net_key and ip_address at every vnf interface
2177 for net_name, net in scenario["networks"].items():
2178 net_type_bridge = False
2179 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002180 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002181 if version == "0.2":
2182 temp_dict = iface_dict
2183 ip_address = None
2184 elif version == "0.3":
2185 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2186 ip_address = iface_dict.get('ip_address', None)
2187 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002188 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002189 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2190 net_name, vnf)
2191 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002192 raise NfvoException(error_text, httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002193 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002194 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2195 .format(net_name, iface)
2196 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002197 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002198 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002199 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2200 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2201 # logger.debug("nfvo.new_scenario_v02 " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002202 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002203 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002204 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002205 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002206 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002207 net_type_bridge = True
2208 else:
2209 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002210
tierno7edb6752016-03-21 17:37:52 +01002211 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002212 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2213 .format(net_name)
2214 # logger.debug("nfvo.new_scenario " + error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002215 raise NfvoException(error_text, httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002216 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002217 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002218 else:
tierno5bb59dc2017-02-13 14:53:54 +01002219 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2220
2221 if net.get("implementation"): # for v0.3
2222 if type_ == "bridge" and net["implementation"] == "underlay":
2223 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2224 "'network':'{}'".format(net_name)
2225 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002226 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002227 elif type_ != "bridge" and net["implementation"] == "overlay":
2228 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2229 "'network':'{}'".format(net_name)
2230 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002231 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002232 net.pop("implementation")
2233 if "type" in net and version == "0.3": # for v0.3
2234 if type_ == "data" and net["type"] == "e-line":
2235 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2236 "'e-line' at 'network':'{}'".format(net_name)
2237 # logger.debug(error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002238 raise NfvoException(error_text, httperrors.Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002239 elif type_ == "ptp" and net["type"] == "e-lan":
2240 type_ = "data"
2241
tierno7edb6752016-03-21 17:37:52 +01002242 net['type'] = type_
2243 net['name'] = net_name
2244 net['external'] = net.get('external', False)
2245
tierno5bb59dc2017-02-13 14:53:54 +01002246 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002247 scenario["nets"] = scenario["networks"]
2248 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002249 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002250 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002251
tiernob3d36742017-03-03 23:51:05 +01002252
tiernof1ba57e2017-09-07 12:23:19 +02002253def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2254 """
2255 Parses an OSM IM nsd_catalog and insert at DB
2256 :param mydb:
2257 :param tenant_id:
2258 :param nsd_descriptor:
Igor D.Ccaadc442017-11-06 12:48:48 +00002259 :return: The list of created NSD ids
tiernof1ba57e2017-09-07 12:23:19 +02002260 """
2261 try:
2262 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002263 try:
2264 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd)
2265 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002266 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002267 db_scenarios = []
2268 db_sce_nets = []
2269 db_sce_vnfs = []
2270 db_sce_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002271 db_sce_vnffgs = []
2272 db_sce_rsps = []
2273 db_sce_rsp_hops = []
2274 db_sce_classifiers = []
2275 db_sce_classifier_matches = []
tiernof1ba57e2017-09-07 12:23:19 +02002276 db_ip_profiles = []
2277 db_ip_profiles_index = 0
2278 uuid_list = []
2279 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002280 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2281 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002282
Igor D.Ccaadc442017-11-06 12:48:48 +00002283 # table scenarios
tiernof1ba57e2017-09-07 12:23:19 +02002284 scenario_uuid = str(uuid4())
2285 uuid_list.append(scenario_uuid)
2286 nsd_uuid_list.append(scenario_uuid)
2287 db_scenario = {
2288 "uuid": scenario_uuid,
2289 "osm_id": get_str(nsd, "id", 255),
2290 "name": get_str(nsd, "name", 255),
2291 "description": get_str(nsd, "description", 255),
2292 "tenant_id": tenant_id,
2293 "vendor": get_str(nsd, "vendor", 255),
2294 "short_name": get_str(nsd, "short-name", 255),
2295 "descriptor": str(nsd_descriptor)[:60000],
2296 }
2297 db_scenarios.append(db_scenario)
2298
2299 # table sce_vnfs (constituent-vnfd)
2300 vnf_index2scevnf_uuid = {}
2301 vnf_index2vnf_uuid = {}
2302 for vnf in nsd.get("constituent-vnfd").itervalues():
2303 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2304 'tenant_id': tenant_id})
2305 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002306 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2307 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2308 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002309 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002310 sce_vnf_uuid = str(uuid4())
2311 uuid_list.append(sce_vnf_uuid)
2312 db_sce_vnf = {
2313 "uuid": sce_vnf_uuid,
2314 "scenario_id": scenario_uuid,
tierno92c36fd2018-05-04 12:21:10 +02002315 # "name": get_str(vnf, "member-vnf-index", 255),
2316 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 50),
tiernof1ba57e2017-09-07 12:23:19 +02002317 "vnf_id": existing_vnf[0]["uuid"],
tierno16e3dd42018-04-24 12:52:40 +02002318 "member_vnf_index": str(vnf["member-vnf-index"]),
tiernof1ba57e2017-09-07 12:23:19 +02002319 # TODO 'start-by-default': True
2320 }
tierno16e3dd42018-04-24 12:52:40 +02002321 vnf_index2scevnf_uuid[str(vnf['member-vnf-index'])] = sce_vnf_uuid
2322 vnf_index2vnf_uuid[str(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
tiernof1ba57e2017-09-07 12:23:19 +02002323 db_sce_vnfs.append(db_sce_vnf)
2324
2325 # table ip_profiles (ip-profiles)
2326 ip_profile_name2db_table_index = {}
2327 for ip_profile in nsd.get("ip-profiles").itervalues():
2328 db_ip_profile = {
2329 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2330 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2331 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2332 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2333 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2334 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2335 }
2336 dns_list = []
2337 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2338 dns_list.append(str(dns.get("address")))
2339 db_ip_profile["dns_address"] = ";".join(dns_list)
2340 if ip_profile["ip-profile-params"].get('security-group'):
2341 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2342 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2343 db_ip_profiles_index += 1
2344 db_ip_profiles.append(db_ip_profile)
2345
2346 # table sce_nets (internal-vld)
2347 for vld in nsd.get("vld").itervalues():
2348 sce_net_uuid = str(uuid4())
2349 uuid_list.append(sce_net_uuid)
2350 db_sce_net = {
2351 "uuid": sce_net_uuid,
2352 "name": get_str(vld, "name", 255),
2353 "scenario_id": scenario_uuid,
2354 # "type": #TODO
2355 "multipoint": not vld.get("type") == "ELINE",
tierno1df468d2018-07-06 14:25:16 +02002356 "osm_id": get_str(vld, "id", 255),
tiernof1ba57e2017-09-07 12:23:19 +02002357 # "external": #TODO
2358 "description": get_str(vld, "description", 255),
2359 }
2360 # guess type of network
2361 if vld.get("mgmt-network"):
2362 db_sce_net["type"] = "bridge"
2363 db_sce_net["external"] = True
2364 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2365 db_sce_net["type"] = "data"
2366 else:
tierno66eba6e2017-11-10 17:09:18 +01002367 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2368 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002369 db_sce_nets.append(db_sce_net)
2370
2371 # ip-profile, link db_ip_profile with db_sce_net
2372 if vld.get("ip-profile-ref"):
2373 ip_profile_name = vld.get("ip-profile-ref")
2374 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002375 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2376 " Reference to a non-existing 'ip_profiles'".format(
2377 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002378 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002379 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
tierno8f79ea12018-05-03 17:37:40 +02002380 elif vld.get("vim-network-name"):
2381 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
tiernof1ba57e2017-09-07 12:23:19 +02002382
2383 # table sce_interfaces (vld:vnfd-connection-point-ref)
2384 for iface in vld.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002385 vnf_index = str(iface['member-vnf-index-ref'])
tiernof1ba57e2017-09-07 12:23:19 +02002386 # check correct parameters
2387 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002388 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2389 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2390 "'nsd':'constituent-vnfd'".format(
2391 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002392 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002393
tierno66eba6e2017-11-10 17:09:18 +01002394 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002395 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2396 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2397 'external_name': get_str(iface, "vnfd-connection-point-ref",
2398 255)})
2399 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002400 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2401 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2402 "connection-point name at VNFD '{}'".format(
2403 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2404 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002405 httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002406 interface_uuid = existing_ifaces[0]["uuid"]
tierno66eba6e2017-11-10 17:09:18 +01002407 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2408 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002409 sce_interface_uuid = str(uuid4())
2410 uuid_list.append(sce_net_uuid)
tierno41a69812018-02-16 14:34:33 +01002411 iface_ip_address = None
2412 if iface.get("ip-address"):
2413 iface_ip_address = str(iface.get("ip-address"))
tiernof1ba57e2017-09-07 12:23:19 +02002414 db_sce_interface = {
2415 "uuid": sce_interface_uuid,
2416 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2417 "sce_net_id": sce_net_uuid,
2418 "interface_id": interface_uuid,
tierno41a69812018-02-16 14:34:33 +01002419 "ip_address": iface_ip_address,
tiernof1ba57e2017-09-07 12:23:19 +02002420 }
2421 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002422 if not db_sce_net["type"]:
2423 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002424
Igor D.Ccaadc442017-11-06 12:48:48 +00002425 # table sce_vnffgs (vnffgd)
2426 for vnffg in nsd.get("vnffgd").itervalues():
2427 sce_vnffg_uuid = str(uuid4())
2428 uuid_list.append(sce_vnffg_uuid)
2429 db_sce_vnffg = {
2430 "uuid": sce_vnffg_uuid,
2431 "name": get_str(vnffg, "name", 255),
2432 "scenario_id": scenario_uuid,
2433 "vendor": get_str(vnffg, "vendor", 255),
2434 "description": get_str(vld, "description", 255),
2435 }
2436 db_sce_vnffgs.append(db_sce_vnffg)
2437
2438 # deal with rsps
2439 db_sce_rsps = []
2440 for rsp in vnffg.get("rsp").itervalues():
2441 sce_rsp_uuid = str(uuid4())
2442 uuid_list.append(sce_rsp_uuid)
2443 db_sce_rsp = {
2444 "uuid": sce_rsp_uuid,
2445 "name": get_str(rsp, "name", 255),
2446 "sce_vnffg_id": sce_vnffg_uuid,
2447 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2448 }
2449 db_sce_rsps.append(db_sce_rsp)
2450 db_sce_rsp_hops = []
2451 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
tierno16e3dd42018-04-24 12:52:40 +02002452 vnf_index = str(iface['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002453 if_order = int(iface['order'])
2454 # check correct parameters
2455 if vnf_index not in vnf_index2vnf_uuid:
2456 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2457 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2458 "'nsd':'constituent-vnfd'".format(
2459 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002460 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002461
2462 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2463 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2464 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2465 'external_name': get_str(iface, "vnfd-connection-point-ref",
2466 255)})
2467 if not existing_ifaces:
2468 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2469 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2470 "connection-point name at VNFD '{}'".format(
2471 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2472 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002473 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002474 interface_uuid = existing_ifaces[0]["uuid"]
2475 sce_rsp_hop_uuid = str(uuid4())
2476 uuid_list.append(sce_rsp_hop_uuid)
2477 db_sce_rsp_hop = {
2478 "uuid": sce_rsp_hop_uuid,
2479 "if_order": if_order,
2480 "interface_id": interface_uuid,
2481 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2482 "sce_rsp_id": sce_rsp_uuid,
2483 }
2484 db_sce_rsp_hops.append(db_sce_rsp_hop)
2485
2486 # deal with classifiers
2487 db_sce_classifiers = []
2488 for classifier in vnffg.get("classifier").itervalues():
2489 sce_classifier_uuid = str(uuid4())
2490 uuid_list.append(sce_classifier_uuid)
2491
2492 # source VNF
tierno16e3dd42018-04-24 12:52:40 +02002493 vnf_index = str(classifier['member-vnf-index-ref'])
Igor D.Ccaadc442017-11-06 12:48:48 +00002494 if vnf_index not in vnf_index2vnf_uuid:
2495 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2496 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2497 "'nsd':'constituent-vnfd'".format(
2498 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002499 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002500 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2501 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2502 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2503 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2504 255)})
2505 if not existing_ifaces:
2506 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2507 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2508 "connection-point name at VNFD '{}'".format(
2509 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2510 str(iface.get("vnfd-id-ref"))[:255]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002511 httperrors.Bad_Request)
Igor D.Ccaadc442017-11-06 12:48:48 +00002512 interface_uuid = existing_ifaces[0]["uuid"]
2513
2514 db_sce_classifier = {
2515 "uuid": sce_classifier_uuid,
2516 "name": get_str(classifier, "name", 255),
2517 "sce_vnffg_id": sce_vnffg_uuid,
2518 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2519 "interface_id": interface_uuid,
2520 }
2521 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2522 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2523 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2524 db_sce_classifiers.append(db_sce_classifier)
2525
2526 db_sce_classifier_matches = []
2527 for match in classifier.get("match-attributes").itervalues():
2528 sce_classifier_match_uuid = str(uuid4())
2529 uuid_list.append(sce_classifier_match_uuid)
2530 db_sce_classifier_match = {
2531 "uuid": sce_classifier_match_uuid,
2532 "ip_proto": get_str(match, "ip-proto", 2),
2533 "source_ip": get_str(match, "source-ip-address", 16),
2534 "destination_ip": get_str(match, "destination-ip-address", 16),
2535 "source_port": get_str(match, "source-port", 5),
2536 "destination_port": get_str(match, "destination-port", 5),
2537 "sce_classifier_id": sce_classifier_uuid,
2538 }
2539 db_sce_classifier_matches.append(db_sce_classifier_match)
2540 # TODO: vnf/cp keys
2541
2542 # remove unneeded id's in sce_rsps
2543 for rsp in db_sce_rsps:
2544 rsp.pop('id')
2545
tiernof1ba57e2017-09-07 12:23:19 +02002546 db_tables = [
2547 {"scenarios": db_scenarios},
2548 {"sce_nets": db_sce_nets},
2549 {"ip_profiles": db_ip_profiles},
2550 {"sce_vnfs": db_sce_vnfs},
2551 {"sce_interfaces": db_sce_interfaces},
Igor D.Ccaadc442017-11-06 12:48:48 +00002552 {"sce_vnffgs": db_sce_vnffgs},
2553 {"sce_rsps": db_sce_rsps},
2554 {"sce_rsp_hops": db_sce_rsp_hops},
2555 {"sce_classifiers": db_sce_classifiers},
2556 {"sce_classifier_matches": db_sce_classifier_matches},
tiernof1ba57e2017-09-07 12:23:19 +02002557 ]
2558
Igor D.Ccaadc442017-11-06 12:48:48 +00002559 logger.debug("new_nsd_v3 done: %s",
tiernof1ba57e2017-09-07 12:23:19 +02002560 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2561 mydb.new_rows(db_tables, uuid_list)
2562 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002563 except NfvoException:
2564 raise
tiernof1ba57e2017-09-07 12:23:19 +02002565 except Exception as e:
2566 logger.error("Exception {}".format(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002567 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002568
2569
tierno7edb6752016-03-21 17:37:52 +01002570def edit_scenario(mydb, tenant_id, scenario_id, data):
2571 data["uuid"] = scenario_id
2572 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002573 c = mydb.edit_scenario( data )
2574 return c
tierno7edb6752016-03-21 17:37:52 +01002575
tiernob3d36742017-03-03 23:51:05 +01002576
tiernob8569aa2018-08-24 11:34:54 +02002577@deprecated("Use create_instance")
tierno7edb6752016-03-21 17:37:52 +01002578def 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 +02002579 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002580 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2581 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002582 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002583 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002584
tierno7edb6752016-03-21 17:37:52 +01002585 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002586 try:
2587 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002588 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002589 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002590 scenarioDict['datacenter_id'] = datacenter_id
2591 #print '================scenarioDict======================='
2592 #print json.dumps(scenarioDict, indent=4)
2593 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002594
tiernoae4a8d12016-07-08 12:30:39 +02002595 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2596 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002597
tiernoae4a8d12016-07-08 12:30:39 +02002598 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2599 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002600
tiernoae4a8d12016-07-08 12:30:39 +02002601 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2602 for sce_net in scenarioDict['nets']:
2603 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002604
tiernoae4a8d12016-07-08 12:30:39 +02002605 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002606 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002607 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002608 myNetDict = {}
2609 myNetDict["name"] = myNetName
2610 myNetDict["type"] = myNetType
2611 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002612 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002613 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002614 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002615 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002616 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02002617 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002618 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2619 sce_net['vim_id'] = network_id
2620 auxNetDict['scenario'][sce_net['uuid']] = network_id
2621 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002622 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002623 else:
2624 if sce_net['vim_id'] == None:
2625 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2626 _, message = rollback(mydb, vims, rollbackList)
2627 logger.error("nfvo.start_scenario: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002628 raise NfvoException(error_text, httperrors.Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002629 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2630 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002631
tiernoae4a8d12016-07-08 12:30:39 +02002632 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2633 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002634
tiernoae4a8d12016-07-08 12:30:39 +02002635 for sce_vnf in scenarioDict['vnfs']:
2636 for net in sce_vnf['nets']:
2637 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002638
tiernoae4a8d12016-07-08 12:30:39 +02002639 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2640 myNetName = myNetName[0:255] #limit length
2641 myNetType = net['type']
2642 myNetDict = {}
2643 myNetDict["name"] = myNetName
2644 myNetDict["type"] = myNetType
2645 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002646 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002647 #print myNetDict
2648 #TODO:
2649 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02002650 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002651 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2652 net['vim_id'] = network_id
2653 if sce_vnf['uuid'] not in auxNetDict:
2654 auxNetDict[sce_vnf['uuid']] = {}
2655 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2656 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002657 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002658
tiernoae4a8d12016-07-08 12:30:39 +02002659 #print "auxNetDict:"
2660 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002661
tiernoae4a8d12016-07-08 12:30:39 +02002662 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2663 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2664 i = 0
2665 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002666 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002667 for vm in sce_vnf['vms']:
2668 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002669 if vm_av and vm_av not in vnf_availability_zones:
2670 vnf_availability_zones.append(vm_av)
2671
2672 # check if there is enough availability zones available at vim level.
2673 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2674 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002675 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno5a3273c2017-08-29 11:43:46 +02002676
tiernoae4a8d12016-07-08 12:30:39 +02002677 for vm in sce_vnf['vms']:
2678 i += 1
2679 myVMDict = {}
2680 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002681 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002682 #myVMDict['description'] = vm['description']
2683 myVMDict['description'] = myVMDict['name'][0:99]
2684 if not startvms:
2685 myVMDict['start'] = "no"
2686 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2687 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002688
tiernoae4a8d12016-07-08 12:30:39 +02002689 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002690 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002691 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002692 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002693
tiernoae4a8d12016-07-08 12:30:39 +02002694 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002695 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002696 if flavor_dict['extended']!=None:
2697 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002698 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002699 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002700
2701
tiernoae4a8d12016-07-08 12:30:39 +02002702 myVMDict['imageRef'] = vm['vim_image_id']
2703 myVMDict['flavorRef'] = vm['vim_flavor_id']
2704 myVMDict['networks'] = []
2705 for iface in vm['interfaces']:
2706 netDict = {}
2707 if iface['type']=="data":
2708 netDict['type'] = iface['model']
2709 elif "model" in iface and iface["model"]!=None:
2710 netDict['model']=iface['model']
2711 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2712 #discover type of interface looking at flavor
2713 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2714 for flavor_iface in numa.get('interfaces',[]):
2715 if flavor_iface.get('name') == iface['internal_name']:
2716 if flavor_iface['dedicated'] == 'yes':
2717 netDict['type']="PF" #passthrough
2718 elif flavor_iface['dedicated'] == 'no':
2719 netDict['type']="VF" #siov
2720 elif flavor_iface['dedicated'] == 'yes:sriov':
2721 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2722 netDict["mac_address"] = flavor_iface.get("mac_address")
2723 break;
2724 netDict["use"]=iface['type']
2725 if netDict["use"]=="data" and not netDict.get("type"):
2726 #print "netDict", netDict
2727 #print "iface", iface
2728 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'])
2729 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002730 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002731 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002732 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002733 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002734 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2735 netDict["type"]="virtual"
2736 if "vpci" in iface and iface["vpci"] is not None:
2737 netDict['vpci'] = iface['vpci']
2738 if "mac" in iface and iface["mac"] is not None:
2739 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002740 if "port-security" in iface and iface["port-security"] is not None:
2741 netDict['port_security'] = iface['port-security']
2742 if "floating-ip" in iface and iface["floating-ip"] is not None:
2743 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002744 netDict['name'] = iface['internal_name']
2745 if iface['net_id'] is None:
2746 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002747 #print iface
2748 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002749 if vnf_iface['interface_id']==iface['uuid']:
2750 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2751 break
2752 else:
2753 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2754 #skip bridge ifaces not connected to any net
2755 #if 'net_id' not in netDict or netDict['net_id']==None:
2756 # continue
2757 myVMDict['networks'].append(netDict)
2758 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2759 #print myVMDict['name']
2760 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2761 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2762 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002763
2764 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002765 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002766 else:
tierno5a3273c2017-08-29 11:43:46 +02002767 av_index = None
mirabal29356312017-07-27 12:21:22 +02002768
tierno98e909c2017-10-14 13:27:03 +02002769 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002770 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002771 availability_zone_index=av_index,
2772 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002773 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2774 vm['vim_id'] = vm_id
2775 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2776 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2777 for net in myVMDict['networks']:
2778 if "vim_id" in net:
2779 for iface in vm['interfaces']:
2780 if net["name"]==iface["internal_name"]:
2781 iface["vim_id"]=net["vim_id"]
2782 break
tierno42026a02017-02-10 15:13:40 +01002783
tiernoae4a8d12016-07-08 12:30:39 +02002784 logger.debug("start scenario Deployment done")
2785 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2786 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002787 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2788 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002789
tiernof97fd272016-07-11 14:32:37 +02002790 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002791 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002792 if isinstance(e, db_base_Exception):
2793 error_text = "Exception at database"
2794 else:
2795 error_text = "Exception at VIM"
2796 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2797 #logger.error("start_scenario %s", error_text)
2798 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002799
tierno36c0b172017-01-12 18:32:28 +01002800def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002801 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002802 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002803 None is allowed
2804 """
tierno36c0b172017-01-12 18:32:28 +01002805 if not cloud_config_preserve and not cloud_config:
2806 return None
2807
2808 new_cloud_config = {"key-pairs":[], "users":[]}
2809 # key-pairs
2810 if cloud_config_preserve:
2811 for key in cloud_config_preserve.get("key-pairs", () ):
2812 if key not in new_cloud_config["key-pairs"]:
2813 new_cloud_config["key-pairs"].append(key)
2814 if cloud_config:
2815 for key in cloud_config.get("key-pairs", () ):
2816 if key not in new_cloud_config["key-pairs"]:
2817 new_cloud_config["key-pairs"].append(key)
2818 if not new_cloud_config["key-pairs"]:
2819 del new_cloud_config["key-pairs"]
2820
2821 # users
2822 if cloud_config:
2823 new_cloud_config["users"] += cloud_config.get("users", () )
2824 if cloud_config_preserve:
2825 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002826 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002827 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002828 for index0 in range(0,len(users)):
2829 if index0 in index_to_delete:
2830 continue
2831 for index1 in range(index0+1,len(users)):
2832 if index1 in index_to_delete:
2833 continue
2834 if users[index0]["name"] == users[index1]["name"]:
2835 index_to_delete.append(index1)
2836 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002837 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002838 users[index0]["key-pairs"] = [key]
2839 elif key not in users[index0]["key-pairs"]:
2840 users[index0]["key-pairs"].append(key)
2841 index_to_delete.sort(reverse=True)
2842 for index in index_to_delete:
2843 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002844 if not new_cloud_config["users"]:
2845 del new_cloud_config["users"]
2846
2847 #boot-data-drive
2848 if cloud_config and cloud_config.get("boot-data-drive") != None:
2849 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2850 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2851 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2852
2853 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002854 new_cloud_config["user-data"] = []
2855 if cloud_config and cloud_config.get("user-data"):
2856 if isinstance(cloud_config["user-data"], list):
2857 new_cloud_config["user-data"] += cloud_config["user-data"]
2858 else:
2859 new_cloud_config["user-data"].append(cloud_config["user-data"])
2860 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2861 if isinstance(cloud_config_preserve["user-data"], list):
2862 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2863 else:
2864 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2865 if not new_cloud_config["user-data"]:
2866 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002867
2868 # config files
2869 new_cloud_config["config-files"] = []
2870 if cloud_config and cloud_config.get("config-files") != None:
2871 new_cloud_config["config-files"] += cloud_config["config-files"]
2872 if cloud_config_preserve:
2873 for file in cloud_config_preserve.get("config-files", ()):
2874 for index in range(0, len(new_cloud_config["config-files"])):
2875 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2876 new_cloud_config["config-files"][index] = file
2877 break
2878 else:
2879 new_cloud_config["config-files"].append(file)
2880 if not new_cloud_config["config-files"]:
2881 del new_cloud_config["config-files"]
2882 return new_cloud_config
2883
2884
tierno867ffe92017-03-27 12:50:34 +02002885def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002886 datacenter_id = None
2887 datacenter_name = None
2888 thread = None
tierno867ffe92017-03-27 12:50:34 +02002889 try:
2890 if datacenter_tenant_id:
2891 thread_id = datacenter_tenant_id
2892 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002893 else:
tierno867ffe92017-03-27 12:50:34 +02002894 where_={"td.nfvo_tenant_id": tenant_id}
2895 if datacenter_id_name:
2896 if utils.check_valid_uuid(datacenter_id_name):
2897 datacenter_id = datacenter_id_name
2898 where_["dt.datacenter_id"] = datacenter_id
2899 else:
2900 datacenter_name = datacenter_id_name
2901 where_["d.name"] = datacenter_name
2902 if datacenter_tenant_id:
2903 where_["dt.uuid"] = datacenter_tenant_id
2904 datacenters = mydb.get_rows(
2905 SELECT=("dt.uuid as datacenter_tenant_id",),
2906 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2907 "join datacenters as d on d.uuid=dt.datacenter_id",
2908 WHERE=where_)
2909 if len(datacenters) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002910 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tierno867ffe92017-03-27 12:50:34 +02002911 elif datacenters:
2912 thread_id = datacenters[0]["datacenter_tenant_id"]
2913 thread = vim_threads["running"].get(thread_id)
2914 if not thread:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002915 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tierno867ffe92017-03-27 12:50:34 +02002916 return thread_id, thread
2917 except db_base_Exception as e:
2918 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002919
tiernof5755962017-07-13 15:44:34 +02002920
tiernoa15c4b92017-10-05 12:41:44 +02002921def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2922 WHERE_dict={}
2923 if utils.check_valid_uuid(datacenter_id_name):
2924 WHERE_dict['d.uuid'] = datacenter_id_name
2925 else:
2926 WHERE_dict['d.name'] = datacenter_id_name
2927
2928 if tenant_id:
2929 WHERE_dict['nfvo_tenant_id'] = tenant_id
2930 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2931 " dt on td.datacenter_tenant_id=dt.uuid"
2932 else:
2933 from_ = 'datacenters as d'
tiernod3750b32018-07-20 15:33:08 +02002934 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid, d.name as name",), WHERE=WHERE_dict )
tiernoa15c4b92017-10-05 12:41:44 +02002935 if len(vimaccounts) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002936 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernoa15c4b92017-10-05 12:41:44 +02002937 elif len(vimaccounts)>1:
2938 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002939 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02002940 return vimaccounts[0]["uuid"], vimaccounts[0]["name"]
tiernoa15c4b92017-10-05 12:41:44 +02002941
2942
tiernoa2793912016-10-04 08:15:08 +00002943def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002944 datacenter_id = None
2945 datacenter_name = None
2946 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002947 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02002948 datacenter_id = datacenter_id_name
2949 else:
2950 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00002951 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02002952 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002953 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
tiernobe41e222016-09-02 15:16:13 +02002954 elif len(vims)>1:
2955 #print "nfvo.datacenter_action() error. Several datacenters found"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01002956 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
tiernobe41e222016-09-02 15:16:13 +02002957 return vims.keys()[0], vims.values()[0]
2958
tiernob3d36742017-03-03 23:51:05 +01002959
garciadeblas9f8456e2016-09-05 05:02:59 +02002960def update(d, u):
2961 '''Takes dict d and updates it with the values in dict u.'''
2962 '''It merges all depth levels'''
2963 for k, v in u.iteritems():
2964 if isinstance(v, collections.Mapping):
2965 r = update(d.get(k, {}), v)
2966 d[k] = r
2967 else:
2968 d[k] = u[k]
2969 return d
2970
tierno16e3dd42018-04-24 12:52:40 +02002971
tierno7edb6752016-03-21 17:37:52 +01002972def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01002973 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2974 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01002975 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01002976
tierno868220c2017-09-26 00:11:05 +02002977 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02002978 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02002979 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01002980 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02002981 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
2982 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02002983 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02002984 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02002985 # myvim_tenant = myvim['tenant_id']
tierno16e3dd42018-04-24 12:52:40 +02002986 rollbackList = []
tierno42026a02017-02-10 15:13:40 +01002987
tierno868220c2017-09-26 00:11:05 +02002988 # print "Checking that the scenario exists and getting the scenario dictionary"
tierno7fe82642018-11-26 14:14:51 +00002989 if isinstance(scenario, str):
2990 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
2991 datacenter_id=default_datacenter_id)
2992 else:
2993 scenarioDict = scenario
2994 scenarioDict["uuid"] = None
tierno42026a02017-02-10 15:13:40 +01002995
tierno868220c2017-09-26 00:11:05 +02002996 # logger.debug(">>>>>> Dictionaries before merging")
2997 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
2998 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01002999
tierno868220c2017-09-26 00:11:05 +02003000 db_instance_vnfs = []
3001 db_instance_vms = []
3002 db_instance_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00003003 db_instance_sfis = []
3004 db_instance_sfs = []
3005 db_instance_classifications = []
3006 db_instance_sfps = []
tierno868220c2017-09-26 00:11:05 +02003007 db_ip_profiles = []
3008 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02003009 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02003010 task_index = 0
tierno8e690322017-08-10 15:58:50 +02003011 instance_name = instance_dict["name"]
3012 instance_uuid = str(uuid4())
3013 uuid_list.append(instance_uuid)
3014 db_instance_scenario = {
3015 "uuid": instance_uuid,
3016 "name": instance_name,
3017 "tenant_id": tenant_id,
3018 "scenario_id": scenarioDict['uuid'],
3019 "datacenter_id": default_datacenter_id,
3020 # filled bellow 'datacenter_tenant_id'
3021 "description": instance_dict.get("description"),
3022 }
tierno8e690322017-08-10 15:58:50 +02003023 if scenarioDict.get("cloud-config"):
3024 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
3025 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003026 instance_action_id = get_task_id()
3027 db_instance_action = {
3028 "uuid": instance_action_id, # same uuid for the instance and the action on create
3029 "tenant_id": tenant_id,
3030 "instance_id": instance_uuid,
3031 "description": "CREATE",
3032 }
garciadeblas9f8456e2016-09-05 05:02:59 +02003033
tierno868220c2017-09-26 00:11:05 +02003034 # Auxiliary dictionaries from x to y
tierno8e690322017-08-10 15:58:50 +02003035 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02003036 net2task_id = {'scenario': {}}
tierno42026a02017-02-10 15:13:40 +01003037
tierno1df468d2018-07-06 14:25:16 +02003038 def ip_profile_IM2RO(ip_profile_im):
3039 # translate from input format to database format
3040 ip_profile_ro = {}
3041 if 'subnet-address' in ip_profile_im:
3042 ip_profile_ro['subnet_address'] = ip_profile_im['subnet-address']
3043 if 'ip-version' in ip_profile_im:
3044 ip_profile_ro['ip_version'] = ip_profile_im['ip-version']
3045 if 'gateway-address' in ip_profile_im:
3046 ip_profile_ro['gateway_address'] = ip_profile_im['gateway-address']
3047 if 'dns-address' in ip_profile_im:
3048 ip_profile_ro['dns_address'] = ip_profile_im['dns-address']
3049 if isinstance(ip_profile_ro['dns_address'], (list, tuple)):
3050 ip_profile_ro['dns_address'] = ";".join(ip_profile_ro['dns_address'])
3051 if 'dhcp' in ip_profile_im:
3052 ip_profile_ro['dhcp_start_address'] = ip_profile_im['dhcp'].get('start-address')
3053 ip_profile_ro['dhcp_enabled'] = ip_profile_im['dhcp'].get('enabled', True)
3054 ip_profile_ro['dhcp_count'] = ip_profile_im['dhcp'].get('count')
3055 return ip_profile_ro
3056
tierno868220c2017-09-26 00:11:05 +02003057 # logger.debug("Creating instance from scenario-dict:\n%s",
3058 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01003059 try:
tiernob3d36742017-03-03 23:51:05 +01003060 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02003061 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003062 for scenario_net in scenarioDict['nets']:
tierno1df468d2018-07-06 14:25:16 +02003063 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 +01003064 break
tierno1df468d2018-07-06 14:25:16 +02003065 else:
3066 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003067 httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003068 if "sites" not in net_instance_desc:
3069 net_instance_desc["sites"] = [ {} ]
3070 site_without_datacenter_field = False
3071 for site in net_instance_desc["sites"]:
3072 if site.get("datacenter"):
tiernod3750b32018-07-20 15:33:08 +02003073 site["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003074 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02003075 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02003076 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
3077 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003078 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
3079 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02003080 else:
3081 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02003082 raise NfvoException("Found more than one entries without datacenter field at "
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003083 "instance:networks:{}:sites".format(net_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003084 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02003085 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01003086
tiernobe41e222016-09-02 15:16:13 +02003087 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01003088 for scenario_vnf in scenarioDict['vnfs']:
tierno1df468d2018-07-06 14:25:16 +02003089 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 +01003090 break
tierno1df468d2018-07-06 14:25:16 +02003091 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003092 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name), httperrors.Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02003093 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02003094 # Add this datacenter to myvims
tiernod3750b32018-07-20 15:33:08 +02003095 vnf_instance_desc["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02003096 if vnf_instance_desc["datacenter"] not in myvims:
3097 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3098 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02003099 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00003100 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01003101
tierno1df468d2018-07-06 14:25:16 +02003102 for net_id, net_instance_desc in vnf_instance_desc.get("networks", {}).iteritems():
3103 for scenario_net in scenario_vnf['nets']:
3104 if net_id == scenario_net['osm_id'] or net_id == scenario_net['uuid'] or net_id == scenario_net["name"]:
3105 break
3106 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003107 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003108 if net_instance_desc.get("vim-network-name"):
3109 scenario_net["vim-network-name"] = net_instance_desc["vim-network-name"]
3110 if net_instance_desc.get("name"):
3111 scenario_net["name"] = net_instance_desc["name"]
3112 if 'ip-profile' in net_instance_desc:
3113 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3114 if 'ip_profile' not in scenario_net:
3115 scenario_net['ip_profile'] = ipprofile_db
3116 else:
3117 update(scenario_net['ip_profile'], ipprofile_db)
3118
3119 for vdu_id, vdu_instance_desc in vnf_instance_desc.get("vdus", {}).iteritems():
3120 for scenario_vm in scenario_vnf['vms']:
3121 if vdu_id == scenario_vm['osm_id'] or vdu_id == scenario_vm["name"]:
3122 break
3123 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003124 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003125 scenario_vm["instance_parameters"] = vdu_instance_desc
3126 for iface_id, iface_instance_desc in vdu_instance_desc.get("interfaces", {}).iteritems():
3127 for scenario_interface in scenario_vm['interfaces']:
3128 if iface_id == scenario_interface['internal_name'] or iface_id == scenario_interface["external_name"]:
3129 scenario_interface.update(iface_instance_desc)
3130 break
3131 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003132 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
tierno1df468d2018-07-06 14:25:16 +02003133
tierno868220c2017-09-26 00:11:05 +02003134 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01003135 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02003136
tierno868220c2017-09-26 00:11:05 +02003137 # 0.2 merge instance information into scenario
3138 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3139 # However, this is not possible yet.
tierno41a69812018-02-16 14:34:33 +01003140 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
garciadeblas9f8456e2016-09-05 05:02:59 +02003141 for scenario_net in scenarioDict['nets']:
3142 if net_name == scenario_net["name"]:
3143 if 'ip-profile' in net_instance_desc:
tierno1df468d2018-07-06 14:25:16 +02003144 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
garciadeblasedca7b32016-09-29 14:01:52 +00003145 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02003146 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00003147 else:
tierno455612d2017-05-30 16:40:10 +02003148 update(scenario_net['ip_profile'], ipprofile_db)
tierno41a69812018-02-16 14:34:33 +01003149 for interface in net_instance_desc.get('interfaces', ()):
garciadeblas9f8456e2016-09-05 05:02:59 +02003150 if 'ip_address' in interface:
3151 for vnf in scenarioDict['vnfs']:
3152 if interface['vnf'] == vnf['name']:
3153 for vnf_interface in vnf['interfaces']:
3154 if interface['vnf_interface'] == vnf_interface['external_name']:
tierno41a69812018-02-16 14:34:33 +01003155 vnf_interface['ip_address'] = interface['ip_address']
garciadeblas9f8456e2016-09-05 05:02:59 +02003156
tierno868220c2017-09-26 00:11:05 +02003157 # logger.debug(">>>>>>>> Merged dictionary")
3158 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3159 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02003160
tiernob3d36742017-03-03 23:51:05 +01003161 # 1. Creating new nets (sce_nets) in the VIM"
tierno8f79ea12018-05-03 17:37:40 +02003162 number_mgmt_networks = 0
tierno8e690322017-08-10 15:58:50 +02003163 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01003164 for sce_net in scenarioDict['nets']:
tierno7fe82642018-11-26 14:14:51 +00003165 sce_net_uuid = sce_net.get('uuid', sce_net["name"])
tierno1df468d2018-07-06 14:25:16 +02003166 # get involved datacenters where this network need to be created
3167 involved_datacenters = []
tierno7fe82642018-11-26 14:14:51 +00003168 for sce_vnf in scenarioDict.get("vnfs", ()):
tierno1df468d2018-07-06 14:25:16 +02003169 vnf_datacenter = sce_vnf.get("datacenter", default_datacenter_id)
3170 if vnf_datacenter in involved_datacenters:
3171 continue
3172 if sce_vnf.get("interfaces"):
3173 for sce_vnf_ifaces in sce_vnf["interfaces"]:
3174 if sce_vnf_ifaces.get("sce_net_id") == sce_net["uuid"]:
3175 involved_datacenters.append(vnf_datacenter)
3176 break
gcalvinod6fac4d2018-11-05 10:42:06 +01003177 if not involved_datacenters:
3178 involved_datacenters.append(default_datacenter_id)
tierno1df468d2018-07-06 14:25:16 +02003179
3180 descriptor_net = {}
3181 if instance_dict.get("networks") and instance_dict["networks"].get(sce_net["name"]):
3182 descriptor_net = instance_dict["networks"][sce_net["name"]]
tiernobe41e222016-09-02 15:16:13 +02003183 net_name = descriptor_net.get("vim-network-name")
tierno7fe82642018-11-26 14:14:51 +00003184 # add datacenters from instantiation parameters
3185 if descriptor_net.get("sites"):
3186 for site in descriptor_net["sites"]:
3187 if site.get("datacenter") and site["datacenter"] not in involved_datacenters:
3188 involved_datacenters.append(site["datacenter"])
3189 sce_net2instance[sce_net_uuid] = {}
3190 net2task_id['scenario'][sce_net_uuid] = {}
tiernobe41e222016-09-02 15:16:13 +02003191
tierno1df468d2018-07-06 14:25:16 +02003192 if sce_net["external"]:
3193 number_mgmt_networks += 1
3194
3195 for datacenter_id in involved_datacenters:
3196 netmap_use = None
3197 netmap_create = None
3198 if descriptor_net.get("sites"):
3199 for site in descriptor_net["sites"]:
3200 if site.get("datacenter") == datacenter_id:
3201 netmap_use = site.get("netmap-use")
3202 netmap_create = site.get("netmap-create")
3203 break
3204
3205 vim = myvims[datacenter_id]
3206 myvim_thread_id = myvim_threads_id[datacenter_id]
3207
tiernobe41e222016-09-02 15:16:13 +02003208 net_type = sce_net['type']
tiernob6990792018-11-13 10:37:42 +01003209 net_vim_name = None
tierno868220c2017-09-26 00:11:05 +02003210 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01003211
tiernof1ba57e2017-09-07 12:23:19 +02003212 if not net_name:
3213 if sce_net["external"]:
3214 net_name = sce_net["name"]
3215 else:
tierno1df468d2018-07-06 14:25:16 +02003216 net_name = "{}-{}".format(instance_name, sce_net["name"])
tiernof1ba57e2017-09-07 12:23:19 +02003217 net_name = net_name[:255] # limit length
3218
tierno1df468d2018-07-06 14:25:16 +02003219 if netmap_use or netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003220 create_network = False
3221 lookfor_network = False
tierno1df468d2018-07-06 14:25:16 +02003222 if netmap_use:
tiernof1ba57e2017-09-07 12:23:19 +02003223 lookfor_network = True
tierno1df468d2018-07-06 14:25:16 +02003224 if utils.check_valid_uuid(netmap_use):
3225 lookfor_filter["id"] = netmap_use
tiernof1ba57e2017-09-07 12:23:19 +02003226 else:
tierno1df468d2018-07-06 14:25:16 +02003227 lookfor_filter["name"] = netmap_use
3228 if netmap_create:
tiernof1ba57e2017-09-07 12:23:19 +02003229 create_network = True
3230 net_vim_name = net_name
tierno1df468d2018-07-06 14:25:16 +02003231 if isinstance(netmap_create, str):
3232 net_vim_name = netmap_create
tierno8f79ea12018-05-03 17:37:40 +02003233 elif sce_net.get("vim_network_name"):
3234 create_network = False
3235 lookfor_network = True
3236 lookfor_filter["name"] = sce_net.get("vim_network_name")
tiernof1ba57e2017-09-07 12:23:19 +02003237 elif sce_net["external"]:
tierno1df468d2018-07-06 14:25:16 +02003238 if sce_net['vim_id'] is not None:
tierno868220c2017-09-26 00:11:05 +02003239 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02003240 create_network = False
3241 lookfor_network = True
3242 lookfor_filter["id"] = sce_net['vim_id']
tierno8f79ea12018-05-03 17:37:40 +02003243 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3244 if number_mgmt_networks > 1:
3245 raise NfvoException("Found several VLD of type mgmt. "
3246 "You must concrete what vim-network must be use for each one",
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003247 httperrors.Bad_Request)
tierno8f79ea12018-05-03 17:37:40 +02003248 create_network = False
3249 lookfor_network = True
3250 if vim["config"].get("management_network_id"):
3251 lookfor_filter["id"] = vim["config"]["management_network_id"]
3252 else:
3253 lookfor_filter["name"] = vim["config"]["management_network_name"]
tiernobe41e222016-09-02 15:16:13 +02003254 else:
tierno868220c2017-09-26 00:11:05 +02003255 # 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 +02003256 create_network = True
3257 lookfor_network = True
3258 lookfor_filter["name"] = sce_net["name"]
3259 net_vim_name = sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01003260 else:
tiernobe41e222016-09-02 15:16:13 +02003261 net_vim_name = net_name
3262 create_network = True
3263 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01003264
tiernof1450872017-10-17 23:15:08 +02003265 task_extra = {}
3266 if create_network:
3267 task_action = "CREATE"
3268 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None))
3269 if lookfor_network:
3270 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02003271 elif lookfor_network:
3272 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02003273 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01003274
tierno8e690322017-08-10 15:58:50 +02003275 # fill database content
3276 net_uuid = str(uuid4())
3277 uuid_list.append(net_uuid)
tierno7fe82642018-11-26 14:14:51 +00003278 sce_net2instance[sce_net_uuid][datacenter_id] = net_uuid
tierno8e690322017-08-10 15:58:50 +02003279 db_net = {
3280 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02003281 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003282 "vim_name": net_vim_name,
tierno8e690322017-08-10 15:58:50 +02003283 "instance_scenario_id": instance_uuid,
tierno7fe82642018-11-26 14:14:51 +00003284 "sce_net_id": sce_net.get("uuid"),
tierno8e690322017-08-10 15:58:50 +02003285 "created": create_network,
3286 'datacenter_id': datacenter_id,
3287 'datacenter_tenant_id': myvim_thread_id,
tiernod2836fc2018-05-30 15:03:27 +02003288 'status': 'BUILD' # if create_network else "ACTIVE"
tierno8e690322017-08-10 15:58:50 +02003289 }
3290 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003291 db_vim_action = {
3292 "instance_action_id": instance_action_id,
3293 "status": "SCHEDULED",
3294 "task_index": task_index,
3295 "datacenter_vim_id": myvim_thread_id,
3296 "action": task_action,
3297 "item": "instance_nets",
3298 "item_id": net_uuid,
tiernof1450872017-10-17 23:15:08 +02003299 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003300 }
tierno7fe82642018-11-26 14:14:51 +00003301 net2task_id['scenario'][sce_net_uuid][datacenter_id] = task_index
tierno868220c2017-09-26 00:11:05 +02003302 task_index += 1
3303 db_vim_actions.append(db_vim_action)
3304
tierno8e690322017-08-10 15:58:50 +02003305 if 'ip_profile' in sce_net:
3306 db_ip_profile={
3307 'instance_net_id': net_uuid,
3308 'ip_version': sce_net['ip_profile']['ip_version'],
3309 'subnet_address': sce_net['ip_profile']['subnet_address'],
3310 'gateway_address': sce_net['ip_profile']['gateway_address'],
3311 'dns_address': sce_net['ip_profile']['dns_address'],
3312 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3313 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3314 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3315 }
3316 db_ip_profiles.append(db_ip_profile)
3317
tierno16e3dd42018-04-24 12:52:40 +02003318 # Create VNFs
3319 vnf_params = {
3320 "default_datacenter_id": default_datacenter_id,
3321 "myvim_threads_id": myvim_threads_id,
3322 "instance_uuid": instance_uuid,
3323 "instance_name": instance_name,
3324 "instance_action_id": instance_action_id,
3325 "myvims": myvims,
3326 "cloud_config": cloud_config,
3327 "RO_pub_key": tenant[0].get('RO_pub_key'),
tierno67881db2018-10-24 18:46:03 +02003328 "instance_parameters": instance_dict,
tierno16e3dd42018-04-24 12:52:40 +02003329 }
3330 vnf_params_out = {
3331 "task_index": task_index,
3332 "uuid_list": uuid_list,
3333 "db_instance_nets": db_instance_nets,
3334 "db_vim_actions": db_vim_actions,
3335 "db_ip_profiles": db_ip_profiles,
3336 "db_instance_vnfs": db_instance_vnfs,
3337 "db_instance_vms": db_instance_vms,
3338 "db_instance_interfaces": db_instance_interfaces,
3339 "net2task_id": net2task_id,
3340 "sce_net2instance": sce_net2instance,
3341 }
tierno55d234c2018-07-04 18:29:21 +02003342 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
tierno7fe82642018-11-26 14:14:51 +00003343 for sce_vnf in scenarioDict.get('vnfs', ()): # sce_vnf_list:
tierno16e3dd42018-04-24 12:52:40 +02003344 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3345 task_index = vnf_params_out["task_index"]
3346 uuid_list = vnf_params_out["uuid_list"]
mirabal29356312017-07-27 12:21:22 +02003347
tierno16e3dd42018-04-24 12:52:40 +02003348 # Create VNFFGs
3349 # task_depends_on = []
tierno7fe82642018-11-26 14:14:51 +00003350 for vnffg in scenarioDict.get('vnffgs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003351 for rsp in vnffg['rsps']:
3352 sfs_created = []
3353 for cp in rsp['connection_points']:
3354 count = mydb.get_rows(
3355 SELECT=('vms.count'),
3356 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h on interfaces.uuid=h.interface_id",
3357 WHERE={'h.uuid': cp['uuid']})[0]['count']
3358 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3359 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3360 dependencies = []
3361 for instance_vm in instance_vms:
3362 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3363 if action:
3364 dependencies.append(action['task_index'])
3365 # TODO: throw exception if count != len(instance_vms)
3366 # TODO: and action shouldn't ever be None
3367 sfis_created = []
3368 for i in range(count):
3369 # create sfis
3370 sfi_uuid = str(uuid4())
3371 uuid_list.append(sfi_uuid)
3372 db_sfi = {
3373 "uuid": sfi_uuid,
3374 "instance_scenario_id": instance_uuid,
3375 'sce_rsp_hop_id': cp['uuid'],
3376 'datacenter_id': datacenter_id,
3377 'datacenter_tenant_id': myvim_thread_id,
3378 "vim_sfi_id": None, # vim thread will populate
3379 }
3380 db_instance_sfis.append(db_sfi)
3381 db_vim_action = {
3382 "instance_action_id": instance_action_id,
3383 "task_index": task_index,
3384 "datacenter_vim_id": myvim_thread_id,
3385 "action": "CREATE",
3386 "status": "SCHEDULED",
3387 "item": "instance_sfis",
3388 "item_id": sfi_uuid,
3389 "extra": yaml.safe_dump({"params": "", "depends_on": [dependencies[i]]},
3390 default_flow_style=True, width=256)
3391 }
3392 sfis_created.append(task_index)
3393 task_index += 1
3394 db_vim_actions.append(db_vim_action)
3395 # create sfs
3396 sf_uuid = str(uuid4())
3397 uuid_list.append(sf_uuid)
3398 db_sf = {
3399 "uuid": sf_uuid,
3400 "instance_scenario_id": instance_uuid,
3401 'sce_rsp_hop_id': cp['uuid'],
3402 'datacenter_id': datacenter_id,
3403 'datacenter_tenant_id': myvim_thread_id,
3404 "vim_sf_id": None, # vim thread will populate
3405 }
3406 db_instance_sfs.append(db_sf)
3407 db_vim_action = {
3408 "instance_action_id": instance_action_id,
3409 "task_index": task_index,
3410 "datacenter_vim_id": myvim_thread_id,
3411 "action": "CREATE",
3412 "status": "SCHEDULED",
3413 "item": "instance_sfs",
3414 "item_id": sf_uuid,
3415 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3416 default_flow_style=True, width=256)
3417 }
3418 sfs_created.append(task_index)
3419 task_index += 1
3420 db_vim_actions.append(db_vim_action)
3421 classifier = rsp['classifier']
3422
3423 # TODO the following ~13 lines can be reused for the sfi case
3424 count = mydb.get_rows(
3425 SELECT=('vms.count'),
3426 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3427 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3428 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3429 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3430 dependencies = []
3431 for instance_vm in instance_vms:
3432 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3433 if action:
3434 dependencies.append(action['task_index'])
3435 # TODO: throw exception if count != len(instance_vms)
3436 # TODO: and action shouldn't ever be None
3437 classifications_created = []
3438 for i in range(count):
3439 for match in classifier['matches']:
3440 # create classifications
3441 classification_uuid = str(uuid4())
3442 uuid_list.append(classification_uuid)
3443 db_classification = {
3444 "uuid": classification_uuid,
3445 "instance_scenario_id": instance_uuid,
3446 'sce_classifier_match_id': match['uuid'],
3447 'datacenter_id': datacenter_id,
3448 'datacenter_tenant_id': myvim_thread_id,
3449 "vim_classification_id": None, # vim thread will populate
3450 }
3451 db_instance_classifications.append(db_classification)
3452 classification_params = {
3453 "ip_proto": match["ip_proto"],
3454 "source_ip": match["source_ip"],
3455 "destination_ip": match["destination_ip"],
3456 "source_port": match["source_port"],
3457 "destination_port": match["destination_port"]
3458 }
3459 db_vim_action = {
3460 "instance_action_id": instance_action_id,
3461 "task_index": task_index,
3462 "datacenter_vim_id": myvim_thread_id,
3463 "action": "CREATE",
3464 "status": "SCHEDULED",
3465 "item": "instance_classifications",
3466 "item_id": classification_uuid,
3467 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3468 default_flow_style=True, width=256)
3469 }
3470 classifications_created.append(task_index)
3471 task_index += 1
3472 db_vim_actions.append(db_vim_action)
3473
3474 # create sfps
3475 sfp_uuid = str(uuid4())
3476 uuid_list.append(sfp_uuid)
3477 db_sfp = {
3478 "uuid": sfp_uuid,
3479 "instance_scenario_id": instance_uuid,
3480 'sce_rsp_id': rsp['uuid'],
3481 'datacenter_id': datacenter_id,
3482 'datacenter_tenant_id': myvim_thread_id,
3483 "vim_sfp_id": None, # vim thread will populate
3484 }
3485 db_instance_sfps.append(db_sfp)
3486 db_vim_action = {
3487 "instance_action_id": instance_action_id,
3488 "task_index": task_index,
3489 "datacenter_vim_id": myvim_thread_id,
3490 "action": "CREATE",
3491 "status": "SCHEDULED",
3492 "item": "instance_sfps",
3493 "item_id": sfp_uuid,
3494 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3495 default_flow_style=True, width=256)
3496 }
3497 task_index += 1
3498 db_vim_actions.append(db_vim_action)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003499 db_instance_action["number_tasks"] = task_index
3500
3501 # --> WIM
3502 wan_links = wim_engine.derive_wan_links(db_instance_nets, tenant_id)
3503 wim_actions = wim_engine.create_actions(wan_links)
3504 wim_actions, db_instance_action = (
3505 wim_engine.incorporate_actions(wim_actions, db_instance_action))
3506 # <-- WIM
Igor D.Ccaadc442017-11-06 12:48:48 +00003507
tierno867ffe92017-03-27 12:50:34 +02003508 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003509
3510 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3511 db_instance_scenario['datacenter_id'] = default_datacenter_id
3512 db_tables=[
3513 {"instance_scenarios": db_instance_scenario},
3514 {"instance_vnfs": db_instance_vnfs},
3515 {"instance_nets": db_instance_nets},
3516 {"ip_profiles": db_ip_profiles},
3517 {"instance_vms": db_instance_vms},
3518 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003519 {"instance_actions": db_instance_action},
Igor D.Ccaadc442017-11-06 12:48:48 +00003520 {"instance_sfis": db_instance_sfis},
3521 {"instance_sfs": db_instance_sfs},
3522 {"instance_classifications": db_instance_classifications},
3523 {"instance_sfps": db_instance_sfps},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003524 {"instance_wim_nets": wan_links},
3525 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno8e690322017-08-10 15:58:50 +02003526 ]
3527
tierno868220c2017-09-26 00:11:05 +02003528 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003529 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3530 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003531 for myvim_thread_id in myvim_threads_id.values():
3532 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003533
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003534 wim_engine.dispatch(wim_actions)
3535
tierno868220c2017-09-26 00:11:05 +02003536 returned_instance = mydb.get_instance_scenario(instance_uuid)
3537 returned_instance["action_id"] = instance_action_id
3538 return returned_instance
3539 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003540 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003541 if isinstance(e, db_base_Exception):
3542 error_text = "database Exception"
3543 elif isinstance(e, vimconn.vimconnException):
3544 error_text = "VIM Exception"
3545 else:
3546 error_text = "Exception"
3547 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003548 # logger.error("create_instance: %s", error_text)
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003549 logger.exception(e)
tiernof97fd272016-07-11 14:32:37 +02003550 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003551
tiernob3d36742017-03-03 23:51:05 +01003552
tierno16e3dd42018-04-24 12:52:40 +02003553def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3554 default_datacenter_id = params["default_datacenter_id"]
3555 myvim_threads_id = params["myvim_threads_id"]
3556 instance_uuid = params["instance_uuid"]
3557 instance_name = params["instance_name"]
3558 instance_action_id = params["instance_action_id"]
3559 myvims = params["myvims"]
3560 cloud_config = params["cloud_config"]
3561 RO_pub_key = params["RO_pub_key"]
3562
3563 task_index = params_out["task_index"]
3564 uuid_list = params_out["uuid_list"]
3565 db_instance_nets = params_out["db_instance_nets"]
3566 db_vim_actions = params_out["db_vim_actions"]
3567 db_ip_profiles = params_out["db_ip_profiles"]
3568 db_instance_vnfs = params_out["db_instance_vnfs"]
3569 db_instance_vms = params_out["db_instance_vms"]
3570 db_instance_interfaces = params_out["db_instance_interfaces"]
3571 net2task_id = params_out["net2task_id"]
3572 sce_net2instance = params_out["sce_net2instance"]
3573
3574 vnf_net2instance = {}
3575
3576 # 2. Creating new nets (vnf internal nets) in the VIM"
3577 # For each vnf net, we create it and we add it to instanceNetlist.
3578 if sce_vnf.get("datacenter"):
3579 datacenter_id = sce_vnf["datacenter"]
3580 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3581 else:
3582 datacenter_id = default_datacenter_id
3583 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3584 for net in sce_vnf['nets']:
3585 # TODO revis
3586 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3587 # net_name = descriptor_net.get("name")
3588 net_name = None
3589 if not net_name:
tierno1df468d2018-07-06 14:25:16 +02003590 net_name = "{}-{}".format(instance_name, net["name"])
tierno16e3dd42018-04-24 12:52:40 +02003591 net_name = net_name[:255] # limit length
3592 net_type = net['type']
3593
3594 if sce_vnf['uuid'] not in vnf_net2instance:
3595 vnf_net2instance[sce_vnf['uuid']] = {}
3596 if sce_vnf['uuid'] not in net2task_id:
3597 net2task_id[sce_vnf['uuid']] = {}
3598 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3599
3600 # fill database content
3601 net_uuid = str(uuid4())
3602 uuid_list.append(net_uuid)
3603 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3604 db_net = {
3605 "uuid": net_uuid,
3606 'vim_net_id': None,
tiernob6990792018-11-13 10:37:42 +01003607 "vim_name": net_name,
tierno16e3dd42018-04-24 12:52:40 +02003608 "instance_scenario_id": instance_uuid,
3609 "net_id": net["uuid"],
3610 "created": True,
3611 'datacenter_id': datacenter_id,
3612 'datacenter_tenant_id': myvim_thread_id,
3613 }
3614 db_instance_nets.append(db_net)
3615
tierno1df468d2018-07-06 14:25:16 +02003616 if net.get("vim-network-name"):
3617 lookfor_filter = {"name": net["vim-network-name"]}
3618 task_action = "FIND"
3619 task_extra = {"params": (lookfor_filter,)}
3620 else:
3621 task_action = "CREATE"
3622 task_extra = {"params": (net_name, net_type, net.get('ip_profile', None))}
3623
tierno16e3dd42018-04-24 12:52:40 +02003624 db_vim_action = {
3625 "instance_action_id": instance_action_id,
3626 "task_index": task_index,
3627 "datacenter_vim_id": myvim_thread_id,
3628 "status": "SCHEDULED",
tierno1df468d2018-07-06 14:25:16 +02003629 "action": task_action,
tierno16e3dd42018-04-24 12:52:40 +02003630 "item": "instance_nets",
3631 "item_id": net_uuid,
tierno1df468d2018-07-06 14:25:16 +02003632 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno16e3dd42018-04-24 12:52:40 +02003633 }
3634 task_index += 1
3635 db_vim_actions.append(db_vim_action)
3636
3637 if 'ip_profile' in net:
3638 db_ip_profile = {
3639 'instance_net_id': net_uuid,
3640 'ip_version': net['ip_profile']['ip_version'],
3641 'subnet_address': net['ip_profile']['subnet_address'],
3642 'gateway_address': net['ip_profile']['gateway_address'],
3643 'dns_address': net['ip_profile']['dns_address'],
3644 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3645 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3646 'dhcp_count': net['ip_profile']['dhcp_count'],
3647 }
3648 db_ip_profiles.append(db_ip_profile)
3649
3650 # print "vnf_net2instance:"
3651 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3652
3653 # 3. Creating new vm instances in the VIM
3654 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3655 ssh_access = None
3656 if sce_vnf.get('mgmt_access'):
3657 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3658 vnf_availability_zones = []
gcalvinod6fac4d2018-11-05 10:42:06 +01003659 for vm in sce_vnf.get('vms'):
tierno16e3dd42018-04-24 12:52:40 +02003660 vm_av = vm.get('availability_zone')
3661 if vm_av and vm_av not in vnf_availability_zones:
3662 vnf_availability_zones.append(vm_av)
3663
3664 # check if there is enough availability zones available at vim level.
3665 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3666 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003667 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
tierno16e3dd42018-04-24 12:52:40 +02003668
3669 if sce_vnf.get("datacenter"):
3670 vim = myvims[sce_vnf["datacenter"]]
3671 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3672 datacenter_id = sce_vnf["datacenter"]
3673 else:
3674 vim = myvims[default_datacenter_id]
3675 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3676 datacenter_id = default_datacenter_id
3677 sce_vnf["datacenter_id"] = datacenter_id
3678 i = 0
3679
3680 vnf_uuid = str(uuid4())
3681 uuid_list.append(vnf_uuid)
3682 db_instance_vnf = {
3683 'uuid': vnf_uuid,
3684 'instance_scenario_id': instance_uuid,
3685 'vnf_id': sce_vnf['vnf_id'],
3686 'sce_vnf_id': sce_vnf['uuid'],
3687 'datacenter_id': datacenter_id,
3688 'datacenter_tenant_id': myvim_thread_id,
3689 }
3690 db_instance_vnfs.append(db_instance_vnf)
3691
3692 for vm in sce_vnf['vms']:
tiernob6990792018-11-13 10:37:42 +01003693 # skip PDUs
3694 if vm.get("pdu_type"):
3695 continue
3696
tierno16e3dd42018-04-24 12:52:40 +02003697 myVMDict = {}
tierno7f426e92018-06-28 15:21:32 +02003698 sce_vnf_name = sce_vnf['member_vnf_index'] if sce_vnf['member_vnf_index'] else sce_vnf['name']
3699 myVMDict['name'] = "{}-{}-{}".format(instance_name[:64], sce_vnf_name[:64], vm["name"][:64])
tierno16e3dd42018-04-24 12:52:40 +02003700 myVMDict['description'] = myVMDict['name'][0:99]
3701 # if not startvms:
3702 # myVMDict['start'] = "no"
tierno1df468d2018-07-06 14:25:16 +02003703 if vm.get("instance_parameters") and vm["instance_parameters"].get("name"):
3704 myVMDict['name'] = vm["instance_parameters"].get("name")
tierno16e3dd42018-04-24 12:52:40 +02003705 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3706 # create image at vim in case it not exist
3707 image_uuid = vm['image_id']
3708 if vm.get("image_list"):
3709 for alternative_image in vm["image_list"]:
tiernob6434212018-04-26 16:27:47 +02003710 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
tierno16e3dd42018-04-24 12:52:40 +02003711 image_uuid = alternative_image['image_id']
3712 break
3713 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
3714 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
3715 vm['vim_image_id'] = image_id
3716
3717 # create flavor at vim in case it not exist
3718 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
3719 if flavor_dict['extended'] != None:
3720 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
3721 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3722
3723 # Obtain information for additional disks
3724 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
3725 WHERE={'vim_id': flavor_id})
3726 if not extended_flavor_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003727 raise NfvoException("flavor '{}' not found".format(flavor_id), httperrors.Not_Found)
tierno16e3dd42018-04-24 12:52:40 +02003728
3729 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
3730 myVMDict['disks'] = None
3731 extended_info = extended_flavor_dict[0]['extended']
3732 if extended_info != None:
3733 extended_flavor_dict_yaml = yaml.load(extended_info)
3734 if 'disks' in extended_flavor_dict_yaml:
3735 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
tierno1df468d2018-07-06 14:25:16 +02003736 if vm.get("instance_parameters") and vm["instance_parameters"].get("devices"):
3737 for disk in myVMDict['disks']:
3738 if disk.get("name") in vm["instance_parameters"]["devices"]:
3739 disk.update(vm["instance_parameters"]["devices"][disk.get("name")])
tierno16e3dd42018-04-24 12:52:40 +02003740
3741 vm['vim_flavor_id'] = flavor_id
3742 myVMDict['imageRef'] = vm['vim_image_id']
3743 myVMDict['flavorRef'] = vm['vim_flavor_id']
3744 myVMDict['availability_zone'] = vm.get('availability_zone')
3745 myVMDict['networks'] = []
3746 task_depends_on = []
3747 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno67881db2018-10-24 18:46:03 +02003748 is_management_vm = False
tierno16e3dd42018-04-24 12:52:40 +02003749 db_vm_ifaces = []
3750 for iface in vm['interfaces']:
3751 netDict = {}
3752 if iface['type'] == "data":
3753 netDict['type'] = iface['model']
3754 elif "model" in iface and iface["model"] != None:
3755 netDict['model'] = iface['model']
3756 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3757 # is obtained from iterface table model
3758 # discover type of interface looking at flavor
3759 for numa in flavor_dict.get('extended', {}).get('numas', []):
3760 for flavor_iface in numa.get('interfaces', []):
3761 if flavor_iface.get('name') == iface['internal_name']:
3762 if flavor_iface['dedicated'] == 'yes':
3763 netDict['type'] = "PF" # passthrough
3764 elif flavor_iface['dedicated'] == 'no':
3765 netDict['type'] = "VF" # siov
3766 elif flavor_iface['dedicated'] == 'yes:sriov':
3767 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
3768 netDict["mac_address"] = flavor_iface.get("mac_address")
3769 break
3770 netDict["use"] = iface['type']
3771 if netDict["use"] == "data" and not netDict.get("type"):
3772 # print "netDict", netDict
3773 # print "iface", iface
3774 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3775 sce_vnf['name'], vm['name'], iface['internal_name'])
3776 if flavor_dict.get('extended') == None:
3777 raise NfvoException(e_text + "After database migration some information is not available. \
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003778 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
tierno16e3dd42018-04-24 12:52:40 +02003779 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003780 raise NfvoException(e_text, httperrors.Internal_Server_Error)
tierno67881db2018-10-24 18:46:03 +02003781 if netDict["use"] == "mgmt":
3782 is_management_vm = True
3783 netDict["type"] = "virtual"
3784 if netDict["use"] == "bridge":
tierno16e3dd42018-04-24 12:52:40 +02003785 netDict["type"] = "virtual"
3786 if iface.get("vpci"):
3787 netDict['vpci'] = iface['vpci']
3788 if iface.get("mac"):
3789 netDict['mac_address'] = iface['mac']
tierno6082b7d2018-08-31 11:24:08 +00003790 if iface.get("mac_address"):
3791 netDict['mac_address'] = iface['mac_address']
tierno16e3dd42018-04-24 12:52:40 +02003792 if iface.get("ip_address"):
3793 netDict['ip_address'] = iface['ip_address']
3794 if iface.get("port-security") is not None:
3795 netDict['port_security'] = iface['port-security']
3796 if iface.get("floating-ip") is not None:
3797 netDict['floating_ip'] = iface['floating-ip']
3798 netDict['name'] = iface['internal_name']
3799 if iface['net_id'] is None:
3800 for vnf_iface in sce_vnf["interfaces"]:
3801 # print iface
3802 # print vnf_iface
3803 if vnf_iface['interface_id'] == iface['uuid']:
3804 netDict['net_id'] = "TASK-{}".format(
3805 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3806 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
3807 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3808 break
3809 else:
3810 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
3811 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
3812 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
3813 # skip bridge ifaces not connected to any net
3814 if 'net_id' not in netDict or netDict['net_id'] == None:
3815 continue
3816 myVMDict['networks'].append(netDict)
3817 db_vm_iface = {
3818 # "uuid"
3819 # 'instance_vm_id': instance_vm_uuid,
3820 "instance_net_id": instance_net_id,
3821 'interface_id': iface['uuid'],
3822 # 'vim_interface_id': ,
3823 'type': 'external' if iface['external_name'] is not None else 'internal',
3824 'ip_address': iface.get('ip_address'),
3825 'mac_address': iface.get('mac'),
3826 'floating_ip': int(iface.get('floating-ip', False)),
3827 'port_security': int(iface.get('port-security', True))
3828 }
3829 db_vm_ifaces.append(db_vm_iface)
3830 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3831 # print myVMDict['name']
3832 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3833 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3834 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3835
3836 # We add the RO key to cloud_config if vnf will need ssh access
3837 cloud_config_vm = cloud_config
tierno67881db2018-10-24 18:46:03 +02003838 if is_management_vm and params["instance_parameters"].get("mgmt_keys"):
3839 cloud_config_vm = unify_cloud_config({"key-pairs": params["instance_parameters"]["mgmt_keys"]},
3840 cloud_config_vm)
3841
3842 if vm.get("instance_parameters") and vm["instance_parameters"].get("mgmt_keys"):
3843 cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
3844 cloud_config_vm)
3845 # if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3846 # RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3847 # cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
tierno16e3dd42018-04-24 12:52:40 +02003848 if vm.get("boot_data"):
3849 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3850
3851 if myVMDict.get('availability_zone'):
3852 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
3853 else:
3854 av_index = None
3855 for vm_index in range(0, vm.get('count', 1)):
tiernofc5f80b2018-05-29 16:00:43 +02003856 vm_name = myVMDict['name'] + "-" + str(vm_index+1)
3857 task_params = (vm_name, myVMDict['description'], myVMDict.get('start', None),
tierno16e3dd42018-04-24 12:52:40 +02003858 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3859 myVMDict['disks'], av_index, vnf_availability_zones)
3860 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3861 for net in myVMDict['networks']:
3862 if "vim_id" in net:
3863 for iface in vm['interfaces']:
3864 if net["name"] == iface["internal_name"]:
3865 iface["vim_id"] = net["vim_id"]
3866 break
3867 vm_uuid = str(uuid4())
3868 uuid_list.append(vm_uuid)
3869 db_vm = {
3870 "uuid": vm_uuid,
3871 'instance_vnf_id': vnf_uuid,
3872 # TODO delete "vim_vm_id": vm_id,
3873 "vm_id": vm["uuid"],
tiernofc5f80b2018-05-29 16:00:43 +02003874 "vim_name": vm_name,
tierno16e3dd42018-04-24 12:52:40 +02003875 # "status":
3876 }
3877 db_instance_vms.append(db_vm)
3878
3879 iface_index = 0
3880 for db_vm_iface in db_vm_ifaces:
3881 iface_uuid = str(uuid4())
3882 uuid_list.append(iface_uuid)
3883 db_vm_iface_instance = {
3884 "uuid": iface_uuid,
3885 "instance_vm_id": vm_uuid
3886 }
3887 db_vm_iface_instance.update(db_vm_iface)
3888 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3889 ip = db_vm_iface_instance.get("ip_address")
3890 i = ip.rfind(".")
3891 if i > 0:
3892 try:
3893 i += 1
3894 ip = ip[i:] + str(int(ip[:i]) + 1)
3895 db_vm_iface_instance["ip_address"] = ip
3896 except:
3897 db_vm_iface_instance["ip_address"] = None
3898 db_instance_interfaces.append(db_vm_iface_instance)
3899 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3900 iface_index += 1
3901
3902 db_vim_action = {
3903 "instance_action_id": instance_action_id,
3904 "task_index": task_index,
3905 "datacenter_vim_id": myvim_thread_id,
3906 "action": "CREATE",
3907 "status": "SCHEDULED",
3908 "item": "instance_vms",
3909 "item_id": vm_uuid,
3910 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3911 default_flow_style=True, width=256)
3912 }
3913 task_index += 1
3914 db_vim_actions.append(db_vim_action)
3915 params_out["task_index"] = task_index
3916 params_out["uuid_list"] = uuid_list
3917
3918
tierno7edb6752016-03-21 17:37:52 +01003919def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02003920 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003921 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02003922 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01003923 tenant_id = instanceDict["tenant_id"]
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01003924
3925 # --> WIM
3926 # We need to retrieve the WIM Actions now, before the instance_scenario is
3927 # deleted. The reason for that is that: ON CASCADE rules will delete the
3928 # instance_wim_nets record in the database
3929 wim_actions = wim_engine.delete_actions(instance_scenario_id=instance_id)
3930 # <-- WIM
3931
tierno868220c2017-09-26 00:11:05 +02003932 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno868220c2017-09-26 00:11:05 +02003933 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02003934 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003935
tierno868220c2017-09-26 00:11:05 +02003936 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00003937 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01003938 myvims = {}
3939 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02003940 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02003941 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01003942
tierno868220c2017-09-26 00:11:05 +02003943 task_index = 0
3944 instance_action_id = get_task_id()
3945 db_vim_actions = []
3946 db_instance_action = {
3947 "uuid": instance_action_id, # same uuid for the instance and the action on create
3948 "tenant_id": tenant_id,
3949 "instance_id": instance_id,
3950 "description": "DELETE",
3951 # "number_tasks": 0 # filled bellow
3952 }
3953
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01003954 # 2.1 deleting VNFFGs
tierno69b590e2018-03-13 18:52:23 +01003955 for sfp in instanceDict.get('sfps', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003956 vimthread_affected[sfp["datacenter_tenant_id"]] = None
3957 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
3958 if datacenter_key not in myvims:
3959 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01003960 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00003961 except NfvoException as e:
3962 logger.error(str(e))
3963 myvim_thread = None
3964 myvim_threads[datacenter_key] = myvim_thread
3965 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
3966 datacenter_tenant_id=sfp["datacenter_tenant_id"])
3967 if len(vims) == 0:
3968 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
3969 myvims[datacenter_key] = None
3970 else:
3971 myvims[datacenter_key] = vims.values()[0]
3972 myvim = myvims[datacenter_key]
3973 myvim_thread = myvim_threads[datacenter_key]
3974
3975 if not myvim:
3976 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
3977 continue
3978 extra = {"params": (sfp['vim_sfp_id'])}
3979 db_vim_action = {
3980 "instance_action_id": instance_action_id,
3981 "task_index": task_index,
3982 "datacenter_vim_id": sfp["datacenter_tenant_id"],
3983 "action": "DELETE",
3984 "status": "SCHEDULED",
3985 "item": "instance_sfps",
3986 "item_id": sfp["uuid"],
3987 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3988 }
3989 task_index += 1
3990 db_vim_actions.append(db_vim_action)
3991
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01003992 for classification in instanceDict['classifications']:
3993 vimthread_affected[classification["datacenter_tenant_id"]] = None
3994 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
3995 if datacenter_key not in myvims:
3996 try:
3997 _, myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
3998 except NfvoException as e:
3999 logger.error(str(e))
4000 myvim_thread = None
4001 myvim_threads[datacenter_key] = myvim_thread
4002 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
4003 datacenter_tenant_id=classification["datacenter_tenant_id"])
4004 if len(vims) == 0:
4005 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"],
4006 classification["datacenter_tenant_id"]))
4007 myvims[datacenter_key] = None
4008 else:
4009 myvims[datacenter_key] = vims.values()[0]
4010 myvim = myvims[datacenter_key]
4011 myvim_thread = myvim_threads[datacenter_key]
4012
4013 if not myvim:
4014 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'],
4015 classification["datacenter_id"])
4016 continue
4017 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4018 extra = {"params": (classification['vim_classification_id']), "depends_on": depends_on}
4019 db_vim_action = {
4020 "instance_action_id": instance_action_id,
4021 "task_index": task_index,
4022 "datacenter_vim_id": classification["datacenter_tenant_id"],
4023 "action": "DELETE",
4024 "status": "SCHEDULED",
4025 "item": "instance_classifications",
4026 "item_id": classification["uuid"],
4027 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4028 }
4029 task_index += 1
4030 db_vim_actions.append(db_vim_action)
4031
tierno69b590e2018-03-13 18:52:23 +01004032 for sf in instanceDict.get('sfs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004033 vimthread_affected[sf["datacenter_tenant_id"]] = None
4034 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
4035 if datacenter_key not in myvims:
4036 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004037 _, myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004038 except NfvoException as e:
4039 logger.error(str(e))
4040 myvim_thread = None
4041 myvim_threads[datacenter_key] = myvim_thread
4042 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
4043 datacenter_tenant_id=sf["datacenter_tenant_id"])
4044 if len(vims) == 0:
4045 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
4046 myvims[datacenter_key] = None
4047 else:
4048 myvims[datacenter_key] = vims.values()[0]
4049 myvim = myvims[datacenter_key]
4050 myvim_thread = myvim_threads[datacenter_key]
4051
4052 if not myvim:
4053 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
4054 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004055 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4056 extra = {"params": (sf['vim_sf_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004057 db_vim_action = {
4058 "instance_action_id": instance_action_id,
4059 "task_index": task_index,
4060 "datacenter_vim_id": sf["datacenter_tenant_id"],
4061 "action": "DELETE",
4062 "status": "SCHEDULED",
4063 "item": "instance_sfs",
4064 "item_id": sf["uuid"],
4065 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4066 }
4067 task_index += 1
4068 db_vim_actions.append(db_vim_action)
4069
tierno69b590e2018-03-13 18:52:23 +01004070 for sfi in instanceDict.get('sfis', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00004071 vimthread_affected[sfi["datacenter_tenant_id"]] = None
4072 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4073 if datacenter_key not in myvims:
4074 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004075 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004076 except NfvoException as e:
4077 logger.error(str(e))
4078 myvim_thread = None
4079 myvim_threads[datacenter_key] = myvim_thread
4080 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
4081 datacenter_tenant_id=sfi["datacenter_tenant_id"])
4082 if len(vims) == 0:
4083 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
4084 myvims[datacenter_key] = None
4085 else:
4086 myvims[datacenter_key] = vims.values()[0]
4087 myvim = myvims[datacenter_key]
4088 myvim_thread = myvim_threads[datacenter_key]
4089
4090 if not myvim:
4091 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
4092 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004093 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfs"]
4094 extra = {"params": (sfi['vim_sfi_id']), "depends_on": depends_on}
Igor D.Ccaadc442017-11-06 12:48:48 +00004095 db_vim_action = {
4096 "instance_action_id": instance_action_id,
4097 "task_index": task_index,
4098 "datacenter_vim_id": sfi["datacenter_tenant_id"],
4099 "action": "DELETE",
4100 "status": "SCHEDULED",
4101 "item": "instance_sfis",
4102 "item_id": sfi["uuid"],
4103 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4104 }
4105 task_index += 1
4106 db_vim_actions.append(db_vim_action)
4107
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004108 # 2.2 deleting VMs
4109 # vm_fail_list=[]
gcalvinod6fac4d2018-11-05 10:42:06 +01004110 for sce_vnf in instanceDict.get('vnfs', ()):
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004111 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4112 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
Igor D.Ccaadc442017-11-06 12:48:48 +00004113 if datacenter_key not in myvims:
4114 try:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004115 _, 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 +00004116 except NfvoException as e:
4117 logger.error(str(e))
4118 myvim_thread = None
4119 myvim_threads[datacenter_key] = myvim_thread
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004120 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
4121 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
Igor D.Ccaadc442017-11-06 12:48:48 +00004122 if len(vims) == 0:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004123 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
4124 sce_vnf["datacenter_tenant_id"]))
4125 myvims[datacenter_key] = None
4126 else:
4127 myvims[datacenter_key] = vims.values()[0]
4128 myvim = myvims[datacenter_key]
4129 myvim_thread = myvim_threads[datacenter_key]
4130
4131 for vm in sce_vnf['vms']:
4132 if not myvim:
4133 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
4134 continue
4135 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4136 db_vim_action = {
4137 "instance_action_id": instance_action_id,
4138 "task_index": task_index,
4139 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
4140 "action": "DELETE",
4141 "status": "SCHEDULED",
4142 "item": "instance_vms",
4143 "item_id": vm["uuid"],
4144 "extra": yaml.safe_dump({"params": vm["interfaces"], "depends_on": sfi_dependencies},
4145 default_flow_style=True, width=256)
4146 }
4147 db_vim_actions.append(db_vim_action)
4148 for interface in vm["interfaces"]:
4149 if not interface.get("instance_net_id"):
4150 continue
4151 if interface["instance_net_id"] not in net2vm_dependencies:
4152 net2vm_dependencies[interface["instance_net_id"]] = []
4153 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
4154 task_index += 1
4155
4156 # 2.3 deleting NETS
4157 # net_fail_list=[]
4158 for net in instanceDict['nets']:
4159 vimthread_affected[net["datacenter_tenant_id"]] = None
4160 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4161 if datacenter_key not in myvims:
4162 try:
gcalvinod6fac4d2018-11-05 10:42:06 +01004163 _,myvim_thread = get_vim_thread(mydb, tenant_id, net["datacenter_id"], net["datacenter_tenant_id"])
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004164 except NfvoException as e:
4165 logger.error(str(e))
4166 myvim_thread = None
4167 myvim_threads[datacenter_key] = myvim_thread
4168 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
4169 datacenter_tenant_id=net["datacenter_tenant_id"])
4170 if len(vims) == 0:
4171 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 +00004172 myvims[datacenter_key] = None
4173 else:
4174 myvims[datacenter_key] = vims.values()[0]
4175 myvim = myvims[datacenter_key]
4176 myvim_thread = myvim_threads[datacenter_key]
4177
4178 if not myvim:
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004179 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 +00004180 continue
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004181 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
4182 if net2vm_dependencies.get(net["uuid"]):
4183 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
4184 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4185 if len(sfi_dependencies) > 0:
4186 if "depends_on" in extra:
4187 extra["depends_on"] += sfi_dependencies
4188 else:
4189 extra["depends_on"] = sfi_dependencies
Igor D.Ccaadc442017-11-06 12:48:48 +00004190 db_vim_action = {
4191 "instance_action_id": instance_action_id,
4192 "task_index": task_index,
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004193 "datacenter_vim_id": net["datacenter_tenant_id"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004194 "action": "DELETE",
4195 "status": "SCHEDULED",
Eduardo Sousaab24d8b2018-10-17 17:10:04 +01004196 "item": "instance_nets",
4197 "item_id": net["uuid"],
Igor D.Ccaadc442017-11-06 12:48:48 +00004198 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4199 }
4200 task_index += 1
4201 db_vim_actions.append(db_vim_action)
4202
tierno868220c2017-09-26 00:11:05 +02004203 db_instance_action["number_tasks"] = task_index
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004204
4205 # --> WIM
4206 wim_actions, db_instance_action = (
4207 wim_engine.incorporate_actions(wim_actions, db_instance_action))
4208 # <-- WIM
4209
tierno868220c2017-09-26 00:11:05 +02004210 db_tables = [
4211 {"instance_actions": db_instance_action},
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004212 {"vim_wim_actions": db_vim_actions + wim_actions}
tierno868220c2017-09-26 00:11:05 +02004213 ]
4214
4215 logger.debug("delete_instance done DB tables: %s",
4216 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4217 mydb.new_rows(db_tables, ())
4218 for myvim_thread_id in vimthread_affected.keys():
4219 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4220
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004221 wim_engine.dispatch(wim_actions)
4222
tiernob3d36742017-03-03 23:51:05 +01004223 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02004224 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4225 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01004226 else:
tierno868220c2017-09-26 00:11:05 +02004227 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01004228
tierno7f426e92018-06-28 15:21:32 +02004229def get_instance_id(mydb, tenant_id, instance_id):
4230 global ovim
4231 #check valid tenant_id
4232 check_tenant(mydb, tenant_id)
4233 #obtain data
4234
4235 instance_dict = mydb.get_instance_scenario(instance_id, tenant_id, verbose=True)
4236 for net in instance_dict["nets"]:
4237 if net.get("sdn_net_id"):
4238 net_sdn = ovim.show_network(net["sdn_net_id"])
4239 net["sdn_info"] = {
4240 "admin_state_up": net_sdn.get("admin_state_up"),
4241 "flows": net_sdn.get("flows"),
4242 "last_error": net_sdn.get("last_error"),
4243 "ports": net_sdn.get("ports"),
4244 "type": net_sdn.get("type"),
4245 "status": net_sdn.get("status"),
4246 "vlan": net_sdn.get("vlan"),
4247 }
4248 return instance_dict
tiernob3d36742017-03-03 23:51:05 +01004249
tiernob8569aa2018-08-24 11:34:54 +02004250@deprecated("Instance is automatically refreshed by vim_threads")
tierno7edb6752016-03-21 17:37:52 +01004251def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4252 '''Refreshes a scenario instance. It modifies instanceDict'''
4253 '''Returns:
4254 - 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
4255 - error_msg
4256 '''
tierno867ffe92017-03-27 12:50:34 +02004257 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4258 # #print "nfvo.refresh_instance begins"
4259 # #print json.dumps(instanceDict, indent=4)
4260 #
4261 # #print "Getting the VIM URL and the VIM tenant_id"
4262 # myvims={}
4263 #
4264 # # 1. Getting VIM vm and net list
4265 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4266 # vms_notupdated=[]
4267 # vm_list = {}
4268 # for sce_vnf in instanceDict['vnfs']:
4269 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4270 # if datacenter_key not in vm_list:
4271 # vm_list[datacenter_key] = []
4272 # if datacenter_key not in myvims:
4273 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4274 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4275 # if len(vims) == 0:
4276 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4277 # myvims[datacenter_key] = None
4278 # else:
4279 # myvims[datacenter_key] = vims.values()[0]
4280 # for vm in sce_vnf['vms']:
4281 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4282 # vms_notupdated.append(vm["uuid"])
4283 #
4284 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4285 # nets_notupdated=[]
4286 # net_list = {}
4287 # for net in instanceDict['nets']:
4288 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4289 # if datacenter_key not in net_list:
4290 # net_list[datacenter_key] = []
4291 # if datacenter_key not in myvims:
4292 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4293 # datacenter_tenant_id=net["datacenter_tenant_id"])
4294 # if len(vims) == 0:
4295 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4296 # myvims[datacenter_key] = None
4297 # else:
4298 # myvims[datacenter_key] = vims.values()[0]
4299 #
4300 # net_list[datacenter_key].append(net['vim_net_id'])
4301 # nets_notupdated.append(net["uuid"])
4302 #
4303 # # 1. Getting the status of all VMs
4304 # vm_dict={}
4305 # for datacenter_key in myvims:
4306 # if not vm_list.get(datacenter_key):
4307 # continue
4308 # failed = True
4309 # failed_message=""
4310 # if not myvims[datacenter_key]:
4311 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4312 # else:
4313 # try:
4314 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4315 # failed = False
4316 # except vimconn.vimconnException as e:
4317 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4318 # failed_message = str(e)
4319 # if failed:
4320 # for vm in vm_list[datacenter_key]:
4321 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4322 #
4323 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4324 # for sce_vnf in instanceDict['vnfs']:
4325 # for vm in sce_vnf['vms']:
4326 # vm_id = vm['vim_vm_id']
4327 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4328 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4329 # has_mgmt_iface = False
4330 # for iface in vm["interfaces"]:
4331 # if iface["type"]=="mgmt":
4332 # has_mgmt_iface = True
4333 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4334 # vm_dict[vm_id]['status'] = "ACTIVE"
4335 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4336 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4337 # 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'):
4338 # vm['status'] = vm_dict[vm_id]['status']
4339 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4340 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4341 # # 2.1. Update in openmano DB the VMs whose status changed
4342 # try:
4343 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4344 # vms_notupdated.remove(vm["uuid"])
4345 # if updates>0:
4346 # vms_updated.append(vm["uuid"])
4347 # except db_base_Exception as e:
4348 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4349 # # 2.2. Update in openmano DB the interface VMs
4350 # for interface in interfaces:
4351 # #translate from vim_net_id to instance_net_id
4352 # network_id_list=[]
4353 # for net in instanceDict['nets']:
4354 # if net["vim_net_id"] == interface["vim_net_id"]:
4355 # network_id_list.append(net["uuid"])
4356 # if not network_id_list:
4357 # continue
4358 # del interface["vim_net_id"]
4359 # try:
4360 # for network_id in network_id_list:
4361 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4362 # except db_base_Exception as e:
4363 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4364 #
4365 # # 3. Getting the status of all nets
4366 # net_dict = {}
4367 # for datacenter_key in myvims:
4368 # if not net_list.get(datacenter_key):
4369 # continue
4370 # failed = True
4371 # failed_message = ""
4372 # if not myvims[datacenter_key]:
4373 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4374 # else:
4375 # try:
4376 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4377 # failed = False
4378 # except vimconn.vimconnException as e:
4379 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4380 # failed_message = str(e)
4381 # if failed:
4382 # for net in net_list[datacenter_key]:
4383 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4384 #
4385 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4386 # # TODO: update nets inside a vnf
4387 # for net in instanceDict['nets']:
4388 # net_id = net['vim_net_id']
4389 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4390 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4391 # 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'):
4392 # net['status'] = net_dict[net_id]['status']
4393 # net['error_msg'] = net_dict[net_id].get('error_msg')
4394 # net['vim_info'] = net_dict[net_id].get('vim_info')
4395 # # 5.1. Update in openmano DB the nets whose status changed
4396 # try:
4397 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4398 # nets_notupdated.remove(net["uuid"])
4399 # if updated>0:
4400 # nets_updated.append(net["uuid"])
4401 # except db_base_Exception as e:
4402 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4403 #
4404 # # Returns appropriate output
4405 # #print "nfvo.refresh_instance finishes"
4406 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4407 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01004408 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02004409 # if len(vms_notupdated)+len(nets_notupdated)>0:
4410 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4411 # 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 +01004412
tiernoae4a8d12016-07-08 12:30:39 +02004413 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01004414
4415def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02004416 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004417 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01004418 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4419
tiernoae4a8d12016-07-08 12:30:39 +02004420 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02004421 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4422 if len(vims) == 0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004423 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004424 myvim = vims.values()[0]
tiernofc5f80b2018-05-29 16:00:43 +02004425 vm_result = {}
4426 vm_error = 0
4427 vm_ok = 0
tierno42026a02017-02-10 15:13:40 +01004428
tiernofc5f80b2018-05-29 16:00:43 +02004429 myvim_threads_id = {}
4430 if action_dict.get("vdu-scaling"):
4431 db_instance_vms = []
4432 db_vim_actions = []
4433 db_instance_interfaces = []
4434 instance_action_id = get_task_id()
4435 db_instance_action = {
4436 "uuid": instance_action_id, # same uuid for the instance and the action on create
4437 "tenant_id": nfvo_tenant,
4438 "instance_id": instance_id,
4439 "description": "SCALE",
4440 }
4441 vm_result["instance_action_id"] = instance_action_id
tierno67881db2018-10-24 18:46:03 +02004442 vm_result["created"] = []
4443 vm_result["deleted"] = []
tiernofc5f80b2018-05-29 16:00:43 +02004444 task_index = 0
4445 for vdu in action_dict["vdu-scaling"]:
tierno868220c2017-09-26 00:11:05 +02004446 vdu_id = vdu.get("vdu-id")
tiernofc5f80b2018-05-29 16:00:43 +02004447 osm_vdu_id = vdu.get("osm_vdu_id")
4448 member_vnf_index = vdu.get("member-vnf-index")
tierno868220c2017-09-26 00:11:05 +02004449 vdu_count = vdu.get("count", 1)
tiernofc5f80b2018-05-29 16:00:43 +02004450 if vdu_id:
tierno67881db2018-10-24 18:46:03 +02004451 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004452 FROM="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4453 WHERE={"vms.uuid": vdu_id},
4454 ORDER_BY="vms.created_at"
4455 )
tierno67881db2018-10-24 18:46:03 +02004456 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004457 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id), httperrors.Not_Found)
tiernofc5f80b2018-05-29 16:00:43 +02004458 else:
4459 if not osm_vdu_id and not member_vnf_index:
tiernoa43bd9e2018-11-26 09:28:58 +00004460 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
tierno67881db2018-10-24 18:46:03 +02004461 target_vms = mydb.get_rows(
tiernofc5f80b2018-05-29 16:00:43 +02004462 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4463 FROM="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4464 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4465 " join vms on ivms.vm_id=vms.uuid",
tiernoa43bd9e2018-11-26 09:28:58 +00004466 WHERE={"vms.osm_id": osm_vdu_id, "svnfs.member_vnf_index": member_vnf_index,
4467 "ivnfs.instance_scenario_id": instance_id},
tiernofc5f80b2018-05-29 16:00:43 +02004468 ORDER_BY="ivms.created_at"
4469 )
tierno67881db2018-10-24 18:46:03 +02004470 if not target_vms:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004471 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 +02004472 vdu_id = target_vms[-1]["uuid"]
4473 target_vm = target_vms[-1]
tiernofc5f80b2018-05-29 16:00:43 +02004474 datacenter = target_vm["datacenter_id"]
4475 myvim_threads_id[datacenter], _ = get_vim_thread(mydb, nfvo_tenant, datacenter)
tiernofc5f80b2018-05-29 16:00:43 +02004476
tierno67881db2018-10-24 18:46:03 +02004477 if vdu["type"] == "delete":
4478 for index in range(0, vdu_count):
4479 target_vm = target_vms[-1-index]
4480 vdu_id = target_vm["uuid"]
4481 # look for nm
4482 vm_interfaces = None
4483 for sce_vnf in instanceDict['vnfs']:
4484 for vm in sce_vnf['vms']:
4485 if vm["uuid"] == vdu_id:
4486 vm_interfaces = vm["interfaces"]
4487 break
4488
4489 db_vim_action = {
4490 "instance_action_id": instance_action_id,
4491 "task_index": task_index,
4492 "datacenter_vim_id": target_vm["datacenter_tenant_id"],
4493 "action": "DELETE",
4494 "status": "SCHEDULED",
4495 "item": "instance_vms",
4496 "item_id": vdu_id,
4497 "extra": yaml.safe_dump({"params": vm_interfaces},
4498 default_flow_style=True, width=256)
4499 }
4500 task_index += 1
4501 db_vim_actions.append(db_vim_action)
4502 vm_result["deleted"].append(vdu_id)
4503 # delete from database
4504 db_instance_vms.append({"TO-DELETE": vdu_id})
tiernofc5f80b2018-05-29 16:00:43 +02004505
4506 else: # vdu["type"] == "create":
4507 iface2iface = {}
4508 where = {"item": "instance_vms", "item_id": target_vm["uuid"], "action": "CREATE"}
4509
garciadeblas72cd59f2018-12-05 10:59:40 +01004510 vim_action_to_clone = mydb.get_rows(FROM="vim_wim_actions", WHERE=where)
tiernofc5f80b2018-05-29 16:00:43 +02004511 if not vim_action_to_clone:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004512 raise NfvoException("Cannot find the vim_action at database with {}".format(where), httperrors.Internal_Server_Error)
tiernofc5f80b2018-05-29 16:00:43 +02004513 vim_action_to_clone = vim_action_to_clone[0]
4514 extra = yaml.safe_load(vim_action_to_clone["extra"])
4515
4516 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4517 # TODO do the same for flavor and image when available
4518 task_depends_on = []
4519 task_params = extra["params"]
4520 task_params_networks = deepcopy(task_params[5])
4521 for iface in task_params[5]:
4522 if iface["net_id"].startswith("TASK-"):
4523 if "." not in iface["net_id"]:
4524 task_depends_on.append("{}.{}".format(vim_action_to_clone["instance_action_id"],
4525 iface["net_id"][5:]))
4526 iface["net_id"] = "TASK-{}.{}".format(vim_action_to_clone["instance_action_id"],
4527 iface["net_id"][5:])
4528 else:
4529 task_depends_on.append(iface["net_id"][5:])
4530 if "mac_address" in iface:
4531 del iface["mac_address"]
4532
4533 vm_ifaces_to_clone = mydb.get_rows(FROM="instance_interfaces", WHERE={"instance_vm_id": target_vm["uuid"]})
4534 for index in range(0, vdu_count):
4535 vm_uuid = str(uuid4())
4536 vm_name = target_vm.get('vim_name')
4537 try:
4538 suffix = vm_name.rfind("-")
tierno67881db2018-10-24 18:46:03 +02004539 vm_name = vm_name[:suffix+1] + str(index + 1 + int(vm_name[suffix+1:]))
tiernofc5f80b2018-05-29 16:00:43 +02004540 except Exception:
4541 pass
4542 db_instance_vm = {
4543 "uuid": vm_uuid,
4544 'instance_vnf_id': target_vm['instance_vnf_id'],
4545 'vm_id': target_vm['vm_id'],
4546 'vim_name': vm_name
4547 }
4548 db_instance_vms.append(db_instance_vm)
4549
4550 for vm_iface in vm_ifaces_to_clone:
4551 iface_uuid = str(uuid4())
4552 iface2iface[vm_iface["uuid"]] = iface_uuid
4553 db_vm_iface = {
4554 "uuid": iface_uuid,
4555 'instance_vm_id': vm_uuid,
4556 "instance_net_id": vm_iface["instance_net_id"],
4557 'interface_id': vm_iface['interface_id'],
4558 'type': vm_iface['type'],
4559 'floating_ip': vm_iface['floating_ip'],
4560 'port_security': vm_iface['port_security']
4561 }
4562 db_instance_interfaces.append(db_vm_iface)
4563 task_params_copy = deepcopy(task_params)
4564 for iface in task_params_copy[5]:
4565 iface["uuid"] = iface2iface[iface["uuid"]]
4566 # increment ip_address
4567 if "ip_address" in iface:
4568 ip = iface.get("ip_address")
4569 i = ip.rfind(".")
4570 if i > 0:
4571 try:
4572 i += 1
4573 ip = ip[i:] + str(int(ip[:i]) + 1)
4574 iface["ip_address"] = ip
4575 except:
4576 iface["ip_address"] = None
4577 if vm_name:
4578 task_params_copy[0] = vm_name
4579 db_vim_action = {
4580 "instance_action_id": instance_action_id,
4581 "task_index": task_index,
4582 "datacenter_vim_id": vim_action_to_clone["datacenter_vim_id"],
4583 "action": "CREATE",
4584 "status": "SCHEDULED",
4585 "item": "instance_vms",
4586 "item_id": vm_uuid,
4587 # ALF
4588 # ALF
4589 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4590 # ALF
4591 # ALF
4592 "extra": yaml.safe_dump({"params": task_params_copy, "depends_on": task_depends_on}, default_flow_style=True, width=256)
4593 }
4594 task_index += 1
4595 db_vim_actions.append(db_vim_action)
tierno67881db2018-10-24 18:46:03 +02004596 vm_result["created"].append(vm_uuid)
tiernofc5f80b2018-05-29 16:00:43 +02004597
4598 db_instance_action["number_tasks"] = task_index
4599 db_tables = [
4600 {"instance_vms": db_instance_vms},
4601 {"instance_interfaces": db_instance_interfaces},
4602 {"instance_actions": db_instance_action},
4603 # TODO revise sfps
4604 # {"instance_sfis": db_instance_sfis},
4605 # {"instance_sfs": db_instance_sfs},
4606 # {"instance_classifications": db_instance_classifications},
4607 # {"instance_sfps": db_instance_sfps},
garciadeblasaba7a0d2018-12-05 12:42:35 +01004608 {"vim_wim_actions": db_vim_actions}
tiernofc5f80b2018-05-29 16:00:43 +02004609 ]
4610 logger.debug("create_vdu done DB tables: %s",
4611 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4612 mydb.new_rows(db_tables, [])
4613 for myvim_thread in myvim_threads_id.values():
4614 vim_threads["running"][myvim_thread].insert_task(db_vim_actions)
4615
4616 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004617
4618 input_vnfs = action_dict.pop("vnfs", [])
4619 input_vms = action_dict.pop("vms", [])
tierno92c36fd2018-05-04 12:21:10 +02004620 action_over_all = True if not input_vnfs and not input_vms else False
tierno7edb6752016-03-21 17:37:52 +01004621 for sce_vnf in instanceDict['vnfs']:
4622 for vm in sce_vnf['vms']:
tierno92c36fd2018-05-04 12:21:10 +02004623 if not action_over_all and sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4624 sce_vnf['member_vnf_index'] not in input_vnfs and \
4625 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
4626 continue
tiernoae4a8d12016-07-08 12:30:39 +02004627 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004628 if "add_public_key" in action_dict:
4629 mgmt_access = {}
4630 if sce_vnf.get('mgmt_access'):
4631 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4632 ssh_access = mgmt_access['config-access']['ssh-access']
4633 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01004634 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004635 if ssh_access['required'] and ssh_access['default-user']:
4636 if 'ip_address' in vm:
4637 mgmt_ip = vm['ip_address'].split(';')
4638 password = mgmt_access['config-access'].get('password')
4639 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4640 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4641 action_dict['add_public_key'],
4642 password=password, ro_key=priv_RO_key)
4643 else:
4644 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004645 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004646 except KeyError:
4647 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004648 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004649 else:
4650 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004651 httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02004652 else:
4653 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4654 if "console" in action_dict:
4655 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02004656 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4657 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4658 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02004659 ip = data["server"],
4660 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02004661 suffix = data["suffix"]),
4662 "name":vm['name']
4663 }
4664 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004665 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004666 vm_result[ vm['uuid'] ] = {"vim_result": -httperrors.Unauthorized,
gcalvinoe580c7d2017-09-22 14:09:51 +02004667 "description": "this console is only reachable by local interface",
4668 "name":vm['name']
4669 }
tierno20fc2a22016-08-19 17:02:35 +02004670 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004671 else:
4672 #print "console data", data
4673 try:
4674 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4675 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4676 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4677 protocol=data["protocol"],
4678 ip = global_config["http_console_host"],
4679 port = console_thread.port,
4680 suffix = data["suffix"]),
4681 "name":vm['name']
4682 }
4683 vm_ok +=1
4684 except NfvoException as e:
4685 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4686 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02004687
gcalvinoe580c7d2017-09-22 14:09:51 +02004688 else:
4689 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4690 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02004691 except vimconn.vimconnException as e:
4692 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4693 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01004694
4695 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02004696 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004697 else:
tierno351863c2016-07-23 01:46:03 +02004698 return vm_result
tierno42026a02017-02-10 15:13:40 +01004699
tierno868220c2017-09-26 00:11:05 +02004700def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
tierno16e3dd42018-04-24 12:52:40 +02004701 filter = {}
tierno868220c2017-09-26 00:11:05 +02004702 if nfvo_tenant and nfvo_tenant != "any":
4703 filter["tenant_id"] = nfvo_tenant
4704 if instance_id and instance_id != "any":
4705 filter["instance_id"] = instance_id
4706 if action_id:
4707 filter["uuid"] = action_id
4708 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
tierno16e3dd42018-04-24 12:52:40 +02004709 if action_id:
4710 if not rows:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004711 raise NfvoException("Not found any action with this criteria", httperrors.Not_Found)
4712 vim_wim_actions = mydb.get_rows(FROM="vim_wim_actions", WHERE={"instance_action_id": action_id})
4713 rows[0]["vim_wim_actions"] = vim_wim_actions
tierno31e121f2018-12-03 12:04:48 +00004714 # for backward compatibility set vim_actions = vim_wim_actions
4715 rows[0]["vim_actions"] = vim_wim_actions
tiernofc5f80b2018-05-29 16:00:43 +02004716 return {"actions": rows}
tierno868220c2017-09-26 00:11:05 +02004717
tiernob3d36742017-03-03 23:51:05 +01004718
tierno7edb6752016-03-21 17:37:52 +01004719def create_or_use_console_proxy_thread(console_server, console_port):
4720 #look for a non-used port
4721 console_thread_key = console_server + ":" + str(console_port)
4722 if console_thread_key in global_config["console_thread"]:
4723 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02004724 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01004725
tierno7edb6752016-03-21 17:37:52 +01004726 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02004727 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01004728 if port in global_config["console_ports"]:
4729 continue
4730 try:
4731 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4732 clithread.start()
4733 global_config["console_thread"][console_thread_key] = clithread
4734 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02004735 return clithread
tierno7edb6752016-03-21 17:37:52 +01004736 except cli.ConsoleProxyExceptionPortUsed as e:
4737 #port used, try with onoher
4738 continue
4739 except cli.ConsoleProxyException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004740 raise NfvoException(str(e), httperrors.Bad_Request)
4741 raise NfvoException("Not found any free 'http_console_ports'", httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004742
tiernob3d36742017-03-03 23:51:05 +01004743
tierno7edb6752016-03-21 17:37:52 +01004744def check_tenant(mydb, tenant_id):
4745 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02004746 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4747 if not tenant:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004748 raise NfvoException("tenant '{}' not found".format(tenant_id), httperrors.Not_Found)
tiernof97fd272016-07-11 14:32:37 +02004749 return
tierno7edb6752016-03-21 17:37:52 +01004750
4751def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01004752
gcalvinoe580c7d2017-09-22 14:09:51 +02004753 tenant_uuid = str(uuid4())
4754 tenant_dict['uuid'] = tenant_uuid
4755 try:
4756 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4757 tenant_dict['RO_pub_key'] = pub_key
4758 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02004759 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02004760 except db_base_Exception as e:
tierno9c5c8322018-03-23 15:44:03 +01004761 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
gcalvinoe580c7d2017-09-22 14:09:51 +02004762 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01004763
tierno7edb6752016-03-21 17:37:52 +01004764def delete_tenant(mydb, tenant):
4765 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01004766
tiernof97fd272016-07-11 14:32:37 +02004767 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4768 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4769 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01004770
tiernob3d36742017-03-03 23:51:05 +01004771
tierno7edb6752016-03-21 17:37:52 +01004772def new_datacenter(mydb, datacenter_descriptor):
tierno1c848c02018-05-21 16:40:33 +02004773 sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004774 if "config" in datacenter_descriptor:
tiernoedf3f4f2018-05-17 23:02:47 +02004775 sdn_port_mapping = datacenter_descriptor["config"].pop("sdn-port-mapping", None)
4776 datacenter_descriptor["config"] = yaml.safe_dump(datacenter_descriptor["config"], default_flow_style=True,
4777 width=256)
4778 # Check that datacenter-type is correct
tierno3ae39742016-09-07 12:17:51 +02004779 datacenter_type = datacenter_descriptor.get("type", "openvim");
tiernoedf3f4f2018-05-17 23:02:47 +02004780 # module_info = None
tierno3ae39742016-09-07 12:17:51 +02004781 try:
4782 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02004783 pkg = __import__("osm_ro." + module)
tiernoedf3f4f2018-05-17 23:02:47 +02004784 # vim_conn = getattr(pkg, module)
tierno361275f2017-04-25 16:24:34 +02004785 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02004786 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02004787 # if module_info and module_info[0]:
4788 # file.close(module_info[0])
tiernoedf3f4f2018-05-17 23:02:47 +02004789 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type,
4790 module),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004791 httperrors.Bad_Request)
tierno42026a02017-02-10 15:13:40 +01004792
gcalvinoc62cfa52017-10-05 18:21:25 +02004793 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernoedf3f4f2018-05-17 23:02:47 +02004794 if sdn_port_mapping:
4795 try:
4796 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, sdn_port_mapping)
4797 except Exception as e:
4798 mydb.delete_row_by_id("datacenters", datacenter_id) # Rollback
4799 raise e
tiernof97fd272016-07-11 14:32:37 +02004800 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004801
tiernob3d36742017-03-03 23:51:05 +01004802
tierno7edb6752016-03-21 17:37:52 +01004803def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02004804 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02004805 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02004806
4807 # edit data
tiernof97fd272016-07-11 14:32:37 +02004808 datacenter_id = datacenter['uuid']
tiernod72182f2018-08-29 10:56:13 +02004809 where = {'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02004810 remove_port_mapping = False
tiernoedf3f4f2018-05-17 23:02:47 +02004811 new_sdn_port_mapping = None
tierno7edb6752016-03-21 17:37:52 +01004812 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02004813 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01004814 try:
4815 new_config_dict = datacenter_descriptor["config"]
tiernoedf3f4f2018-05-17 23:02:47 +02004816 if "sdn-port-mapping" in new_config_dict:
4817 remove_port_mapping = True
4818 new_sdn_port_mapping = new_config_dict.pop("sdn-port-mapping")
tiernod72182f2018-08-29 10:56:13 +02004819 # delete null fields
4820 to_delete = []
tierno7edb6752016-03-21 17:37:52 +01004821 for k in new_config_dict:
tiernod72182f2018-08-29 10:56:13 +02004822 if new_config_dict[k] is None:
tierno7edb6752016-03-21 17:37:52 +01004823 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02004824 if k == 'sdn-controller':
4825 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01004826
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004827 config_text = datacenter.get("config")
4828 if not config_text:
4829 config_text = '{}'
4830 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01004831 config_dict.update(new_config_dict)
tiernod72182f2018-08-29 10:56:13 +02004832 # delete null fields
tierno7edb6752016-03-21 17:37:52 +01004833 for k in to_delete:
4834 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02004835 except Exception as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004836 raise NfvoException("Bad format at datacenter:config " + str(e), httperrors.Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02004837 if config_dict:
4838 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4839 else:
4840 datacenter_descriptor["config"] = None
4841 if remove_port_mapping:
4842 try:
4843 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4844 except ovimException as e:
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004845 raise NfvoException("Error deleting datacenter-port-mapping " + str(e), httperrors.Conflict)
tierno8fe7a492017-07-11 13:50:04 +02004846
tiernof97fd272016-07-11 14:32:37 +02004847 mydb.update_rows('datacenters', datacenter_descriptor, where)
tiernoedf3f4f2018-05-17 23:02:47 +02004848 if new_sdn_port_mapping:
4849 try:
4850 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, new_sdn_port_mapping)
4851 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004852 # Rollback
4853 mydb.update_rows('datacenters', datacenter, where)
Anderson Bravalheric5293de2018-11-28 17:21:26 +00004854 raise NfvoException("Error adding datacenter-port-mapping " + str(e), httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02004855 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004856
tiernob3d36742017-03-03 23:51:05 +01004857
tierno7edb6752016-03-21 17:37:52 +01004858def delete_datacenter(mydb, datacenter):
4859 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02004860 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
4861 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02004862 try:
4863 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
4864 except ovimException as e:
tiernod72182f2018-08-29 10:56:13 +02004865 raise NfvoException("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02004866 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01004867
tiernob3d36742017-03-03 23:51:05 +01004868
tiernod3750b32018-07-20 15:33:08 +02004869def create_vim_account(mydb, nfvo_tenant, datacenter_id, name=None, vim_id=None, vim_tenant=None, vim_tenant_name=None,
4870 vim_username=None, vim_password=None, config=None):
tierno9c22f2d2017-10-09 16:23:55 +02004871 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02004872 try:
tiernod3750b32018-07-20 15:33:08 +02004873 if not datacenter_id:
4874 if not vim_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004875 raise NfvoException("You must provide 'vim_id", http_code=httperrors.Bad_Request)
tiernod3750b32018-07-20 15:33:08 +02004876 datacenter_id = vim_id
4877 datacenter_id, datacenter_name = get_datacenter_uuid(mydb, None, datacenter_id)
tierno7edb6752016-03-21 17:37:52 +01004878
tiernod3750b32018-07-20 15:33:08 +02004879 create_vim_tenant = True if not vim_tenant and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01004880
tierno0ea2a7e2017-10-18 00:06:26 +02004881 # get nfvo_tenant info
4882 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
4883 if vim_tenant_name==None:
4884 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01004885
tierno0ea2a7e2017-10-18 00:06:26 +02004886 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernod3750b32018-07-20 15:33:08 +02004887 # #check that this association does not exist before
4888 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4889 # if len(tenants_datacenters)>0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004890 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
tierno7edb6752016-03-21 17:37:52 +01004891
tierno0ea2a7e2017-10-18 00:06:26 +02004892 vim_tenant_id_exist_atdb=False
4893 if not create_vim_tenant:
4894 where_={"datacenter_id": datacenter_id}
tiernod3750b32018-07-20 15:33:08 +02004895 if vim_tenant!=None:
4896 where_["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004897 if vim_tenant_name!=None:
4898 where_["vim_tenant_name"] = vim_tenant_name
4899 #check if vim_tenant_id is already at database
4900 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
4901 if len(datacenter_tenants_dict)>=1:
4902 datacenter_tenants_dict = datacenter_tenants_dict[0]
4903 vim_tenant_id_exist_atdb=True
4904 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
4905 else: #result=0
4906 datacenter_tenants_dict = {}
4907 #insert at table datacenter_tenants
tiernod3750b32018-07-20 15:33:08 +02004908 else: #if vim_tenant==None:
tierno0ea2a7e2017-10-18 00:06:26 +02004909 #create tenant at VIM if not provided
4910 try:
4911 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
4912 vim_passwd=vim_password)
4913 datacenter_name = myvim["name"]
tiernod3750b32018-07-20 15:33:08 +02004914 vim_tenant = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
tierno0ea2a7e2017-10-18 00:06:26 +02004915 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004916 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 +01004917 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02004918 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01004919
tierno0ea2a7e2017-10-18 00:06:26 +02004920 #fill datacenter_tenants table
4921 if not vim_tenant_id_exist_atdb:
tiernod3750b32018-07-20 15:33:08 +02004922 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant
tierno0ea2a7e2017-10-18 00:06:26 +02004923 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
4924 datacenter_tenants_dict["user"] = vim_username
4925 datacenter_tenants_dict["passwd"] = vim_password
4926 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tiernod3750b32018-07-20 15:33:08 +02004927 if name:
4928 datacenter_tenants_dict["name"] = name
4929 else:
4930 datacenter_tenants_dict["name"] = datacenter_name
tierno0ea2a7e2017-10-18 00:06:26 +02004931 if config:
4932 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
4933 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
4934 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01004935
tierno0ea2a7e2017-10-18 00:06:26 +02004936 #fill tenants_datacenters table
4937 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
4938 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
4939 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tiernod3750b32018-07-20 15:33:08 +02004940
tierno0ea2a7e2017-10-18 00:06:26 +02004941 # create thread
tierno0ea2a7e2017-10-18 00:06:26 +02004942 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tiernod3750b32018-07-20 15:33:08 +02004943 new_thread = vim_thread.vim_thread(task_lock, thread_name, datacenter_name, datacenter_tenant_id,
tierno0ea2a7e2017-10-18 00:06:26 +02004944 db=db, db_lock=db_lock, ovim=ovim)
4945 new_thread.start()
4946 thread_id = datacenter_tenants_dict["uuid"]
4947 vim_threads["running"][thread_id] = new_thread
tiernod3750b32018-07-20 15:33:08 +02004948 return thread_id
tierno0ea2a7e2017-10-18 00:06:26 +02004949 except vimconn.vimconnException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004950 raise NfvoException(str(e), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01004951
tierno99314902017-04-26 13:23:09 +02004952
tiernod3750b32018-07-20 15:33:08 +02004953def edit_vim_account(mydb, nfvo_tenant, datacenter_tenant_id, datacenter_id=None, name=None, vim_tenant=None,
4954 vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004955
tiernod3750b32018-07-20 15:33:08 +02004956 # get vim_account; check is valid for this tenant
4957 from_ = "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
4958 where_ = {"td.nfvo_tenant_id": nfvo_tenant}
4959 if datacenter_tenant_id:
4960 where_["dt.uuid"] = datacenter_tenant_id
4961 if datacenter_id:
4962 where_["dt.datacenter_id"] = datacenter_id
4963 vim_accounts = mydb.get_rows(SELECT="dt.uuid as uuid, config", FROM=from_, WHERE=where_)
4964 if not vim_accounts:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004965 raise NfvoException("vim_account not found for this tenant", http_code=httperrors.Not_Found)
tiernod3750b32018-07-20 15:33:08 +02004966 elif len(vim_accounts) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01004967 raise NfvoException("found more than one vim_account for this tenant", http_code=httperrors.Conflict)
tiernod3750b32018-07-20 15:33:08 +02004968 datacenter_tenant_id = vim_accounts[0]["uuid"]
4969 original_config = vim_accounts[0]["config"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004970
tiernod3750b32018-07-20 15:33:08 +02004971 update_ = {}
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004972 if config:
tiernod3750b32018-07-20 15:33:08 +02004973 original_config_dict = yaml.load(original_config)
4974 original_config_dict.update(config)
4975 update["config"] = yaml.safe_dump(original_config_dict, default_flow_style=True, width=256)
4976 if name:
4977 update_['name'] = name
4978 if vim_tenant:
4979 update_['vim_tenant_id'] = vim_tenant
4980 if vim_tenant_name:
4981 update_['vim_tenant_name'] = vim_tenant_name
4982 if vim_username:
4983 update_['user'] = vim_username
4984 if vim_password:
4985 update_['passwd'] = vim_password
4986 if update_:
4987 mydb.update_rows("datacenter_tenants", UPDATE=update_, WHERE={"uuid": datacenter_tenant_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004988
tiernod3750b32018-07-20 15:33:08 +02004989 vim_threads["running"][datacenter_tenant_id].insert_task("reload")
4990 return datacenter_tenant_id
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004991
tiernod3750b32018-07-20 15:33:08 +02004992def delete_vim_account(mydb, tenant_id, vim_account_id, datacenter=None):
tierno7edb6752016-03-21 17:37:52 +01004993 #get nfvo_tenant info
4994 if not tenant_id or tenant_id=="any":
4995 tenant_uuid = None
4996 else:
tiernof97fd272016-07-11 14:32:37 +02004997 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01004998 tenant_uuid = tenant_dict['uuid']
4999
5000 #check that this association exist before
tiernod3750b32018-07-20 15:33:08 +02005001 tenants_datacenter_dict = {}
5002 if datacenter:
5003 datacenter_id, _ = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
5004 tenants_datacenter_dict["datacenter_id"] = datacenter_id
5005 elif vim_account_id:
5006 tenants_datacenter_dict["datacenter_tenant_id"] = vim_account_id
tierno7edb6752016-03-21 17:37:52 +01005007 if tenant_uuid:
5008 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02005009 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5010 if len(tenant_datacenter_list)==0 and tenant_uuid:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005011 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005012
5013 #delete this association
tiernof97fd272016-07-11 14:32:37 +02005014 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01005015
5016 #get vim_tenant info and deletes
5017 warning=''
5018 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02005019 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5020 #try to delete vim:tenant
5021 try:
5022 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5023 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01005024 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01005025 try:
tierno0ea2a7e2017-10-18 00:06:26 +02005026 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005027 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
5028 except vimconn.vimconnException as e:
5029 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
5030 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02005031 except db_base_Exception as e:
5032 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01005033 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02005034 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tiernoa3572692018-05-14 13:09:33 +02005035 thread = vim_threads["running"].get(thread_id)
5036 if thread:
5037 thread.insert_task("exit")
5038 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02005039 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01005040
tiernob3d36742017-03-03 23:51:05 +01005041
tierno7edb6752016-03-21 17:37:52 +01005042def datacenter_action(mydb, tenant_id, datacenter, action_dict):
5043 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01005044 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005045 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005046
5047 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02005048 try:
tiernof97fd272016-07-11 14:32:37 +02005049 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02005050 #print content
5051 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005052 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005053 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01005054 #update nets Change from VIM format to NFVO format
5055 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005056 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01005057 net_nfvo={'datacenter_id': datacenter_id}
5058 net_nfvo['name'] = net['name']
5059 #net_nfvo['description']= net['name']
5060 net_nfvo['vim_net_id'] = net['id']
5061 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5062 net_nfvo['shared'] = net['shared']
5063 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5064 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02005065 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
5066 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
5067 return inserted
tierno7edb6752016-03-21 17:37:52 +01005068 elif 'net-edit' in action_dict:
5069 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02005070 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005071 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01005072 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005073 return result
tierno7edb6752016-03-21 17:37:52 +01005074 elif 'net-delete' in action_dict:
5075 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02005076 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01005077 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01005078 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02005079 return result
tierno7edb6752016-03-21 17:37:52 +01005080
5081 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005082 raise NfvoException("Unknown action " + str(action_dict), httperrors.Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01005083
tiernob3d36742017-03-03 23:51:05 +01005084
tierno7edb6752016-03-21 17:37:52 +01005085def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
5086 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005087 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005088
tierno42fcc3b2016-07-06 17:20:40 +02005089 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01005090 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01005091 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02005092 return result
tierno7edb6752016-03-21 17:37:52 +01005093
tiernob3d36742017-03-03 23:51:05 +01005094
tierno7edb6752016-03-21 17:37:52 +01005095def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
5096 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005097 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005098 filter_dict={}
5099 if action_dict:
5100 action_dict = action_dict["netmap"]
5101 if 'vim_id' in action_dict:
5102 filter_dict["id"] = action_dict['vim_id']
5103 if 'vim_name' in action_dict:
5104 filter_dict["name"] = action_dict['vim_name']
5105 else:
5106 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01005107
tiernoae4a8d12016-07-08 12:30:39 +02005108 try:
tiernof97fd272016-07-11 14:32:37 +02005109 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005110 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005111 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005112 raise NfvoException(str(e), httperrors.Internal_Server_Error)
tiernof97fd272016-07-11 14:32:37 +02005113 if len(vim_nets)>1 and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005114 raise NfvoException("more than two networks found, specify with vim_id", httperrors.Conflict)
tiernof97fd272016-07-11 14:32:37 +02005115 elif len(vim_nets)==0: # and action_dict:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005116 raise NfvoException("Not found a network at VIM with " + str(filter_dict), httperrors.Not_Found)
tierno7edb6752016-03-21 17:37:52 +01005117 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02005118 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01005119 net_nfvo={'datacenter_id': datacenter_id}
5120 if action_dict and "name" in action_dict:
5121 net_nfvo['name'] = action_dict['name']
5122 else:
5123 net_nfvo['name'] = net['name']
5124 #net_nfvo['description']= net['name']
5125 net_nfvo['vim_net_id'] = net['id']
5126 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5127 net_nfvo['shared'] = net['shared']
5128 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02005129 try:
5130 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01005131 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02005132 net_nfvo["uuid"] = net_id
5133 except db_base_Exception as e:
5134 if action_dict:
5135 raise
5136 else:
5137 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01005138 net_list.append(net_nfvo)
5139 return net_list
tierno7edb6752016-03-21 17:37:52 +01005140
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005141def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
5142 # obtain all network data
5143 try:
5144 if utils.check_valid_uuid(network_id):
5145 filter_dict = {"id": network_id}
5146 else:
5147 filter_dict = {"name": network_id}
5148
5149 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5150 network = myvim.get_network_list(filter_dict=filter_dict)
5151 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02005152 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 +02005153
5154 # ensure the network is defined
5155 if len(network) == 0:
5156 raise NfvoException("Network {} is not present in the system".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005157 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005158
5159 # ensure there is only one network with the provided name
5160 if len(network) > 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005161 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005162
5163 # ensure it is a dataplane network
5164 if network[0]['type'] != 'data':
5165 return None
5166
5167 # ensure we use the id
5168 network_id = network[0]['id']
5169
5170 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5171 # and with instance_scenario_id==NULL
5172 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5173 search_dict = {'vim_net_id': network_id}
5174
5175 try:
5176 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5177 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
5178 except db_base_Exception as e:
5179 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005180 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005181
5182 sdn_net_counter = 0
5183 for net in result:
5184 if net['sdn_net_id'] != None:
5185 sdn_net_counter+=1
5186 sdn_net_id = net['sdn_net_id']
5187
5188 if sdn_net_counter == 0:
5189 return None
5190 elif sdn_net_counter == 1:
5191 return sdn_net_id
5192 else:
5193 raise NfvoException("More than one SDN network is associated to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005194 network_id), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005195
5196def get_sdn_controller_id(mydb, datacenter):
5197 # Obtain sdn controller id
5198 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
5199 if not config:
5200 return None
5201
5202 return yaml.load(config).get('sdn-controller')
5203
5204def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
5205 try:
5206 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5207 if not sdn_network_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005208 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 +02005209
5210 #Obtain sdn controller id
5211 controller_id = get_sdn_controller_id(mydb, datacenter)
5212 if not controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005213 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005214
5215 #Obtain sdn controller info
5216 sdn_controller = ovim.show_of_controller(controller_id)
5217
5218 port_data = {
5219 'name': 'external_port',
5220 'net_id': sdn_network_id,
5221 'ofc_id': controller_id,
5222 'switch_dpid': sdn_controller['dpid'],
5223 'switch_port': descriptor['port']
5224 }
5225
5226 if 'vlan' in descriptor:
5227 port_data['vlan'] = descriptor['vlan']
5228 if 'mac' in descriptor:
5229 port_data['mac'] = descriptor['mac']
5230
5231 result = ovim.new_port(port_data)
5232 except ovimException as e:
5233 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005234 sdn_network_id, network_id) + str(e), httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005235 except db_base_Exception as e:
5236 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005237 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005238
5239 return 'Port uuid: '+ result
5240
5241def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
5242 if port_id:
5243 filter = {'uuid': port_id}
5244 else:
5245 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5246 if not sdn_network_id:
5247 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005248 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005249 #in case no port_id is specified only ports marked as 'external_port' will be detached
5250 filter = {'name': 'external_port', 'net_id': sdn_network_id}
5251
5252 try:
5253 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
5254 except ovimException as e:
5255 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005256 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005257
5258 if len(port_list) == 0:
5259 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005260 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005261
5262 port_uuid_list = []
5263 for port in port_list:
5264 try:
5265 port_uuid_list.append(port['uuid'])
5266 ovim.delete_port(port['uuid'])
5267 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005268 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 +02005269
5270 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01005271
tierno7edb6752016-03-21 17:37:52 +01005272def vim_action_get(mydb, tenant_id, datacenter, item, name):
5273 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005274 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01005275 filter_dict={}
5276 if name:
tierno42fcc3b2016-07-06 17:20:40 +02005277 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01005278 filter_dict["id"] = name
5279 else:
5280 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02005281 try:
5282 if item=="networks":
5283 #filter_dict['tenant_id'] = myvim['tenant_id']
5284 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005285
5286 if len(content) == 0:
5287 raise NfvoException("Network {} is not present in the system. ".format(name),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005288 httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005289
5290 #Update the networks with the attached ports
5291 for net in content:
5292 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
5293 if sdn_network_id != None:
5294 try:
5295 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5296 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
5297 except ovimException as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005298 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 +02005299 #Remove field name and if port name is external_port save it as 'type'
5300 for port in port_list:
5301 if port['name'] == 'external_port':
5302 port['type'] = "External"
5303 del port['name']
5304 net['sdn_network_id'] = sdn_network_id
5305 net['sdn_attached_ports'] = port_list
5306
tiernoae4a8d12016-07-08 12:30:39 +02005307 elif item=="tenants":
5308 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01005309 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005310
tierno4540ea52017-01-18 17:44:32 +01005311 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02005312 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005313 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02005314 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02005315 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02005316 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02005317 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02005318 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 +02005319 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005320 else:
tiernof97fd272016-07-11 14:32:37 +02005321 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02005322 except vimconn.vimconnException as e:
5323 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02005324 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01005325
tiernob3d36742017-03-03 23:51:05 +01005326
tierno7edb6752016-03-21 17:37:52 +01005327def vim_action_delete(mydb, tenant_id, datacenter, item, name):
5328 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02005329 if tenant_id == "any":
5330 tenant_id=None
5331
tiernoa2793912016-10-04 08:15:08 +00005332 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02005333 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02005334 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
5335 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02005336 items = content.values()[0]
5337 if type(items)==list and len(items)==0:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005338 raise NfvoException("Not found " + item, httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005339 elif type(items)==list and len(items)>1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005340 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), httperrors.Not_Found)
tierno392f2852016-05-13 12:28:55 +02005341 else: # it is a dict
5342 item_id = items["id"]
5343 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01005344
tiernoae4a8d12016-07-08 12:30:39 +02005345 try:
5346 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005347 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5348 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
5349 if sdn_network_id != None:
5350 #Delete any port attachment to this network
5351 try:
5352 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
5353 except ovimException as e:
5354 raise NfvoException(
5355 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005356 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005357
5358 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5359 for port in port_list:
5360 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
5361
5362 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5363 try:
5364 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
5365 except db_base_Exception as e:
5366 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
tierno9c5c8322018-03-23 15:44:03 +01005367 str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005368
5369 #Delete the SDN network
5370 try:
5371 ovim.delete_network(sdn_network_id)
5372 except ovimException as e:
5373 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
5374 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005375 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005376
tiernoae4a8d12016-07-08 12:30:39 +02005377 content = myvim.delete_network(item_id)
5378 elif item=="tenants":
5379 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01005380 elif item == "images":
5381 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02005382 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005383 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005384 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005385 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5386 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005387
tiernof97fd272016-07-11 14:32:37 +02005388 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01005389
tiernob3d36742017-03-03 23:51:05 +01005390
tierno7edb6752016-03-21 17:37:52 +01005391def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
5392 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00005393 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02005394 if tenant_id == "any":
5395 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00005396 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02005397 try:
5398 if item=="networks":
5399 net = descriptor["network"]
5400 net_name = net.pop("name")
5401 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02005402 net_public = net.pop("shared", False)
5403 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01005404 net_vlan = net.pop("vlan", None)
5405 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 +02005406
5407 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5408 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
tierno00e3df72017-11-29 17:20:13 +01005409 #obtain datacenter_tenant_id
5410 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
5411 FROM='datacenter_tenants',
5412 WHERE={'datacenter_id': datacenter})[0]['uuid']
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005413 try:
5414 sdn_network = {}
5415 sdn_network['vlan'] = net_vlan
5416 sdn_network['type'] = net_type
5417 sdn_network['name'] = net_name
tierno00e3df72017-11-29 17:20:13 +01005418 sdn_network['region'] = datacenter_tenant_id
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005419 ovim_content = ovim.new_network(sdn_network)
5420 except ovimException as e:
tierno00e3df72017-11-29 17:20:13 +01005421 logger.error("ovimException creating SDN network={} ".format(
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005422 sdn_network) + str(e), exc_info=True)
5423 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005424 httperrors.Internal_Server_Error)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005425
5426 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5427 # use instance_scenario_id=None to distinguish from real instaces of nets
tierno00e3df72017-11-29 17:20:13 +01005428 correspondence = {'instance_scenario_id': None,
5429 'sdn_net_id': ovim_content,
5430 'vim_net_id': content,
5431 'datacenter_tenant_id': datacenter_tenant_id
5432 }
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005433 try:
5434 mydb.new_row('instance_nets', correspondence, add_uuid=True)
5435 except db_base_Exception as e:
tierno00e3df72017-11-29 17:20:13 +01005436 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
tierno9c5c8322018-03-23 15:44:03 +01005437 correspondence, e), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005438 elif item=="tenants":
5439 tenant = descriptor["tenant"]
5440 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
5441 else:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005442 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02005443 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02005444 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02005445
tierno7edb6752016-03-21 17:37:52 +01005446 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005447
5448def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005449 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005450 logger.debug('New SDN controller created with uuid {}'.format(data))
5451 return data
5452
5453def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005454 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005455 msg = 'SDN controller {} updated'.format(data)
5456 logger.debug(msg)
5457 return msg
5458
5459def sdn_controller_list(mydb, tenant_id, controller_id=None):
5460 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005461 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005462 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005463 data = ovim.show_of_controller(controller_id)
5464
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005465 msg = 'SDN controller list:\n {}'.format(data)
5466 logger.debug(msg)
5467 return data
5468
5469def sdn_controller_delete(mydb, tenant_id, controller_id):
5470 select_ = ('uuid', 'config')
5471 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5472 for datacenter in datacenters:
5473 if datacenter['config']:
5474 config = yaml.load(datacenter['config'])
5475 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005476 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), httperrors.Conflict)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005477
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005478 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005479 msg = 'SDN controller {} deleted'.format(data)
5480 logger.debug(msg)
5481 return msg
5482
5483def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5484 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5485 if len(controller) < 1:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005486 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), httperrors.Not_Found)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005487
5488 try:
5489 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
5490 except:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005491 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005492
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005493 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5494 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005495
5496 maps = list()
5497 for compute_node in sdn_port_mapping:
5498 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5499 element = dict()
5500 element["compute_node"] = compute_node["compute_node"]
5501 for port in compute_node["ports"]:
tierno7f426e92018-06-28 15:21:32 +02005502 pci = port.get("pci")
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005503 element["switch_port"] = port.get("switch_port")
5504 element["switch_mac"] = port.get("switch_mac")
tierno7f426e92018-06-28 15:21:32 +02005505 if not pci or not (element["switch_port"] or element["switch_mac"]):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005506 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005507 " or 'switch_mac'", httperrors.Bad_Request)
tierno7f426e92018-06-28 15:21:32 +02005508 for pci_expanded in utils.expand_brackets(pci):
5509 element["pci"] = pci_expanded
5510 maps.append(dict(element))
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005511
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005512 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 +01005513
5514def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02005515 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005516
5517 result = {
5518 "sdn-controller": None,
5519 "datacenter-id": datacenter_id,
5520 "dpid": None,
5521 "ports_mapping": list()
5522 }
5523
5524 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5525 if datacenter['config']:
5526 config = yaml.load(datacenter['config'])
5527 if 'sdn-controller' in config:
5528 controller_id = config['sdn-controller']
5529 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5530 result["sdn-controller"] = controller_id
5531 result["dpid"] = sdn_controller["dpid"]
5532
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005533 if result["sdn-controller"] == None:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005534 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), httperrors.Bad_Request)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02005535 if result["dpid"] == None:
5536 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005537 httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005538
5539 if len(maps) == 0:
5540 return result
5541
5542 ports_correspondence_dict = dict()
5543 for link in maps:
5544 if result["sdn-controller"] != link["ofc_id"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005545 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005546 if result["dpid"] != link["switch_dpid"]:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005547 raise NfvoException("The dpid specified for different port mappings differ", httperrors.Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01005548 element = dict()
5549 element["pci"] = link["pci"]
5550 if link["switch_port"]:
5551 element["switch_port"] = link["switch_port"]
5552 if link["switch_mac"]:
5553 element["switch_mac"] = link["switch_mac"]
5554
5555 if not link["compute_node"] in ports_correspondence_dict:
5556 content = dict()
5557 content["compute_node"] = link["compute_node"]
5558 content["ports"] = list()
5559 ports_correspondence_dict[link["compute_node"]] = content
5560
5561 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5562
5563 for key in sorted(ports_correspondence_dict):
5564 result["ports_mapping"].append(ports_correspondence_dict[key])
5565
5566 return result
5567
5568def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02005569 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02005570
5571def create_RO_keypair(tenant_id):
5572 """
5573 Creates a public / private keys for a RO tenant and returns their values
5574 Params:
5575 tenant_id: ID of the tenant
5576 Return:
5577 public_key: Public key for the RO tenant
5578 private_key: Encrypted private key for RO tenant
5579 """
5580
5581 bits = 2048
5582 key = RSA.generate(bits)
5583 try:
5584 public_key = key.publickey().exportKey('OpenSSH')
5585 if isinstance(public_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005586 raise NfvoException("Unable to create public key: {}".format(public_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005587 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5588 except (ValueError, NameError) as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005589 raise NfvoException("Unable to create private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005590 return public_key, private_key
5591
5592def decrypt_key (key, tenant_id):
5593 """
5594 Decrypts an encrypted RSA key
5595 Params:
5596 key: Private key to be decrypted
5597 tenant_id: ID of the tenant
5598 Return:
5599 unencrypted_key: Unencrypted private key for RO tenant
5600 """
5601 try:
5602 key = RSA.importKey(key,tenant_id)
5603 unencrypted_key = key.exportKey('PEM')
5604 if isinstance(unencrypted_key, ValueError):
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005605 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005606 except ValueError as e:
Anderson Bravalheri0446cd52018-08-17 15:26:19 +01005607 raise NfvoException("Unable to decrypt the private key: {}".format(e), httperrors.Internal_Server_Error)
gcalvinoe580c7d2017-09-22 14:09:51 +02005608 return unencrypted_key