blob: 6bb14f9fe129cf7f63f60a4f62ef903bd48639ea [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5# This file is part of openmano
6# All Rights Reserved.
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License. You may obtain
10# a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17# License for the specific language governing permissions and limitations
18# under the License.
19#
20# For those usages not covered by the Apache License, Version 2.0 please
21# contact with: nfvlabs@tid.es
22##
23
24'''
25NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
26'''
27__author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28__date__ ="$16-sep-2014 22:05:01$"
29
tierno361275f2017-04-25 16:24:34 +020030# import imp
31# import json
tierno7edb6752016-03-21 17:37:52 +010032import yaml
tierno42fcc3b2016-07-06 17:20:40 +020033import utils
tierno42026a02017-02-10 15:13:40 +010034import vim_thread
tiernof97fd272016-07-11 14:32:37 +020035from db_base import HTTP_Unauthorized, HTTP_Bad_Request, HTTP_Internal_Server_Error, HTTP_Not_Found,\
tierno7edb6752016-03-21 17:37:52 +010036 HTTP_Conflict, HTTP_Method_Not_Allowed
37import console_proxy_thread as cli
tiernoae4a8d12016-07-08 12:30:39 +020038import vimconn
39import logging
garciadeblas9f8456e2016-09-05 05:02:59 +020040import collections
tierno66eba6e2017-11-10 17:09:18 +010041import math
tierno8e690322017-08-10 15:58:50 +020042from uuid import uuid4
tiernof97fd272016-07-11 14:32:37 +020043from db_base import db_base_Exception
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010044
tiernob3d36742017-03-03 23:51:05 +010045import nfvo_db
46from threading import Lock
tierno868220c2017-09-26 00:11:05 +020047import time as t
tierno01b3e172017-04-21 10:52:34 +020048from lib_osm_openvim import ovim as ovim_module
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +020049from lib_osm_openvim.ovim import ovimException
gcalvinoe580c7d2017-09-22 14:09:51 +020050from Crypto.PublicKey import RSA
tierno7edb6752016-03-21 17:37:52 +010051
tiernof1ba57e2017-09-07 12:23:19 +020052import osm_im.vnfd as vnfd_catalog
53import osm_im.nsd as nsd_catalog
tiernof1ba57e2017-09-07 12:23:19 +020054from pyangbind.lib.serialise import pybindJSONDecoder
55from itertools import chain
56
tierno7edb6752016-03-21 17:37:52 +010057global global_config
58global vimconn_imported
tierno73ad9e42016-09-12 18:11:11 +020059global logger
montesmoreno0c8def02016-12-22 12:16:23 +000060global default_volume_size
61default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010062global ovim
63ovim = None
tiernoc5651792017-03-27 10:50:43 +020064global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020065
tierno42026a02017-02-10 15:13:40 +010066vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
67vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010068vim_persistent_info = {}
tierno73ad9e42016-09-12 18:11:11 +020069logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010070task_lock = Lock()
tiernob3d36742017-03-03 23:51:05 +010071last_task_id = 0.0
tierno868220c2017-09-26 00:11:05 +020072db = None
73db_lock = Lock()
tierno7edb6752016-03-21 17:37:52 +010074
75class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020076 def __init__(self, message, http_code):
77 self.http_code = http_code
78 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010079
80
tiernob3d36742017-03-03 23:51:05 +010081def get_task_id():
82 global last_task_id
tierno868220c2017-09-26 00:11:05 +020083 task_id = t.time()
tiernob3d36742017-03-03 23:51:05 +010084 if task_id <= last_task_id:
85 task_id = last_task_id + 0.000001
86 last_task_id = task_id
tierno868220c2017-09-26 00:11:05 +020087 return "ACTION-{:.6f}".format(task_id)
88 # 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 +010089
90
tierno867ffe92017-03-27 12:50:34 +020091def new_task(name, params, depends=None):
tierno868220c2017-09-26 00:11:05 +020092 """Deprected!!!"""
tiernob3d36742017-03-03 23:51:05 +010093 task_id = get_task_id()
94 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
95 if depends:
96 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +010097 return task
98
99
100def is_task_id(id):
tierno868220c2017-09-26 00:11:05 +0200101 return True if id[:5] == "TASK-" else False
tiernob3d36742017-03-03 23:51:05 +0100102
103
tierno42026a02017-02-10 15:13:40 +0100104def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
105 name = datacenter_name[:16]
106 if name not in vim_threads["names"]:
107 vim_threads["names"].append(name)
108 return name
tiernob3d36742017-03-03 23:51:05 +0100109 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100110 if name not in vim_threads["names"]:
111 vim_threads["names"].append(name)
112 return name
113 name = datacenter_id + "-" + tenant_id
114 vim_threads["names"].append(name)
115 return name
116
117
118def start_service(mydb):
tiernob3d36742017-03-03 23:51:05 +0100119 global db, global_config
120 db = nfvo_db.nfvo_db()
121 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 +0100122 global ovim
123
124 # Initialize openvim for SDN control
125 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
126 # TODO: review ovim.py to delete not needed configuration
127 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200128 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100129 'network_vlan_range_start': 1000,
130 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200131 'db_name': global_config["db_ovim_name"],
132 'db_host': global_config["db_ovim_host"],
133 'db_user': global_config["db_ovim_user"],
134 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100135 'bridge_ifaces': {},
136 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100137 'network_type': 'bridge',
138 #TODO: log_level_of should not be needed. To be modified in ovim
139 'log_level_of': 'DEBUG'
140 }
tierno42026a02017-02-10 15:13:40 +0100141 try:
tierno3fcfdb72017-10-24 07:48:24 +0200142 # starts ovim library
tierno46df9672017-05-26 13:12:21 +0200143 ovim = ovim_module.ovim(ovim_configuration)
144 ovim.start_service()
145
tierno3fcfdb72017-10-24 07:48:24 +0200146 #delete old unneeded vim_actions
147 clean_db(mydb)
148
149 # starts vim_threads
tierno46df9672017-05-26 13:12:21 +0200150 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
151 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
152 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
153 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
154 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
155 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100156 vims = mydb.get_rows(FROM=from_, SELECT=select_)
157 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200158 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
159 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100160 if vim["config"]:
161 extra.update(yaml.load(vim["config"]))
162 if vim.get('dt_config'):
163 extra.update(yaml.load(vim["dt_config"]))
164 if vim["type"] not in vimconn_imported:
165 module_info=None
166 try:
167 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200168 pkg = __import__("osm_ro." + module)
169 vim_conn = getattr(pkg, module)
170 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
171 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100172 vimconn_imported[vim["type"]] = vim_conn
173 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200174 # if module_info and module_info[0]:
175 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200176 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
tiernob3d36742017-03-03 23:51:05 +0100177 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100178
tierno867ffe92017-03-27 12:50:34 +0200179 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100180 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100181 try:
182 #if not tenant:
183 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
184 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100185 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
186 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
187 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
188 user=vim['user'], passwd=vim['passwd'],
189 config=extra, persistent_info=vim_persistent_info[thread_id]
190 )
tierno9c22f2d2017-10-09 16:23:55 +0200191 except vimconn.vimconnException as e:
192 myvim = e
193 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
194 vim['datacenter_id'], e))
tierno42026a02017-02-10 15:13:40 +0100195 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200196 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
197 HTTP_Internal_Server_Error)
198 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
199 vim['vim_tenant_id'])
tiernob3d36742017-03-03 23:51:05 +0100200 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200201 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100202 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100203 vim_threads["running"][thread_id] = new_thread
204 except db_base_Exception as e:
205 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200206 except ovim_module.ovimException as e:
207 message = str(e)
208 if message[:22] == "DATABASE wrong version":
209 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
210 "at host {dbhost}".format(
211 msg=message[22:-3], dbname=global_config["db_ovim_name"],
212 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
213 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
214 raise NfvoException(message, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100215
tierno867ffe92017-03-27 12:50:34 +0200216
tierno42026a02017-02-10 15:13:40 +0100217def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200218 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100219 if ovim:
220 ovim.stop_service()
tierno42026a02017-02-10 15:13:40 +0100221 for thread_id,thread in vim_threads["running"].items():
tierno868220c2017-09-26 00:11:05 +0200222 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +0100223 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100224 vim_threads["running"] = {}
tiernoc5651792017-03-27 10:50:43 +0200225 if global_config and global_config.get("console_thread"):
226 for thread in global_config["console_thread"]:
227 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100228
tierno6ddeded2017-05-16 15:40:26 +0200229def get_version():
230 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
231 global_config["version_date"] ))
232
tierno3fcfdb72017-10-24 07:48:24 +0200233def clean_db(mydb):
234 """
235 Clean unused or old entries at database to avoid unlimited growing
236 :param mydb: database connector
237 :return: None
238 """
239 # get and delete unused vim_actions: all elements deleted, one week before, instance not present
240 now = t.time()-3600*24*7
241 instance_action_id = None
242 nb_deleted = 0
243 while True:
244 actions_to_delete = mydb.get_rows(
245 SELECT=("item", "item_id", "instance_action_id"),
246 FROM="vim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
247 "left join instance_scenarios as i on ia.instance_id=i.uuid",
248 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
249 "va.status": ("DONE", "SUPERSEDED")},
250 LIMIT=100
251 )
252 for to_delete in actions_to_delete:
253 mydb.delete_row(FROM="vim_actions", WHERE=to_delete)
254 if instance_action_id != to_delete["instance_action_id"]:
255 instance_action_id = to_delete["instance_action_id"]
256 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
257 nb_deleted += len(actions_to_delete)
258 if len(actions_to_delete) < 100:
259 break
260 if nb_deleted:
261 logger.debug("Removed {} unused vim_actions".format(nb_deleted))
262
263
tierno42026a02017-02-10 15:13:40 +0100264
tierno7edb6752016-03-21 17:37:52 +0100265def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
266 '''Obtain flavorList
267 return result, content:
268 <0, error_text upon error
269 nb_records, flavor_list on success
270 '''
271 WHERE_dict={}
272 WHERE_dict['vnf_id'] = vnf_id
273 if nfvo_tenant is not None:
274 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100275
tierno7edb6752016-03-21 17:37:52 +0100276 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
277 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200278 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
279 #print "get_flavor_list result:", result
280 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100281 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200282 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100283 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200284 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100285
tiernob3d36742017-03-03 23:51:05 +0100286
tierno7edb6752016-03-21 17:37:52 +0100287def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
288 '''Obtain imageList
289 return result, content:
290 <0, error_text upon error
291 nb_records, flavor_list on success
292 '''
293 WHERE_dict={}
294 WHERE_dict['vnf_id'] = vnf_id
295 if nfvo_tenant is not None:
296 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100297
tierno7edb6752016-03-21 17:37:52 +0100298 #result, content = mydb.get_table(FROM='vms join vnfs on vms-vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200299 images = mydb.get_rows(FROM='vms join images on vms.image_id=images.uuid',SELECT=('image_id',),WHERE=WHERE_dict )
tierno7edb6752016-03-21 17:37:52 +0100300 imageList=[]
tiernof97fd272016-07-11 14:32:37 +0200301 for image in images:
tierno7edb6752016-03-21 17:37:52 +0100302 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +0200303 return imageList
tierno7edb6752016-03-21 17:37:52 +0100304
tiernob3d36742017-03-03 23:51:05 +0100305
tiernoa2793912016-10-04 08:15:08 +0000306def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
307 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None):
tierno7edb6752016-03-21 17:37:52 +0100308 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100309 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100310 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200311 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100312 '''
313 WHERE_dict={}
314 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
315 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000316 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100317 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
318 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000319 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
320 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100321 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 +0000322 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 +0100323 '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 +0000324 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100325 else:
326 from_ = 'datacenters as d'
327 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200328 try:
329 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
330 vim_dict={}
331 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200332 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
333 'datacenter_id': vim.get('datacenter_id')}
tierno8008c3a2016-10-13 15:34:28 +0000334 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200335 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000336 if vim.get('dt_config'):
337 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200338 if vim["type"] not in vimconn_imported:
339 module_info=None
340 try:
341 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200342 pkg = __import__("osm_ro." + module)
343 vim_conn = getattr(pkg, module)
344 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
345 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200346 vimconn_imported[vim["type"]] = vim_conn
347 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200348 # if module_info and module_info[0]:
349 # file.close(module_info[0])
tiernof97fd272016-07-11 14:32:37 +0200350 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
351 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100352
tierno7edb6752016-03-21 17:37:52 +0100353 try:
tierno867ffe92017-03-27 12:50:34 +0200354 if 'datacenter_tenant_id' in vim:
355 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100356 if thread_id not in vim_persistent_info:
357 vim_persistent_info[thread_id] = {}
358 persistent_info = vim_persistent_info[thread_id]
359 else:
360 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200361 #if not tenant:
362 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
363 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
364 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100365 tenant_id=vim.get('vim_tenant_id',vim_tenant),
366 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100367 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200368 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100369 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200370 )
371 except Exception as e:
372 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
373 return vim_dict
374 except db_base_Exception as e:
375 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100376
tiernob3d36742017-03-03 23:51:05 +0100377
tierno7edb6752016-03-21 17:37:52 +0100378def rollback(mydb, vims, rollback_list):
379 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100380 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100381 for i in range(len(rollback_list)-1, -1, -1):
382 item = rollback_list[i]
383 if item["where"]=="vim":
384 if item["vim_id"] not in vims:
385 continue
tierno56d73d22017-08-02 13:53:02 +0200386 if is_task_id(item["uuid"]):
387 continue
388 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200389 try:
390 if item["what"]=="image":
391 vim.delete_image(item["uuid"])
tierno868220c2017-09-26 00:11:05 +0200392 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200393 elif item["what"]=="flavor":
394 vim.delete_flavor(item["uuid"])
tiernoad6bdd42018-01-10 10:43:46 +0100395 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200396 elif item["what"]=="network":
397 vim.delete_network(item["uuid"])
398 elif item["what"]=="vm":
399 vim.delete_vminstance(item["uuid"])
400 except vimconn.vimconnException as e:
401 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
402 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200403 except db_base_Exception as e:
404 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 +0100405
tierno7edb6752016-03-21 17:37:52 +0100406 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200407 try:
408 if item["what"]=="image":
409 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
410 elif item["what"]=="flavor":
411 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
412 except db_base_Exception as e:
413 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
414 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100415 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100416 return True," Rollback successful."
417 else:
418 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100419
tiernob3d36742017-03-03 23:51:05 +0100420
tiernoafed5f12017-01-26 17:57:43 +0100421def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100422 global global_config
tierno42026a02017-02-10 15:13:40 +0100423 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100424 vnfc_interfaces={}
425 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100426 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100427 #dataplane interfaces
428 for numa in vnfc.get("numas",() ):
429 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100430 if interface["name"] in name_dict:
431 raise NfvoException(
432 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
433 vnfc["name"], interface["name"]),
434 HTTP_Bad_Request)
435 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100436 #bridge interfaces
437 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100438 if interface["name"] in name_dict:
439 raise NfvoException(
440 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
441 vnfc["name"], interface["name"]),
442 HTTP_Bad_Request)
443 name_dict[ interface["name"] ] = "overlay"
444 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100445 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200446 # if "boot-data" in vnfc:
447 # # check that user-data is incompatible with users and config-files
448 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
449 # raise NfvoException(
450 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
451 # HTTP_Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100452
tierno7edb6752016-03-21 17:37:52 +0100453 #check if the info in external_connections matches with the one in the vnfcs
454 name_list=[]
455 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
456 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100457 raise NfvoException(
458 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
459 external_connection["name"]),
460 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100461 name_list.append(external_connection["name"])
462 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100463 raise NfvoException(
464 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
465 external_connection["name"], external_connection["VNFC"]),
466 HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100467
tierno7edb6752016-03-21 17:37:52 +0100468 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100469 raise NfvoException(
470 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
471 external_connection["name"],
472 external_connection["local_iface_name"]),
473 HTTP_Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100474
tierno7edb6752016-03-21 17:37:52 +0100475 #check if the info in internal_connections matches with the one in the vnfcs
476 name_list=[]
477 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
478 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100479 raise NfvoException(
480 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
481 internal_connection["name"]),
482 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100483 name_list.append(internal_connection["name"])
484 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100485
486 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
487 raise NfvoException(
488 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
489 internal_connection["name"],
490 'ptp' if vnf_descriptor_version==1 else 'e-line',
491 'data' if vnf_descriptor_version==1 else "e-lan"),
492 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100493 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100494 vnf = port["VNFC"]
495 iface = port["local_iface_name"]
496 if vnf not in vnfc_interfaces:
497 raise NfvoException(
498 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
499 internal_connection["name"], vnf),
500 HTTP_Bad_Request)
501 if iface not in vnfc_interfaces[ vnf ]:
502 raise NfvoException(
503 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
504 internal_connection["name"], iface),
505 HTTP_Bad_Request)
506 return -HTTP_Bad_Request,
507 if vnf_descriptor_version==1 and "type" not in internal_connection:
508 if vnfc_interfaces[vnf][iface] == "overlay":
509 internal_connection["type"] = "bridge"
510 else:
511 internal_connection["type"] = "data"
512 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
513 if vnfc_interfaces[vnf][iface] == "overlay":
514 internal_connection["implementation"] = "overlay"
515 else:
516 internal_connection["implementation"] = "underlay"
517 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
518 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
519 raise NfvoException(
520 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
521 internal_connection["name"],
522 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
523 'data' if vnf_descriptor_version==1 else 'underlay'),
524 HTTP_Bad_Request)
525 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
526 vnfc_interfaces[vnf][iface] == "underlay":
527 raise NfvoException(
528 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
529 internal_connection["name"], iface,
530 'data' if vnf_descriptor_version==1 else 'underlay',
531 'bridge' if vnf_descriptor_version==1 else 'overlay'),
532 HTTP_Bad_Request)
533
tierno7edb6752016-03-21 17:37:52 +0100534
tierno56d73d22017-08-02 13:53:02 +0200535def 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 +0100536 #look if image exist
537 if only_create_at_vim:
538 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000539 if return_on_error == None:
540 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100541 else:
garciadeblas14480452017-01-10 13:08:07 +0100542 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200543 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
544 else:
545 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200546 if len(images)>=1:
547 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100548 else:
garciadeblas14480452017-01-10 13:08:07 +0100549 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100550 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200551 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
552 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100553 }
garciadeblas14480452017-01-10 13:08:07 +0100554 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200555 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
556 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100557 #create image at every vim
558 for vim_id,vim in vims.iteritems():
tierno868220c2017-09-26 00:11:05 +0200559 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100560 image_created="false"
561 #look at database
tierno868220c2017-09-26 00:11:05 +0200562 image_db = mydb.get_rows(FROM="datacenters_images",
563 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100564 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200565 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200566 if image_dict['location'] is not None:
567 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
568 else:
garciadeblas30833382017-01-09 09:46:31 +0100569 filter_dict = {}
570 filter_dict['name'] = image_dict['universal_name']
571 if image_dict.get('checksum') != None:
572 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000573 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200574 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100575 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200576 if len(vim_images) > 1:
garciadeblas3fa2c052017-01-05 12:00:08 +0100577 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), HTTP_Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000578 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100579 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200580 else:
garciadeblas14480452017-01-10 13:08:07 +0100581 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
582 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200583
tiernoae4a8d12016-07-08 12:30:39 +0200584 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100585 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100586 try:
garciadeblas14480452017-01-10 13:08:07 +0100587 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
588 if image_dict['location']:
589 image_vim_id = vim.new_image(image_dict)
590 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
591 image_created="true"
592 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100593 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
594 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200595 except vimconn.vimconnException as e:
596 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100597 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200598 raise
tierno5e91eb82016-10-04 09:39:07 +0000599 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100600 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200601 continue
602 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000603 if return_on_error:
604 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
605 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200606 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000607 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100608 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200609 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200610 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100611 #add new vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200612 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
613 'image_id':image_mano_id,
614 'vim_id': image_vim_id,
615 'created':image_created})
tierno7edb6752016-03-21 17:37:52 +0100616 elif image_db[0]["vim_id"]!=image_vim_id:
617 #modify existing vim_id at datacenters_images
tierno868220c2017-09-26 00:11:05 +0200618 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 +0100619
tiernof97fd272016-07-11 14:32:37 +0200620 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100621
tiernob3d36742017-03-03 23:51:05 +0100622
tierno5e91eb82016-10-04 09:39:07 +0000623def 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 +0100624 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
tierno7edb6752016-03-21 17:37:52 +0100625 'ram':flavor_dict.get('ram'),
626 'vcpus':flavor_dict.get('vcpus'),
627 }
628 if 'extended' in flavor_dict and flavor_dict['extended']==None:
629 del flavor_dict['extended']
630 if 'extended' in flavor_dict:
631 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
632
633 #look if flavor exist
634 if only_create_at_vim:
635 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000636 if return_on_error == None:
637 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100638 else:
tiernof97fd272016-07-11 14:32:37 +0200639 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
640 if len(flavors)>=1:
641 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100642 else:
643 #create flavor
644 #create one by one the images of aditional disks
645 dev_image_list=[] #list of images
646 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
647 dev_nb=0
648 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200649 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100650 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200651 image_dict={}
652 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
653 image_dict['universal_name']=device.get('image name')
654 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
655 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100656 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200657 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100658 image_metadata_dict = device.get('image metadata', None)
659 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100660 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100661 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
662 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200663 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
664 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100665 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100666 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100667 temp_flavor_dict['name'] = flavor_dict['name']
668 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200669 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
670 flavor_mano_id= content
671 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100672 #create flavor at every vim
673 if 'uuid' in flavor_dict:
674 del flavor_dict['uuid']
675 flavor_vim_id=None
676 for vim_id,vim in vims.items():
tierno868220c2017-09-26 00:11:05 +0200677 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
tierno7edb6752016-03-21 17:37:52 +0100678 flavor_created="false"
679 #look at database
tierno868220c2017-09-26 00:11:05 +0200680 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
681 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100682 #look at VIM if this flavor exist SKIPPED
683 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
684 #if res_vim < 0:
685 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
686 # continue
687 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100688
tiernof1ba57e2017-09-07 12:23:19 +0200689 # Create the flavor in VIM
690 # Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000691 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100692 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
tiernof1ba57e2017-09-07 12:23:19 +0200693 # make a copy of original devices
tierno7edb6752016-03-21 17:37:52 +0100694 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000695
tierno7edb6752016-03-21 17:37:52 +0100696 for device in flavor_dict["extended"].get("devices",[]):
697 dev={}
698 dev.update(device)
699 devices_original.append(dev)
700 if 'image' in device:
701 del device['image']
702 if 'image metadata' in device:
703 del device['image metadata']
tiernof1ba57e2017-09-07 12:23:19 +0200704 if 'image checksum' in device:
705 del device['image checksum']
706 dev_nb = 0
tierno7edb6752016-03-21 17:37:52 +0100707 for index in range(0,len(devices_original)) :
708 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000709 if "image" not in device and "image name" not in device:
710 if 'size' in device:
711 disk_list.append({'size': device.get('size', default_volume_size)})
tierno7edb6752016-03-21 17:37:52 +0100712 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200713 image_dict={}
714 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
715 image_dict['universal_name']=device.get('image name')
716 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
717 image_dict['location']=device.get('image')
tiernof1ba57e2017-09-07 12:23:19 +0200718 # image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200719 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100720 image_metadata_dict = device.get('image metadata', None)
721 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100722 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100723 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
724 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200725 image_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 +0100726 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200727 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 +0000728
729 #save disk information (image must be based on and size
730 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
731
tierno7edb6752016-03-21 17:37:52 +0100732 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
733 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200734 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100735 #check that this vim_id exist in VIM, if not create
736 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200737 try:
738 vim.get_flavor(flavor_vim_id)
739 continue #flavor exist
740 except vimconn.vimconnException:
741 pass
tierno7edb6752016-03-21 17:37:52 +0100742 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200743 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
744 try:
tiernocf157a82017-01-30 14:07:06 +0100745 flavor_vim_id = None
746 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
747 flavor_create="false"
748 except vimconn.vimconnException as e:
749 pass
750 try:
751 if not flavor_vim_id:
752 flavor_vim_id = vim.new_flavor(flavor_dict)
753 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
754 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200755 except vimconn.vimconnException as e:
756 if return_on_error:
757 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200758 raise
tiernoae4a8d12016-07-08 12:30:39 +0200759 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000760 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200761 continue
tierno7edb6752016-03-21 17:37:52 +0100762 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200763 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100764 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000765 extended_devices_yaml = None
766 if len(disk_list) > 0:
767 extended_devices = dict()
768 extended_devices['disks'] = disk_list
769 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
770 mydb.new_row('datacenters_flavors',
tierno868220c2017-09-26 00:11:05 +0200771 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
772 'created': flavor_created, 'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100773 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
774 #modify existing vim_id at datacenters_flavors
tierno868220c2017-09-26 00:11:05 +0200775 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
776 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100777
tiernof97fd272016-07-11 14:32:37 +0200778 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100779
tiernob3d36742017-03-03 23:51:05 +0100780
tiernof1ba57e2017-09-07 12:23:19 +0200781def get_str(obj, field, length):
782 """
783 Obtain the str value,
784 :param obj:
785 :param length:
786 :return:
787 """
788 value = obj.get(field)
789 if value is not None:
790 value = str(value)[:length]
791 return value
792
793def _lookfor_or_create_image(db_image, mydb, descriptor):
794 """
795 fill image content at db_image dictionary. Check if the image with this image and checksum exist
796 :param db_image: dictionary to insert data
797 :param mydb: database connector
798 :param descriptor: yang descriptor
799 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
800 """
801
802 db_image["name"] = get_str(descriptor, "image", 255)
803 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
804 if not db_image["checksum"]: # Ensure that if empty string, None is stored
805 db_image["checksum"] = None
806 if db_image["name"].startswith("/"):
807 db_image["location"] = db_image["name"]
808 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
809 else:
810 db_image["universal_name"] = db_image["name"]
811 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
812 'checksum': db_image['checksum']})
813 if existing_images:
814 return existing_images[0]["uuid"]
815 else:
816 image_uuid = str(uuid4())
817 db_image["uuid"] = image_uuid
818 return None
819
820def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
821 """
822 Parses an OSM IM vnfd_catalog and insert at DB
823 :param mydb:
824 :param tenant_id:
825 :param vnf_descriptor:
826 :return: The list of cretated vnf ids
827 """
828 try:
829 myvnfd = vnfd_catalog.vnfd()
tiernoa9550202017-09-22 13:31:35 +0200830 try:
tiernoad6bdd42018-01-10 10:43:46 +0100831 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True)
tiernoa9550202017-09-22 13:31:35 +0200832 except Exception as e:
tiernob2880eb2017-10-04 15:04:53 +0200833 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200834 db_vnfs = []
835 db_nets = []
836 db_vms = []
837 db_vms_index = 0
838 db_interfaces = []
839 db_images = []
840 db_flavors = []
tierno41a69812018-02-16 14:34:33 +0100841 db_ip_profiles_index = 0
842 db_ip_profiles = []
tiernof1ba57e2017-09-07 12:23:19 +0200843 uuid_list = []
844 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200845 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
846 if not vnfd_catalog_descriptor:
847 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
848 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
849 if not vnfd_descriptor_list:
850 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200851 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
852 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200853
854 # table vnf
855 vnf_uuid = str(uuid4())
856 uuid_list.append(vnf_uuid)
857 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100858 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200859 db_vnf = {
860 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100861 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200862 "name": get_str(vnfd, "name", 255),
863 "description": get_str(vnfd, "description", 255),
864 "tenant_id": tenant_id,
865 "vendor": get_str(vnfd, "vendor", 255),
866 "short_name": get_str(vnfd, "short-name", 255),
867 "descriptor": str(vnf_descriptor)[:60000]
868 }
869
tiernoe18ba432017-10-12 10:22:45 +0200870 for vnfd_descriptor in vnfd_descriptor_list:
871 if vnfd_descriptor["id"] == str(vnfd["id"]):
872 break
873
tierno41a69812018-02-16 14:34:33 +0100874 # table ip_profiles (ip-profiles)
875 ip_profile_name2db_table_index = {}
876 for ip_profile in vnfd.get("ip-profiles").itervalues():
877 db_ip_profile = {
878 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
879 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
880 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
881 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
882 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
883 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
884 }
885 dns_list = []
886 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
887 dns_list.append(str(dns.get("address")))
888 db_ip_profile["dns_address"] = ";".join(dns_list)
889 if ip_profile["ip-profile-params"].get('security-group'):
890 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
891 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
892 db_ip_profiles_index += 1
893 db_ip_profiles.append(db_ip_profile)
894
tiernof1ba57e2017-09-07 12:23:19 +0200895 # table nets (internal-vld)
896 net_id2uuid = {} # for mapping interface with network
897 for vld in vnfd.get("internal-vld").itervalues():
898 net_uuid = str(uuid4())
899 uuid_list.append(net_uuid)
900 db_net = {
901 "name": get_str(vld, "name", 255),
902 "vnf_id": vnf_uuid,
903 "uuid": net_uuid,
904 "description": get_str(vld, "description", 255),
905 "type": "bridge", # TODO adjust depending on connection point type
906 }
907 net_id2uuid[vld.get("id")] = net_uuid
908 db_nets.append(db_net)
tierno41a69812018-02-16 14:34:33 +0100909 # ip-profile, link db_ip_profile with db_sce_net
910 if vld.get("ip-profile-ref"):
911 ip_profile_name = vld.get("ip-profile-ref")
912 if ip_profile_name not in ip_profile_name2db_table_index:
913 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
914 "'{}'. Reference to a non-existing 'ip_profiles'".format(
915 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
916 HTTP_Bad_Request)
917 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
918 else: #check no ip-address has been defined
tierno45140f52018-03-26 12:11:46 +0200919 for icp in vld.get("internal-connection-point").itervalues():
tierno41a69812018-02-16 14:34:33 +0100920 if icp.get("ip-address"):
921 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
922 "contains an ip-address but no ip-profile has been defined at VLD".format(
923 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
924 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +0200925
tiernocf596692017-11-20 15:47:51 +0100926 # connection points vaiable declaration
927 cp_name2iface_uuid = {}
928 cp_name2vm_uuid = {}
929 cp_name2db_interface = {}
930
tiernof1ba57e2017-09-07 12:23:19 +0200931 # table vms (vdus)
932 vdu_id2uuid = {}
933 vdu_id2db_table_index = {}
934 for vdu in vnfd.get("vdu").itervalues():
tierno41a69812018-02-16 14:34:33 +0100935
936 for vdu_descriptor in vnfd_descriptor["vdu"]:
937 if vdu_descriptor["id"] == str(vdu["id"]):
938 break
tiernof1ba57e2017-09-07 12:23:19 +0200939 vm_uuid = str(uuid4())
940 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100941 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200942 db_vm = {
943 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100944 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +0200945 "name": get_str(vdu, "name", 255),
946 "description": get_str(vdu, "description", 255),
947 "vnf_id": vnf_uuid,
948 }
949 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
950 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
951 if vdu.get("count"):
952 db_vm["count"] = int(vdu["count"])
953
954 # table image
955 image_present = False
956 if vdu.get("image"):
957 image_present = True
958 db_image = {}
959 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
960 if not image_uuid:
961 image_uuid = db_image["uuid"]
962 db_images.append(db_image)
963 db_vm["image_id"] = image_uuid
964
965 # volumes
966 devices = []
967 if vdu.get("volumes"):
968 for volume_key in sorted(vdu["volumes"]):
969 volume = vdu["volumes"][volume_key]
970 if not image_present:
971 # Convert the first volume to vnfc.image
972 image_present = True
973 db_image = {}
974 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
975 if not image_uuid:
976 image_uuid = db_image["uuid"]
977 db_images.append(db_image)
978 db_vm["image_id"] = image_uuid
979 else:
980 # Add Openmano devices
981 device = {}
982 device["type"] = str(volume.get("device-type"))
983 if volume.get("size"):
984 device["size"] = int(volume["size"])
985 if volume.get("image"):
986 device["image name"] = str(volume["image"])
987 if volume.get("image-checksum"):
988 device["image checksum"] = str(volume["image-checksum"])
989 devices.append(device)
990
tierno66eba6e2017-11-10 17:09:18 +0100991 # cloud-init
992 boot_data = {}
993 if vdu.get("cloud-init"):
994 boot_data["user-data"] = str(vdu["cloud-init"])
995 elif vdu.get("cloud-init-file"):
996 # TODO Where this file content is present???
997 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
998 boot_data["user-data"] = str(vdu["cloud-init-file"])
999
1000 if vdu.get("supplemental-boot-data"):
1001 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1002 boot_data['boot-data-drive'] = True
1003 if vdu["supplemental-boot-data"].get('config-file'):
1004 om_cfgfile_list = list()
1005 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
1006 # TODO Where this file content is present???
1007 cfg_source = str(custom_config_file["source"])
1008 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1009 "content": cfg_source})
1010 boot_data['config-files'] = om_cfgfile_list
1011 if boot_data:
1012 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1013
1014 db_vms.append(db_vm)
1015 db_vms_index += 1
1016
1017 # table interfaces (internal/external interfaces)
1018 flavor_epa_interfaces = []
tierno66eba6e2017-11-10 17:09:18 +01001019 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
1020 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
1021 for iface in vdu.get("interface").itervalues():
1022 flavor_epa_interface = {}
1023 iface_uuid = str(uuid4())
1024 uuid_list.append(iface_uuid)
1025 db_interface = {
1026 "uuid": iface_uuid,
1027 "internal_name": get_str(iface, "name", 255),
1028 "vm_id": vm_uuid,
1029 }
1030 flavor_epa_interface["name"] = db_interface["internal_name"]
1031 if iface.get("virtual-interface").get("vpci"):
1032 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1033 flavor_epa_interface["vpci"] = db_interface["vpci"]
1034
1035 if iface.get("virtual-interface").get("bandwidth"):
1036 bps = int(iface.get("virtual-interface").get("bandwidth"))
1037 db_interface["bw"] = int(math.ceil(bps/1000000.0))
1038 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1039
1040 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1041 db_interface["type"] = "mgmt"
1042 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000"):
1043 db_interface["type"] = "bridge"
1044 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1045 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1046 db_interface["type"] = "data"
1047 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1048 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1049 else "yes"
1050 flavor_epa_interfaces.append(flavor_epa_interface)
1051 else:
1052 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1053 "-interface':'type':'{}'. Interface type is not supported".format(
1054 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
1055 HTTP_Bad_Request)
1056
1057 if iface.get("external-connection-point-ref"):
1058 try:
1059 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1060 db_interface["external_name"] = get_str(cp, "name", 255)
1061 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1062 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1063 cp_name2db_interface[db_interface["external_name"]] = db_interface
1064 for cp_descriptor in vnfd_descriptor["connection-point"]:
1065 if cp_descriptor["name"] == db_interface["external_name"]:
1066 break
1067 else:
1068 raise KeyError()
1069
1070 if vdu_id in vdu_id2cp_name:
1071 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1072 else:
1073 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1074
1075 # port security
1076 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1077 db_interface["port_security"] = 0
1078 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1079 db_interface["port_security"] = 1
1080 except KeyError:
1081 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1082 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1083 " at connection-point".format(
1084 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1085 cp=iface.get("vnfd-connection-point-ref")),
1086 HTTP_Bad_Request)
1087 elif iface.get("internal-connection-point-ref"):
1088 try:
tierno41a69812018-02-16 14:34:33 +01001089 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1090 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1091 break
1092 else:
1093 raise KeyError("does not exist at vdu:internal-connection-point")
1094 icp = None
1095 icp_vld = None
tierno66eba6e2017-11-10 17:09:18 +01001096 for vld in vnfd.get("internal-vld").itervalues():
1097 for cp in vld.get("internal-connection-point").itervalues():
1098 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
tierno41a69812018-02-16 14:34:33 +01001099 if icp:
1100 raise KeyError("is referenced by more than one 'internal-vld'")
1101 icp = cp
1102 icp_vld = vld
1103 if not icp:
1104 raise KeyError("is not referenced by any 'internal-vld'")
1105
1106 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1107 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1108 db_interface["port_security"] = 0
1109 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1110 db_interface["port_security"] = 1
1111 if icp.get("ip-address"):
1112 if not icp_vld.get("ip-profile-ref"):
1113 raise NfvoException
1114 db_interface["ip_address"] = str(icp.get("ip-address"))
1115 except KeyError as e:
tierno66eba6e2017-11-10 17:09:18 +01001116 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
tierno41a69812018-02-16 14:34:33 +01001117 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1118 " {msg}".format(
tierno66eba6e2017-11-10 17:09:18 +01001119 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
tierno41a69812018-02-16 14:34:33 +01001120 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
tierno66eba6e2017-11-10 17:09:18 +01001121 HTTP_Bad_Request)
1122 if iface.get("position") is not None:
1123 db_interface["created_at"] = int(iface.get("position")) - 1000
tierno41a69812018-02-16 14:34:33 +01001124 if iface.get("mac-address"):
1125 db_interface["mac"] = str(iface.get("mac-address"))
tierno66eba6e2017-11-10 17:09:18 +01001126 db_interfaces.append(db_interface)
1127
tiernof1ba57e2017-09-07 12:23:19 +02001128 # table flavors
1129 db_flavor = {
1130 "name": get_str(vdu, "name", 250) + "-flv",
1131 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1132 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
garciadeblas79d1a1a2017-12-11 16:07:07 +01001133 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
tiernof1ba57e2017-09-07 12:23:19 +02001134 }
tiernocf596692017-11-20 15:47:51 +01001135 # TODO revise the case of several numa-node-policy node
tiernof1ba57e2017-09-07 12:23:19 +02001136 extended = {}
1137 numa = {}
1138 if devices:
1139 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001140 if flavor_epa_interfaces:
1141 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001142 if vdu.get("guest-epa"): # TODO or dedicated_int:
1143 epa_vcpu_set = False
1144 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1145 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1146 if numa_node_policy.get("node"):
tiernocf596692017-11-20 15:47:51 +01001147 numa_node = numa_node_policy["node"].values()[0]
tiernof1ba57e2017-09-07 12:23:19 +02001148 if numa_node.get("num-cores"):
1149 numa["cores"] = numa_node["num-cores"]
1150 epa_vcpu_set = True
1151 if numa_node.get("paired-threads"):
1152 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001153 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001154 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001155 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001156 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001157 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001158 numa["paired-threads-id"].append(
1159 (str(pair["thread-a"]), str(pair["thread-b"]))
1160 )
1161 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001162 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001163 epa_vcpu_set = True
1164 if numa_node.get("memory-mb"):
1165 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1166 if vdu["guest-epa"].get("mempage-size"):
1167 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1168 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1169 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1170 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1171 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1172 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1173 numa["cores"] = max(db_flavor["vcpus"], 1)
1174 else:
1175 numa["threads"] = max(db_flavor["vcpus"], 1)
1176 if numa:
1177 extended["numas"] = [numa]
1178 if extended:
1179 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1180 db_flavor["extended"] = extended_text
1181 # look if flavor exist
garciadeblas79d1a1a2017-12-11 16:07:07 +01001182 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
tiernof1ba57e2017-09-07 12:23:19 +02001183 'ram': db_flavor.get('ram'),
1184 'vcpus': db_flavor.get('vcpus'),
1185 'extended': db_flavor.get('extended')
1186 }
1187 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1188 if existing_flavors:
1189 flavor_uuid = existing_flavors[0]["uuid"]
1190 else:
1191 flavor_uuid = str(uuid4())
1192 uuid_list.append(flavor_uuid)
1193 db_flavor["uuid"] = flavor_uuid
1194 db_flavors.append(db_flavor)
1195 db_vm["flavor_id"] = flavor_uuid
1196
tiernof1ba57e2017-09-07 12:23:19 +02001197 # VNF affinity and antiaffinity
1198 for pg in vnfd.get("placement-groups").itervalues():
1199 pg_name = get_str(pg, "name", 255)
1200 for vdu in pg.get("member-vdus").itervalues():
1201 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1202 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001203 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1204 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001205 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
tiernob2880eb2017-10-04 15:04:53 +02001206 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001207 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
1208 # TODO consider the case of isolation and not colocation
1209 # if pg.get("strategy") == "ISOLATION":
1210
1211 # VNF mgmt configuration
1212 mgmt_access = {}
1213 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001214 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1215 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001216 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1217 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001218 vnf=vnfd_id, vdu=mgmt_vdu_id),
tiernob2880eb2017-10-04 15:04:53 +02001219 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001220 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001221 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1222 if vdu_id2cp_name.get(mgmt_vdu_id):
1223 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
1224
tiernof1ba57e2017-09-07 12:23:19 +02001225 if vnfd["mgmt-interface"].get("ip-address"):
1226 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1227 if vnfd["mgmt-interface"].get("cp"):
1228 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob2880eb2017-10-04 15:04:53 +02001229 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp':'{cp}'. "
1230 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001231 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
tiernob2880eb2017-10-04 15:04:53 +02001232 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001233 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1234 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001235 # mark this interface as of type mgmt
1236 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
1237
tiernoa9550202017-09-22 13:31:35 +02001238 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001239 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001240
tiernof1ba57e2017-09-07 12:23:19 +02001241 if default_user:
1242 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001243 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1244 "required", 6)
1245 if required:
1246 mgmt_access["required"] = required
1247
tiernof1ba57e2017-09-07 12:23:19 +02001248 if mgmt_access:
1249 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1250
1251 db_vnfs.append(db_vnf)
1252 db_tables=[
1253 {"vnfs": db_vnfs},
1254 {"nets": db_nets},
1255 {"images": db_images},
1256 {"flavors": db_flavors},
tierno41a69812018-02-16 14:34:33 +01001257 {"ip_profiles": db_ip_profiles},
tiernof1ba57e2017-09-07 12:23:19 +02001258 {"vms": db_vms},
1259 {"interfaces": db_interfaces},
1260 ]
1261
1262 logger.debug("create_vnf Deployment done vnfDict: %s",
1263 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1264 mydb.new_rows(db_tables, uuid_list)
1265 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001266 except NfvoException:
1267 raise
tiernof1ba57e2017-09-07 12:23:19 +02001268 except Exception as e:
1269 logger.error("Exception {}".format(e))
1270 raise # NfvoException("Exception {}".format(e), HTTP_Bad_Request)
1271
1272
tierno7edb6752016-03-21 17:37:52 +01001273def new_vnf(mydb, tenant_id, vnf_descriptor):
1274 global global_config
tierno42026a02017-02-10 15:13:40 +01001275
tierno7edb6752016-03-21 17:37:52 +01001276 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001277 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001278 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001279 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001280 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001281 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001282 if "tenant_id" in vnf_descriptor["vnf"]:
1283 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001284 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1285 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001286 else:
1287 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1288 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001289 if global_config["auto_push_VNF_to_VIMs"]:
1290 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001291
1292 # Step 4. Review the descriptor and add missing fields
1293 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001294 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001295 vnf_name = vnf_descriptor['vnf']['name']
1296 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1297 if "physical" in vnf_descriptor['vnf']:
1298 del vnf_descriptor['vnf']['physical']
1299 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001300
tierno42026a02017-02-10 15:13:40 +01001301 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001302 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1303 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001304
tierno7edb6752016-03-21 17:37:52 +01001305 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1306 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1307 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001308 try:
tiernof97fd272016-07-11 14:32:37 +02001309 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001310 for vnfc in vnf_descriptor['vnf']['VNFC']:
1311 VNFCitem={}
1312 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001313 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001314 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001315
tiernof97fd272016-07-11 14:32:37 +02001316 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001317
tierno7edb6752016-03-21 17:37:52 +01001318 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001319 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 +01001320 myflavorDict["description"] = VNFCitem["description"]
1321 myflavorDict["ram"] = vnfc.get("ram", 0)
1322 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001323 myflavorDict["disk"] = vnfc.get("disk", 0)
tierno7edb6752016-03-21 17:37:52 +01001324 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001325
tierno7edb6752016-03-21 17:37:52 +01001326 devices = vnfc.get("devices")
1327 if devices != None:
1328 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001329
tierno7edb6752016-03-21 17:37:52 +01001330 # TODO:
1331 # 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 +01001332 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1333
tierno7edb6752016-03-21 17:37:52 +01001334 # Previous code has been commented
1335 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1336 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1337 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1338 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1339 #else:
1340 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1341 # if result2:
1342 # print "Error creating flavor: unknown processor model. Rollback successful."
1343 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1344 # else:
1345 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1346 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001347
tierno7edb6752016-03-21 17:37:52 +01001348 if 'numas' in vnfc and len(vnfc['numas'])>0:
1349 myflavorDict['extended']['numas'] = vnfc['numas']
1350
1351 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001352
tierno7edb6752016-03-21 17:37:52 +01001353 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001354 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001355
tiernof97fd272016-07-11 14:32:37 +02001356 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001357 VNFCitem["flavor_id"] = flavor_id
1358 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001359
tiernof97fd272016-07-11 14:32:37 +02001360 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001361 # Step 6.3 New images are created in the VIM
1362 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001363 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001364 #In case this integration is made, the VNFCDict might become a VNFClist.
1365 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001366 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001367 image_dict={}
1368 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1369 image_dict['universal_name']=vnfc.get('image name')
1370 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1371 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001372 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001373 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001374 image_metadata_dict = vnfc.get('image metadata', None)
1375 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001376 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001377 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1378 image_dict['metadata']=image_metadata_str
1379 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001380 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1381 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001382 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001383 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001384 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001385 if vnfc.get("boot-data"):
1386 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001387
tierno42026a02017-02-10 15:13:40 +01001388
tiernof97fd272016-07-11 14:32:37 +02001389 # Step 7. Storing the VNF descriptor in the repository
1390 if "descriptor" not in vnf_descriptor["vnf"]:
1391 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001392
tiernof97fd272016-07-11 14:32:37 +02001393 # Step 8. Adding the VNF to the NFVO DB
1394 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1395 return vnf_id
1396 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001397 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001398 if isinstance(e, db_base_Exception):
1399 error_text = "Exception at database"
1400 elif isinstance(e, KeyError):
1401 error_text = "KeyError exception "
1402 e.http_code = HTTP_Internal_Server_Error
1403 else:
1404 error_text = "Exception at VIM"
1405 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1406 #logger.error("start_scenario %s", error_text)
1407 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001408
tiernob3d36742017-03-03 23:51:05 +01001409
garciadeblas9f8456e2016-09-05 05:02:59 +02001410def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1411 global global_config
tierno42026a02017-02-10 15:13:40 +01001412
garciadeblas9f8456e2016-09-05 05:02:59 +02001413 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001414 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001415 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001416 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001417 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001418 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001419 if "tenant_id" in vnf_descriptor["vnf"]:
1420 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1421 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1422 HTTP_Unauthorized)
1423 else:
1424 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1425 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001426 if global_config["auto_push_VNF_to_VIMs"]:
1427 vims = get_vim(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001428
1429 # Step 4. Review the descriptor and add missing fields
1430 #print vnf_descriptor
1431 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1432 vnf_name = vnf_descriptor['vnf']['name']
1433 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1434 if "physical" in vnf_descriptor['vnf']:
1435 del vnf_descriptor['vnf']['physical']
1436 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001437
tierno42026a02017-02-10 15:13:40 +01001438 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001439 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1440 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001441
garciadeblas9f8456e2016-09-05 05:02:59 +02001442 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1443 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1444 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1445 try:
1446 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1447 for vnfc in vnf_descriptor['vnf']['VNFC']:
1448 VNFCitem={}
1449 VNFCitem["name"] = vnfc['name']
1450 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001451
garciadeblas9f8456e2016-09-05 05:02:59 +02001452 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001453
garciadeblas9f8456e2016-09-05 05:02:59 +02001454 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001455 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 +02001456 myflavorDict["description"] = VNFCitem["description"]
1457 myflavorDict["ram"] = vnfc.get("ram", 0)
1458 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
garciadeblas79d1a1a2017-12-11 16:07:07 +01001459 myflavorDict["disk"] = vnfc.get("disk", 0)
garciadeblas9f8456e2016-09-05 05:02:59 +02001460 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001461
garciadeblas9f8456e2016-09-05 05:02:59 +02001462 devices = vnfc.get("devices")
1463 if devices != None:
1464 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001465
garciadeblas9f8456e2016-09-05 05:02:59 +02001466 # TODO:
1467 # 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 +01001468 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1469
garciadeblas9f8456e2016-09-05 05:02:59 +02001470 # Previous code has been commented
1471 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1472 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1473 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1474 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1475 #else:
1476 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1477 # if result2:
1478 # print "Error creating flavor: unknown processor model. Rollback successful."
1479 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1480 # else:
1481 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1482 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001483
garciadeblas9f8456e2016-09-05 05:02:59 +02001484 if 'numas' in vnfc and len(vnfc['numas'])>0:
1485 myflavorDict['extended']['numas'] = vnfc['numas']
1486
1487 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001488
garciadeblas9f8456e2016-09-05 05:02:59 +02001489 # Step 6.2 New flavors are created in the VIM
1490 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1491
1492 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1493 VNFCitem["flavor_id"] = flavor_id
1494 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001495
garciadeblas9f8456e2016-09-05 05:02:59 +02001496 logger.debug("Creating new images in the VIM for each VNFC")
1497 # Step 6.3 New images are created in the VIM
1498 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001499 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001500 #In case this integration is made, the VNFCDict might become a VNFClist.
1501 for vnfc in vnf_descriptor['vnf']['VNFC']:
1502 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001503 image_dict={}
1504 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1505 image_dict['universal_name']=vnfc.get('image name')
1506 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1507 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001508 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001509 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001510 image_metadata_dict = vnfc.get('image metadata', None)
1511 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001512 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001513 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1514 image_dict['metadata']=image_metadata_str
1515 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1516 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1517 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1518 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001519 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001520 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001521 if vnfc.get("boot-data"):
1522 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001523
garciadeblas9f8456e2016-09-05 05:02:59 +02001524 # Step 7. Storing the VNF descriptor in the repository
1525 if "descriptor" not in vnf_descriptor["vnf"]:
1526 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001527
garciadeblas9f8456e2016-09-05 05:02:59 +02001528 # Step 8. Adding the VNF to the NFVO DB
1529 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1530 return vnf_id
1531 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1532 _, message = rollback(mydb, vims, rollback_list)
1533 if isinstance(e, db_base_Exception):
1534 error_text = "Exception at database"
1535 elif isinstance(e, KeyError):
1536 error_text = "KeyError exception "
1537 e.http_code = HTTP_Internal_Server_Error
1538 else:
1539 error_text = "Exception at VIM"
1540 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1541 #logger.error("start_scenario %s", error_text)
1542 raise NfvoException(error_text, e.http_code)
1543
tiernob3d36742017-03-03 23:51:05 +01001544
tierno7edb6752016-03-21 17:37:52 +01001545def get_vnf_id(mydb, tenant_id, vnf_id):
1546 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001547 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001548 #obtain data
1549 where_or = {}
1550 if tenant_id != "any":
1551 where_or["tenant_id"] = tenant_id
1552 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001553 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1554
tiernof1ba57e2017-09-07 12:23:19 +02001555 vnf_id = vnf["uuid"]
1556 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001557 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001558 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1559 data={'vnf' : filtered_content}
1560 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001561 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001562 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1563 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001564 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001565 if len(content)==0:
1566 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001567 # change boot_data into boot-data
1568 for vm in content:
1569 if vm.get("boot_data"):
1570 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1571 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001572
1573 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001574 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001575
tierno7edb6752016-03-21 17:37:52 +01001576 #GET NET
tierno42026a02017-02-10 15:13:40 +01001577 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001578 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1579 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001580 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001581
1582 #GET ip-profile for each net
1583 for net in data['vnf']['nets']:
1584 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1585 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1586 WHERE={'net_id': net["uuid"]} )
1587 if len(ipprofiles)==1:
1588 net["ip_profile"] = ipprofiles[0]
1589 elif len(ipprofiles)>1:
1590 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net['uuid']), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001591
1592
garciadeblas9f8456e2016-09-05 05:02:59 +02001593 #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 +01001594
garciadeblas9f8456e2016-09-05 05:02:59 +02001595 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001596 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 +01001597 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1598 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001599 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001600 #print content
tiernof97fd272016-07-11 14:32:37 +02001601 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001602
tiernof97fd272016-07-11 14:32:37 +02001603 return data
tierno7edb6752016-03-21 17:37:52 +01001604
1605
1606def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1607 # Check tenant exist
1608 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001609 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001610 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +02001611 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001612 else:
1613 vims={}
1614
1615 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1616 where_or = {}
1617 if tenant_id != "any":
1618 where_or["tenant_id"] = tenant_id
1619 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001620 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 +02001621 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001622
tierno7edb6752016-03-21 17:37:52 +01001623 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001624 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001625 if len(flavorList)==0:
1626 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001627
tiernof97fd272016-07-11 14:32:37 +02001628 imageList = get_imagelist(mydb, vnf_id)
1629 if len(imageList)==0:
1630 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001631
tiernof97fd272016-07-11 14:32:37 +02001632 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1633 if deleted == 0:
1634 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno42026a02017-02-10 15:13:40 +01001635
tierno7edb6752016-03-21 17:37:52 +01001636 undeletedItems = []
1637 for flavor in flavorList:
1638 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001639 try:
1640 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1641 if len(c) > 0:
1642 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1643 continue
1644 #flavor not used, must be deleted
1645 #delelte at VIM
tierno96ebf002017-12-13 10:55:38 +01001646 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
tierno7edb6752016-03-21 17:37:52 +01001647 for flavor_vim in c:
tierno96ebf002017-12-13 10:55:38 +01001648 if not flavor_vim['created']: # skip this flavor because not created by openmano
tierno7edb6752016-03-21 17:37:52 +01001649 continue
tierno96ebf002017-12-13 10:55:38 +01001650 # look for vim
1651 myvim = None
1652 for vim in vims.values():
1653 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1654 myvim = vim
1655 break
1656 if not myvim:
tierno7edb6752016-03-21 17:37:52 +01001657 continue
tiernoae4a8d12016-07-08 12:30:39 +02001658 try:
1659 myvim.delete_flavor(flavor_vim["vim_id"])
tierno96ebf002017-12-13 10:55:38 +01001660 except vimconn.vimconnNotFoundException:
1661 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1662 flavor_vim["datacenter_vim_id"] )
tiernoae4a8d12016-07-08 12:30:39 +02001663 except vimconn.vimconnException as e:
1664 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
tierno96ebf002017-12-13 10:55:38 +01001665 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1666 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1667 flavor_vim["datacenter_vim_id"]))
1668 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
tiernof97fd272016-07-11 14:32:37 +02001669 mydb.delete_row_by_id('flavors', flavor)
1670 except db_base_Exception as e:
1671 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno96ebf002017-12-13 10:55:38 +01001672 undeletedItems.append("flavor {}".format(flavor))
tiernof97fd272016-07-11 14:32:37 +02001673
tierno42026a02017-02-10 15:13:40 +01001674
tierno7edb6752016-03-21 17:37:52 +01001675 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001676 try:
1677 #check if image is used by other vnf
1678 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
1679 if len(c) > 0:
1680 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1681 continue
1682 #image not used, must be deleted
1683 #delelte at VIM
1684 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001685 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001686 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001687 continue
1688 if image_vim['created']=='false': #skip this image because not created by openmano
1689 continue
1690 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001691 try:
1692 myvim.delete_image(image_vim["vim_id"])
1693 except vimconn.vimconnNotFoundException as e:
1694 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1695 except vimconn.vimconnException as e:
1696 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1697 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1698 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001699 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1700 mydb.delete_row_by_id('images', image)
1701 except db_base_Exception as e:
1702 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001703 undeletedItems.append("image %s" % image)
1704
tiernof97fd272016-07-11 14:32:37 +02001705 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001706 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001707 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001708
tiernob3d36742017-03-03 23:51:05 +01001709
tierno7edb6752016-03-21 17:37:52 +01001710def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1711 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1712 if result < 0:
1713 return result, vims
1714 elif result == 0:
1715 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
1716 myvim = vims.values()[0]
1717 result,servers = myvim.get_hosts_info()
1718 if result < 0:
1719 return result, servers
1720 topology = {'name':myvim['name'] , 'servers': servers}
1721 return result, topology
1722
tiernob3d36742017-03-03 23:51:05 +01001723
tierno7edb6752016-03-21 17:37:52 +01001724def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001725 vims = get_vim(mydb, nfvo_tenant_id)
1726 if len(vims) == 0:
1727 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
1728 elif len(vims)>1:
1729 #print "nfvo.datacenter_action() error. Several datacenters found"
1730 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001731 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001732 try:
1733 hosts = myvim.get_hosts()
1734 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001735
tiernof97fd272016-07-11 14:32:37 +02001736 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1737 for host in hosts:
1738 server={'name':host['name'], 'vms':[]}
1739 for vm in host['instances']:
1740 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001741 try:
tiernof97fd272016-07-11 14:32:37 +02001742 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1743 WHERE={'vim_vm_id':vm['id']} )
1744 if len(c) == 0:
1745 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1746 continue
1747 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001748
tiernof97fd272016-07-11 14:32:37 +02001749 except db_base_Exception as e:
1750 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1751 datacenter['Datacenters'][0]['servers'].append(server)
1752 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001753
tiernof97fd272016-07-11 14:32:37 +02001754 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1755 return datacenter
1756 except vimconn.vimconnException as e:
1757 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001758
tiernob3d36742017-03-03 23:51:05 +01001759
tierno7edb6752016-03-21 17:37:52 +01001760def new_scenario(mydb, tenant_id, topo):
1761
1762# result, vims = get_vim(mydb, tenant_id)
1763# if result < 0:
1764# return result, vims
1765#1: parse input
1766 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001767 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001768 if "tenant_id" in topo:
1769 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001770 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
1771 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001772 else:
1773 tenant_id=None
1774
tierno42026a02017-02-10 15:13:40 +01001775#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001776 vnfs={}
1777 other_nets={} #external_networks, bridge_networks and data_networkds
1778 nodes = topo['topology']['nodes']
1779 for k in nodes.keys():
1780 if nodes[k]['type'] == 'VNF':
1781 vnfs[k] = nodes[k]
1782 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001783 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001784 other_nets[k] = nodes[k]
1785 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001786 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001787 other_nets[k] = nodes[k]
1788 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001789
tierno7edb6752016-03-21 17:37:52 +01001790
1791#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1792 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001793 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001794 error_text = ""
1795 error_pos = "'topology':'nodes':'" + name + "'"
1796 if 'vnf_id' in vnf:
1797 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001798 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001799 if 'VNF model' in vnf:
1800 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001801 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001802 if len(where) == 1:
tiernof97fd272016-07-11 14:32:37 +02001803 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001804
tiernocea279c2016-07-18 12:36:49 +02001805 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1806 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001807 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001808 if len(vnf_db)==0:
1809 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1810 elif len(vnf_db)>1:
1811 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001812 vnf['uuid']=vnf_db[0]['uuid']
1813 vnf['description']=vnf_db[0]['description']
1814 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001815 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1816 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 +02001817 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001818 for ext_iface in ext_ifaces:
1819 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1820
1821#1.4 get list of connections
1822 conections = topo['topology']['connections']
1823 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001824 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001825 for k in conections.keys():
1826 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1827 ifaces_list = conections[k]['nodes'].items()
1828 elif type(conections[k]['nodes'])==list: #list with dictionary
1829 ifaces_list=[]
1830 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1831 for k2 in conection_pair_list:
1832 ifaces_list += k2
1833
1834 con_type = conections[k].get("type", "link")
1835 if con_type != "link":
1836 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001837 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001838 other_nets[k] = {'external': False}
1839 if conections[k].get("graph"):
1840 other_nets[k]["graph"] = conections[k]["graph"]
1841 ifaces_list.append( (k, None) )
1842
tierno42026a02017-02-10 15:13:40 +01001843
tierno7edb6752016-03-21 17:37:52 +01001844 if con_type == "external_network":
1845 other_nets[k]['external'] = True
1846 if conections[k].get("model"):
1847 other_nets[k]["model"] = conections[k]["model"]
1848 else:
1849 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001850 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001851 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001852
tiernoefd80c92016-09-16 14:17:46 +02001853 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001854 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)
1855 #print set(ifaces_list)
1856 #check valid VNF and iface names
1857 for iface in ifaces_list:
1858 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001859 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1860 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001861 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001862 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1863 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001864
1865#1.5 unify connections from the pair list to a consolidated list
1866 index=0
1867 while index < len(conections_list):
1868 index2 = index+1
1869 while index2 < len(conections_list):
1870 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1871 conections_list[index] |= conections_list[index2]
1872 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001873 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001874 else:
1875 index2 += 1
1876 conections_list[index] = list(conections_list[index]) # from set to list again
1877 index += 1
1878 #for k in conections_list:
1879 # print k
tierno42026a02017-02-10 15:13:40 +01001880
tierno7edb6752016-03-21 17:37:52 +01001881
1882
1883#1.6 Delete non external nets
1884# for k in other_nets.keys():
1885# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1886# for con in conections_list:
1887# delete_indexes=[]
1888# for index in range(0,len(con)):
1889# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1890# for index in delete_indexes:
1891# del con[index]
1892# del other_nets[k]
1893#1.7: Check external_ports are present at database table datacenter_nets
1894 for k,net in other_nets.items():
1895 error_pos = "'topology':'nodes':'" + k + "'"
1896 if net['external']==False:
1897 if 'name' not in net:
1898 net['name']=k
1899 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001900 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001901 if net['model']=='bridge_net':
1902 net['type']='bridge';
1903 elif net['model']=='dataplane_net':
1904 net['type']='data';
1905 else:
tiernof97fd272016-07-11 14:32:37 +02001906 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001907 else: #external
1908#IF we do not want to check that external network exist at datacenter
1909 pass
tierno42026a02017-02-10 15:13:40 +01001910#ELSE
tierno7edb6752016-03-21 17:37:52 +01001911# error_text = ""
1912# WHERE_={}
1913# if 'net_id' in net:
1914# error_text += " 'net_id' " + net['net_id']
1915# WHERE_['uuid'] = net['net_id']
1916# if 'model' in net:
1917# error_text += " 'model' " + net['model']
1918# WHERE_['name'] = net['model']
1919# if len(WHERE_) == 0:
1920# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1921# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1922# FROM='datacenter_nets', WHERE=WHERE_ )
1923# if r<0:
1924# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1925# elif r==0:
1926# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1927# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1928# elif r>1:
tierno42026a02017-02-10 15:13:40 +01001929# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1930# return -HTTP_Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
tierno7edb6752016-03-21 17:37:52 +01001931# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01001932#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001933 net_list={}
1934 net_nb=0 #Number of nets
1935 for con in conections_list:
1936 #check if this is connected to a external net
1937 other_net_index=-1
1938 #print
1939 #print "con", con
1940 for index in range(0,len(con)):
1941 #check if this is connected to a external net
1942 for net_key in other_nets.keys():
1943 if con[index][0]==net_key:
1944 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01001945 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 +02001946 #print "nfvo.new_scenario " + error_text
1947 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001948 else:
1949 other_net_index = index
1950 net_target = net_key
1951 break
1952 #print "other_net_index", other_net_index
1953 try:
1954 if other_net_index>=0:
1955 del con[other_net_index]
1956#IF we do not want to check that external network exist at datacenter
1957 if other_nets[net_target]['external'] :
1958 if "name" not in other_nets[net_target]:
1959 other_nets[net_target]['name'] = other_nets[net_target]['model']
1960 if other_nets[net_target]["type"] == "external_network":
1961 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1962 other_nets[net_target]["type"] = "data"
1963 else:
1964 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01001965#ELSE
tierno7edb6752016-03-21 17:37:52 +01001966# if other_nets[net_target]['external'] :
1967# 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
1968# if type_=='data' and other_nets[net_target]['type']=="ptp":
1969# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1970# print "nfvo.new_scenario " + error_text
1971# return -HTTP_Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01001972#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001973 for iface in con:
1974 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1975 else:
1976 #create a net
1977 net_type_bridge=False
1978 net_type_data=False
1979 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01001980 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02001981 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01001982 'external':False}
tierno7edb6752016-03-21 17:37:52 +01001983 for iface in con:
1984 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1985 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1986 if iface_type=='mgmt' or iface_type=='bridge':
1987 net_type_bridge = True
1988 else:
1989 net_type_data = True
1990 if net_type_bridge and net_type_data:
1991 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 +02001992 #print "nfvo.new_scenario " + error_text
1993 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001994 elif net_type_bridge:
1995 type_='bridge'
1996 else:
1997 type_='data' if len(con)>2 else 'ptp'
1998 net_list[net_target]['type'] = type_
1999 net_nb+=1
2000 except Exception:
2001 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02002002 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01002003 #raise e
tiernof97fd272016-07-11 14:32:37 +02002004 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002005
2006#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01002007 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02002008 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01002009 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01002010 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02002011 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01002012 add_mgmt_net = False
2013 for vnf in vnfs.values():
2014 for iface in vnf['ifaces'].values():
2015 if iface['type']=='mgmt' and 'net_key' not in iface:
2016 #iface not connected
2017 iface['net_key'] = 'mgmt'
2018 add_mgmt_net = True
2019 if add_mgmt_net and 'mgmt' not in net_list:
2020 net_list['mgmt']=mgmt_net[0]
2021 net_list['mgmt']['external']=True
2022 net_list['mgmt']['graph']={'visible':False}
2023
2024 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02002025 #print
2026 #print 'net_list', net_list
2027 #print
2028 #print 'vnfs', vnfs
2029 #print
tierno7edb6752016-03-21 17:37:52 +01002030
2031#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02002032 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02002033 'tenant_id':tenant_id, 'name':topo['name'],
2034 'description':topo.get('description',topo['name']),
2035 'public': topo.get('public', False)
2036 })
tierno42026a02017-02-10 15:13:40 +01002037
tiernof97fd272016-07-11 14:32:37 +02002038 return c
tierno7edb6752016-03-21 17:37:52 +01002039
tiernob3d36742017-03-03 23:51:05 +01002040
tierno5bb59dc2017-02-13 14:53:54 +01002041def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2042 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02002043 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01002044 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01002045 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002046 if "tenant_id" in scenario:
2047 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01002048 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02002049 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
2050 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01002051 else:
2052 tenant_id=None
2053
tierno5bb59dc2017-02-13 14:53:54 +01002054 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01002055 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02002056 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01002057 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02002058 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01002059 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002060 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02002061 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02002062 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01002063 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02002064 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02002065 if len(where) == 1:
garciadeblas71781ea2016-09-19 14:41:59 +02002066 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002067 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002068 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002069 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002070 if len(vnf_db) == 0:
tiernof97fd272016-07-11 14:32:37 +02002071 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002072 elif len(vnf_db) > 1:
tiernof97fd272016-07-11 14:32:37 +02002073 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002074 vnf['uuid'] = vnf_db[0]['uuid']
2075 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002076 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002077 # get external interfaces
2078 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2079 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 +02002080 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002081 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002082 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2083 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002084
tierno5bb59dc2017-02-13 14:53:54 +01002085 # 2: Insert net_key and ip_address at every vnf interface
2086 for net_name, net in scenario["networks"].items():
2087 net_type_bridge = False
2088 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002089 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002090 if version == "0.2":
2091 temp_dict = iface_dict
2092 ip_address = None
2093 elif version == "0.3":
2094 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2095 ip_address = iface_dict.get('ip_address', None)
2096 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002097 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002098 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2099 net_name, vnf)
2100 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002101 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002102 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002103 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2104 .format(net_name, iface)
2105 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002106 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002107 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002108 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2109 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2110 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002111 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002112 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002113 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002114 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002115 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002116 net_type_bridge = True
2117 else:
2118 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002119
tierno7edb6752016-03-21 17:37:52 +01002120 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002121 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2122 .format(net_name)
2123 # logger.debug("nfvo.new_scenario " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002124 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002125 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002126 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002127 else:
tierno5bb59dc2017-02-13 14:53:54 +01002128 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2129
2130 if net.get("implementation"): # for v0.3
2131 if type_ == "bridge" and net["implementation"] == "underlay":
2132 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2133 "'network':'{}'".format(net_name)
2134 # logger.debug(error_text)
2135 raise NfvoException(error_text, HTTP_Bad_Request)
2136 elif type_ != "bridge" and net["implementation"] == "overlay":
2137 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2138 "'network':'{}'".format(net_name)
2139 # logger.debug(error_text)
2140 raise NfvoException(error_text, HTTP_Bad_Request)
2141 net.pop("implementation")
2142 if "type" in net and version == "0.3": # for v0.3
2143 if type_ == "data" and net["type"] == "e-line":
2144 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2145 "'e-line' at 'network':'{}'".format(net_name)
2146 # logger.debug(error_text)
2147 raise NfvoException(error_text, HTTP_Bad_Request)
2148 elif type_ == "ptp" and net["type"] == "e-lan":
2149 type_ = "data"
2150
tierno7edb6752016-03-21 17:37:52 +01002151 net['type'] = type_
2152 net['name'] = net_name
2153 net['external'] = net.get('external', False)
2154
tierno5bb59dc2017-02-13 14:53:54 +01002155 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002156 scenario["nets"] = scenario["networks"]
2157 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002158 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002159 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002160
tiernob3d36742017-03-03 23:51:05 +01002161
tiernof1ba57e2017-09-07 12:23:19 +02002162def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2163 """
2164 Parses an OSM IM nsd_catalog and insert at DB
2165 :param mydb:
2166 :param tenant_id:
2167 :param nsd_descriptor:
Igor D.Ccaadc442017-11-06 12:48:48 +00002168 :return: The list of created NSD ids
tiernof1ba57e2017-09-07 12:23:19 +02002169 """
2170 try:
2171 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002172 try:
2173 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd)
2174 except Exception as e:
tiernob2880eb2017-10-04 15:04:53 +02002175 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002176 db_scenarios = []
2177 db_sce_nets = []
2178 db_sce_vnfs = []
2179 db_sce_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002180 db_sce_vnffgs = []
2181 db_sce_rsps = []
2182 db_sce_rsp_hops = []
2183 db_sce_classifiers = []
2184 db_sce_classifier_matches = []
tiernof1ba57e2017-09-07 12:23:19 +02002185 db_ip_profiles = []
2186 db_ip_profiles_index = 0
2187 uuid_list = []
2188 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002189 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2190 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002191
Igor D.Ccaadc442017-11-06 12:48:48 +00002192 # table scenarios
tiernof1ba57e2017-09-07 12:23:19 +02002193 scenario_uuid = str(uuid4())
2194 uuid_list.append(scenario_uuid)
2195 nsd_uuid_list.append(scenario_uuid)
2196 db_scenario = {
2197 "uuid": scenario_uuid,
2198 "osm_id": get_str(nsd, "id", 255),
2199 "name": get_str(nsd, "name", 255),
2200 "description": get_str(nsd, "description", 255),
2201 "tenant_id": tenant_id,
2202 "vendor": get_str(nsd, "vendor", 255),
2203 "short_name": get_str(nsd, "short-name", 255),
2204 "descriptor": str(nsd_descriptor)[:60000],
2205 }
2206 db_scenarios.append(db_scenario)
2207
2208 # table sce_vnfs (constituent-vnfd)
2209 vnf_index2scevnf_uuid = {}
2210 vnf_index2vnf_uuid = {}
2211 for vnf in nsd.get("constituent-vnfd").itervalues():
2212 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2213 'tenant_id': tenant_id})
2214 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002215 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2216 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2217 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
2218 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002219 sce_vnf_uuid = str(uuid4())
2220 uuid_list.append(sce_vnf_uuid)
2221 db_sce_vnf = {
2222 "uuid": sce_vnf_uuid,
2223 "scenario_id": scenario_uuid,
2224 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 5),
2225 "vnf_id": existing_vnf[0]["uuid"],
2226 "member_vnf_index": int(vnf["member-vnf-index"]),
2227 # TODO 'start-by-default': True
2228 }
2229 vnf_index2scevnf_uuid[int(vnf['member-vnf-index'])] = sce_vnf_uuid
2230 vnf_index2vnf_uuid[int(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
2231 db_sce_vnfs.append(db_sce_vnf)
2232
2233 # table ip_profiles (ip-profiles)
2234 ip_profile_name2db_table_index = {}
2235 for ip_profile in nsd.get("ip-profiles").itervalues():
2236 db_ip_profile = {
2237 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2238 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2239 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2240 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2241 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2242 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2243 }
2244 dns_list = []
2245 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2246 dns_list.append(str(dns.get("address")))
2247 db_ip_profile["dns_address"] = ";".join(dns_list)
2248 if ip_profile["ip-profile-params"].get('security-group'):
2249 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2250 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2251 db_ip_profiles_index += 1
2252 db_ip_profiles.append(db_ip_profile)
2253
2254 # table sce_nets (internal-vld)
2255 for vld in nsd.get("vld").itervalues():
2256 sce_net_uuid = str(uuid4())
2257 uuid_list.append(sce_net_uuid)
2258 db_sce_net = {
2259 "uuid": sce_net_uuid,
2260 "name": get_str(vld, "name", 255),
2261 "scenario_id": scenario_uuid,
2262 # "type": #TODO
2263 "multipoint": not vld.get("type") == "ELINE",
2264 # "external": #TODO
2265 "description": get_str(vld, "description", 255),
2266 }
2267 # guess type of network
2268 if vld.get("mgmt-network"):
2269 db_sce_net["type"] = "bridge"
2270 db_sce_net["external"] = True
2271 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2272 db_sce_net["type"] = "data"
2273 else:
tierno66eba6e2017-11-10 17:09:18 +01002274 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2275 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002276 db_sce_nets.append(db_sce_net)
2277
2278 # ip-profile, link db_ip_profile with db_sce_net
2279 if vld.get("ip-profile-ref"):
2280 ip_profile_name = vld.get("ip-profile-ref")
2281 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002282 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2283 " Reference to a non-existing 'ip_profiles'".format(
2284 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
2285 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002286 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
2287
2288 # table sce_interfaces (vld:vnfd-connection-point-ref)
2289 for iface in vld.get("vnfd-connection-point-ref").itervalues():
2290 vnf_index = int(iface['member-vnf-index-ref'])
2291 # check correct parameters
2292 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002293 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2294 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2295 "'nsd':'constituent-vnfd'".format(
2296 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
2297 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002298
tierno66eba6e2017-11-10 17:09:18 +01002299 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002300 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2301 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2302 'external_name': get_str(iface, "vnfd-connection-point-ref",
2303 255)})
2304 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002305 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2306 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2307 "connection-point name at VNFD '{}'".format(
2308 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2309 str(iface.get("vnfd-id-ref"))[:255]),
2310 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002311 interface_uuid = existing_ifaces[0]["uuid"]
tierno66eba6e2017-11-10 17:09:18 +01002312 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2313 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002314 sce_interface_uuid = str(uuid4())
2315 uuid_list.append(sce_net_uuid)
tierno41a69812018-02-16 14:34:33 +01002316 iface_ip_address = None
2317 if iface.get("ip-address"):
2318 iface_ip_address = str(iface.get("ip-address"))
tiernof1ba57e2017-09-07 12:23:19 +02002319 db_sce_interface = {
2320 "uuid": sce_interface_uuid,
2321 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2322 "sce_net_id": sce_net_uuid,
2323 "interface_id": interface_uuid,
tierno41a69812018-02-16 14:34:33 +01002324 "ip_address": iface_ip_address,
tiernof1ba57e2017-09-07 12:23:19 +02002325 }
2326 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002327 if not db_sce_net["type"]:
2328 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002329
Igor D.Ccaadc442017-11-06 12:48:48 +00002330 # table sce_vnffgs (vnffgd)
2331 for vnffg in nsd.get("vnffgd").itervalues():
2332 sce_vnffg_uuid = str(uuid4())
2333 uuid_list.append(sce_vnffg_uuid)
2334 db_sce_vnffg = {
2335 "uuid": sce_vnffg_uuid,
2336 "name": get_str(vnffg, "name", 255),
2337 "scenario_id": scenario_uuid,
2338 "vendor": get_str(vnffg, "vendor", 255),
2339 "description": get_str(vld, "description", 255),
2340 }
2341 db_sce_vnffgs.append(db_sce_vnffg)
2342
2343 # deal with rsps
2344 db_sce_rsps = []
2345 for rsp in vnffg.get("rsp").itervalues():
2346 sce_rsp_uuid = str(uuid4())
2347 uuid_list.append(sce_rsp_uuid)
2348 db_sce_rsp = {
2349 "uuid": sce_rsp_uuid,
2350 "name": get_str(rsp, "name", 255),
2351 "sce_vnffg_id": sce_vnffg_uuid,
2352 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2353 }
2354 db_sce_rsps.append(db_sce_rsp)
2355 db_sce_rsp_hops = []
2356 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
2357 vnf_index = int(iface['member-vnf-index-ref'])
2358 if_order = int(iface['order'])
2359 # check correct parameters
2360 if vnf_index not in vnf_index2vnf_uuid:
2361 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2362 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2363 "'nsd':'constituent-vnfd'".format(
2364 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
2365 HTTP_Bad_Request)
2366
2367 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2368 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2369 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2370 'external_name': get_str(iface, "vnfd-connection-point-ref",
2371 255)})
2372 if not existing_ifaces:
2373 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2374 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2375 "connection-point name at VNFD '{}'".format(
2376 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2377 str(iface.get("vnfd-id-ref"))[:255]),
2378 HTTP_Bad_Request)
2379 interface_uuid = existing_ifaces[0]["uuid"]
2380 sce_rsp_hop_uuid = str(uuid4())
2381 uuid_list.append(sce_rsp_hop_uuid)
2382 db_sce_rsp_hop = {
2383 "uuid": sce_rsp_hop_uuid,
2384 "if_order": if_order,
2385 "interface_id": interface_uuid,
2386 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2387 "sce_rsp_id": sce_rsp_uuid,
2388 }
2389 db_sce_rsp_hops.append(db_sce_rsp_hop)
2390
2391 # deal with classifiers
2392 db_sce_classifiers = []
2393 for classifier in vnffg.get("classifier").itervalues():
2394 sce_classifier_uuid = str(uuid4())
2395 uuid_list.append(sce_classifier_uuid)
2396
2397 # source VNF
2398 vnf_index = int(classifier['member-vnf-index-ref'])
2399 if vnf_index not in vnf_index2vnf_uuid:
2400 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2401 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2402 "'nsd':'constituent-vnfd'".format(
2403 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
2404 HTTP_Bad_Request)
2405 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2406 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2407 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2408 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2409 255)})
2410 if not existing_ifaces:
2411 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2412 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2413 "connection-point name at VNFD '{}'".format(
2414 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2415 str(iface.get("vnfd-id-ref"))[:255]),
2416 HTTP_Bad_Request)
2417 interface_uuid = existing_ifaces[0]["uuid"]
2418
2419 db_sce_classifier = {
2420 "uuid": sce_classifier_uuid,
2421 "name": get_str(classifier, "name", 255),
2422 "sce_vnffg_id": sce_vnffg_uuid,
2423 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2424 "interface_id": interface_uuid,
2425 }
2426 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2427 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2428 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2429 db_sce_classifiers.append(db_sce_classifier)
2430
2431 db_sce_classifier_matches = []
2432 for match in classifier.get("match-attributes").itervalues():
2433 sce_classifier_match_uuid = str(uuid4())
2434 uuid_list.append(sce_classifier_match_uuid)
2435 db_sce_classifier_match = {
2436 "uuid": sce_classifier_match_uuid,
2437 "ip_proto": get_str(match, "ip-proto", 2),
2438 "source_ip": get_str(match, "source-ip-address", 16),
2439 "destination_ip": get_str(match, "destination-ip-address", 16),
2440 "source_port": get_str(match, "source-port", 5),
2441 "destination_port": get_str(match, "destination-port", 5),
2442 "sce_classifier_id": sce_classifier_uuid,
2443 }
2444 db_sce_classifier_matches.append(db_sce_classifier_match)
2445 # TODO: vnf/cp keys
2446
2447 # remove unneeded id's in sce_rsps
2448 for rsp in db_sce_rsps:
2449 rsp.pop('id')
2450
tiernof1ba57e2017-09-07 12:23:19 +02002451 db_tables = [
2452 {"scenarios": db_scenarios},
2453 {"sce_nets": db_sce_nets},
2454 {"ip_profiles": db_ip_profiles},
2455 {"sce_vnfs": db_sce_vnfs},
2456 {"sce_interfaces": db_sce_interfaces},
Igor D.Ccaadc442017-11-06 12:48:48 +00002457 {"sce_vnffgs": db_sce_vnffgs},
2458 {"sce_rsps": db_sce_rsps},
2459 {"sce_rsp_hops": db_sce_rsp_hops},
2460 {"sce_classifiers": db_sce_classifiers},
2461 {"sce_classifier_matches": db_sce_classifier_matches},
tiernof1ba57e2017-09-07 12:23:19 +02002462 ]
2463
Igor D.Ccaadc442017-11-06 12:48:48 +00002464 logger.debug("new_nsd_v3 done: %s",
tiernof1ba57e2017-09-07 12:23:19 +02002465 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2466 mydb.new_rows(db_tables, uuid_list)
2467 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002468 except NfvoException:
2469 raise
tiernof1ba57e2017-09-07 12:23:19 +02002470 except Exception as e:
2471 logger.error("Exception {}".format(e))
2472 raise # NfvoException("Exception {}".format(e), HTTP_Bad_Request)
2473
2474
tierno7edb6752016-03-21 17:37:52 +01002475def edit_scenario(mydb, tenant_id, scenario_id, data):
2476 data["uuid"] = scenario_id
2477 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002478 c = mydb.edit_scenario( data )
2479 return c
tierno7edb6752016-03-21 17:37:52 +01002480
tiernob3d36742017-03-03 23:51:05 +01002481
tierno7edb6752016-03-21 17:37:52 +01002482def 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 +02002483 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002484 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2485 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002486 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002487 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002488
tierno7edb6752016-03-21 17:37:52 +01002489 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002490 try:
2491 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002492 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002493 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002494 scenarioDict['datacenter_id'] = datacenter_id
2495 #print '================scenarioDict======================='
2496 #print json.dumps(scenarioDict, indent=4)
2497 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002498
tiernoae4a8d12016-07-08 12:30:39 +02002499 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2500 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002501
tiernoae4a8d12016-07-08 12:30:39 +02002502 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2503 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002504
tiernoae4a8d12016-07-08 12:30:39 +02002505 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2506 for sce_net in scenarioDict['nets']:
2507 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002508
tiernoae4a8d12016-07-08 12:30:39 +02002509 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002510 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002511 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002512 myNetDict = {}
2513 myNetDict["name"] = myNetName
2514 myNetDict["type"] = myNetType
2515 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002516 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002517 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002518 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002519 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002520 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02002521 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002522 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2523 sce_net['vim_id'] = network_id
2524 auxNetDict['scenario'][sce_net['uuid']] = network_id
2525 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002526 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002527 else:
2528 if sce_net['vim_id'] == None:
2529 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2530 _, message = rollback(mydb, vims, rollbackList)
2531 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02002532 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002533 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2534 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002535
tiernoae4a8d12016-07-08 12:30:39 +02002536 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2537 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002538
tiernoae4a8d12016-07-08 12:30:39 +02002539 for sce_vnf in scenarioDict['vnfs']:
2540 for net in sce_vnf['nets']:
2541 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002542
tiernoae4a8d12016-07-08 12:30:39 +02002543 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2544 myNetName = myNetName[0:255] #limit length
2545 myNetType = net['type']
2546 myNetDict = {}
2547 myNetDict["name"] = myNetName
2548 myNetDict["type"] = myNetType
2549 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002550 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002551 #print myNetDict
2552 #TODO:
2553 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02002554 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002555 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2556 net['vim_id'] = network_id
2557 if sce_vnf['uuid'] not in auxNetDict:
2558 auxNetDict[sce_vnf['uuid']] = {}
2559 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2560 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002561 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002562
tiernoae4a8d12016-07-08 12:30:39 +02002563 #print "auxNetDict:"
2564 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002565
tiernoae4a8d12016-07-08 12:30:39 +02002566 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2567 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2568 i = 0
2569 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002570 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002571 for vm in sce_vnf['vms']:
2572 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002573 if vm_av and vm_av not in vnf_availability_zones:
2574 vnf_availability_zones.append(vm_av)
2575
2576 # check if there is enough availability zones available at vim level.
2577 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2578 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
2579 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
2580
tiernoae4a8d12016-07-08 12:30:39 +02002581 for vm in sce_vnf['vms']:
2582 i += 1
2583 myVMDict = {}
2584 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002585 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002586 #myVMDict['description'] = vm['description']
2587 myVMDict['description'] = myVMDict['name'][0:99]
2588 if not startvms:
2589 myVMDict['start'] = "no"
2590 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2591 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002592
tiernoae4a8d12016-07-08 12:30:39 +02002593 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002594 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002595 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002596 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002597
tiernoae4a8d12016-07-08 12:30:39 +02002598 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002599 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002600 if flavor_dict['extended']!=None:
2601 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002602 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002603 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002604
2605
tiernoae4a8d12016-07-08 12:30:39 +02002606 myVMDict['imageRef'] = vm['vim_image_id']
2607 myVMDict['flavorRef'] = vm['vim_flavor_id']
2608 myVMDict['networks'] = []
2609 for iface in vm['interfaces']:
2610 netDict = {}
2611 if iface['type']=="data":
2612 netDict['type'] = iface['model']
2613 elif "model" in iface and iface["model"]!=None:
2614 netDict['model']=iface['model']
2615 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2616 #discover type of interface looking at flavor
2617 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2618 for flavor_iface in numa.get('interfaces',[]):
2619 if flavor_iface.get('name') == iface['internal_name']:
2620 if flavor_iface['dedicated'] == 'yes':
2621 netDict['type']="PF" #passthrough
2622 elif flavor_iface['dedicated'] == 'no':
2623 netDict['type']="VF" #siov
2624 elif flavor_iface['dedicated'] == 'yes:sriov':
2625 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2626 netDict["mac_address"] = flavor_iface.get("mac_address")
2627 break;
2628 netDict["use"]=iface['type']
2629 if netDict["use"]=="data" and not netDict.get("type"):
2630 #print "netDict", netDict
2631 #print "iface", iface
2632 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'])
2633 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002634 raise NfvoException(e_text + "After database migration some information is not available. \
2635 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002636 else:
tiernof97fd272016-07-11 14:32:37 +02002637 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002638 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2639 netDict["type"]="virtual"
2640 if "vpci" in iface and iface["vpci"] is not None:
2641 netDict['vpci'] = iface['vpci']
2642 if "mac" in iface and iface["mac"] is not None:
2643 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002644 if "port-security" in iface and iface["port-security"] is not None:
2645 netDict['port_security'] = iface['port-security']
2646 if "floating-ip" in iface and iface["floating-ip"] is not None:
2647 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002648 netDict['name'] = iface['internal_name']
2649 if iface['net_id'] is None:
2650 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002651 #print iface
2652 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002653 if vnf_iface['interface_id']==iface['uuid']:
2654 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2655 break
2656 else:
2657 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2658 #skip bridge ifaces not connected to any net
2659 #if 'net_id' not in netDict or netDict['net_id']==None:
2660 # continue
2661 myVMDict['networks'].append(netDict)
2662 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2663 #print myVMDict['name']
2664 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2665 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2666 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002667
2668 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002669 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002670 else:
tierno5a3273c2017-08-29 11:43:46 +02002671 av_index = None
mirabal29356312017-07-27 12:21:22 +02002672
tierno98e909c2017-10-14 13:27:03 +02002673 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002674 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002675 availability_zone_index=av_index,
2676 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002677 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2678 vm['vim_id'] = vm_id
2679 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2680 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2681 for net in myVMDict['networks']:
2682 if "vim_id" in net:
2683 for iface in vm['interfaces']:
2684 if net["name"]==iface["internal_name"]:
2685 iface["vim_id"]=net["vim_id"]
2686 break
tierno42026a02017-02-10 15:13:40 +01002687
tiernoae4a8d12016-07-08 12:30:39 +02002688 logger.debug("start scenario Deployment done")
2689 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2690 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002691 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2692 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002693
tiernof97fd272016-07-11 14:32:37 +02002694 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002695 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002696 if isinstance(e, db_base_Exception):
2697 error_text = "Exception at database"
2698 else:
2699 error_text = "Exception at VIM"
2700 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2701 #logger.error("start_scenario %s", error_text)
2702 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002703
tierno36c0b172017-01-12 18:32:28 +01002704def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002705 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002706 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002707 None is allowed
2708 """
tierno36c0b172017-01-12 18:32:28 +01002709 if not cloud_config_preserve and not cloud_config:
2710 return None
2711
2712 new_cloud_config = {"key-pairs":[], "users":[]}
2713 # key-pairs
2714 if cloud_config_preserve:
2715 for key in cloud_config_preserve.get("key-pairs", () ):
2716 if key not in new_cloud_config["key-pairs"]:
2717 new_cloud_config["key-pairs"].append(key)
2718 if cloud_config:
2719 for key in cloud_config.get("key-pairs", () ):
2720 if key not in new_cloud_config["key-pairs"]:
2721 new_cloud_config["key-pairs"].append(key)
2722 if not new_cloud_config["key-pairs"]:
2723 del new_cloud_config["key-pairs"]
2724
2725 # users
2726 if cloud_config:
2727 new_cloud_config["users"] += cloud_config.get("users", () )
2728 if cloud_config_preserve:
2729 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002730 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002731 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002732 for index0 in range(0,len(users)):
2733 if index0 in index_to_delete:
2734 continue
2735 for index1 in range(index0+1,len(users)):
2736 if index1 in index_to_delete:
2737 continue
2738 if users[index0]["name"] == users[index1]["name"]:
2739 index_to_delete.append(index1)
2740 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002741 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002742 users[index0]["key-pairs"] = [key]
2743 elif key not in users[index0]["key-pairs"]:
2744 users[index0]["key-pairs"].append(key)
2745 index_to_delete.sort(reverse=True)
2746 for index in index_to_delete:
2747 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002748 if not new_cloud_config["users"]:
2749 del new_cloud_config["users"]
2750
2751 #boot-data-drive
2752 if cloud_config and cloud_config.get("boot-data-drive") != None:
2753 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2754 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2755 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2756
2757 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002758 new_cloud_config["user-data"] = []
2759 if cloud_config and cloud_config.get("user-data"):
2760 if isinstance(cloud_config["user-data"], list):
2761 new_cloud_config["user-data"] += cloud_config["user-data"]
2762 else:
2763 new_cloud_config["user-data"].append(cloud_config["user-data"])
2764 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2765 if isinstance(cloud_config_preserve["user-data"], list):
2766 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2767 else:
2768 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2769 if not new_cloud_config["user-data"]:
2770 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002771
2772 # config files
2773 new_cloud_config["config-files"] = []
2774 if cloud_config and cloud_config.get("config-files") != None:
2775 new_cloud_config["config-files"] += cloud_config["config-files"]
2776 if cloud_config_preserve:
2777 for file in cloud_config_preserve.get("config-files", ()):
2778 for index in range(0, len(new_cloud_config["config-files"])):
2779 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2780 new_cloud_config["config-files"][index] = file
2781 break
2782 else:
2783 new_cloud_config["config-files"].append(file)
2784 if not new_cloud_config["config-files"]:
2785 del new_cloud_config["config-files"]
2786 return new_cloud_config
2787
2788
tierno867ffe92017-03-27 12:50:34 +02002789def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002790 datacenter_id = None
2791 datacenter_name = None
2792 thread = None
tierno867ffe92017-03-27 12:50:34 +02002793 try:
2794 if datacenter_tenant_id:
2795 thread_id = datacenter_tenant_id
2796 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002797 else:
tierno867ffe92017-03-27 12:50:34 +02002798 where_={"td.nfvo_tenant_id": tenant_id}
2799 if datacenter_id_name:
2800 if utils.check_valid_uuid(datacenter_id_name):
2801 datacenter_id = datacenter_id_name
2802 where_["dt.datacenter_id"] = datacenter_id
2803 else:
2804 datacenter_name = datacenter_id_name
2805 where_["d.name"] = datacenter_name
2806 if datacenter_tenant_id:
2807 where_["dt.uuid"] = datacenter_tenant_id
2808 datacenters = mydb.get_rows(
2809 SELECT=("dt.uuid as datacenter_tenant_id",),
2810 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2811 "join datacenters as d on d.uuid=dt.datacenter_id",
2812 WHERE=where_)
2813 if len(datacenters) > 1:
2814 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2815 elif datacenters:
2816 thread_id = datacenters[0]["datacenter_tenant_id"]
2817 thread = vim_threads["running"].get(thread_id)
2818 if not thread:
2819 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2820 return thread_id, thread
2821 except db_base_Exception as e:
2822 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002823
tiernof5755962017-07-13 15:44:34 +02002824
tiernoa15c4b92017-10-05 12:41:44 +02002825def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2826 WHERE_dict={}
2827 if utils.check_valid_uuid(datacenter_id_name):
2828 WHERE_dict['d.uuid'] = datacenter_id_name
2829 else:
2830 WHERE_dict['d.name'] = datacenter_id_name
2831
2832 if tenant_id:
2833 WHERE_dict['nfvo_tenant_id'] = tenant_id
2834 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2835 " dt on td.datacenter_tenant_id=dt.uuid"
2836 else:
2837 from_ = 'datacenters as d'
2838 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid",), WHERE=WHERE_dict )
2839 if len(vimaccounts) == 0:
2840 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2841 elif len(vimaccounts)>1:
2842 #print "nfvo.datacenter_action() error. Several datacenters found"
2843 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2844 return vimaccounts[0]["uuid"]
2845
2846
tiernoa2793912016-10-04 08:15:08 +00002847def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002848 datacenter_id = None
2849 datacenter_name = None
2850 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002851 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02002852 datacenter_id = datacenter_id_name
2853 else:
2854 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00002855 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02002856 if len(vims) == 0:
2857 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2858 elif len(vims)>1:
2859 #print "nfvo.datacenter_action() error. Several datacenters found"
2860 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2861 return vims.keys()[0], vims.values()[0]
2862
tiernob3d36742017-03-03 23:51:05 +01002863
garciadeblas9f8456e2016-09-05 05:02:59 +02002864def update(d, u):
2865 '''Takes dict d and updates it with the values in dict u.'''
2866 '''It merges all depth levels'''
2867 for k, v in u.iteritems():
2868 if isinstance(v, collections.Mapping):
2869 r = update(d.get(k, {}), v)
2870 d[k] = r
2871 else:
2872 d[k] = u[k]
2873 return d
2874
tierno7edb6752016-03-21 17:37:52 +01002875def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01002876 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2877 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01002878 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01002879
tierno868220c2017-09-26 00:11:05 +02002880 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02002881 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02002882 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01002883 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02002884 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
2885 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02002886 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02002887 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02002888 # myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002889 rollbackList=[]
tierno42026a02017-02-10 15:13:40 +01002890
tierno868220c2017-09-26 00:11:05 +02002891 # print "Checking that the scenario exists and getting the scenario dictionary"
2892 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
2893 datacenter_id=default_datacenter_id)
tierno42026a02017-02-10 15:13:40 +01002894
tierno868220c2017-09-26 00:11:05 +02002895 # logger.debug(">>>>>> Dictionaries before merging")
2896 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
2897 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01002898
tierno868220c2017-09-26 00:11:05 +02002899 db_instance_vnfs = []
2900 db_instance_vms = []
2901 db_instance_interfaces = []
Igor D.Ccaadc442017-11-06 12:48:48 +00002902 db_instance_sfis = []
2903 db_instance_sfs = []
2904 db_instance_classifications = []
2905 db_instance_sfps = []
tierno868220c2017-09-26 00:11:05 +02002906 db_ip_profiles = []
2907 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02002908 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02002909 task_index = 0
tierno8e690322017-08-10 15:58:50 +02002910 instance_name = instance_dict["name"]
2911 instance_uuid = str(uuid4())
2912 uuid_list.append(instance_uuid)
2913 db_instance_scenario = {
2914 "uuid": instance_uuid,
2915 "name": instance_name,
2916 "tenant_id": tenant_id,
2917 "scenario_id": scenarioDict['uuid'],
2918 "datacenter_id": default_datacenter_id,
2919 # filled bellow 'datacenter_tenant_id'
2920 "description": instance_dict.get("description"),
2921 }
tierno8e690322017-08-10 15:58:50 +02002922 if scenarioDict.get("cloud-config"):
2923 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
2924 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02002925 instance_action_id = get_task_id()
2926 db_instance_action = {
2927 "uuid": instance_action_id, # same uuid for the instance and the action on create
2928 "tenant_id": tenant_id,
2929 "instance_id": instance_uuid,
2930 "description": "CREATE",
2931 }
garciadeblas9f8456e2016-09-05 05:02:59 +02002932
tierno868220c2017-09-26 00:11:05 +02002933 # Auxiliary dictionaries from x to y
2934 vnf_net2instance = {}
tierno8e690322017-08-10 15:58:50 +02002935 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02002936 net2task_id = {'scenario': {}}
tierno42026a02017-02-10 15:13:40 +01002937
tierno868220c2017-09-26 00:11:05 +02002938 # logger.debug("Creating instance from scenario-dict:\n%s",
2939 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01002940 try:
tiernob3d36742017-03-03 23:51:05 +01002941 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02002942 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tiernob3d36742017-03-03 23:51:05 +01002943 found = False
tierno7edb6752016-03-21 17:37:52 +01002944 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02002945 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01002946 found = True
2947 break
2948 if not found:
tierno868220c2017-09-26 00:11:05 +02002949 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name),
2950 HTTP_Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02002951 if "sites" not in net_instance_desc:
2952 net_instance_desc["sites"] = [ {} ]
2953 site_without_datacenter_field = False
2954 for site in net_instance_desc["sites"]:
2955 if site.get("datacenter"):
tiernoa15c4b92017-10-05 12:41:44 +02002956 site["datacenter"] = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02002957 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02002958 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02002959 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
2960 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02002961 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
2962 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02002963 else:
2964 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02002965 raise NfvoException("Found more than one entries without datacenter field at "
2966 "instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02002967 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02002968 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01002969
tiernobe41e222016-09-02 15:16:13 +02002970 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno868220c2017-09-26 00:11:05 +02002971 found = False
tierno7edb6752016-03-21 17:37:52 +01002972 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02002973 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01002974 found = True
2975 break
2976 if not found:
tiernobe41e222016-09-02 15:16:13 +02002977 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
2978 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02002979 # Add this datacenter to myvims
tiernoa15c4b92017-10-05 12:41:44 +02002980 vnf_instance_desc["datacenter"] = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02002981 if vnf_instance_desc["datacenter"] not in myvims:
2982 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
2983 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02002984 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00002985 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01002986
tierno868220c2017-09-26 00:11:05 +02002987 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01002988 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02002989
tierno868220c2017-09-26 00:11:05 +02002990 # 0.2 merge instance information into scenario
2991 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
2992 # However, this is not possible yet.
tierno41a69812018-02-16 14:34:33 +01002993 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
garciadeblas9f8456e2016-09-05 05:02:59 +02002994 for scenario_net in scenarioDict['nets']:
2995 if net_name == scenario_net["name"]:
2996 if 'ip-profile' in net_instance_desc:
tierno455612d2017-05-30 16:40:10 +02002997 # translate from input format to database format
2998 ipprofile_in = net_instance_desc['ip-profile']
2999 ipprofile_db = {}
3000 ipprofile_db['subnet_address'] = ipprofile_in.get('subnet-address')
3001 ipprofile_db['ip_version'] = ipprofile_in.get('ip-version', 'IPv4')
3002 ipprofile_db['gateway_address'] = ipprofile_in.get('gateway-address')
3003 ipprofile_db['dns_address'] = ipprofile_in.get('dns-address')
3004 if isinstance(ipprofile_db['dns_address'], (list, tuple)):
3005 ipprofile_db['dns_address'] = ";".join(ipprofile_db['dns_address'])
3006 if 'dhcp' in ipprofile_in:
3007 ipprofile_db['dhcp_start_address'] = ipprofile_in['dhcp'].get('start-address')
3008 ipprofile_db['dhcp_enabled'] = ipprofile_in['dhcp'].get('enabled', True)
3009 ipprofile_db['dhcp_count'] = ipprofile_in['dhcp'].get('count' )
garciadeblasedca7b32016-09-29 14:01:52 +00003010 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02003011 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00003012 else:
tierno455612d2017-05-30 16:40:10 +02003013 update(scenario_net['ip_profile'], ipprofile_db)
tierno41a69812018-02-16 14:34:33 +01003014 for interface in net_instance_desc.get('interfaces', ()):
garciadeblas9f8456e2016-09-05 05:02:59 +02003015 if 'ip_address' in interface:
3016 for vnf in scenarioDict['vnfs']:
3017 if interface['vnf'] == vnf['name']:
3018 for vnf_interface in vnf['interfaces']:
3019 if interface['vnf_interface'] == vnf_interface['external_name']:
tierno41a69812018-02-16 14:34:33 +01003020 vnf_interface['ip_address'] = interface['ip_address']
garciadeblas9f8456e2016-09-05 05:02:59 +02003021
tierno868220c2017-09-26 00:11:05 +02003022 # logger.debug(">>>>>>>> Merged dictionary")
3023 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3024 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02003025
tiernob3d36742017-03-03 23:51:05 +01003026 # 1. Creating new nets (sce_nets) in the VIM"
tierno8e690322017-08-10 15:58:50 +02003027 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01003028 for sce_net in scenarioDict['nets']:
tierno868220c2017-09-26 00:11:05 +02003029 descriptor_net = instance_dict.get("networks", {}).get(sce_net["name"], {})
tiernobe41e222016-09-02 15:16:13 +02003030 net_name = descriptor_net.get("vim-network-name")
tierno8e690322017-08-10 15:58:50 +02003031 sce_net2instance[sce_net['uuid']] = {}
tierno868220c2017-09-26 00:11:05 +02003032 net2task_id['scenario'][sce_net['uuid']] = {}
tiernobe41e222016-09-02 15:16:13 +02003033
3034 sites = descriptor_net.get("sites", [ {} ])
3035 for site in sites:
3036 if site.get("datacenter"):
3037 vim = myvims[ site["datacenter"] ]
3038 datacenter_id = site["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02003039 myvim_thread_id = myvim_threads_id[ site["datacenter"] ]
tierno7edb6752016-03-21 17:37:52 +01003040 else:
tiernobe41e222016-09-02 15:16:13 +02003041 vim = myvims[ default_datacenter_id ]
3042 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02003043 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tiernobe41e222016-09-02 15:16:13 +02003044 net_type = sce_net['type']
tierno868220c2017-09-26 00:11:05 +02003045 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01003046
tiernof1ba57e2017-09-07 12:23:19 +02003047 if not net_name:
3048 if sce_net["external"]:
3049 net_name = sce_net["name"]
3050 else:
3051 net_name = "{}.{}".format(instance_name, sce_net["name"])
3052 net_name = net_name[:255] # limit length
3053
3054 if "netmap-use" in site or "netmap-create" in site:
3055 create_network = False
3056 lookfor_network = False
3057 if "netmap-use" in site:
3058 lookfor_network = True
3059 if utils.check_valid_uuid(site["netmap-use"]):
3060 filter_text = "scenario id '%s'" % site["netmap-use"]
3061 lookfor_filter["id"] = site["netmap-use"]
3062 else:
3063 filter_text = "scenario name '%s'" % site["netmap-use"]
3064 lookfor_filter["name"] = site["netmap-use"]
3065 if "netmap-create" in site:
3066 create_network = True
3067 net_vim_name = net_name
3068 if site["netmap-create"]:
3069 net_vim_name = site["netmap-create"]
3070 elif sce_net["external"]:
3071 if sce_net['vim_id'] != None:
tierno868220c2017-09-26 00:11:05 +02003072 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02003073 create_network = False
3074 lookfor_network = True
3075 lookfor_filter["id"] = sce_net['vim_id']
tierno868220c2017-09-26 00:11:05 +02003076 filter_text = "vim_id '{}' datacenter_netmap name '{}'. Try to reload vims with "\
3077 "datacenter-net-update".format(sce_net['vim_id'], sce_net["name"])
3078 # look for network at datacenter and return error
tiernobe41e222016-09-02 15:16:13 +02003079 else:
tierno868220c2017-09-26 00:11:05 +02003080 # 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 +02003081 create_network = True
3082 lookfor_network = True
3083 lookfor_filter["name"] = sce_net["name"]
3084 net_vim_name = sce_net["name"]
3085 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01003086 else:
tiernobe41e222016-09-02 15:16:13 +02003087 net_vim_name = net_name
3088 create_network = True
3089 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01003090
tiernof1450872017-10-17 23:15:08 +02003091 task_extra = {}
3092 if create_network:
3093 task_action = "CREATE"
3094 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None))
3095 if lookfor_network:
3096 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02003097 elif lookfor_network:
3098 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02003099 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01003100
tierno8e690322017-08-10 15:58:50 +02003101 # fill database content
3102 net_uuid = str(uuid4())
3103 uuid_list.append(net_uuid)
3104 sce_net2instance[sce_net['uuid']][datacenter_id] = net_uuid
3105 db_net = {
3106 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02003107 'vim_net_id': None,
tierno8e690322017-08-10 15:58:50 +02003108 "instance_scenario_id": instance_uuid,
3109 "sce_net_id": sce_net["uuid"],
3110 "created": create_network,
3111 'datacenter_id': datacenter_id,
3112 'datacenter_tenant_id': myvim_thread_id,
3113 'status': 'BUILD' if create_network else "ACTIVE"
3114 }
3115 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003116 db_vim_action = {
3117 "instance_action_id": instance_action_id,
3118 "status": "SCHEDULED",
3119 "task_index": task_index,
3120 "datacenter_vim_id": myvim_thread_id,
3121 "action": task_action,
3122 "item": "instance_nets",
3123 "item_id": net_uuid,
tiernof1450872017-10-17 23:15:08 +02003124 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02003125 }
3126 net2task_id['scenario'][sce_net['uuid']][datacenter_id] = task_index
3127 task_index += 1
3128 db_vim_actions.append(db_vim_action)
3129
tierno8e690322017-08-10 15:58:50 +02003130 if 'ip_profile' in sce_net:
3131 db_ip_profile={
3132 'instance_net_id': net_uuid,
3133 'ip_version': sce_net['ip_profile']['ip_version'],
3134 'subnet_address': sce_net['ip_profile']['subnet_address'],
3135 'gateway_address': sce_net['ip_profile']['gateway_address'],
3136 'dns_address': sce_net['ip_profile']['dns_address'],
3137 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3138 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3139 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3140 }
3141 db_ip_profiles.append(db_ip_profile)
3142
tiernob3d36742017-03-03 23:51:05 +01003143 # 2. Creating new nets (vnf internal nets) in the VIM"
mirabal29356312017-07-27 12:21:22 +02003144 # For each vnf net, we create it and we add it to instanceNetlist.
tierno7edb6752016-03-21 17:37:52 +01003145 for sce_vnf in scenarioDict['vnfs']:
3146 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02003147 if sce_vnf.get("datacenter"):
tiernobe41e222016-09-02 15:16:13 +02003148 datacenter_id = sce_vnf["datacenter"]
tierno868220c2017-09-26 00:11:05 +02003149 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
tiernobe41e222016-09-02 15:16:13 +02003150 else:
tiernobe41e222016-09-02 15:16:13 +02003151 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02003152 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tierno868220c2017-09-26 00:11:05 +02003153 descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
tierno7edb6752016-03-21 17:37:52 +01003154 net_name = descriptor_net.get("name")
3155 if not net_name:
tierno868220c2017-09-26 00:11:05 +02003156 net_name = "{}.{}".format(instance_name, net["name"])
3157 net_name = net_name[:255] # limit length
tierno7edb6752016-03-21 17:37:52 +01003158 net_type = net['type']
tierno868220c2017-09-26 00:11:05 +02003159
tierno8e690322017-08-10 15:58:50 +02003160 if sce_vnf['uuid'] not in vnf_net2instance:
3161 vnf_net2instance[sce_vnf['uuid']] = {}
tierno868220c2017-09-26 00:11:05 +02003162 if sce_vnf['uuid'] not in net2task_id:
3163 net2task_id[sce_vnf['uuid']] = {}
3164 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
tierno66345bc2016-09-26 11:37:55 +02003165
tierno8e690322017-08-10 15:58:50 +02003166 # fill database content
3167 net_uuid = str(uuid4())
3168 uuid_list.append(net_uuid)
3169 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3170 db_net = {
3171 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02003172 'vim_net_id': None,
tierno8e690322017-08-10 15:58:50 +02003173 "instance_scenario_id": instance_uuid,
3174 "net_id": net["uuid"],
3175 "created": True,
3176 'datacenter_id': datacenter_id,
3177 'datacenter_tenant_id': myvim_thread_id,
3178 }
3179 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02003180
3181 db_vim_action = {
3182 "instance_action_id": instance_action_id,
3183 "task_index": task_index,
3184 "datacenter_vim_id": myvim_thread_id,
3185 "status": "SCHEDULED",
3186 "action": "CREATE",
3187 "item": "instance_nets",
3188 "item_id": net_uuid,
3189 "extra": yaml.safe_dump({"params": (net_name, net_type, net.get('ip_profile',None))},
3190 default_flow_style=True, width=256)
3191 }
3192 task_index += 1
3193 db_vim_actions.append(db_vim_action)
3194
tierno8e690322017-08-10 15:58:50 +02003195 if 'ip_profile' in net:
3196 db_ip_profile = {
3197 'instance_net_id': net_uuid,
3198 'ip_version': net['ip_profile']['ip_version'],
3199 'subnet_address': net['ip_profile']['subnet_address'],
3200 'gateway_address': net['ip_profile']['gateway_address'],
3201 'dns_address': net['ip_profile']['dns_address'],
3202 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3203 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3204 'dhcp_count': net['ip_profile']['dhcp_count'],
3205 }
3206 db_ip_profiles.append(db_ip_profile)
3207
tierno868220c2017-09-26 00:11:05 +02003208 # print "vnf_net2instance:"
3209 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01003210
tiernob3d36742017-03-03 23:51:05 +01003211 # 3. Creating new vm instances in the VIM
tierno868220c2017-09-26 00:11:05 +02003212 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3213 sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
garciadeblasacd4e782017-07-23 19:44:55 +02003214 for sce_vnf in sce_vnf_list:
tiernof1c8e222018-01-17 18:31:28 +01003215 ssh_access = None
3216 if sce_vnf.get('mgmt_access'):
tiernoce62cc42018-01-25 10:37:16 +01003217 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
tierno5a3273c2017-08-29 11:43:46 +02003218 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02003219 for vm in sce_vnf['vms']:
3220 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02003221 if vm_av and vm_av not in vnf_availability_zones:
3222 vnf_availability_zones.append(vm_av)
mirabal29356312017-07-27 12:21:22 +02003223
3224 # check if there is enough availability zones available at vim level.
tierno5a3273c2017-08-29 11:43:46 +02003225 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3226 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
3227 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
mirabal29356312017-07-27 12:21:22 +02003228
tiernobe41e222016-09-02 15:16:13 +02003229 if sce_vnf.get("datacenter"):
3230 vim = myvims[ sce_vnf["datacenter"] ]
tierno867ffe92017-03-27 12:50:34 +02003231 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"] ]
tiernobe41e222016-09-02 15:16:13 +02003232 datacenter_id = sce_vnf["datacenter"]
3233 else:
3234 vim = myvims[ default_datacenter_id ]
tierno867ffe92017-03-27 12:50:34 +02003235 myvim_thread_id = myvim_threads_id[ default_datacenter_id ]
tiernobe41e222016-09-02 15:16:13 +02003236 datacenter_id = default_datacenter_id
mirabal29356312017-07-27 12:21:22 +02003237 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003238 i = 0
mirabal29356312017-07-27 12:21:22 +02003239
tierno8e690322017-08-10 15:58:50 +02003240 vnf_uuid = str(uuid4())
3241 uuid_list.append(vnf_uuid)
3242 db_instance_vnf = {
3243 'uuid': vnf_uuid,
3244 'instance_scenario_id': instance_uuid,
3245 'vnf_id': sce_vnf['vnf_id'],
3246 'sce_vnf_id': sce_vnf['uuid'],
3247 'datacenter_id': datacenter_id,
3248 'datacenter_tenant_id': myvim_thread_id,
3249 }
3250 db_instance_vnfs.append(db_instance_vnf)
3251
tierno7edb6752016-03-21 17:37:52 +01003252 for vm in sce_vnf['vms']:
tierno7edb6752016-03-21 17:37:52 +01003253 myVMDict = {}
tierno8e690322017-08-10 15:58:50 +02003254 myVMDict['name'] = "{}.{}.{}".format(instance_name[:64], sce_vnf['name'][:64], vm["name"][:64])
tierno7edb6752016-03-21 17:37:52 +01003255 myVMDict['description'] = myVMDict['name'][0:99]
3256# if not startvms:
3257# myVMDict['start'] = "no"
tierno868220c2017-09-26 00:11:05 +02003258 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
tierno7edb6752016-03-21 17:37:52 +01003259 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02003260 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00003261 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01003262 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01003263
tierno868220c2017-09-26 00:11:05 +02003264 # create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02003265 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01003266 if flavor_dict['extended']!=None:
tierno868220c2017-09-26 00:11:05 +02003267 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
montesmoreno0c8def02016-12-22 12:16:23 +00003268 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3269
tierno868220c2017-09-26 00:11:05 +02003270 # Obtain information for additional disks
montesmoreno0c8def02016-12-22 12:16:23 +00003271 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id})
3272 if not extended_flavor_dict:
3273 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
3274 return
3275
tierno868220c2017-09-26 00:11:05 +02003276 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
montesmoreno0c8def02016-12-22 12:16:23 +00003277 myVMDict['disks'] = None
3278 extended_info = extended_flavor_dict[0]['extended']
3279 if extended_info != None:
3280 extended_flavor_dict_yaml = yaml.load(extended_info)
3281 if 'disks' in extended_flavor_dict_yaml:
3282 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
3283
tierno7edb6752016-03-21 17:37:52 +01003284 vm['vim_flavor_id'] = flavor_id
tierno7edb6752016-03-21 17:37:52 +01003285 myVMDict['imageRef'] = vm['vim_image_id']
3286 myVMDict['flavorRef'] = vm['vim_flavor_id']
mirabal29356312017-07-27 12:21:22 +02003287 myVMDict['availability_zone'] = vm.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01003288 myVMDict['networks'] = []
tierno868220c2017-09-26 00:11:05 +02003289 task_depends_on = []
3290 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno8e690322017-08-10 15:58:50 +02003291 db_vm_ifaces = []
tierno7edb6752016-03-21 17:37:52 +01003292 for iface in vm['interfaces']:
3293 netDict = {}
tierno41a69812018-02-16 14:34:33 +01003294 if iface['type'] == "data":
tierno7edb6752016-03-21 17:37:52 +01003295 netDict['type'] = iface['model']
tierno41a69812018-02-16 14:34:33 +01003296 elif "model" in iface and iface["model"] != None:
3297 netDict['model'] = iface['model']
tierno868220c2017-09-26 00:11:05 +02003298 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3299 # is obtained from iterface table model
3300 # discover type of interface looking at flavor
tierno41a69812018-02-16 14:34:33 +01003301 for numa in flavor_dict.get('extended', {}).get('numas', []):
3302 for flavor_iface in numa.get('interfaces', []):
tierno7edb6752016-03-21 17:37:52 +01003303 if flavor_iface.get('name') == iface['internal_name']:
3304 if flavor_iface['dedicated'] == 'yes':
tierno41a69812018-02-16 14:34:33 +01003305 netDict['type'] = "PF" # passthrough
tierno7edb6752016-03-21 17:37:52 +01003306 elif flavor_iface['dedicated'] == 'no':
tierno41a69812018-02-16 14:34:33 +01003307 netDict['type'] = "VF" # siov
tierno7edb6752016-03-21 17:37:52 +01003308 elif flavor_iface['dedicated'] == 'yes:sriov':
tierno41a69812018-02-16 14:34:33 +01003309 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
tierno7edb6752016-03-21 17:37:52 +01003310 netDict["mac_address"] = flavor_iface.get("mac_address")
tierno41a69812018-02-16 14:34:33 +01003311 break
tierno7edb6752016-03-21 17:37:52 +01003312 netDict["use"]=iface['type']
tierno41a69812018-02-16 14:34:33 +01003313 if netDict["use"] == "data" and not netDict.get("type"):
3314 # print "netDict", netDict
3315 # print "iface", iface
3316 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3317 sce_vnf['name'], vm['name'], iface['internal_name'])
3318 if flavor_dict.get('extended') == None:
tiernoae4a8d12016-07-08 12:30:39 +02003319 raise NfvoException(e_text + "After database migration some information is not available. \
3320 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01003321 else:
tiernoae4a8d12016-07-08 12:30:39 +02003322 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno41a69812018-02-16 14:34:33 +01003323 if netDict["use"] == "mgmt" or netDict["use"] == "bridge":
tierno7edb6752016-03-21 17:37:52 +01003324 netDict["type"]="virtual"
tierno41a69812018-02-16 14:34:33 +01003325 if iface.get("vpci"):
tierno7edb6752016-03-21 17:37:52 +01003326 netDict['vpci'] = iface['vpci']
tierno41a69812018-02-16 14:34:33 +01003327 if iface.get("mac"):
tierno7edb6752016-03-21 17:37:52 +01003328 netDict['mac_address'] = iface['mac']
tierno41a69812018-02-16 14:34:33 +01003329 if iface.get("ip_address"):
3330 netDict['ip_address'] = iface['ip_address']
3331 if iface.get("port-security") is not None:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00003332 netDict['port_security'] = iface['port-security']
tierno41a69812018-02-16 14:34:33 +01003333 if iface.get("floating-ip") is not None:
montesmoreno2a1fc4e2017-01-09 16:46:04 +00003334 netDict['floating_ip'] = iface['floating-ip']
tierno7edb6752016-03-21 17:37:52 +01003335 netDict['name'] = iface['internal_name']
3336 if iface['net_id'] is None:
3337 for vnf_iface in sce_vnf["interfaces"]:
tierno868220c2017-09-26 00:11:05 +02003338 # print iface
3339 # print vnf_iface
tierno41a69812018-02-16 14:34:33 +01003340 if vnf_iface['interface_id'] == iface['uuid']:
tierno868220c2017-09-26 00:11:05 +02003341 netDict['net_id'] = "TASK-{}".format(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id])
tierno8e690322017-08-10 15:58:50 +02003342 instance_net_id = sce_net2instance[ vnf_iface['sce_net_id'] ][datacenter_id]
tierno868220c2017-09-26 00:11:05 +02003343 task_depends_on.append(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id])
tierno7edb6752016-03-21 17:37:52 +01003344 break
3345 else:
tierno868220c2017-09-26 00:11:05 +02003346 netDict['net_id'] = "TASK-{}".format(net2task_id[ sce_vnf['uuid'] ][ iface['net_id'] ])
tierno8e690322017-08-10 15:58:50 +02003347 instance_net_id = vnf_net2instance[ sce_vnf['uuid'] ][ iface['net_id'] ]
tierno868220c2017-09-26 00:11:05 +02003348 task_depends_on.append(net2task_id[sce_vnf['uuid'] ][ iface['net_id']])
3349 # skip bridge ifaces not connected to any net
3350 if 'net_id' not in netDict or netDict['net_id']==None:
3351 continue
tierno7edb6752016-03-21 17:37:52 +01003352 myVMDict['networks'].append(netDict)
tierno8e690322017-08-10 15:58:50 +02003353 db_vm_iface={
3354 # "uuid"
3355 # 'instance_vm_id': instance_vm_uuid,
3356 "instance_net_id": instance_net_id,
3357 'interface_id': iface['uuid'],
3358 # 'vim_interface_id': ,
3359 'type': 'external' if iface['external_name'] is not None else 'internal',
3360 'ip_address': iface.get('ip_address'),
tierno41a69812018-02-16 14:34:33 +01003361 'mac_address': iface.get('mac'),
tierno8e690322017-08-10 15:58:50 +02003362 'floating_ip': int(iface.get('floating-ip', False)),
3363 'port_security': int(iface.get('port-security', True))
3364 }
3365 db_vm_ifaces.append(db_vm_iface)
3366 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3367 # print myVMDict['name']
3368 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3369 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3370 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tiernof1c8e222018-01-17 18:31:28 +01003371
3372 # We add the RO key to cloud_config if vnf will need ssh access
3373 cloud_config_vm = cloud_config
3374 if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3375 RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3376 cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
tierno36c0b172017-01-12 18:32:28 +01003377 if vm.get("boot_data"):
tiernof1c8e222018-01-17 18:31:28 +01003378 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3379
tierno5a3273c2017-08-29 11:43:46 +02003380 if myVMDict.get('availability_zone'):
3381 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02003382 else:
tierno5a3273c2017-08-29 11:43:46 +02003383 av_index = None
tierno8e690322017-08-10 15:58:50 +02003384 for vm_index in range(0, vm.get('count', 1)):
3385 vm_index_name = ""
3386 if vm.get('count', 1) > 1:
3387 vm_index_name += "." + chr(97 + vm_index)
tierno868220c2017-09-26 00:11:05 +02003388 task_params = (myVMDict['name']+vm_index_name, myVMDict['description'], myVMDict.get('start', None),
3389 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3390 myVMDict['disks'], av_index, vnf_availability_zones)
tierno8e690322017-08-10 15:58:50 +02003391 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3392 for net in myVMDict['networks']:
3393 if "vim_id" in net:
3394 for iface in vm['interfaces']:
tierno41a69812018-02-16 14:34:33 +01003395 if net["name"] == iface["internal_name"]:
3396 iface["vim_id"] = net["vim_id"]
tierno8e690322017-08-10 15:58:50 +02003397 break
3398 vm_uuid = str(uuid4())
3399 uuid_list.append(vm_uuid)
3400 db_vm = {
3401 "uuid": vm_uuid,
3402 'instance_vnf_id': vnf_uuid,
tierno868220c2017-09-26 00:11:05 +02003403 #TODO delete "vim_vm_id": vm_id,
tierno8e690322017-08-10 15:58:50 +02003404 "vm_id": vm["uuid"],
3405 # "status":
3406 }
3407 db_instance_vms.append(db_vm)
tierno868220c2017-09-26 00:11:05 +02003408
3409 iface_index = 0
tierno8e690322017-08-10 15:58:50 +02003410 for db_vm_iface in db_vm_ifaces:
3411 iface_uuid = str(uuid4())
3412 uuid_list.append(iface_uuid)
3413 db_vm_iface_instance = {
3414 "uuid": iface_uuid,
3415 "instance_vm_id": vm_uuid
3416 }
3417 db_vm_iface_instance.update(db_vm_iface)
3418 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3419 ip = db_vm_iface_instance.get("ip_address")
3420 i = ip.rfind(".")
3421 if i > 0:
3422 try:
3423 i += 1
3424 ip = ip[i:] + str(int(ip[:i]) +1)
3425 db_vm_iface_instance["ip_address"] = ip
3426 except:
3427 db_vm_iface_instance["ip_address"] = None
3428 db_instance_interfaces.append(db_vm_iface_instance)
tierno868220c2017-09-26 00:11:05 +02003429 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3430 iface_index += 1
3431
3432 db_vim_action = {
3433 "instance_action_id": instance_action_id,
3434 "task_index": task_index,
3435 "datacenter_vim_id": myvim_thread_id,
3436 "action": "CREATE",
3437 "status": "SCHEDULED",
3438 "item": "instance_vms",
3439 "item_id": vm_uuid,
3440 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3441 default_flow_style=True, width=256)
3442 }
3443 task_index += 1
3444 db_vim_actions.append(db_vim_action)
tierno8e690322017-08-10 15:58:50 +02003445
Igor D.Ccaadc442017-11-06 12:48:48 +00003446 task_depends_on = []
3447 for vnffg in scenarioDict['vnffgs']:
3448 for rsp in vnffg['rsps']:
3449 sfs_created = []
3450 for cp in rsp['connection_points']:
3451 count = mydb.get_rows(
3452 SELECT=('vms.count'),
3453 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h on interfaces.uuid=h.interface_id",
3454 WHERE={'h.uuid': cp['uuid']})[0]['count']
3455 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3456 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3457 dependencies = []
3458 for instance_vm in instance_vms:
3459 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3460 if action:
3461 dependencies.append(action['task_index'])
3462 # TODO: throw exception if count != len(instance_vms)
3463 # TODO: and action shouldn't ever be None
3464 sfis_created = []
3465 for i in range(count):
3466 # create sfis
3467 sfi_uuid = str(uuid4())
3468 uuid_list.append(sfi_uuid)
3469 db_sfi = {
3470 "uuid": sfi_uuid,
3471 "instance_scenario_id": instance_uuid,
3472 'sce_rsp_hop_id': cp['uuid'],
3473 'datacenter_id': datacenter_id,
3474 'datacenter_tenant_id': myvim_thread_id,
3475 "vim_sfi_id": None, # vim thread will populate
3476 }
3477 db_instance_sfis.append(db_sfi)
3478 db_vim_action = {
3479 "instance_action_id": instance_action_id,
3480 "task_index": task_index,
3481 "datacenter_vim_id": myvim_thread_id,
3482 "action": "CREATE",
3483 "status": "SCHEDULED",
3484 "item": "instance_sfis",
3485 "item_id": sfi_uuid,
3486 "extra": yaml.safe_dump({"params": "", "depends_on": [dependencies[i]]},
3487 default_flow_style=True, width=256)
3488 }
3489 sfis_created.append(task_index)
3490 task_index += 1
3491 db_vim_actions.append(db_vim_action)
3492 # create sfs
3493 sf_uuid = str(uuid4())
3494 uuid_list.append(sf_uuid)
3495 db_sf = {
3496 "uuid": sf_uuid,
3497 "instance_scenario_id": instance_uuid,
3498 'sce_rsp_hop_id': cp['uuid'],
3499 'datacenter_id': datacenter_id,
3500 'datacenter_tenant_id': myvim_thread_id,
3501 "vim_sf_id": None, # vim thread will populate
3502 }
3503 db_instance_sfs.append(db_sf)
3504 db_vim_action = {
3505 "instance_action_id": instance_action_id,
3506 "task_index": task_index,
3507 "datacenter_vim_id": myvim_thread_id,
3508 "action": "CREATE",
3509 "status": "SCHEDULED",
3510 "item": "instance_sfs",
3511 "item_id": sf_uuid,
3512 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3513 default_flow_style=True, width=256)
3514 }
3515 sfs_created.append(task_index)
3516 task_index += 1
3517 db_vim_actions.append(db_vim_action)
3518 classifier = rsp['classifier']
3519
3520 # TODO the following ~13 lines can be reused for the sfi case
3521 count = mydb.get_rows(
3522 SELECT=('vms.count'),
3523 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3524 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3525 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3526 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3527 dependencies = []
3528 for instance_vm in instance_vms:
3529 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3530 if action:
3531 dependencies.append(action['task_index'])
3532 # TODO: throw exception if count != len(instance_vms)
3533 # TODO: and action shouldn't ever be None
3534 classifications_created = []
3535 for i in range(count):
3536 for match in classifier['matches']:
3537 # create classifications
3538 classification_uuid = str(uuid4())
3539 uuid_list.append(classification_uuid)
3540 db_classification = {
3541 "uuid": classification_uuid,
3542 "instance_scenario_id": instance_uuid,
3543 'sce_classifier_match_id': match['uuid'],
3544 'datacenter_id': datacenter_id,
3545 'datacenter_tenant_id': myvim_thread_id,
3546 "vim_classification_id": None, # vim thread will populate
3547 }
3548 db_instance_classifications.append(db_classification)
3549 classification_params = {
3550 "ip_proto": match["ip_proto"],
3551 "source_ip": match["source_ip"],
3552 "destination_ip": match["destination_ip"],
3553 "source_port": match["source_port"],
3554 "destination_port": match["destination_port"]
3555 }
3556 db_vim_action = {
3557 "instance_action_id": instance_action_id,
3558 "task_index": task_index,
3559 "datacenter_vim_id": myvim_thread_id,
3560 "action": "CREATE",
3561 "status": "SCHEDULED",
3562 "item": "instance_classifications",
3563 "item_id": classification_uuid,
3564 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3565 default_flow_style=True, width=256)
3566 }
3567 classifications_created.append(task_index)
3568 task_index += 1
3569 db_vim_actions.append(db_vim_action)
3570
3571 # create sfps
3572 sfp_uuid = str(uuid4())
3573 uuid_list.append(sfp_uuid)
3574 db_sfp = {
3575 "uuid": sfp_uuid,
3576 "instance_scenario_id": instance_uuid,
3577 'sce_rsp_id': rsp['uuid'],
3578 'datacenter_id': datacenter_id,
3579 'datacenter_tenant_id': myvim_thread_id,
3580 "vim_sfp_id": None, # vim thread will populate
3581 }
3582 db_instance_sfps.append(db_sfp)
3583 db_vim_action = {
3584 "instance_action_id": instance_action_id,
3585 "task_index": task_index,
3586 "datacenter_vim_id": myvim_thread_id,
3587 "action": "CREATE",
3588 "status": "SCHEDULED",
3589 "item": "instance_sfps",
3590 "item_id": sfp_uuid,
3591 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3592 default_flow_style=True, width=256)
3593 }
3594 task_index += 1
3595 db_vim_actions.append(db_vim_action)
3596
tierno867ffe92017-03-27 12:50:34 +02003597 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003598
tierno868220c2017-09-26 00:11:05 +02003599 db_instance_action["number_tasks"] = task_index
tierno8e690322017-08-10 15:58:50 +02003600 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3601 db_instance_scenario['datacenter_id'] = default_datacenter_id
3602 db_tables=[
3603 {"instance_scenarios": db_instance_scenario},
3604 {"instance_vnfs": db_instance_vnfs},
3605 {"instance_nets": db_instance_nets},
3606 {"ip_profiles": db_ip_profiles},
3607 {"instance_vms": db_instance_vms},
3608 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003609 {"instance_actions": db_instance_action},
Igor D.Ccaadc442017-11-06 12:48:48 +00003610 {"instance_sfis": db_instance_sfis},
3611 {"instance_sfs": db_instance_sfs},
3612 {"instance_classifications": db_instance_classifications},
3613 {"instance_sfps": db_instance_sfps},
tierno868220c2017-09-26 00:11:05 +02003614 {"vim_actions": db_vim_actions}
tierno8e690322017-08-10 15:58:50 +02003615 ]
3616
tierno868220c2017-09-26 00:11:05 +02003617 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003618 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3619 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003620 for myvim_thread_id in myvim_threads_id.values():
3621 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003622
tierno868220c2017-09-26 00:11:05 +02003623 returned_instance = mydb.get_instance_scenario(instance_uuid)
3624 returned_instance["action_id"] = instance_action_id
3625 return returned_instance
3626 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003627 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003628 if isinstance(e, db_base_Exception):
3629 error_text = "database Exception"
3630 elif isinstance(e, vimconn.vimconnException):
3631 error_text = "VIM Exception"
3632 else:
3633 error_text = "Exception"
3634 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003635 # logger.error("create_instance: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02003636 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003637
tiernob3d36742017-03-03 23:51:05 +01003638
tierno7edb6752016-03-21 17:37:52 +01003639def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02003640 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003641 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02003642 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01003643 tenant_id = instanceDict["tenant_id"]
tierno868220c2017-09-26 00:11:05 +02003644 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno868220c2017-09-26 00:11:05 +02003645 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02003646 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003647
tierno868220c2017-09-26 00:11:05 +02003648 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00003649 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01003650 myvims = {}
3651 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02003652 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02003653 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01003654
tierno868220c2017-09-26 00:11:05 +02003655 task_index = 0
3656 instance_action_id = get_task_id()
3657 db_vim_actions = []
3658 db_instance_action = {
3659 "uuid": instance_action_id, # same uuid for the instance and the action on create
3660 "tenant_id": tenant_id,
3661 "instance_id": instance_id,
3662 "description": "DELETE",
3663 # "number_tasks": 0 # filled bellow
3664 }
3665
3666 # 2.1 deleting VMs
3667 # vm_fail_list=[]
tierno7edb6752016-03-21 17:37:52 +01003668 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00003669 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tierno868220c2017-09-26 00:11:05 +02003670 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
tiernoa2793912016-10-04 08:15:08 +00003671 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01003672 try:
tierno867ffe92017-03-27 12:50:34 +02003673 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01003674 except NfvoException as e:
3675 logger.error(str(e))
3676 myvim_thread = None
3677 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00003678 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
3679 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
3680 if len(vims) == 0:
3681 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
3682 sce_vnf["datacenter_tenant_id"]))
3683 myvims[datacenter_key] = None
3684 else:
3685 myvims[datacenter_key] = vims.values()[0]
3686 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01003687 myvim_thread = myvim_threads[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01003688 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00003689 if not myvim:
3690 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
3691 continue
tierno3fcfdb72017-10-24 07:48:24 +02003692 db_vim_action = {
3693 "instance_action_id": instance_action_id,
3694 "task_index": task_index,
3695 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
3696 "action": "DELETE",
3697 "status": "SCHEDULED",
3698 "item": "instance_vms",
3699 "item_id": vm["uuid"],
3700 "extra": yaml.safe_dump({"params": vm["interfaces"]},
3701 default_flow_style=True, width=256)
3702 }
3703 db_vim_actions.append(db_vim_action)
3704 for interface in vm["interfaces"]:
3705 if not interface.get("instance_net_id"):
3706 continue
3707 if interface["instance_net_id"] not in net2vm_dependencies:
3708 net2vm_dependencies[interface["instance_net_id"]] = []
3709 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
3710 task_index += 1
tierno42026a02017-02-10 15:13:40 +01003711
tierno868220c2017-09-26 00:11:05 +02003712 # 2.2 deleting NETS
3713 # net_fail_list=[]
tierno7edb6752016-03-21 17:37:52 +01003714 for net in instanceDict['nets']:
tierno868220c2017-09-26 00:11:05 +02003715 vimthread_affected[net["datacenter_tenant_id"]] = None
tiernoa2793912016-10-04 08:15:08 +00003716 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
3717 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01003718 try:
tierno867ffe92017-03-27 12:50:34 +02003719 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01003720 except NfvoException as e:
3721 logger.error(str(e))
3722 myvim_thread = None
3723 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00003724 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
3725 datacenter_tenant_id=net["datacenter_tenant_id"])
3726 if len(vims) == 0:
3727 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
3728 myvims[datacenter_key] = None
3729 else:
3730 myvims[datacenter_key] = vims.values()[0]
3731 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01003732 myvim_thread = myvim_threads[datacenter_key]
tiernoa2793912016-10-04 08:15:08 +00003733
tierno7edb6752016-03-21 17:37:52 +01003734 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00003735 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
tierno7edb6752016-03-21 17:37:52 +01003736 continue
tierno3fcfdb72017-10-24 07:48:24 +02003737 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
3738 if net2vm_dependencies.get(net["uuid"]):
3739 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
3740 db_vim_action = {
3741 "instance_action_id": instance_action_id,
3742 "task_index": task_index,
3743 "datacenter_vim_id": net["datacenter_tenant_id"],
3744 "action": "DELETE",
3745 "status": "SCHEDULED",
3746 "item": "instance_nets",
3747 "item_id": net["uuid"],
3748 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3749 }
3750 task_index += 1
3751 db_vim_actions.append(db_vim_action)
tierno868220c2017-09-26 00:11:05 +02003752
Igor D.Ccaadc442017-11-06 12:48:48 +00003753 # 2.3 deleting VNFFGs
3754
tierno69b590e2018-03-13 18:52:23 +01003755 for sfp in instanceDict.get('sfps', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003756 vimthread_affected[sfp["datacenter_tenant_id"]] = None
3757 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
3758 if datacenter_key not in myvims:
3759 try:
3760 _,myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
3761 except NfvoException as e:
3762 logger.error(str(e))
3763 myvim_thread = None
3764 myvim_threads[datacenter_key] = myvim_thread
3765 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
3766 datacenter_tenant_id=sfp["datacenter_tenant_id"])
3767 if len(vims) == 0:
3768 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
3769 myvims[datacenter_key] = None
3770 else:
3771 myvims[datacenter_key] = vims.values()[0]
3772 myvim = myvims[datacenter_key]
3773 myvim_thread = myvim_threads[datacenter_key]
3774
3775 if not myvim:
3776 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
3777 continue
3778 extra = {"params": (sfp['vim_sfp_id'])}
3779 db_vim_action = {
3780 "instance_action_id": instance_action_id,
3781 "task_index": task_index,
3782 "datacenter_vim_id": sfp["datacenter_tenant_id"],
3783 "action": "DELETE",
3784 "status": "SCHEDULED",
3785 "item": "instance_sfps",
3786 "item_id": sfp["uuid"],
3787 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3788 }
3789 task_index += 1
3790 db_vim_actions.append(db_vim_action)
3791
tierno69b590e2018-03-13 18:52:23 +01003792 for sf in instanceDict.get('sfs', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003793 vimthread_affected[sf["datacenter_tenant_id"]] = None
3794 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
3795 if datacenter_key not in myvims:
3796 try:
3797 _,myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
3798 except NfvoException as e:
3799 logger.error(str(e))
3800 myvim_thread = None
3801 myvim_threads[datacenter_key] = myvim_thread
3802 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
3803 datacenter_tenant_id=sf["datacenter_tenant_id"])
3804 if len(vims) == 0:
3805 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
3806 myvims[datacenter_key] = None
3807 else:
3808 myvims[datacenter_key] = vims.values()[0]
3809 myvim = myvims[datacenter_key]
3810 myvim_thread = myvim_threads[datacenter_key]
3811
3812 if not myvim:
3813 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
3814 continue
3815 extra = {"params": (sf['vim_sf_id'])}
3816 db_vim_action = {
3817 "instance_action_id": instance_action_id,
3818 "task_index": task_index,
3819 "datacenter_vim_id": sf["datacenter_tenant_id"],
3820 "action": "DELETE",
3821 "status": "SCHEDULED",
3822 "item": "instance_sfs",
3823 "item_id": sf["uuid"],
3824 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3825 }
3826 task_index += 1
3827 db_vim_actions.append(db_vim_action)
3828
tierno69b590e2018-03-13 18:52:23 +01003829 for sfi in instanceDict.get('sfis', ()):
Igor D.Ccaadc442017-11-06 12:48:48 +00003830 vimthread_affected[sfi["datacenter_tenant_id"]] = None
3831 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
3832 if datacenter_key not in myvims:
3833 try:
3834 _,myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
3835 except NfvoException as e:
3836 logger.error(str(e))
3837 myvim_thread = None
3838 myvim_threads[datacenter_key] = myvim_thread
3839 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
3840 datacenter_tenant_id=sfi["datacenter_tenant_id"])
3841 if len(vims) == 0:
3842 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
3843 myvims[datacenter_key] = None
3844 else:
3845 myvims[datacenter_key] = vims.values()[0]
3846 myvim = myvims[datacenter_key]
3847 myvim_thread = myvim_threads[datacenter_key]
3848
3849 if not myvim:
3850 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
3851 continue
3852 extra = {"params": (sfi['vim_sfi_id'])}
3853 db_vim_action = {
3854 "instance_action_id": instance_action_id,
3855 "task_index": task_index,
3856 "datacenter_vim_id": sfi["datacenter_tenant_id"],
3857 "action": "DELETE",
3858 "status": "SCHEDULED",
3859 "item": "instance_sfis",
3860 "item_id": sfi["uuid"],
3861 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3862 }
3863 task_index += 1
3864 db_vim_actions.append(db_vim_action)
3865
3866 for classification in instanceDict['classifications']:
3867 vimthread_affected[classification["datacenter_tenant_id"]] = None
3868 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
3869 if datacenter_key not in myvims:
3870 try:
3871 _,myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
3872 except NfvoException as e:
3873 logger.error(str(e))
3874 myvim_thread = None
3875 myvim_threads[datacenter_key] = myvim_thread
3876 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
3877 datacenter_tenant_id=classification["datacenter_tenant_id"])
3878 if len(vims) == 0:
3879 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"], classification["datacenter_tenant_id"]))
3880 myvims[datacenter_key] = None
3881 else:
3882 myvims[datacenter_key] = vims.values()[0]
3883 myvim = myvims[datacenter_key]
3884 myvim_thread = myvim_threads[datacenter_key]
3885
3886 if not myvim:
3887 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'], classification["datacenter_id"])
3888 continue
3889 extra = {"params": (classification['vim_classification_id'])}
3890 db_vim_action = {
3891 "instance_action_id": instance_action_id,
3892 "task_index": task_index,
3893 "datacenter_vim_id": classification["datacenter_tenant_id"],
3894 "action": "DELETE",
3895 "status": "SCHEDULED",
3896 "item": "instance_classifications",
3897 "item_id": classification["uuid"],
3898 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3899 }
3900 task_index += 1
3901 db_vim_actions.append(db_vim_action)
3902
tierno868220c2017-09-26 00:11:05 +02003903 db_instance_action["number_tasks"] = task_index
3904 db_tables = [
3905 {"instance_actions": db_instance_action},
3906 {"vim_actions": db_vim_actions}
3907 ]
3908
3909 logger.debug("delete_instance done DB tables: %s",
3910 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
3911 mydb.new_rows(db_tables, ())
3912 for myvim_thread_id in vimthread_affected.keys():
3913 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
3914
tiernob3d36742017-03-03 23:51:05 +01003915 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02003916 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
3917 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01003918 else:
tierno868220c2017-09-26 00:11:05 +02003919 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01003920
tiernob3d36742017-03-03 23:51:05 +01003921
tierno7edb6752016-03-21 17:37:52 +01003922def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
3923 '''Refreshes a scenario instance. It modifies instanceDict'''
3924 '''Returns:
3925 - 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
3926 - error_msg
3927 '''
tierno867ffe92017-03-27 12:50:34 +02003928 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
3929 # #print "nfvo.refresh_instance begins"
3930 # #print json.dumps(instanceDict, indent=4)
3931 #
3932 # #print "Getting the VIM URL and the VIM tenant_id"
3933 # myvims={}
3934 #
3935 # # 1. Getting VIM vm and net list
3936 # vms_updated = [] #List of VM instance uuids in openmano that were updated
3937 # vms_notupdated=[]
3938 # vm_list = {}
3939 # for sce_vnf in instanceDict['vnfs']:
3940 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
3941 # if datacenter_key not in vm_list:
3942 # vm_list[datacenter_key] = []
3943 # if datacenter_key not in myvims:
3944 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
3945 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
3946 # if len(vims) == 0:
3947 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
3948 # myvims[datacenter_key] = None
3949 # else:
3950 # myvims[datacenter_key] = vims.values()[0]
3951 # for vm in sce_vnf['vms']:
3952 # vm_list[datacenter_key].append(vm['vim_vm_id'])
3953 # vms_notupdated.append(vm["uuid"])
3954 #
3955 # nets_updated = [] #List of VM instance uuids in openmano that were updated
3956 # nets_notupdated=[]
3957 # net_list = {}
3958 # for net in instanceDict['nets']:
3959 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
3960 # if datacenter_key not in net_list:
3961 # net_list[datacenter_key] = []
3962 # if datacenter_key not in myvims:
3963 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
3964 # datacenter_tenant_id=net["datacenter_tenant_id"])
3965 # if len(vims) == 0:
3966 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
3967 # myvims[datacenter_key] = None
3968 # else:
3969 # myvims[datacenter_key] = vims.values()[0]
3970 #
3971 # net_list[datacenter_key].append(net['vim_net_id'])
3972 # nets_notupdated.append(net["uuid"])
3973 #
3974 # # 1. Getting the status of all VMs
3975 # vm_dict={}
3976 # for datacenter_key in myvims:
3977 # if not vm_list.get(datacenter_key):
3978 # continue
3979 # failed = True
3980 # failed_message=""
3981 # if not myvims[datacenter_key]:
3982 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
3983 # else:
3984 # try:
3985 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
3986 # failed = False
3987 # except vimconn.vimconnException as e:
3988 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
3989 # failed_message = str(e)
3990 # if failed:
3991 # for vm in vm_list[datacenter_key]:
3992 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
3993 #
3994 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
3995 # for sce_vnf in instanceDict['vnfs']:
3996 # for vm in sce_vnf['vms']:
3997 # vm_id = vm['vim_vm_id']
3998 # interfaces = vm_dict[vm_id].pop('interfaces', [])
3999 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4000 # has_mgmt_iface = False
4001 # for iface in vm["interfaces"]:
4002 # if iface["type"]=="mgmt":
4003 # has_mgmt_iface = True
4004 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4005 # vm_dict[vm_id]['status'] = "ACTIVE"
4006 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4007 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4008 # 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'):
4009 # vm['status'] = vm_dict[vm_id]['status']
4010 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4011 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4012 # # 2.1. Update in openmano DB the VMs whose status changed
4013 # try:
4014 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4015 # vms_notupdated.remove(vm["uuid"])
4016 # if updates>0:
4017 # vms_updated.append(vm["uuid"])
4018 # except db_base_Exception as e:
4019 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4020 # # 2.2. Update in openmano DB the interface VMs
4021 # for interface in interfaces:
4022 # #translate from vim_net_id to instance_net_id
4023 # network_id_list=[]
4024 # for net in instanceDict['nets']:
4025 # if net["vim_net_id"] == interface["vim_net_id"]:
4026 # network_id_list.append(net["uuid"])
4027 # if not network_id_list:
4028 # continue
4029 # del interface["vim_net_id"]
4030 # try:
4031 # for network_id in network_id_list:
4032 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4033 # except db_base_Exception as e:
4034 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4035 #
4036 # # 3. Getting the status of all nets
4037 # net_dict = {}
4038 # for datacenter_key in myvims:
4039 # if not net_list.get(datacenter_key):
4040 # continue
4041 # failed = True
4042 # failed_message = ""
4043 # if not myvims[datacenter_key]:
4044 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4045 # else:
4046 # try:
4047 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4048 # failed = False
4049 # except vimconn.vimconnException as e:
4050 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4051 # failed_message = str(e)
4052 # if failed:
4053 # for net in net_list[datacenter_key]:
4054 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4055 #
4056 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4057 # # TODO: update nets inside a vnf
4058 # for net in instanceDict['nets']:
4059 # net_id = net['vim_net_id']
4060 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4061 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4062 # 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'):
4063 # net['status'] = net_dict[net_id]['status']
4064 # net['error_msg'] = net_dict[net_id].get('error_msg')
4065 # net['vim_info'] = net_dict[net_id].get('vim_info')
4066 # # 5.1. Update in openmano DB the nets whose status changed
4067 # try:
4068 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4069 # nets_notupdated.remove(net["uuid"])
4070 # if updated>0:
4071 # nets_updated.append(net["uuid"])
4072 # except db_base_Exception as e:
4073 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4074 #
4075 # # Returns appropriate output
4076 # #print "nfvo.refresh_instance finishes"
4077 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4078 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01004079 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02004080 # if len(vms_notupdated)+len(nets_notupdated)>0:
4081 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4082 # 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 +01004083
tiernoae4a8d12016-07-08 12:30:39 +02004084 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01004085
4086def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02004087 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02004088 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01004089 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4090
tiernoae4a8d12016-07-08 12:30:39 +02004091 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02004092 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4093 if len(vims) == 0:
4094 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004095 myvim = vims.values()[0]
tierno42026a02017-02-10 15:13:40 +01004096
tierno868220c2017-09-26 00:11:05 +02004097 if action_dict.get("create-vdu"):
4098 for vdu in action_dict["create-vdu"]:
4099 vdu_id = vdu.get("vdu-id")
4100 vdu_count = vdu.get("count", 1)
4101 # get from database TODO
4102 # insert tasks TODO
4103 pass
tierno7edb6752016-03-21 17:37:52 +01004104
4105 input_vnfs = action_dict.pop("vnfs", [])
4106 input_vms = action_dict.pop("vms", [])
4107 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
4108 vm_result = {}
4109 vm_error = 0
4110 vm_ok = 0
4111 for sce_vnf in instanceDict['vnfs']:
4112 for vm in sce_vnf['vms']:
4113 if not action_over_all:
4114 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
tierno868220c2017-09-26 00:11:05 +02004115 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
tierno7edb6752016-03-21 17:37:52 +01004116 continue
tiernoae4a8d12016-07-08 12:30:39 +02004117 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004118 if "add_public_key" in action_dict:
4119 mgmt_access = {}
4120 if sce_vnf.get('mgmt_access'):
4121 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4122 ssh_access = mgmt_access['config-access']['ssh-access']
4123 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01004124 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02004125 if ssh_access['required'] and ssh_access['default-user']:
4126 if 'ip_address' in vm:
4127 mgmt_ip = vm['ip_address'].split(';')
4128 password = mgmt_access['config-access'].get('password')
4129 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4130 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4131 action_dict['add_public_key'],
4132 password=password, ro_key=priv_RO_key)
4133 else:
4134 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4135 HTTP_Internal_Server_Error)
4136 except KeyError:
4137 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4138 HTTP_Internal_Server_Error)
4139 else:
4140 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4141 HTTP_Internal_Server_Error)
4142 else:
4143 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4144 if "console" in action_dict:
4145 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02004146 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4147 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4148 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02004149 ip = data["server"],
4150 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02004151 suffix = data["suffix"]),
4152 "name":vm['name']
4153 }
4154 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004155 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
4156 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
4157 "description": "this console is only reachable by local interface",
4158 "name":vm['name']
4159 }
tierno20fc2a22016-08-19 17:02:35 +02004160 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02004161 else:
4162 #print "console data", data
4163 try:
4164 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4165 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4166 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4167 protocol=data["protocol"],
4168 ip = global_config["http_console_host"],
4169 port = console_thread.port,
4170 suffix = data["suffix"]),
4171 "name":vm['name']
4172 }
4173 vm_ok +=1
4174 except NfvoException as e:
4175 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4176 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02004177
gcalvinoe580c7d2017-09-22 14:09:51 +02004178 else:
4179 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4180 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02004181 except vimconn.vimconnException as e:
4182 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4183 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01004184
4185 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02004186 return vm_result
tierno7edb6752016-03-21 17:37:52 +01004187 else:
tierno351863c2016-07-23 01:46:03 +02004188 return vm_result
tierno42026a02017-02-10 15:13:40 +01004189
tierno868220c2017-09-26 00:11:05 +02004190def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
4191 filter={}
4192 if nfvo_tenant and nfvo_tenant != "any":
4193 filter["tenant_id"] = nfvo_tenant
4194 if instance_id and instance_id != "any":
4195 filter["instance_id"] = instance_id
4196 if action_id:
4197 filter["uuid"] = action_id
4198 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
4199 if not rows and action_id:
4200 raise NfvoException("Not found any action with this criteria", HTTP_Not_Found)
4201 return {"ations": rows}
4202
tiernob3d36742017-03-03 23:51:05 +01004203
tierno7edb6752016-03-21 17:37:52 +01004204def create_or_use_console_proxy_thread(console_server, console_port):
4205 #look for a non-used port
4206 console_thread_key = console_server + ":" + str(console_port)
4207 if console_thread_key in global_config["console_thread"]:
4208 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02004209 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01004210
tierno7edb6752016-03-21 17:37:52 +01004211 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02004212 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01004213 if port in global_config["console_ports"]:
4214 continue
4215 try:
4216 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4217 clithread.start()
4218 global_config["console_thread"][console_thread_key] = clithread
4219 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02004220 return clithread
tierno7edb6752016-03-21 17:37:52 +01004221 except cli.ConsoleProxyExceptionPortUsed as e:
4222 #port used, try with onoher
4223 continue
4224 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02004225 raise NfvoException(str(e), HTTP_Bad_Request)
4226 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01004227
tiernob3d36742017-03-03 23:51:05 +01004228
tierno7edb6752016-03-21 17:37:52 +01004229def check_tenant(mydb, tenant_id):
4230 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02004231 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4232 if not tenant:
4233 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
4234 return
tierno7edb6752016-03-21 17:37:52 +01004235
4236def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01004237
gcalvinoe580c7d2017-09-22 14:09:51 +02004238 tenant_uuid = str(uuid4())
4239 tenant_dict['uuid'] = tenant_uuid
4240 try:
4241 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4242 tenant_dict['RO_pub_key'] = pub_key
4243 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02004244 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02004245 except db_base_Exception as e:
tierno9c5c8322018-03-23 15:44:03 +01004246 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
gcalvinoe580c7d2017-09-22 14:09:51 +02004247 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01004248
tierno7edb6752016-03-21 17:37:52 +01004249def delete_tenant(mydb, tenant):
4250 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01004251
tiernof97fd272016-07-11 14:32:37 +02004252 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4253 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4254 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01004255
tiernob3d36742017-03-03 23:51:05 +01004256
tierno7edb6752016-03-21 17:37:52 +01004257def new_datacenter(mydb, datacenter_descriptor):
4258 if "config" in datacenter_descriptor:
4259 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02004260 #Check that datacenter-type is correct
4261 datacenter_type = datacenter_descriptor.get("type", "openvim");
4262 module_info = None
4263 try:
4264 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02004265 pkg = __import__("osm_ro." + module)
4266 vim_conn = getattr(pkg, module)
4267 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02004268 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02004269 # if module_info and module_info[0]:
4270 # file.close(module_info[0])
tierno56d877d2018-01-15 13:59:05 +01004271 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type, module), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01004272
gcalvinoc62cfa52017-10-05 18:21:25 +02004273 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernof97fd272016-07-11 14:32:37 +02004274 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004275
tiernob3d36742017-03-03 23:51:05 +01004276
tierno7edb6752016-03-21 17:37:52 +01004277def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02004278 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02004279 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02004280
4281 # edit data
tiernof97fd272016-07-11 14:32:37 +02004282 datacenter_id = datacenter['uuid']
4283 where={'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02004284 remove_port_mapping = False
tierno7edb6752016-03-21 17:37:52 +01004285 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02004286 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01004287 try:
4288 new_config_dict = datacenter_descriptor["config"]
4289 #delete null fields
4290 to_delete=[]
4291 for k in new_config_dict:
tierno8fe7a492017-07-11 13:50:04 +02004292 if new_config_dict[k] == None:
tierno7edb6752016-03-21 17:37:52 +01004293 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02004294 if k == 'sdn-controller':
4295 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01004296
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004297 config_text = datacenter.get("config")
4298 if not config_text:
4299 config_text = '{}'
4300 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01004301 config_dict.update(new_config_dict)
4302 #delete null fields
4303 for k in to_delete:
4304 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02004305 except Exception as e:
4306 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02004307 if config_dict:
4308 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4309 else:
4310 datacenter_descriptor["config"] = None
4311 if remove_port_mapping:
4312 try:
4313 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4314 except ovimException as e:
4315 logger.error("Error deleting datacenter-port-mapping " + str(e))
4316
tiernof97fd272016-07-11 14:32:37 +02004317 mydb.update_rows('datacenters', datacenter_descriptor, where)
4318 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01004319
tiernob3d36742017-03-03 23:51:05 +01004320
tierno7edb6752016-03-21 17:37:52 +01004321def delete_datacenter(mydb, datacenter):
4322 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02004323 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
4324 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02004325 try:
4326 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
4327 except ovimException as e:
4328 logger.error("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02004329 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01004330
tiernob3d36742017-03-03 23:51:05 +01004331
tierno8008c3a2016-10-13 15:34:28 +00004332def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
tierno9c22f2d2017-10-09 16:23:55 +02004333 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02004334 try:
4335 datacenter_id = get_datacenter_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004336
tierno0ea2a7e2017-10-18 00:06:26 +02004337 create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01004338
tierno0ea2a7e2017-10-18 00:06:26 +02004339 # get nfvo_tenant info
4340 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
4341 if vim_tenant_name==None:
4342 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01004343
tierno0ea2a7e2017-10-18 00:06:26 +02004344 #check that this association does not exist before
4345 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
4346 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4347 if len(tenants_datacenters)>0:
4348 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01004349
tierno0ea2a7e2017-10-18 00:06:26 +02004350 vim_tenant_id_exist_atdb=False
4351 if not create_vim_tenant:
4352 where_={"datacenter_id": datacenter_id}
4353 if vim_tenant_id!=None:
4354 where_["vim_tenant_id"] = vim_tenant_id
4355 if vim_tenant_name!=None:
4356 where_["vim_tenant_name"] = vim_tenant_name
4357 #check if vim_tenant_id is already at database
4358 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
4359 if len(datacenter_tenants_dict)>=1:
4360 datacenter_tenants_dict = datacenter_tenants_dict[0]
4361 vim_tenant_id_exist_atdb=True
4362 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
4363 else: #result=0
4364 datacenter_tenants_dict = {}
4365 #insert at table datacenter_tenants
4366 else: #if vim_tenant_id==None:
4367 #create tenant at VIM if not provided
4368 try:
4369 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
4370 vim_passwd=vim_password)
4371 datacenter_name = myvim["name"]
4372 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
4373 except vimconn.vimconnException as e:
4374 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id, str(e)), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01004375 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02004376 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01004377
tierno0ea2a7e2017-10-18 00:06:26 +02004378 #fill datacenter_tenants table
4379 if not vim_tenant_id_exist_atdb:
4380 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
4381 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
4382 datacenter_tenants_dict["user"] = vim_username
4383 datacenter_tenants_dict["passwd"] = vim_password
4384 datacenter_tenants_dict["datacenter_id"] = datacenter_id
4385 if config:
4386 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
4387 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
4388 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01004389
tierno0ea2a7e2017-10-18 00:06:26 +02004390 #fill tenants_datacenters table
4391 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
4392 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
4393 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
4394 # create thread
4395 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id) # reload data
4396 datacenter_name = myvim["name"]
4397 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
4398 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
4399 db=db, db_lock=db_lock, ovim=ovim)
4400 new_thread.start()
4401 thread_id = datacenter_tenants_dict["uuid"]
4402 vim_threads["running"][thread_id] = new_thread
4403 return datacenter_id
4404 except vimconn.vimconnException as e:
4405 raise NfvoException(str(e), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01004406
tierno99314902017-04-26 13:23:09 +02004407
4408def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
4409 vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004410 #Obtain the data of this datacenter_tenant_id
4411 vim_data = mydb.get_rows(
4412 SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",
4413 "datacenter_tenants.passwd", "datacenter_tenants.config"),
4414 FROM="datacenter_tenants JOIN tenants_datacenters ON datacenter_tenants.uuid=tenants_datacenters.datacenter_tenant_id",
4415 WHERE={"tenants_datacenters.nfvo_tenant_id": nfvo_tenant,
4416 "tenants_datacenters.datacenter_id": datacenter_id})
4417
4418 logger.debug(str(vim_data))
4419 if len(vim_data) < 1:
4420 raise NfvoException("Datacenter {} is not attached for tenant {}".format(datacenter_id, nfvo_tenant), HTTP_Conflict)
4421
4422 v = vim_data[0]
4423 if v['config']:
4424 v['config'] = yaml.load(v['config'])
4425
4426 if vim_tenant_id:
4427 v['vim_tenant_id'] = vim_tenant_id
4428 if vim_tenant_name:
4429 v['vim_tenant_name'] = vim_tenant_name
4430 if vim_username:
4431 v['user'] = vim_username
4432 if vim_password:
4433 v['passwd'] = vim_password
4434 if config:
4435 if not v['config']:
4436 v['config'] = {}
4437 v['config'].update(config)
4438
4439 logger.debug(str(v))
4440 deassociate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'])
4441 associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'], vim_tenant_name=v['vim_tenant_name'],
4442 vim_username=v['user'], vim_password=v['passwd'], config=v['config'])
4443
4444 return datacenter_id
tiernob3d36742017-03-03 23:51:05 +01004445
tierno7edb6752016-03-21 17:37:52 +01004446def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
tierno7edb6752016-03-21 17:37:52 +01004447 #get nfvo_tenant info
4448 if not tenant_id or tenant_id=="any":
4449 tenant_uuid = None
4450 else:
tiernof97fd272016-07-11 14:32:37 +02004451 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01004452 tenant_uuid = tenant_dict['uuid']
4453
tierno0ea2a7e2017-10-18 00:06:26 +02004454 datacenter_id = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004455 #check that this association exist before
tierno0ea2a7e2017-10-18 00:06:26 +02004456 tenants_datacenter_dict={"datacenter_id": datacenter_id }
tierno7edb6752016-03-21 17:37:52 +01004457 if tenant_uuid:
4458 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02004459 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4460 if len(tenant_datacenter_list)==0 and tenant_uuid:
4461 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004462
4463 #delete this association
tiernof97fd272016-07-11 14:32:37 +02004464 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01004465
4466 #get vim_tenant info and deletes
4467 warning=''
4468 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02004469 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
4470 #try to delete vim:tenant
4471 try:
4472 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
4473 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01004474 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01004475 try:
tierno0ea2a7e2017-10-18 00:06:26 +02004476 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02004477 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
4478 except vimconn.vimconnException as e:
4479 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
4480 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02004481 except db_base_Exception as e:
4482 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01004483 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02004484 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tierno42026a02017-02-10 15:13:40 +01004485 thread = vim_threads["running"][thread_id]
tierno868220c2017-09-26 00:11:05 +02004486 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +01004487 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02004488 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01004489
tiernob3d36742017-03-03 23:51:05 +01004490
tierno7edb6752016-03-21 17:37:52 +01004491def datacenter_action(mydb, tenant_id, datacenter, action_dict):
4492 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01004493 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004494 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004495
4496 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02004497 try:
tiernof97fd272016-07-11 14:32:37 +02004498 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02004499 #print content
4500 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004501 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
4502 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01004503 #update nets Change from VIM format to NFVO format
4504 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02004505 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01004506 net_nfvo={'datacenter_id': datacenter_id}
4507 net_nfvo['name'] = net['name']
4508 #net_nfvo['description']= net['name']
4509 net_nfvo['vim_net_id'] = net['id']
4510 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
4511 net_nfvo['shared'] = net['shared']
4512 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
4513 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02004514 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
4515 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
4516 return inserted
tierno7edb6752016-03-21 17:37:52 +01004517 elif 'net-edit' in action_dict:
4518 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02004519 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01004520 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01004521 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02004522 return result
tierno7edb6752016-03-21 17:37:52 +01004523 elif 'net-delete' in action_dict:
4524 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02004525 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01004526 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01004527 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02004528 return result
tierno7edb6752016-03-21 17:37:52 +01004529
4530 else:
tiernof97fd272016-07-11 14:32:37 +02004531 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01004532
tiernob3d36742017-03-03 23:51:05 +01004533
tierno7edb6752016-03-21 17:37:52 +01004534def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
4535 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004536 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004537
tierno42fcc3b2016-07-06 17:20:40 +02004538 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01004539 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01004540 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02004541 return result
tierno7edb6752016-03-21 17:37:52 +01004542
tiernob3d36742017-03-03 23:51:05 +01004543
tierno7edb6752016-03-21 17:37:52 +01004544def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
4545 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004546 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004547 filter_dict={}
4548 if action_dict:
4549 action_dict = action_dict["netmap"]
4550 if 'vim_id' in action_dict:
4551 filter_dict["id"] = action_dict['vim_id']
4552 if 'vim_name' in action_dict:
4553 filter_dict["name"] = action_dict['vim_name']
4554 else:
4555 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01004556
tiernoae4a8d12016-07-08 12:30:39 +02004557 try:
tiernof97fd272016-07-11 14:32:37 +02004558 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02004559 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004560 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
4561 raise NfvoException(str(e), HTTP_Internal_Server_Error)
4562 if len(vim_nets)>1 and action_dict:
4563 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
4564 elif len(vim_nets)==0: # and action_dict:
4565 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004566 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02004567 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01004568 net_nfvo={'datacenter_id': datacenter_id}
4569 if action_dict and "name" in action_dict:
4570 net_nfvo['name'] = action_dict['name']
4571 else:
4572 net_nfvo['name'] = net['name']
4573 #net_nfvo['description']= net['name']
4574 net_nfvo['vim_net_id'] = net['id']
4575 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
4576 net_nfvo['shared'] = net['shared']
4577 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02004578 try:
4579 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01004580 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02004581 net_nfvo["uuid"] = net_id
4582 except db_base_Exception as e:
4583 if action_dict:
4584 raise
4585 else:
4586 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01004587 net_list.append(net_nfvo)
4588 return net_list
tierno7edb6752016-03-21 17:37:52 +01004589
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004590def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
4591 # obtain all network data
4592 try:
4593 if utils.check_valid_uuid(network_id):
4594 filter_dict = {"id": network_id}
4595 else:
4596 filter_dict = {"name": network_id}
4597
4598 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4599 network = myvim.get_network_list(filter_dict=filter_dict)
4600 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02004601 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 +02004602
4603 # ensure the network is defined
4604 if len(network) == 0:
4605 raise NfvoException("Network {} is not present in the system".format(network_id),
4606 HTTP_Bad_Request)
4607
4608 # ensure there is only one network with the provided name
4609 if len(network) > 1:
4610 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), HTTP_Bad_Request)
4611
4612 # ensure it is a dataplane network
4613 if network[0]['type'] != 'data':
4614 return None
4615
4616 # ensure we use the id
4617 network_id = network[0]['id']
4618
4619 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
4620 # and with instance_scenario_id==NULL
4621 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
4622 search_dict = {'vim_net_id': network_id}
4623
4624 try:
4625 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
4626 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
4627 except db_base_Exception as e:
4628 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01004629 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004630
4631 sdn_net_counter = 0
4632 for net in result:
4633 if net['sdn_net_id'] != None:
4634 sdn_net_counter+=1
4635 sdn_net_id = net['sdn_net_id']
4636
4637 if sdn_net_counter == 0:
4638 return None
4639 elif sdn_net_counter == 1:
4640 return sdn_net_id
4641 else:
4642 raise NfvoException("More than one SDN network is associated to vim network {}".format(
4643 network_id), HTTP_Internal_Server_Error)
4644
4645def get_sdn_controller_id(mydb, datacenter):
4646 # Obtain sdn controller id
4647 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
4648 if not config:
4649 return None
4650
4651 return yaml.load(config).get('sdn-controller')
4652
4653def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
4654 try:
4655 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4656 if not sdn_network_id:
4657 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), HTTP_Internal_Server_Error)
4658
4659 #Obtain sdn controller id
4660 controller_id = get_sdn_controller_id(mydb, datacenter)
4661 if not controller_id:
4662 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), HTTP_Internal_Server_Error)
4663
4664 #Obtain sdn controller info
4665 sdn_controller = ovim.show_of_controller(controller_id)
4666
4667 port_data = {
4668 'name': 'external_port',
4669 'net_id': sdn_network_id,
4670 'ofc_id': controller_id,
4671 'switch_dpid': sdn_controller['dpid'],
4672 'switch_port': descriptor['port']
4673 }
4674
4675 if 'vlan' in descriptor:
4676 port_data['vlan'] = descriptor['vlan']
4677 if 'mac' in descriptor:
4678 port_data['mac'] = descriptor['mac']
4679
4680 result = ovim.new_port(port_data)
4681 except ovimException as e:
4682 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
4683 sdn_network_id, network_id) + str(e), HTTP_Internal_Server_Error)
4684 except db_base_Exception as e:
4685 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
tierno9c5c8322018-03-23 15:44:03 +01004686 network_id) + str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004687
4688 return 'Port uuid: '+ result
4689
4690def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
4691 if port_id:
4692 filter = {'uuid': port_id}
4693 else:
4694 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4695 if not sdn_network_id:
4696 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
4697 HTTP_Internal_Server_Error)
4698 #in case no port_id is specified only ports marked as 'external_port' will be detached
4699 filter = {'name': 'external_port', 'net_id': sdn_network_id}
4700
4701 try:
4702 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
4703 except ovimException as e:
4704 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4705 HTTP_Internal_Server_Error)
4706
4707 if len(port_list) == 0:
4708 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
4709 HTTP_Bad_Request)
4710
4711 port_uuid_list = []
4712 for port in port_list:
4713 try:
4714 port_uuid_list.append(port['uuid'])
4715 ovim.delete_port(port['uuid'])
4716 except ovimException as e:
4717 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), HTTP_Internal_Server_Error)
4718
4719 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01004720
tierno7edb6752016-03-21 17:37:52 +01004721def vim_action_get(mydb, tenant_id, datacenter, item, name):
4722 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004723 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004724 filter_dict={}
4725 if name:
tierno42fcc3b2016-07-06 17:20:40 +02004726 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01004727 filter_dict["id"] = name
4728 else:
4729 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02004730 try:
4731 if item=="networks":
4732 #filter_dict['tenant_id'] = myvim['tenant_id']
4733 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004734
4735 if len(content) == 0:
4736 raise NfvoException("Network {} is not present in the system. ".format(name),
4737 HTTP_Bad_Request)
4738
4739 #Update the networks with the attached ports
4740 for net in content:
4741 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
4742 if sdn_network_id != None:
4743 try:
4744 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
4745 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
4746 except ovimException as e:
4747 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), HTTP_Internal_Server_Error)
4748 #Remove field name and if port name is external_port save it as 'type'
4749 for port in port_list:
4750 if port['name'] == 'external_port':
4751 port['type'] = "External"
4752 del port['name']
4753 net['sdn_network_id'] = sdn_network_id
4754 net['sdn_attached_ports'] = port_list
4755
tiernoae4a8d12016-07-08 12:30:39 +02004756 elif item=="tenants":
4757 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01004758 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004759
tierno4540ea52017-01-18 17:44:32 +01004760 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02004761 else:
tiernof97fd272016-07-11 14:32:37 +02004762 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02004763 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02004764 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02004765 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02004766 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02004767 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 +02004768 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02004769 else:
tiernof97fd272016-07-11 14:32:37 +02004770 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02004771 except vimconn.vimconnException as e:
4772 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02004773 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01004774
tiernob3d36742017-03-03 23:51:05 +01004775
tierno7edb6752016-03-21 17:37:52 +01004776def vim_action_delete(mydb, tenant_id, datacenter, item, name):
4777 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02004778 if tenant_id == "any":
4779 tenant_id=None
4780
tiernoa2793912016-10-04 08:15:08 +00004781 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02004782 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02004783 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
4784 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02004785 items = content.values()[0]
4786 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02004787 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02004788 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02004789 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02004790 else: # it is a dict
4791 item_id = items["id"]
4792 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01004793
tiernoae4a8d12016-07-08 12:30:39 +02004794 try:
4795 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004796 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
4797 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
4798 if sdn_network_id != None:
4799 #Delete any port attachment to this network
4800 try:
4801 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
4802 except ovimException as e:
4803 raise NfvoException(
4804 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4805 HTTP_Internal_Server_Error)
4806
4807 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
4808 for port in port_list:
4809 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
4810
4811 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
4812 try:
4813 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
4814 except db_base_Exception as e:
4815 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
tierno9c5c8322018-03-23 15:44:03 +01004816 str(e), e.http_code)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004817
4818 #Delete the SDN network
4819 try:
4820 ovim.delete_network(sdn_network_id)
4821 except ovimException as e:
4822 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
4823 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
4824 HTTP_Internal_Server_Error)
4825
tiernoae4a8d12016-07-08 12:30:39 +02004826 content = myvim.delete_network(item_id)
4827 elif item=="tenants":
4828 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01004829 elif item == "images":
4830 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02004831 else:
tierno42026a02017-02-10 15:13:40 +01004832 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02004833 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004834 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
4835 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02004836
tiernof97fd272016-07-11 14:32:37 +02004837 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01004838
tiernob3d36742017-03-03 23:51:05 +01004839
tierno7edb6752016-03-21 17:37:52 +01004840def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
4841 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004842 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02004843 if tenant_id == "any":
4844 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00004845 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02004846 try:
4847 if item=="networks":
4848 net = descriptor["network"]
4849 net_name = net.pop("name")
4850 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02004851 net_public = net.pop("shared", False)
4852 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01004853 net_vlan = net.pop("vlan", None)
4854 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 +02004855
4856 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
4857 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
tierno00e3df72017-11-29 17:20:13 +01004858 #obtain datacenter_tenant_id
4859 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
4860 FROM='datacenter_tenants',
4861 WHERE={'datacenter_id': datacenter})[0]['uuid']
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004862 try:
4863 sdn_network = {}
4864 sdn_network['vlan'] = net_vlan
4865 sdn_network['type'] = net_type
4866 sdn_network['name'] = net_name
tierno00e3df72017-11-29 17:20:13 +01004867 sdn_network['region'] = datacenter_tenant_id
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004868 ovim_content = ovim.new_network(sdn_network)
4869 except ovimException as e:
tierno00e3df72017-11-29 17:20:13 +01004870 logger.error("ovimException creating SDN network={} ".format(
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004871 sdn_network) + str(e), exc_info=True)
4872 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
4873 HTTP_Internal_Server_Error)
4874
4875 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
4876 # use instance_scenario_id=None to distinguish from real instaces of nets
tierno00e3df72017-11-29 17:20:13 +01004877 correspondence = {'instance_scenario_id': None,
4878 'sdn_net_id': ovim_content,
4879 'vim_net_id': content,
4880 'datacenter_tenant_id': datacenter_tenant_id
4881 }
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004882 try:
4883 mydb.new_row('instance_nets', correspondence, add_uuid=True)
4884 except db_base_Exception as e:
tierno00e3df72017-11-29 17:20:13 +01004885 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
tierno9c5c8322018-03-23 15:44:03 +01004886 correspondence, e), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02004887 elif item=="tenants":
4888 tenant = descriptor["tenant"]
4889 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
4890 else:
tierno42026a02017-02-10 15:13:40 +01004891 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02004892 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004893 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02004894
tierno7edb6752016-03-21 17:37:52 +01004895 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004896
4897def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004898 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004899 logger.debug('New SDN controller created with uuid {}'.format(data))
4900 return data
4901
4902def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004903 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004904 msg = 'SDN controller {} updated'.format(data)
4905 logger.debug(msg)
4906 return msg
4907
4908def sdn_controller_list(mydb, tenant_id, controller_id=None):
4909 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004910 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004911 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004912 data = ovim.show_of_controller(controller_id)
4913
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004914 msg = 'SDN controller list:\n {}'.format(data)
4915 logger.debug(msg)
4916 return data
4917
4918def sdn_controller_delete(mydb, tenant_id, controller_id):
4919 select_ = ('uuid', 'config')
4920 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
4921 for datacenter in datacenters:
4922 if datacenter['config']:
4923 config = yaml.load(datacenter['config'])
4924 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
4925 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), HTTP_Conflict)
4926
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004927 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004928 msg = 'SDN controller {} deleted'.format(data)
4929 logger.debug(msg)
4930 return msg
4931
4932def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
4933 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
4934 if len(controller) < 1:
4935 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), HTTP_Not_Found)
4936
4937 try:
4938 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
4939 except:
4940 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), HTTP_Bad_Request)
4941
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004942 sdn_controller = ovim.show_of_controller(sdn_controller_id)
4943 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004944
4945 maps = list()
4946 for compute_node in sdn_port_mapping:
4947 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
4948 element = dict()
4949 element["compute_node"] = compute_node["compute_node"]
4950 for port in compute_node["ports"]:
4951 element["pci"] = port.get("pci")
4952 element["switch_port"] = port.get("switch_port")
4953 element["switch_mac"] = port.get("switch_mac")
4954 if not element["pci"] or not (element["switch_port"] or element["switch_mac"]):
4955 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
4956 " or 'switch_mac'", HTTP_Bad_Request)
4957 maps.append(dict(element))
4958
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004959 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 +01004960
4961def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004962 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004963
4964 result = {
4965 "sdn-controller": None,
4966 "datacenter-id": datacenter_id,
4967 "dpid": None,
4968 "ports_mapping": list()
4969 }
4970
4971 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
4972 if datacenter['config']:
4973 config = yaml.load(datacenter['config'])
4974 if 'sdn-controller' in config:
4975 controller_id = config['sdn-controller']
4976 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
4977 result["sdn-controller"] = controller_id
4978 result["dpid"] = sdn_controller["dpid"]
4979
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004980 if result["sdn-controller"] == None:
4981 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), HTTP_Bad_Request)
4982 if result["dpid"] == None:
4983 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
4984 HTTP_Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004985
4986 if len(maps) == 0:
4987 return result
4988
4989 ports_correspondence_dict = dict()
4990 for link in maps:
4991 if result["sdn-controller"] != link["ofc_id"]:
4992 raise NfvoException("The sdn-controller specified for different port mappings differ", HTTP_Internal_Server_Error)
4993 if result["dpid"] != link["switch_dpid"]:
4994 raise NfvoException("The dpid specified for different port mappings differ", HTTP_Internal_Server_Error)
4995 element = dict()
4996 element["pci"] = link["pci"]
4997 if link["switch_port"]:
4998 element["switch_port"] = link["switch_port"]
4999 if link["switch_mac"]:
5000 element["switch_mac"] = link["switch_mac"]
5001
5002 if not link["compute_node"] in ports_correspondence_dict:
5003 content = dict()
5004 content["compute_node"] = link["compute_node"]
5005 content["ports"] = list()
5006 ports_correspondence_dict[link["compute_node"]] = content
5007
5008 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5009
5010 for key in sorted(ports_correspondence_dict):
5011 result["ports_mapping"].append(ports_correspondence_dict[key])
5012
5013 return result
5014
5015def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02005016 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02005017
5018def create_RO_keypair(tenant_id):
5019 """
5020 Creates a public / private keys for a RO tenant and returns their values
5021 Params:
5022 tenant_id: ID of the tenant
5023 Return:
5024 public_key: Public key for the RO tenant
5025 private_key: Encrypted private key for RO tenant
5026 """
5027
5028 bits = 2048
5029 key = RSA.generate(bits)
5030 try:
5031 public_key = key.publickey().exportKey('OpenSSH')
5032 if isinstance(public_key, ValueError):
5033 raise NfvoException("Unable to create public key: {}".format(public_key), HTTP_Internal_Server_Error)
5034 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5035 except (ValueError, NameError) as e:
5036 raise NfvoException("Unable to create private key: {}".format(e), HTTP_Internal_Server_Error)
5037 return public_key, private_key
5038
5039def decrypt_key (key, tenant_id):
5040 """
5041 Decrypts an encrypted RSA key
5042 Params:
5043 key: Private key to be decrypted
5044 tenant_id: ID of the tenant
5045 Return:
5046 unencrypted_key: Unencrypted private key for RO tenant
5047 """
5048 try:
5049 key = RSA.importKey(key,tenant_id)
5050 unencrypted_key = key.exportKey('PEM')
5051 if isinstance(unencrypted_key, ValueError):
5052 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), HTTP_Internal_Server_Error)
5053 except ValueError as e:
5054 raise NfvoException("Unable to decrypt the private key: {}".format(e), HTTP_Internal_Server_Error)
5055 return unencrypted_key