blob: bd9d3689f173df9330822865e4fc88cc6e14bb31 [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"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200395 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_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):
tierno7edb6752016-03-21 17:37:52 +0100624 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
625 '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:
831 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd)
832 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 = []
841 uuid_list = []
842 vnfd_uuid_list = []
tiernoe18ba432017-10-12 10:22:45 +0200843 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
844 if not vnfd_catalog_descriptor:
845 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
846 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
847 if not vnfd_descriptor_list:
848 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
tiernob2880eb2017-10-04 15:04:53 +0200849 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.itervalues():
850 vnfd = vnfd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +0200851
852 # table vnf
853 vnf_uuid = str(uuid4())
854 uuid_list.append(vnf_uuid)
855 vnfd_uuid_list.append(vnf_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100856 vnfd_id = get_str(vnfd, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200857 db_vnf = {
858 "uuid": vnf_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100859 "osm_id": vnfd_id,
tiernof1ba57e2017-09-07 12:23:19 +0200860 "name": get_str(vnfd, "name", 255),
861 "description": get_str(vnfd, "description", 255),
862 "tenant_id": tenant_id,
863 "vendor": get_str(vnfd, "vendor", 255),
864 "short_name": get_str(vnfd, "short-name", 255),
865 "descriptor": str(vnf_descriptor)[:60000]
866 }
867
tiernoe18ba432017-10-12 10:22:45 +0200868 for vnfd_descriptor in vnfd_descriptor_list:
869 if vnfd_descriptor["id"] == str(vnfd["id"]):
870 break
871
tiernof1ba57e2017-09-07 12:23:19 +0200872 # table nets (internal-vld)
873 net_id2uuid = {} # for mapping interface with network
874 for vld in vnfd.get("internal-vld").itervalues():
875 net_uuid = str(uuid4())
876 uuid_list.append(net_uuid)
877 db_net = {
878 "name": get_str(vld, "name", 255),
879 "vnf_id": vnf_uuid,
880 "uuid": net_uuid,
881 "description": get_str(vld, "description", 255),
882 "type": "bridge", # TODO adjust depending on connection point type
883 }
884 net_id2uuid[vld.get("id")] = net_uuid
885 db_nets.append(db_net)
886
887 # table vms (vdus)
888 vdu_id2uuid = {}
889 vdu_id2db_table_index = {}
890 for vdu in vnfd.get("vdu").itervalues():
891 vm_uuid = str(uuid4())
892 uuid_list.append(vm_uuid)
tierno66eba6e2017-11-10 17:09:18 +0100893 vdu_id = get_str(vdu, "id", 255)
tiernof1ba57e2017-09-07 12:23:19 +0200894 db_vm = {
895 "uuid": vm_uuid,
tierno66eba6e2017-11-10 17:09:18 +0100896 "osm_id": vdu_id,
tiernof1ba57e2017-09-07 12:23:19 +0200897 "name": get_str(vdu, "name", 255),
898 "description": get_str(vdu, "description", 255),
899 "vnf_id": vnf_uuid,
900 }
901 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
902 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
903 if vdu.get("count"):
904 db_vm["count"] = int(vdu["count"])
905
906 # table image
907 image_present = False
908 if vdu.get("image"):
909 image_present = True
910 db_image = {}
911 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
912 if not image_uuid:
913 image_uuid = db_image["uuid"]
914 db_images.append(db_image)
915 db_vm["image_id"] = image_uuid
916
917 # volumes
918 devices = []
919 if vdu.get("volumes"):
920 for volume_key in sorted(vdu["volumes"]):
921 volume = vdu["volumes"][volume_key]
922 if not image_present:
923 # Convert the first volume to vnfc.image
924 image_present = True
925 db_image = {}
926 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
927 if not image_uuid:
928 image_uuid = db_image["uuid"]
929 db_images.append(db_image)
930 db_vm["image_id"] = image_uuid
931 else:
932 # Add Openmano devices
933 device = {}
934 device["type"] = str(volume.get("device-type"))
935 if volume.get("size"):
936 device["size"] = int(volume["size"])
937 if volume.get("image"):
938 device["image name"] = str(volume["image"])
939 if volume.get("image-checksum"):
940 device["image checksum"] = str(volume["image-checksum"])
941 devices.append(device)
942
tierno66eba6e2017-11-10 17:09:18 +0100943 # cloud-init
944 boot_data = {}
945 if vdu.get("cloud-init"):
946 boot_data["user-data"] = str(vdu["cloud-init"])
947 elif vdu.get("cloud-init-file"):
948 # TODO Where this file content is present???
949 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
950 boot_data["user-data"] = str(vdu["cloud-init-file"])
951
952 if vdu.get("supplemental-boot-data"):
953 if vdu["supplemental-boot-data"].get('boot-data-drive'):
954 boot_data['boot-data-drive'] = True
955 if vdu["supplemental-boot-data"].get('config-file'):
956 om_cfgfile_list = list()
957 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].itervalues():
958 # TODO Where this file content is present???
959 cfg_source = str(custom_config_file["source"])
960 om_cfgfile_list.append({"dest": custom_config_file["dest"],
961 "content": cfg_source})
962 boot_data['config-files'] = om_cfgfile_list
963 if boot_data:
964 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
965
966 db_vms.append(db_vm)
967 db_vms_index += 1
968
969 # table interfaces (internal/external interfaces)
970 flavor_epa_interfaces = []
971 cp_name2iface_uuid = {}
972 cp_name2vm_uuid = {}
973 cp_name2db_interface = {}
974 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
975 # for iface in chain(vdu.get("internal-interface").itervalues(), vdu.get("external-interface").itervalues()):
976 for iface in vdu.get("interface").itervalues():
977 flavor_epa_interface = {}
978 iface_uuid = str(uuid4())
979 uuid_list.append(iface_uuid)
980 db_interface = {
981 "uuid": iface_uuid,
982 "internal_name": get_str(iface, "name", 255),
983 "vm_id": vm_uuid,
984 }
985 flavor_epa_interface["name"] = db_interface["internal_name"]
986 if iface.get("virtual-interface").get("vpci"):
987 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
988 flavor_epa_interface["vpci"] = db_interface["vpci"]
989
990 if iface.get("virtual-interface").get("bandwidth"):
991 bps = int(iface.get("virtual-interface").get("bandwidth"))
992 db_interface["bw"] = int(math.ceil(bps/1000000.0))
993 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
994
995 if iface.get("virtual-interface").get("type") == "OM-MGMT":
996 db_interface["type"] = "mgmt"
997 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000"):
998 db_interface["type"] = "bridge"
999 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1000 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1001 db_interface["type"] = "data"
1002 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1003 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1004 else "yes"
1005 flavor_epa_interfaces.append(flavor_epa_interface)
1006 else:
1007 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1008 "-interface':'type':'{}'. Interface type is not supported".format(
1009 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
1010 HTTP_Bad_Request)
1011
1012 if iface.get("external-connection-point-ref"):
1013 try:
1014 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1015 db_interface["external_name"] = get_str(cp, "name", 255)
1016 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1017 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1018 cp_name2db_interface[db_interface["external_name"]] = db_interface
1019 for cp_descriptor in vnfd_descriptor["connection-point"]:
1020 if cp_descriptor["name"] == db_interface["external_name"]:
1021 break
1022 else:
1023 raise KeyError()
1024
1025 if vdu_id in vdu_id2cp_name:
1026 vdu_id2cp_name[vdu_id] = None # more than two connecdtion point for this VDU
1027 else:
1028 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1029
1030 # port security
1031 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1032 db_interface["port_security"] = 0
1033 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1034 db_interface["port_security"] = 1
1035 except KeyError:
1036 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1037 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1038 " at connection-point".format(
1039 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1040 cp=iface.get("vnfd-connection-point-ref")),
1041 HTTP_Bad_Request)
1042 elif iface.get("internal-connection-point-ref"):
1043 try:
1044 for vld in vnfd.get("internal-vld").itervalues():
1045 for cp in vld.get("internal-connection-point").itervalues():
1046 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
1047 db_interface["net_id"] = net_id2uuid[vld.get("id")]
1048 for cp_descriptor in vnfd_descriptor["connection-point"]:
1049 if cp_descriptor["name"] == db_interface["external_name"]:
1050 break
1051 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1052 db_interface["port_security"] = 0
1053 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1054 db_interface["port_security"] = 1
1055 break
1056 except KeyError:
1057 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1058 "'interface[{iface}]':'vdu-internal-connection-point-ref':'{cp}' is not"
1059 " referenced by any internal-vld".format(
1060 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1061 cp=iface.get("vdu-internal-connection-point-ref")),
1062 HTTP_Bad_Request)
1063 if iface.get("position") is not None:
1064 db_interface["created_at"] = int(iface.get("position")) - 1000
1065 db_interfaces.append(db_interface)
1066
tiernof1ba57e2017-09-07 12:23:19 +02001067 # table flavors
1068 db_flavor = {
1069 "name": get_str(vdu, "name", 250) + "-flv",
1070 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1071 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
1072 "disk": int(vdu["vm-flavor"].get("storage-gb", 1)),
1073 }
1074 # EPA TODO revise
1075 extended = {}
1076 numa = {}
1077 if devices:
1078 extended["devices"] = devices
tierno66eba6e2017-11-10 17:09:18 +01001079 if flavor_epa_interfaces:
1080 numa["interfaces"] = flavor_epa_interfaces
tiernof1ba57e2017-09-07 12:23:19 +02001081 if vdu.get("guest-epa"): # TODO or dedicated_int:
1082 epa_vcpu_set = False
1083 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1084 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1085 if numa_node_policy.get("node"):
tierno39dddcc2017-10-05 18:48:06 +02001086 numa_node = numa_node_policy["node"]['0']
tiernof1ba57e2017-09-07 12:23:19 +02001087 if numa_node.get("num-cores"):
1088 numa["cores"] = numa_node["num-cores"]
1089 epa_vcpu_set = True
1090 if numa_node.get("paired-threads"):
1091 if numa_node["paired-threads"].get("num-paired-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001092 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001093 epa_vcpu_set = True
tierno39dddcc2017-10-05 18:48:06 +02001094 if len(numa_node["paired-threads"].get("paired-thread-ids")):
tiernof1ba57e2017-09-07 12:23:19 +02001095 numa["paired-threads-id"] = []
tierno39dddcc2017-10-05 18:48:06 +02001096 for pair in numa_node["paired-threads"]["paired-thread-ids"].itervalues():
tiernof1ba57e2017-09-07 12:23:19 +02001097 numa["paired-threads-id"].append(
1098 (str(pair["thread-a"]), str(pair["thread-b"]))
1099 )
1100 if numa_node.get("num-threads"):
tierno39dddcc2017-10-05 18:48:06 +02001101 numa["threads"] = int(numa_node["num-threads"])
tiernof1ba57e2017-09-07 12:23:19 +02001102 epa_vcpu_set = True
1103 if numa_node.get("memory-mb"):
1104 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1105 if vdu["guest-epa"].get("mempage-size"):
1106 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1107 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1108 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1109 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1110 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1111 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1112 numa["cores"] = max(db_flavor["vcpus"], 1)
1113 else:
1114 numa["threads"] = max(db_flavor["vcpus"], 1)
1115 if numa:
1116 extended["numas"] = [numa]
1117 if extended:
1118 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1119 db_flavor["extended"] = extended_text
1120 # look if flavor exist
tiernof1ba57e2017-09-07 12:23:19 +02001121 temp_flavor_dict = {'disk': db_flavor.get('disk', 1),
1122 'ram': db_flavor.get('ram'),
1123 'vcpus': db_flavor.get('vcpus'),
1124 'extended': db_flavor.get('extended')
1125 }
1126 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1127 if existing_flavors:
1128 flavor_uuid = existing_flavors[0]["uuid"]
1129 else:
1130 flavor_uuid = str(uuid4())
1131 uuid_list.append(flavor_uuid)
1132 db_flavor["uuid"] = flavor_uuid
1133 db_flavors.append(db_flavor)
1134 db_vm["flavor_id"] = flavor_uuid
1135
tiernof1ba57e2017-09-07 12:23:19 +02001136 # VNF affinity and antiaffinity
1137 for pg in vnfd.get("placement-groups").itervalues():
1138 pg_name = get_str(pg, "name", 255)
1139 for vdu in pg.get("member-vdus").itervalues():
1140 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1141 if vdu_id not in vdu_id2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02001142 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1143 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001144 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
tiernob2880eb2017-10-04 15:04:53 +02001145 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001146 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
1147 # TODO consider the case of isolation and not colocation
1148 # if pg.get("strategy") == "ISOLATION":
1149
1150 # VNF mgmt configuration
1151 mgmt_access = {}
1152 if vnfd["mgmt-interface"].get("vdu-id"):
tierno66eba6e2017-11-10 17:09:18 +01001153 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1154 if mgmt_vdu_id not in vdu_id2uuid:
tiernob2880eb2017-10-04 15:04:53 +02001155 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1156 "'{vdu}'. Reference to a non-existing vdu".format(
tierno66eba6e2017-11-10 17:09:18 +01001157 vnf=vnfd_id, vdu=mgmt_vdu_id),
tiernob2880eb2017-10-04 15:04:53 +02001158 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001159 mgmt_access["vm_id"] = vdu_id2uuid[vnfd["mgmt-interface"]["vdu-id"]]
tierno66eba6e2017-11-10 17:09:18 +01001160 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1161 if vdu_id2cp_name.get(mgmt_vdu_id):
1162 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
1163
tiernof1ba57e2017-09-07 12:23:19 +02001164 if vnfd["mgmt-interface"].get("ip-address"):
1165 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1166 if vnfd["mgmt-interface"].get("cp"):
1167 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
tiernob2880eb2017-10-04 15:04:53 +02001168 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp':'{cp}'. "
1169 "Reference to a non-existing connection-point".format(
tierno66eba6e2017-11-10 17:09:18 +01001170 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
tiernob2880eb2017-10-04 15:04:53 +02001171 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02001172 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1173 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
tiernoe2ff1ce2017-11-02 17:01:10 +01001174 # mark this interface as of type mgmt
1175 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
1176
tiernoa9550202017-09-22 13:31:35 +02001177 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
tiernof1ba57e2017-09-07 12:23:19 +02001178 "default-user", 64)
gcalvinoe580c7d2017-09-22 14:09:51 +02001179
tiernof1ba57e2017-09-07 12:23:19 +02001180 if default_user:
1181 mgmt_access["default_user"] = default_user
gcalvinoe580c7d2017-09-22 14:09:51 +02001182 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1183 "required", 6)
1184 if required:
1185 mgmt_access["required"] = required
1186
tiernof1ba57e2017-09-07 12:23:19 +02001187 if mgmt_access:
1188 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1189
gcalvinoe580c7d2017-09-22 14:09:51 +02001190
1191
tiernof1ba57e2017-09-07 12:23:19 +02001192 db_vnfs.append(db_vnf)
1193 db_tables=[
1194 {"vnfs": db_vnfs},
1195 {"nets": db_nets},
1196 {"images": db_images},
1197 {"flavors": db_flavors},
1198 {"vms": db_vms},
1199 {"interfaces": db_interfaces},
1200 ]
1201
1202 logger.debug("create_vnf Deployment done vnfDict: %s",
1203 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1204 mydb.new_rows(db_tables, uuid_list)
1205 return vnfd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02001206 except NfvoException:
1207 raise
tiernof1ba57e2017-09-07 12:23:19 +02001208 except Exception as e:
1209 logger.error("Exception {}".format(e))
1210 raise # NfvoException("Exception {}".format(e), HTTP_Bad_Request)
1211
1212
tierno7edb6752016-03-21 17:37:52 +01001213def new_vnf(mydb, tenant_id, vnf_descriptor):
1214 global global_config
tierno42026a02017-02-10 15:13:40 +01001215
tierno7edb6752016-03-21 17:37:52 +01001216 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001217 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +01001218 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001219 vims = {}
tierno7edb6752016-03-21 17:37:52 +01001220 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001221 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001222 if "tenant_id" in vnf_descriptor["vnf"]:
1223 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001224 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1225 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001226 else:
1227 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1228 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001229 if global_config["auto_push_VNF_to_VIMs"]:
1230 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001231
1232 # Step 4. Review the descriptor and add missing fields
1233 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +02001234 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +01001235 vnf_name = vnf_descriptor['vnf']['name']
1236 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1237 if "physical" in vnf_descriptor['vnf']:
1238 del vnf_descriptor['vnf']['physical']
1239 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001240
tierno42026a02017-02-10 15:13:40 +01001241 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001242 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1243 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001244
tierno7edb6752016-03-21 17:37:52 +01001245 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1246 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1247 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +01001248 try:
tiernof97fd272016-07-11 14:32:37 +02001249 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001250 for vnfc in vnf_descriptor['vnf']['VNFC']:
1251 VNFCitem={}
1252 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +02001253 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01001254 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001255
tiernof97fd272016-07-11 14:32:37 +02001256 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001257
tierno7edb6752016-03-21 17:37:52 +01001258 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001259 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 +01001260 myflavorDict["description"] = VNFCitem["description"]
1261 myflavorDict["ram"] = vnfc.get("ram", 0)
1262 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
1263 myflavorDict["disk"] = vnfc.get("disk", 1)
1264 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001265
tierno7edb6752016-03-21 17:37:52 +01001266 devices = vnfc.get("devices")
1267 if devices != None:
1268 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001269
tierno7edb6752016-03-21 17:37:52 +01001270 # TODO:
1271 # 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 +01001272 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1273
tierno7edb6752016-03-21 17:37:52 +01001274 # Previous code has been commented
1275 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1276 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1277 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1278 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1279 #else:
1280 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1281 # if result2:
1282 # print "Error creating flavor: unknown processor model. Rollback successful."
1283 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1284 # else:
1285 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1286 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001287
tierno7edb6752016-03-21 17:37:52 +01001288 if 'numas' in vnfc and len(vnfc['numas'])>0:
1289 myflavorDict['extended']['numas'] = vnfc['numas']
1290
1291 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001292
tierno7edb6752016-03-21 17:37:52 +01001293 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +02001294 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +01001295
tiernof97fd272016-07-11 14:32:37 +02001296 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +01001297 VNFCitem["flavor_id"] = flavor_id
1298 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001299
tiernof97fd272016-07-11 14:32:37 +02001300 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +01001301 # Step 6.3 New images are created in the VIM
1302 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001303 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +01001304 #In case this integration is made, the VNFCDict might become a VNFClist.
1305 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +02001306 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001307 image_dict={}
1308 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1309 image_dict['universal_name']=vnfc.get('image name')
1310 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1311 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001312 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001313 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +01001314 image_metadata_dict = vnfc.get('image metadata', None)
1315 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001316 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +01001317 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1318 image_dict['metadata']=image_metadata_str
1319 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +02001320 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1321 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +01001322 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001323 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001324 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001325 if vnfc.get("boot-data"):
1326 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +01001327
tierno42026a02017-02-10 15:13:40 +01001328
tiernof97fd272016-07-11 14:32:37 +02001329 # Step 7. Storing the VNF descriptor in the repository
1330 if "descriptor" not in vnf_descriptor["vnf"]:
1331 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001332
tiernof97fd272016-07-11 14:32:37 +02001333 # Step 8. Adding the VNF to the NFVO DB
1334 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1335 return vnf_id
1336 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +01001337 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +02001338 if isinstance(e, db_base_Exception):
1339 error_text = "Exception at database"
1340 elif isinstance(e, KeyError):
1341 error_text = "KeyError exception "
1342 e.http_code = HTTP_Internal_Server_Error
1343 else:
1344 error_text = "Exception at VIM"
1345 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1346 #logger.error("start_scenario %s", error_text)
1347 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01001348
tiernob3d36742017-03-03 23:51:05 +01001349
garciadeblas9f8456e2016-09-05 05:02:59 +02001350def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1351 global global_config
tierno42026a02017-02-10 15:13:40 +01001352
garciadeblas9f8456e2016-09-05 05:02:59 +02001353 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +01001354 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +02001355 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +01001356 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +02001357 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001358 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001359 if "tenant_id" in vnf_descriptor["vnf"]:
1360 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1361 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1362 HTTP_Unauthorized)
1363 else:
1364 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1365 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +01001366 if global_config["auto_push_VNF_to_VIMs"]:
1367 vims = get_vim(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +02001368
1369 # Step 4. Review the descriptor and add missing fields
1370 #print vnf_descriptor
1371 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1372 vnf_name = vnf_descriptor['vnf']['name']
1373 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1374 if "physical" in vnf_descriptor['vnf']:
1375 del vnf_descriptor['vnf']['physical']
1376 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +01001377
tierno42026a02017-02-10 15:13:40 +01001378 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +02001379 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1380 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +01001381
garciadeblas9f8456e2016-09-05 05:02:59 +02001382 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1383 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1384 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1385 try:
1386 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1387 for vnfc in vnf_descriptor['vnf']['VNFC']:
1388 VNFCitem={}
1389 VNFCitem["name"] = vnfc['name']
1390 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +01001391
garciadeblas9f8456e2016-09-05 05:02:59 +02001392 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +01001393
garciadeblas9f8456e2016-09-05 05:02:59 +02001394 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +02001395 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 +02001396 myflavorDict["description"] = VNFCitem["description"]
1397 myflavorDict["ram"] = vnfc.get("ram", 0)
1398 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
1399 myflavorDict["disk"] = vnfc.get("disk", 1)
1400 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +01001401
garciadeblas9f8456e2016-09-05 05:02:59 +02001402 devices = vnfc.get("devices")
1403 if devices != None:
1404 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +01001405
garciadeblas9f8456e2016-09-05 05:02:59 +02001406 # TODO:
1407 # 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 +01001408 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1409
garciadeblas9f8456e2016-09-05 05:02:59 +02001410 # Previous code has been commented
1411 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1412 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1413 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1414 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1415 #else:
1416 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1417 # if result2:
1418 # print "Error creating flavor: unknown processor model. Rollback successful."
1419 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1420 # else:
1421 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1422 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +01001423
garciadeblas9f8456e2016-09-05 05:02:59 +02001424 if 'numas' in vnfc and len(vnfc['numas'])>0:
1425 myflavorDict['extended']['numas'] = vnfc['numas']
1426
1427 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +01001428
garciadeblas9f8456e2016-09-05 05:02:59 +02001429 # Step 6.2 New flavors are created in the VIM
1430 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1431
1432 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1433 VNFCitem["flavor_id"] = flavor_id
1434 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +01001435
garciadeblas9f8456e2016-09-05 05:02:59 +02001436 logger.debug("Creating new images in the VIM for each VNFC")
1437 # Step 6.3 New images are created in the VIM
1438 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +01001439 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +02001440 #In case this integration is made, the VNFCDict might become a VNFClist.
1441 for vnfc in vnf_descriptor['vnf']['VNFC']:
1442 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +02001443 image_dict={}
1444 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1445 image_dict['universal_name']=vnfc.get('image name')
1446 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1447 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +01001448 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +02001449 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +02001450 image_metadata_dict = vnfc.get('image metadata', None)
1451 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +01001452 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +02001453 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1454 image_dict['metadata']=image_metadata_str
1455 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1456 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1457 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1458 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +02001459 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +02001460 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +01001461 if vnfc.get("boot-data"):
1462 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02001463
garciadeblas9f8456e2016-09-05 05:02:59 +02001464 # Step 7. Storing the VNF descriptor in the repository
1465 if "descriptor" not in vnf_descriptor["vnf"]:
1466 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001467
garciadeblas9f8456e2016-09-05 05:02:59 +02001468 # Step 8. Adding the VNF to the NFVO DB
1469 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1470 return vnf_id
1471 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1472 _, message = rollback(mydb, vims, rollback_list)
1473 if isinstance(e, db_base_Exception):
1474 error_text = "Exception at database"
1475 elif isinstance(e, KeyError):
1476 error_text = "KeyError exception "
1477 e.http_code = HTTP_Internal_Server_Error
1478 else:
1479 error_text = "Exception at VIM"
1480 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1481 #logger.error("start_scenario %s", error_text)
1482 raise NfvoException(error_text, e.http_code)
1483
tiernob3d36742017-03-03 23:51:05 +01001484
tierno7edb6752016-03-21 17:37:52 +01001485def get_vnf_id(mydb, tenant_id, vnf_id):
1486 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +01001487 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001488 #obtain data
1489 where_or = {}
1490 if tenant_id != "any":
1491 where_or["tenant_id"] = tenant_id
1492 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001493 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1494
tiernof1ba57e2017-09-07 12:23:19 +02001495 vnf_id = vnf["uuid"]
1496 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001497 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001498 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1499 data={'vnf' : filtered_content}
1500 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001501 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tiernof1ba57e2017-09-07 12:23:19 +02001502 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1503 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001504 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001505 if len(content)==0:
1506 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001507 # change boot_data into boot-data
1508 for vm in content:
1509 if vm.get("boot_data"):
1510 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1511 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001512
1513 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001514 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001515
tierno7edb6752016-03-21 17:37:52 +01001516 #GET NET
tierno42026a02017-02-10 15:13:40 +01001517 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001518 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1519 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001520 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001521
1522 #GET ip-profile for each net
1523 for net in data['vnf']['nets']:
1524 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1525 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1526 WHERE={'net_id': net["uuid"]} )
1527 if len(ipprofiles)==1:
1528 net["ip_profile"] = ipprofiles[0]
1529 elif len(ipprofiles)>1:
1530 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 +01001531
1532
garciadeblas9f8456e2016-09-05 05:02:59 +02001533 #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 +01001534
garciadeblas9f8456e2016-09-05 05:02:59 +02001535 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001536 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 +01001537 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1538 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno3fcfdb72017-10-24 07:48:24 +02001539 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001540 #print content
tiernof97fd272016-07-11 14:32:37 +02001541 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001542
tiernof97fd272016-07-11 14:32:37 +02001543 return data
tierno7edb6752016-03-21 17:37:52 +01001544
1545
1546def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1547 # Check tenant exist
1548 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001549 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001550 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +02001551 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001552 else:
1553 vims={}
1554
1555 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1556 where_or = {}
1557 if tenant_id != "any":
1558 where_or["tenant_id"] = tenant_id
1559 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001560 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 +02001561 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001562
tierno7edb6752016-03-21 17:37:52 +01001563 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001564 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001565 if len(flavorList)==0:
1566 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001567
tiernof97fd272016-07-11 14:32:37 +02001568 imageList = get_imagelist(mydb, vnf_id)
1569 if len(imageList)==0:
1570 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001571
tiernof97fd272016-07-11 14:32:37 +02001572 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1573 if deleted == 0:
1574 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno42026a02017-02-10 15:13:40 +01001575
tierno7edb6752016-03-21 17:37:52 +01001576 undeletedItems = []
1577 for flavor in flavorList:
1578 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001579 try:
1580 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1581 if len(c) > 0:
1582 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1583 continue
1584 #flavor not used, must be deleted
1585 #delelte at VIM
1586 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +01001587 for flavor_vim in c:
tierno868220c2017-09-26 00:11:05 +02001588 if flavor_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001589 continue
1590 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
1591 continue
1592 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001593 try:
1594 myvim.delete_flavor(flavor_vim["vim_id"])
1595 except vimconn.vimconnNotFoundException as e:
1596 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
1597 except vimconn.vimconnException as e:
1598 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1599 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
1600 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001601 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1602 mydb.delete_row_by_id('flavors', flavor)
1603 except db_base_Exception as e:
1604 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +01001605 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +02001606
tierno42026a02017-02-10 15:13:40 +01001607
tierno7edb6752016-03-21 17:37:52 +01001608 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001609 try:
1610 #check if image is used by other vnf
1611 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
1612 if len(c) > 0:
1613 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1614 continue
1615 #image not used, must be deleted
1616 #delelte at VIM
1617 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001618 for image_vim in c:
tierno868220c2017-09-26 00:11:05 +02001619 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +01001620 continue
1621 if image_vim['created']=='false': #skip this image because not created by openmano
1622 continue
1623 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001624 try:
1625 myvim.delete_image(image_vim["vim_id"])
1626 except vimconn.vimconnNotFoundException as e:
1627 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1628 except vimconn.vimconnException as e:
1629 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1630 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1631 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001632 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1633 mydb.delete_row_by_id('images', image)
1634 except db_base_Exception as e:
1635 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001636 undeletedItems.append("image %s" % image)
1637
tiernof97fd272016-07-11 14:32:37 +02001638 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001639 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001640 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001641
tiernob3d36742017-03-03 23:51:05 +01001642
tierno7edb6752016-03-21 17:37:52 +01001643def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1644 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1645 if result < 0:
1646 return result, vims
1647 elif result == 0:
1648 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
1649 myvim = vims.values()[0]
1650 result,servers = myvim.get_hosts_info()
1651 if result < 0:
1652 return result, servers
1653 topology = {'name':myvim['name'] , 'servers': servers}
1654 return result, topology
1655
tiernob3d36742017-03-03 23:51:05 +01001656
tierno7edb6752016-03-21 17:37:52 +01001657def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001658 vims = get_vim(mydb, nfvo_tenant_id)
1659 if len(vims) == 0:
1660 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
1661 elif len(vims)>1:
1662 #print "nfvo.datacenter_action() error. Several datacenters found"
1663 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001664 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001665 try:
1666 hosts = myvim.get_hosts()
1667 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001668
tiernof97fd272016-07-11 14:32:37 +02001669 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1670 for host in hosts:
1671 server={'name':host['name'], 'vms':[]}
1672 for vm in host['instances']:
1673 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001674 try:
tiernof97fd272016-07-11 14:32:37 +02001675 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1676 WHERE={'vim_vm_id':vm['id']} )
1677 if len(c) == 0:
1678 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1679 continue
1680 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001681
tiernof97fd272016-07-11 14:32:37 +02001682 except db_base_Exception as e:
1683 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1684 datacenter['Datacenters'][0]['servers'].append(server)
1685 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001686
tiernof97fd272016-07-11 14:32:37 +02001687 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1688 return datacenter
1689 except vimconn.vimconnException as e:
1690 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001691
tiernob3d36742017-03-03 23:51:05 +01001692
tierno7edb6752016-03-21 17:37:52 +01001693def new_scenario(mydb, tenant_id, topo):
1694
1695# result, vims = get_vim(mydb, tenant_id)
1696# if result < 0:
1697# return result, vims
1698#1: parse input
1699 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001700 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001701 if "tenant_id" in topo:
1702 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001703 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
1704 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001705 else:
1706 tenant_id=None
1707
tierno42026a02017-02-10 15:13:40 +01001708#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001709 vnfs={}
1710 other_nets={} #external_networks, bridge_networks and data_networkds
1711 nodes = topo['topology']['nodes']
1712 for k in nodes.keys():
1713 if nodes[k]['type'] == 'VNF':
1714 vnfs[k] = nodes[k]
1715 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001716 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001717 other_nets[k] = nodes[k]
1718 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001719 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001720 other_nets[k] = nodes[k]
1721 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001722
tierno7edb6752016-03-21 17:37:52 +01001723
1724#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1725 for name,vnf in vnfs.items():
tierno3fcfdb72017-10-24 07:48:24 +02001726 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001727 error_text = ""
1728 error_pos = "'topology':'nodes':'" + name + "'"
1729 if 'vnf_id' in vnf:
1730 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001731 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001732 if 'VNF model' in vnf:
1733 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001734 where['name'] = vnf['VNF model']
tierno3fcfdb72017-10-24 07:48:24 +02001735 if len(where) == 1:
tiernof97fd272016-07-11 14:32:37 +02001736 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001737
tiernocea279c2016-07-18 12:36:49 +02001738 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1739 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02001740 WHERE=where)
tiernof97fd272016-07-11 14:32:37 +02001741 if len(vnf_db)==0:
1742 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1743 elif len(vnf_db)>1:
1744 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001745 vnf['uuid']=vnf_db[0]['uuid']
1746 vnf['description']=vnf_db[0]['description']
1747 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001748 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1749 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 +02001750 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01001751 for ext_iface in ext_ifaces:
1752 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1753
1754#1.4 get list of connections
1755 conections = topo['topology']['connections']
1756 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001757 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001758 for k in conections.keys():
1759 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1760 ifaces_list = conections[k]['nodes'].items()
1761 elif type(conections[k]['nodes'])==list: #list with dictionary
1762 ifaces_list=[]
1763 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1764 for k2 in conection_pair_list:
1765 ifaces_list += k2
1766
1767 con_type = conections[k].get("type", "link")
1768 if con_type != "link":
1769 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001770 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001771 other_nets[k] = {'external': False}
1772 if conections[k].get("graph"):
1773 other_nets[k]["graph"] = conections[k]["graph"]
1774 ifaces_list.append( (k, None) )
1775
tierno42026a02017-02-10 15:13:40 +01001776
tierno7edb6752016-03-21 17:37:52 +01001777 if con_type == "external_network":
1778 other_nets[k]['external'] = True
1779 if conections[k].get("model"):
1780 other_nets[k]["model"] = conections[k]["model"]
1781 else:
1782 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001783 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001784 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001785
tiernoefd80c92016-09-16 14:17:46 +02001786 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001787 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)
1788 #print set(ifaces_list)
1789 #check valid VNF and iface names
1790 for iface in ifaces_list:
1791 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001792 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1793 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001794 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001795 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1796 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001797
1798#1.5 unify connections from the pair list to a consolidated list
1799 index=0
1800 while index < len(conections_list):
1801 index2 = index+1
1802 while index2 < len(conections_list):
1803 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1804 conections_list[index] |= conections_list[index2]
1805 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001806 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001807 else:
1808 index2 += 1
1809 conections_list[index] = list(conections_list[index]) # from set to list again
1810 index += 1
1811 #for k in conections_list:
1812 # print k
tierno42026a02017-02-10 15:13:40 +01001813
tierno7edb6752016-03-21 17:37:52 +01001814
1815
1816#1.6 Delete non external nets
1817# for k in other_nets.keys():
1818# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1819# for con in conections_list:
1820# delete_indexes=[]
1821# for index in range(0,len(con)):
1822# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1823# for index in delete_indexes:
1824# del con[index]
1825# del other_nets[k]
1826#1.7: Check external_ports are present at database table datacenter_nets
1827 for k,net in other_nets.items():
1828 error_pos = "'topology':'nodes':'" + k + "'"
1829 if net['external']==False:
1830 if 'name' not in net:
1831 net['name']=k
1832 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001833 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001834 if net['model']=='bridge_net':
1835 net['type']='bridge';
1836 elif net['model']=='dataplane_net':
1837 net['type']='data';
1838 else:
tiernof97fd272016-07-11 14:32:37 +02001839 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001840 else: #external
1841#IF we do not want to check that external network exist at datacenter
1842 pass
tierno42026a02017-02-10 15:13:40 +01001843#ELSE
tierno7edb6752016-03-21 17:37:52 +01001844# error_text = ""
1845# WHERE_={}
1846# if 'net_id' in net:
1847# error_text += " 'net_id' " + net['net_id']
1848# WHERE_['uuid'] = net['net_id']
1849# if 'model' in net:
1850# error_text += " 'model' " + net['model']
1851# WHERE_['name'] = net['model']
1852# if len(WHERE_) == 0:
1853# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1854# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1855# FROM='datacenter_nets', WHERE=WHERE_ )
1856# if r<0:
1857# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1858# elif r==0:
1859# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1860# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1861# elif r>1:
tierno42026a02017-02-10 15:13:40 +01001862# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1863# 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 +01001864# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01001865#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001866 net_list={}
1867 net_nb=0 #Number of nets
1868 for con in conections_list:
1869 #check if this is connected to a external net
1870 other_net_index=-1
1871 #print
1872 #print "con", con
1873 for index in range(0,len(con)):
1874 #check if this is connected to a external net
1875 for net_key in other_nets.keys():
1876 if con[index][0]==net_key:
1877 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01001878 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 +02001879 #print "nfvo.new_scenario " + error_text
1880 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001881 else:
1882 other_net_index = index
1883 net_target = net_key
1884 break
1885 #print "other_net_index", other_net_index
1886 try:
1887 if other_net_index>=0:
1888 del con[other_net_index]
1889#IF we do not want to check that external network exist at datacenter
1890 if other_nets[net_target]['external'] :
1891 if "name" not in other_nets[net_target]:
1892 other_nets[net_target]['name'] = other_nets[net_target]['model']
1893 if other_nets[net_target]["type"] == "external_network":
1894 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1895 other_nets[net_target]["type"] = "data"
1896 else:
1897 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01001898#ELSE
tierno7edb6752016-03-21 17:37:52 +01001899# if other_nets[net_target]['external'] :
1900# 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
1901# if type_=='data' and other_nets[net_target]['type']=="ptp":
1902# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1903# print "nfvo.new_scenario " + error_text
1904# return -HTTP_Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01001905#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001906 for iface in con:
1907 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1908 else:
1909 #create a net
1910 net_type_bridge=False
1911 net_type_data=False
1912 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01001913 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02001914 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01001915 'external':False}
tierno7edb6752016-03-21 17:37:52 +01001916 for iface in con:
1917 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1918 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1919 if iface_type=='mgmt' or iface_type=='bridge':
1920 net_type_bridge = True
1921 else:
1922 net_type_data = True
1923 if net_type_bridge and net_type_data:
1924 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 +02001925 #print "nfvo.new_scenario " + error_text
1926 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001927 elif net_type_bridge:
1928 type_='bridge'
1929 else:
1930 type_='data' if len(con)>2 else 'ptp'
1931 net_list[net_target]['type'] = type_
1932 net_nb+=1
1933 except Exception:
1934 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001935 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01001936 #raise e
tiernof97fd272016-07-11 14:32:37 +02001937 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001938
1939#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01001940 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02001941 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01001942 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01001943 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02001944 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01001945 add_mgmt_net = False
1946 for vnf in vnfs.values():
1947 for iface in vnf['ifaces'].values():
1948 if iface['type']=='mgmt' and 'net_key' not in iface:
1949 #iface not connected
1950 iface['net_key'] = 'mgmt'
1951 add_mgmt_net = True
1952 if add_mgmt_net and 'mgmt' not in net_list:
1953 net_list['mgmt']=mgmt_net[0]
1954 net_list['mgmt']['external']=True
1955 net_list['mgmt']['graph']={'visible':False}
1956
1957 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001958 #print
1959 #print 'net_list', net_list
1960 #print
1961 #print 'vnfs', vnfs
1962 #print
tierno7edb6752016-03-21 17:37:52 +01001963
1964#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001965 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001966 'tenant_id':tenant_id, 'name':topo['name'],
1967 'description':topo.get('description',topo['name']),
1968 'public': topo.get('public', False)
1969 })
tierno42026a02017-02-10 15:13:40 +01001970
tiernof97fd272016-07-11 14:32:37 +02001971 return c
tierno7edb6752016-03-21 17:37:52 +01001972
tiernob3d36742017-03-03 23:51:05 +01001973
tierno5bb59dc2017-02-13 14:53:54 +01001974def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
1975 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02001976 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001977 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001978 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001979 if "tenant_id" in scenario:
1980 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01001981 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001982 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1983 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001984 else:
1985 tenant_id=None
1986
tierno5bb59dc2017-02-13 14:53:54 +01001987 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01001988 for name,vnf in scenario["vnfs"].iteritems():
tierno3fcfdb72017-10-24 07:48:24 +02001989 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
tierno7edb6752016-03-21 17:37:52 +01001990 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001991 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01001992 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001993 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001994 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001995 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001996 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001997 where['name'] = vnf['vnf_name']
tierno3fcfdb72017-10-24 07:48:24 +02001998 if len(where) == 1:
garciadeblas71781ea2016-09-19 14:41:59 +02001999 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01002000 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02002001 FROM='vnfs',
tierno3fcfdb72017-10-24 07:48:24 +02002002 WHERE=where)
tierno5bb59dc2017-02-13 14:53:54 +01002003 if len(vnf_db) == 0:
tiernof97fd272016-07-11 14:32:37 +02002004 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01002005 elif len(vnf_db) > 1:
tiernof97fd272016-07-11 14:32:37 +02002006 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01002007 vnf['uuid'] = vnf_db[0]['uuid']
2008 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01002009 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01002010 # get external interfaces
2011 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2012 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 +02002013 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
tierno7edb6752016-03-21 17:37:52 +01002014 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01002015 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2016 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01002017
tierno5bb59dc2017-02-13 14:53:54 +01002018 # 2: Insert net_key and ip_address at every vnf interface
2019 for net_name, net in scenario["networks"].items():
2020 net_type_bridge = False
2021 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01002022 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01002023 if version == "0.2":
2024 temp_dict = iface_dict
2025 ip_address = None
2026 elif version == "0.3":
2027 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2028 ip_address = iface_dict.get('ip_address', None)
2029 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01002030 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01002031 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2032 net_name, vnf)
2033 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002034 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002035 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01002036 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2037 .format(net_name, iface)
2038 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002039 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002040 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01002041 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2042 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2043 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002044 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002045 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01002046 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01002047 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01002048 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01002049 net_type_bridge = True
2050 else:
2051 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01002052
tierno7edb6752016-03-21 17:37:52 +01002053 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01002054 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2055 .format(net_name)
2056 # logger.debug("nfvo.new_scenario " + error_text)
tiernof97fd272016-07-11 14:32:37 +02002057 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01002058 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01002059 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01002060 else:
tierno5bb59dc2017-02-13 14:53:54 +01002061 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2062
2063 if net.get("implementation"): # for v0.3
2064 if type_ == "bridge" and net["implementation"] == "underlay":
2065 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2066 "'network':'{}'".format(net_name)
2067 # logger.debug(error_text)
2068 raise NfvoException(error_text, HTTP_Bad_Request)
2069 elif type_ != "bridge" and net["implementation"] == "overlay":
2070 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2071 "'network':'{}'".format(net_name)
2072 # logger.debug(error_text)
2073 raise NfvoException(error_text, HTTP_Bad_Request)
2074 net.pop("implementation")
2075 if "type" in net and version == "0.3": # for v0.3
2076 if type_ == "data" and net["type"] == "e-line":
2077 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2078 "'e-line' at 'network':'{}'".format(net_name)
2079 # logger.debug(error_text)
2080 raise NfvoException(error_text, HTTP_Bad_Request)
2081 elif type_ == "ptp" and net["type"] == "e-lan":
2082 type_ = "data"
2083
tierno7edb6752016-03-21 17:37:52 +01002084 net['type'] = type_
2085 net['name'] = net_name
2086 net['external'] = net.get('external', False)
2087
tierno5bb59dc2017-02-13 14:53:54 +01002088 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01002089 scenario["nets"] = scenario["networks"]
2090 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01002091 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02002092 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01002093
tiernob3d36742017-03-03 23:51:05 +01002094
tiernof1ba57e2017-09-07 12:23:19 +02002095def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2096 """
2097 Parses an OSM IM nsd_catalog and insert at DB
2098 :param mydb:
2099 :param tenant_id:
2100 :param nsd_descriptor:
2101 :return: The list of cretated NSD ids
2102 """
2103 try:
2104 mynsd = nsd_catalog.nsd()
tiernoa9550202017-09-22 13:31:35 +02002105 try:
2106 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd)
2107 except Exception as e:
tiernob2880eb2017-10-04 15:04:53 +02002108 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002109 db_scenarios = []
2110 db_sce_nets = []
2111 db_sce_vnfs = []
2112 db_sce_interfaces = []
2113 db_ip_profiles = []
2114 db_ip_profiles_index = 0
2115 uuid_list = []
2116 nsd_uuid_list = []
tiernob2880eb2017-10-04 15:04:53 +02002117 for nsd_yang in mynsd.nsd_catalog.nsd.itervalues():
2118 nsd = nsd_yang.get()
tiernof1ba57e2017-09-07 12:23:19 +02002119
2120 # table sceanrios
2121 scenario_uuid = str(uuid4())
2122 uuid_list.append(scenario_uuid)
2123 nsd_uuid_list.append(scenario_uuid)
2124 db_scenario = {
2125 "uuid": scenario_uuid,
2126 "osm_id": get_str(nsd, "id", 255),
2127 "name": get_str(nsd, "name", 255),
2128 "description": get_str(nsd, "description", 255),
2129 "tenant_id": tenant_id,
2130 "vendor": get_str(nsd, "vendor", 255),
2131 "short_name": get_str(nsd, "short-name", 255),
2132 "descriptor": str(nsd_descriptor)[:60000],
2133 }
2134 db_scenarios.append(db_scenario)
2135
2136 # table sce_vnfs (constituent-vnfd)
2137 vnf_index2scevnf_uuid = {}
2138 vnf_index2vnf_uuid = {}
2139 for vnf in nsd.get("constituent-vnfd").itervalues():
2140 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2141 'tenant_id': tenant_id})
2142 if not existing_vnf:
tiernob2880eb2017-10-04 15:04:53 +02002143 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2144 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2145 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
2146 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002147 sce_vnf_uuid = str(uuid4())
2148 uuid_list.append(sce_vnf_uuid)
2149 db_sce_vnf = {
2150 "uuid": sce_vnf_uuid,
2151 "scenario_id": scenario_uuid,
2152 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 5),
2153 "vnf_id": existing_vnf[0]["uuid"],
2154 "member_vnf_index": int(vnf["member-vnf-index"]),
2155 # TODO 'start-by-default': True
2156 }
2157 vnf_index2scevnf_uuid[int(vnf['member-vnf-index'])] = sce_vnf_uuid
2158 vnf_index2vnf_uuid[int(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
2159 db_sce_vnfs.append(db_sce_vnf)
2160
2161 # table ip_profiles (ip-profiles)
2162 ip_profile_name2db_table_index = {}
2163 for ip_profile in nsd.get("ip-profiles").itervalues():
2164 db_ip_profile = {
2165 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2166 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2167 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2168 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2169 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2170 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2171 }
2172 dns_list = []
2173 for dns in ip_profile["ip-profile-params"]["dns-server"].itervalues():
2174 dns_list.append(str(dns.get("address")))
2175 db_ip_profile["dns_address"] = ";".join(dns_list)
2176 if ip_profile["ip-profile-params"].get('security-group'):
2177 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2178 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2179 db_ip_profiles_index += 1
2180 db_ip_profiles.append(db_ip_profile)
2181
2182 # table sce_nets (internal-vld)
2183 for vld in nsd.get("vld").itervalues():
2184 sce_net_uuid = str(uuid4())
2185 uuid_list.append(sce_net_uuid)
2186 db_sce_net = {
2187 "uuid": sce_net_uuid,
2188 "name": get_str(vld, "name", 255),
2189 "scenario_id": scenario_uuid,
2190 # "type": #TODO
2191 "multipoint": not vld.get("type") == "ELINE",
2192 # "external": #TODO
2193 "description": get_str(vld, "description", 255),
2194 }
2195 # guess type of network
2196 if vld.get("mgmt-network"):
2197 db_sce_net["type"] = "bridge"
2198 db_sce_net["external"] = True
2199 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2200 db_sce_net["type"] = "data"
2201 else:
tierno66eba6e2017-11-10 17:09:18 +01002202 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2203 db_sce_net["type"] = None
tiernof1ba57e2017-09-07 12:23:19 +02002204 db_sce_nets.append(db_sce_net)
2205
2206 # ip-profile, link db_ip_profile with db_sce_net
2207 if vld.get("ip-profile-ref"):
2208 ip_profile_name = vld.get("ip-profile-ref")
2209 if ip_profile_name not in ip_profile_name2db_table_index:
tiernob2880eb2017-10-04 15:04:53 +02002210 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2211 " Reference to a non-existing 'ip_profiles'".format(
2212 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
2213 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002214 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
2215
2216 # table sce_interfaces (vld:vnfd-connection-point-ref)
2217 for iface in vld.get("vnfd-connection-point-ref").itervalues():
2218 vnf_index = int(iface['member-vnf-index-ref'])
2219 # check correct parameters
2220 if vnf_index not in vnf_index2vnf_uuid:
tiernob2880eb2017-10-04 15:04:53 +02002221 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2222 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2223 "'nsd':'constituent-vnfd'".format(
2224 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
2225 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002226
tierno66eba6e2017-11-10 17:09:18 +01002227 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
tiernof1ba57e2017-09-07 12:23:19 +02002228 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2229 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2230 'external_name': get_str(iface, "vnfd-connection-point-ref",
2231 255)})
2232 if not existing_ifaces:
tiernob2880eb2017-10-04 15:04:53 +02002233 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2234 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2235 "connection-point name at VNFD '{}'".format(
2236 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2237 str(iface.get("vnfd-id-ref"))[:255]),
2238 HTTP_Bad_Request)
tiernof1ba57e2017-09-07 12:23:19 +02002239 interface_uuid = existing_ifaces[0]["uuid"]
tierno66eba6e2017-11-10 17:09:18 +01002240 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2241 db_sce_net["type"] = "data"
tiernof1ba57e2017-09-07 12:23:19 +02002242 sce_interface_uuid = str(uuid4())
2243 uuid_list.append(sce_net_uuid)
2244 db_sce_interface = {
2245 "uuid": sce_interface_uuid,
2246 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2247 "sce_net_id": sce_net_uuid,
2248 "interface_id": interface_uuid,
2249 # "ip_address": #TODO
2250 }
2251 db_sce_interfaces.append(db_sce_interface)
tierno66eba6e2017-11-10 17:09:18 +01002252 if not db_sce_net["type"]:
2253 db_sce_net["type"] = "bridge"
tiernof1ba57e2017-09-07 12:23:19 +02002254
2255 db_tables = [
2256 {"scenarios": db_scenarios},
2257 {"sce_nets": db_sce_nets},
2258 {"ip_profiles": db_ip_profiles},
2259 {"sce_vnfs": db_sce_vnfs},
2260 {"sce_interfaces": db_sce_interfaces},
2261 ]
2262
2263 logger.debug("create_vnf Deployment done vnfDict: %s",
2264 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2265 mydb.new_rows(db_tables, uuid_list)
2266 return nsd_uuid_list
tiernob2880eb2017-10-04 15:04:53 +02002267 except NfvoException:
2268 raise
tiernof1ba57e2017-09-07 12:23:19 +02002269 except Exception as e:
2270 logger.error("Exception {}".format(e))
2271 raise # NfvoException("Exception {}".format(e), HTTP_Bad_Request)
2272
2273
tierno7edb6752016-03-21 17:37:52 +01002274def edit_scenario(mydb, tenant_id, scenario_id, data):
2275 data["uuid"] = scenario_id
2276 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02002277 c = mydb.edit_scenario( data )
2278 return c
tierno7edb6752016-03-21 17:37:52 +01002279
tiernob3d36742017-03-03 23:51:05 +01002280
tierno7edb6752016-03-21 17:37:52 +01002281def 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 +02002282 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00002283 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2284 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02002285 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01002286 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00002287
tierno7edb6752016-03-21 17:37:52 +01002288 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02002289 try:
2290 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tierno868220c2017-09-26 00:11:05 +02002291 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00002292 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02002293 scenarioDict['datacenter_id'] = datacenter_id
2294 #print '================scenarioDict======================='
2295 #print json.dumps(scenarioDict, indent=4)
2296 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01002297
tiernoae4a8d12016-07-08 12:30:39 +02002298 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2299 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002300
tiernoae4a8d12016-07-08 12:30:39 +02002301 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2302 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002303
tiernoae4a8d12016-07-08 12:30:39 +02002304 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2305 for sce_net in scenarioDict['nets']:
2306 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01002307
tiernoae4a8d12016-07-08 12:30:39 +02002308 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01002309 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02002310 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01002311 myNetDict = {}
2312 myNetDict["name"] = myNetName
2313 myNetDict["type"] = myNetType
2314 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002315 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01002316 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02002317 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02002318 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02002319 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02002320 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002321 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2322 sce_net['vim_id'] = network_id
2323 auxNetDict['scenario'][sce_net['uuid']] = network_id
2324 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002325 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02002326 else:
2327 if sce_net['vim_id'] == None:
2328 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2329 _, message = rollback(mydb, vims, rollbackList)
2330 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02002331 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02002332 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2333 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01002334
tiernoae4a8d12016-07-08 12:30:39 +02002335 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2336 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02002337
tiernoae4a8d12016-07-08 12:30:39 +02002338 for sce_vnf in scenarioDict['vnfs']:
2339 for net in sce_vnf['nets']:
2340 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01002341
tiernoae4a8d12016-07-08 12:30:39 +02002342 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2343 myNetName = myNetName[0:255] #limit length
2344 myNetType = net['type']
2345 myNetDict = {}
2346 myNetDict["name"] = myNetName
2347 myNetDict["type"] = myNetType
2348 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02002349 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02002350 #print myNetDict
2351 #TODO:
2352 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02002353 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02002354 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2355 net['vim_id'] = network_id
2356 if sce_vnf['uuid'] not in auxNetDict:
2357 auxNetDict[sce_vnf['uuid']] = {}
2358 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2359 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02002360 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002361
tiernoae4a8d12016-07-08 12:30:39 +02002362 #print "auxNetDict:"
2363 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002364
tiernoae4a8d12016-07-08 12:30:39 +02002365 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2366 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2367 i = 0
2368 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02002369 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002370 for vm in sce_vnf['vms']:
2371 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002372 if vm_av and vm_av not in vnf_availability_zones:
2373 vnf_availability_zones.append(vm_av)
2374
2375 # check if there is enough availability zones available at vim level.
2376 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2377 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
2378 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
2379
tiernoae4a8d12016-07-08 12:30:39 +02002380 for vm in sce_vnf['vms']:
2381 i += 1
2382 myVMDict = {}
2383 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01002384 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02002385 #myVMDict['description'] = vm['description']
2386 myVMDict['description'] = myVMDict['name'][0:99]
2387 if not startvms:
2388 myVMDict['start'] = "no"
2389 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2390 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01002391
tiernoae4a8d12016-07-08 12:30:39 +02002392 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002393 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01002394 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002395 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002396
tiernoae4a8d12016-07-08 12:30:39 +02002397 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002398 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02002399 if flavor_dict['extended']!=None:
2400 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01002401 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02002402 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01002403
2404
tiernoae4a8d12016-07-08 12:30:39 +02002405 myVMDict['imageRef'] = vm['vim_image_id']
2406 myVMDict['flavorRef'] = vm['vim_flavor_id']
2407 myVMDict['networks'] = []
2408 for iface in vm['interfaces']:
2409 netDict = {}
2410 if iface['type']=="data":
2411 netDict['type'] = iface['model']
2412 elif "model" in iface and iface["model"]!=None:
2413 netDict['model']=iface['model']
2414 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2415 #discover type of interface looking at flavor
2416 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2417 for flavor_iface in numa.get('interfaces',[]):
2418 if flavor_iface.get('name') == iface['internal_name']:
2419 if flavor_iface['dedicated'] == 'yes':
2420 netDict['type']="PF" #passthrough
2421 elif flavor_iface['dedicated'] == 'no':
2422 netDict['type']="VF" #siov
2423 elif flavor_iface['dedicated'] == 'yes:sriov':
2424 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2425 netDict["mac_address"] = flavor_iface.get("mac_address")
2426 break;
2427 netDict["use"]=iface['type']
2428 if netDict["use"]=="data" and not netDict.get("type"):
2429 #print "netDict", netDict
2430 #print "iface", iface
2431 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'])
2432 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02002433 raise NfvoException(e_text + "After database migration some information is not available. \
2434 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02002435 else:
tiernof97fd272016-07-11 14:32:37 +02002436 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02002437 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2438 netDict["type"]="virtual"
2439 if "vpci" in iface and iface["vpci"] is not None:
2440 netDict['vpci'] = iface['vpci']
2441 if "mac" in iface and iface["mac"] is not None:
2442 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002443 if "port-security" in iface and iface["port-security"] is not None:
2444 netDict['port_security'] = iface['port-security']
2445 if "floating-ip" in iface and iface["floating-ip"] is not None:
2446 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02002447 netDict['name'] = iface['internal_name']
2448 if iface['net_id'] is None:
2449 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002450 #print iface
2451 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02002452 if vnf_iface['interface_id']==iface['uuid']:
2453 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2454 break
2455 else:
2456 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2457 #skip bridge ifaces not connected to any net
2458 #if 'net_id' not in netDict or netDict['net_id']==None:
2459 # continue
2460 myVMDict['networks'].append(netDict)
2461 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2462 #print myVMDict['name']
2463 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2464 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2465 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02002466
2467 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02002468 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002469 else:
tierno5a3273c2017-08-29 11:43:46 +02002470 av_index = None
mirabal29356312017-07-27 12:21:22 +02002471
tierno98e909c2017-10-14 13:27:03 +02002472 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
mirabal29356312017-07-27 12:21:22 +02002473 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02002474 availability_zone_index=av_index,
2475 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02002476 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2477 vm['vim_id'] = vm_id
2478 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2479 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2480 for net in myVMDict['networks']:
2481 if "vim_id" in net:
2482 for iface in vm['interfaces']:
2483 if net["name"]==iface["internal_name"]:
2484 iface["vim_id"]=net["vim_id"]
2485 break
tierno42026a02017-02-10 15:13:40 +01002486
tiernoae4a8d12016-07-08 12:30:39 +02002487 logger.debug("start scenario Deployment done")
2488 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2489 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02002490 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2491 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01002492
tiernof97fd272016-07-11 14:32:37 +02002493 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02002494 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002495 if isinstance(e, db_base_Exception):
2496 error_text = "Exception at database"
2497 else:
2498 error_text = "Exception at VIM"
2499 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2500 #logger.error("start_scenario %s", error_text)
2501 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01002502
tierno36c0b172017-01-12 18:32:28 +01002503def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02002504 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01002505 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02002506 None is allowed
2507 """
tierno36c0b172017-01-12 18:32:28 +01002508 if not cloud_config_preserve and not cloud_config:
2509 return None
2510
2511 new_cloud_config = {"key-pairs":[], "users":[]}
2512 # key-pairs
2513 if cloud_config_preserve:
2514 for key in cloud_config_preserve.get("key-pairs", () ):
2515 if key not in new_cloud_config["key-pairs"]:
2516 new_cloud_config["key-pairs"].append(key)
2517 if cloud_config:
2518 for key in cloud_config.get("key-pairs", () ):
2519 if key not in new_cloud_config["key-pairs"]:
2520 new_cloud_config["key-pairs"].append(key)
2521 if not new_cloud_config["key-pairs"]:
2522 del new_cloud_config["key-pairs"]
2523
2524 # users
2525 if cloud_config:
2526 new_cloud_config["users"] += cloud_config.get("users", () )
2527 if cloud_config_preserve:
2528 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02002529 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01002530 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02002531 for index0 in range(0,len(users)):
2532 if index0 in index_to_delete:
2533 continue
2534 for index1 in range(index0+1,len(users)):
2535 if index1 in index_to_delete:
2536 continue
2537 if users[index0]["name"] == users[index1]["name"]:
2538 index_to_delete.append(index1)
2539 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01002540 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02002541 users[index0]["key-pairs"] = [key]
2542 elif key not in users[index0]["key-pairs"]:
2543 users[index0]["key-pairs"].append(key)
2544 index_to_delete.sort(reverse=True)
2545 for index in index_to_delete:
2546 del users[index]
tierno36c0b172017-01-12 18:32:28 +01002547 if not new_cloud_config["users"]:
2548 del new_cloud_config["users"]
2549
2550 #boot-data-drive
2551 if cloud_config and cloud_config.get("boot-data-drive") != None:
2552 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2553 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2554 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2555
2556 # user-data
tierno40e1bce2017-08-09 09:12:04 +02002557 new_cloud_config["user-data"] = []
2558 if cloud_config and cloud_config.get("user-data"):
2559 if isinstance(cloud_config["user-data"], list):
2560 new_cloud_config["user-data"] += cloud_config["user-data"]
2561 else:
2562 new_cloud_config["user-data"].append(cloud_config["user-data"])
2563 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2564 if isinstance(cloud_config_preserve["user-data"], list):
2565 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2566 else:
2567 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2568 if not new_cloud_config["user-data"]:
2569 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01002570
2571 # config files
2572 new_cloud_config["config-files"] = []
2573 if cloud_config and cloud_config.get("config-files") != None:
2574 new_cloud_config["config-files"] += cloud_config["config-files"]
2575 if cloud_config_preserve:
2576 for file in cloud_config_preserve.get("config-files", ()):
2577 for index in range(0, len(new_cloud_config["config-files"])):
2578 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2579 new_cloud_config["config-files"][index] = file
2580 break
2581 else:
2582 new_cloud_config["config-files"].append(file)
2583 if not new_cloud_config["config-files"]:
2584 del new_cloud_config["config-files"]
2585 return new_cloud_config
2586
2587
tierno867ffe92017-03-27 12:50:34 +02002588def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01002589 datacenter_id = None
2590 datacenter_name = None
2591 thread = None
tierno867ffe92017-03-27 12:50:34 +02002592 try:
2593 if datacenter_tenant_id:
2594 thread_id = datacenter_tenant_id
2595 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01002596 else:
tierno867ffe92017-03-27 12:50:34 +02002597 where_={"td.nfvo_tenant_id": tenant_id}
2598 if datacenter_id_name:
2599 if utils.check_valid_uuid(datacenter_id_name):
2600 datacenter_id = datacenter_id_name
2601 where_["dt.datacenter_id"] = datacenter_id
2602 else:
2603 datacenter_name = datacenter_id_name
2604 where_["d.name"] = datacenter_name
2605 if datacenter_tenant_id:
2606 where_["dt.uuid"] = datacenter_tenant_id
2607 datacenters = mydb.get_rows(
2608 SELECT=("dt.uuid as datacenter_tenant_id",),
2609 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2610 "join datacenters as d on d.uuid=dt.datacenter_id",
2611 WHERE=where_)
2612 if len(datacenters) > 1:
2613 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2614 elif datacenters:
2615 thread_id = datacenters[0]["datacenter_tenant_id"]
2616 thread = vim_threads["running"].get(thread_id)
2617 if not thread:
2618 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2619 return thread_id, thread
2620 except db_base_Exception as e:
2621 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02002622
tiernof5755962017-07-13 15:44:34 +02002623
tiernoa15c4b92017-10-05 12:41:44 +02002624def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2625 WHERE_dict={}
2626 if utils.check_valid_uuid(datacenter_id_name):
2627 WHERE_dict['d.uuid'] = datacenter_id_name
2628 else:
2629 WHERE_dict['d.name'] = datacenter_id_name
2630
2631 if tenant_id:
2632 WHERE_dict['nfvo_tenant_id'] = tenant_id
2633 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2634 " dt on td.datacenter_tenant_id=dt.uuid"
2635 else:
2636 from_ = 'datacenters as d'
2637 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid",), WHERE=WHERE_dict )
2638 if len(vimaccounts) == 0:
2639 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2640 elif len(vimaccounts)>1:
2641 #print "nfvo.datacenter_action() error. Several datacenters found"
2642 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2643 return vimaccounts[0]["uuid"]
2644
2645
tiernoa2793912016-10-04 08:15:08 +00002646def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02002647 datacenter_id = None
2648 datacenter_name = None
2649 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01002650 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02002651 datacenter_id = datacenter_id_name
2652 else:
2653 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00002654 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02002655 if len(vims) == 0:
2656 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2657 elif len(vims)>1:
2658 #print "nfvo.datacenter_action() error. Several datacenters found"
2659 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2660 return vims.keys()[0], vims.values()[0]
2661
tiernob3d36742017-03-03 23:51:05 +01002662
garciadeblas9f8456e2016-09-05 05:02:59 +02002663def update(d, u):
2664 '''Takes dict d and updates it with the values in dict u.'''
2665 '''It merges all depth levels'''
2666 for k, v in u.iteritems():
2667 if isinstance(v, collections.Mapping):
2668 r = update(d.get(k, {}), v)
2669 d[k] = r
2670 else:
2671 d[k] = u[k]
2672 return d
2673
tierno7edb6752016-03-21 17:37:52 +01002674def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01002675 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2676 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01002677 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01002678
tierno868220c2017-09-26 00:11:05 +02002679 # find main datacenter
tiernobe41e222016-09-02 15:16:13 +02002680 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02002681 myvim_threads_id = {}
tierno7edb6752016-03-21 17:37:52 +01002682 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02002683 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
2684 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02002685 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
gcalvinoe580c7d2017-09-22 14:09:51 +02002686 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
tierno868220c2017-09-26 00:11:05 +02002687 # myvim_tenant = myvim['tenant_id']
gcalvinoe580c7d2017-09-22 14:09:51 +02002688
tierno7edb6752016-03-21 17:37:52 +01002689 rollbackList=[]
tierno42026a02017-02-10 15:13:40 +01002690
tierno868220c2017-09-26 00:11:05 +02002691 # print "Checking that the scenario exists and getting the scenario dictionary"
2692 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
2693 datacenter_id=default_datacenter_id)
tierno42026a02017-02-10 15:13:40 +01002694
tierno868220c2017-09-26 00:11:05 +02002695 # logger.debug(">>>>>> Dictionaries before merging")
2696 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
2697 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01002698
tierno868220c2017-09-26 00:11:05 +02002699 db_instance_vnfs = []
2700 db_instance_vms = []
2701 db_instance_interfaces = []
2702 db_ip_profiles = []
2703 db_vim_actions = []
tierno8e690322017-08-10 15:58:50 +02002704 uuid_list = []
tierno868220c2017-09-26 00:11:05 +02002705 task_index = 0
tierno8e690322017-08-10 15:58:50 +02002706 instance_name = instance_dict["name"]
2707 instance_uuid = str(uuid4())
2708 uuid_list.append(instance_uuid)
2709 db_instance_scenario = {
2710 "uuid": instance_uuid,
2711 "name": instance_name,
2712 "tenant_id": tenant_id,
2713 "scenario_id": scenarioDict['uuid'],
2714 "datacenter_id": default_datacenter_id,
2715 # filled bellow 'datacenter_tenant_id'
2716 "description": instance_dict.get("description"),
2717 }
tierno8e690322017-08-10 15:58:50 +02002718 if scenarioDict.get("cloud-config"):
2719 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
2720 default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02002721 instance_action_id = get_task_id()
2722 db_instance_action = {
2723 "uuid": instance_action_id, # same uuid for the instance and the action on create
2724 "tenant_id": tenant_id,
2725 "instance_id": instance_uuid,
2726 "description": "CREATE",
2727 }
garciadeblas9f8456e2016-09-05 05:02:59 +02002728
tierno868220c2017-09-26 00:11:05 +02002729 # Auxiliary dictionaries from x to y
2730 vnf_net2instance = {}
tierno8e690322017-08-10 15:58:50 +02002731 sce_net2instance = {}
tierno868220c2017-09-26 00:11:05 +02002732 net2task_id = {'scenario': {}}
tierno42026a02017-02-10 15:13:40 +01002733
tierno868220c2017-09-26 00:11:05 +02002734 # logger.debug("Creating instance from scenario-dict:\n%s",
2735 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01002736 try:
tiernob3d36742017-03-03 23:51:05 +01002737 # 0 check correct parameters
tierno868220c2017-09-26 00:11:05 +02002738 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
tiernob3d36742017-03-03 23:51:05 +01002739 found = False
tierno7edb6752016-03-21 17:37:52 +01002740 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02002741 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01002742 found = True
2743 break
2744 if not found:
tierno868220c2017-09-26 00:11:05 +02002745 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name),
2746 HTTP_Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02002747 if "sites" not in net_instance_desc:
2748 net_instance_desc["sites"] = [ {} ]
2749 site_without_datacenter_field = False
2750 for site in net_instance_desc["sites"]:
2751 if site.get("datacenter"):
tiernoa15c4b92017-10-05 12:41:44 +02002752 site["datacenter"] = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02002753 if site["datacenter"] not in myvims:
tierno868220c2017-09-26 00:11:05 +02002754 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02002755 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
2756 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02002757 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
2758 site["datacenter"] = d # change name to id
tiernobe41e222016-09-02 15:16:13 +02002759 else:
2760 if site_without_datacenter_field:
tierno868220c2017-09-26 00:11:05 +02002761 raise NfvoException("Found more than one entries without datacenter field at "
2762 "instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
tiernobe41e222016-09-02 15:16:13 +02002763 site_without_datacenter_field = True
tierno868220c2017-09-26 00:11:05 +02002764 site["datacenter"] = default_datacenter_id # change name to id
tierno42026a02017-02-10 15:13:40 +01002765
tiernobe41e222016-09-02 15:16:13 +02002766 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno868220c2017-09-26 00:11:05 +02002767 found = False
tierno7edb6752016-03-21 17:37:52 +01002768 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02002769 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01002770 found = True
2771 break
2772 if not found:
tiernobe41e222016-09-02 15:16:13 +02002773 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
2774 if "datacenter" in vnf_instance_desc:
tierno868220c2017-09-26 00:11:05 +02002775 # Add this datacenter to myvims
tiernoa15c4b92017-10-05 12:41:44 +02002776 vnf_instance_desc["datacenter"] = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernobe41e222016-09-02 15:16:13 +02002777 if vnf_instance_desc["datacenter"] not in myvims:
2778 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
2779 myvims[d] = v
tierno868220c2017-09-26 00:11:05 +02002780 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
tiernoa2793912016-10-04 08:15:08 +00002781 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01002782
tierno868220c2017-09-26 00:11:05 +02002783 # 0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01002784 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
gcalvinoe580c7d2017-09-22 14:09:51 +02002785 # We add the RO key to cloud_config
2786 if tenant[0].get('RO_pub_key'):
2787 RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
2788 cloud_config = unify_cloud_config(cloud_config, RO_key)
garciadeblas9f8456e2016-09-05 05:02:59 +02002789
tierno868220c2017-09-26 00:11:05 +02002790 # 0.2 merge instance information into scenario
2791 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
2792 # However, this is not possible yet.
garciadeblas9f8456e2016-09-05 05:02:59 +02002793 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
2794 for scenario_net in scenarioDict['nets']:
2795 if net_name == scenario_net["name"]:
2796 if 'ip-profile' in net_instance_desc:
tierno455612d2017-05-30 16:40:10 +02002797 # translate from input format to database format
2798 ipprofile_in = net_instance_desc['ip-profile']
2799 ipprofile_db = {}
2800 ipprofile_db['subnet_address'] = ipprofile_in.get('subnet-address')
2801 ipprofile_db['ip_version'] = ipprofile_in.get('ip-version', 'IPv4')
2802 ipprofile_db['gateway_address'] = ipprofile_in.get('gateway-address')
2803 ipprofile_db['dns_address'] = ipprofile_in.get('dns-address')
2804 if isinstance(ipprofile_db['dns_address'], (list, tuple)):
2805 ipprofile_db['dns_address'] = ";".join(ipprofile_db['dns_address'])
2806 if 'dhcp' in ipprofile_in:
2807 ipprofile_db['dhcp_start_address'] = ipprofile_in['dhcp'].get('start-address')
2808 ipprofile_db['dhcp_enabled'] = ipprofile_in['dhcp'].get('enabled', True)
2809 ipprofile_db['dhcp_count'] = ipprofile_in['dhcp'].get('count' )
garciadeblasedca7b32016-09-29 14:01:52 +00002810 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02002811 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00002812 else:
tierno455612d2017-05-30 16:40:10 +02002813 update(scenario_net['ip_profile'], ipprofile_db)
tiernoe6c58ce2016-09-14 16:02:49 +02002814 for interface in net_instance_desc.get('interfaces', () ):
garciadeblas9f8456e2016-09-05 05:02:59 +02002815 if 'ip_address' in interface:
2816 for vnf in scenarioDict['vnfs']:
2817 if interface['vnf'] == vnf['name']:
2818 for vnf_interface in vnf['interfaces']:
2819 if interface['vnf_interface'] == vnf_interface['external_name']:
2820 vnf_interface['ip_address']=interface['ip_address']
2821
tierno868220c2017-09-26 00:11:05 +02002822 # logger.debug(">>>>>>>> Merged dictionary")
2823 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
2824 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02002825
tiernob3d36742017-03-03 23:51:05 +01002826 # 1. Creating new nets (sce_nets) in the VIM"
tierno8e690322017-08-10 15:58:50 +02002827 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01002828 for sce_net in scenarioDict['nets']:
tierno868220c2017-09-26 00:11:05 +02002829 descriptor_net = instance_dict.get("networks", {}).get(sce_net["name"], {})
tiernobe41e222016-09-02 15:16:13 +02002830 net_name = descriptor_net.get("vim-network-name")
tierno8e690322017-08-10 15:58:50 +02002831 sce_net2instance[sce_net['uuid']] = {}
tierno868220c2017-09-26 00:11:05 +02002832 net2task_id['scenario'][sce_net['uuid']] = {}
tiernobe41e222016-09-02 15:16:13 +02002833
2834 sites = descriptor_net.get("sites", [ {} ])
2835 for site in sites:
2836 if site.get("datacenter"):
2837 vim = myvims[ site["datacenter"] ]
2838 datacenter_id = site["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02002839 myvim_thread_id = myvim_threads_id[ site["datacenter"] ]
tierno7edb6752016-03-21 17:37:52 +01002840 else:
tiernobe41e222016-09-02 15:16:13 +02002841 vim = myvims[ default_datacenter_id ]
2842 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002843 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tiernobe41e222016-09-02 15:16:13 +02002844 net_type = sce_net['type']
tierno868220c2017-09-26 00:11:05 +02002845 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
tierno42026a02017-02-10 15:13:40 +01002846
tiernof1ba57e2017-09-07 12:23:19 +02002847 if not net_name:
2848 if sce_net["external"]:
2849 net_name = sce_net["name"]
2850 else:
2851 net_name = "{}.{}".format(instance_name, sce_net["name"])
2852 net_name = net_name[:255] # limit length
2853
2854 if "netmap-use" in site or "netmap-create" in site:
2855 create_network = False
2856 lookfor_network = False
2857 if "netmap-use" in site:
2858 lookfor_network = True
2859 if utils.check_valid_uuid(site["netmap-use"]):
2860 filter_text = "scenario id '%s'" % site["netmap-use"]
2861 lookfor_filter["id"] = site["netmap-use"]
2862 else:
2863 filter_text = "scenario name '%s'" % site["netmap-use"]
2864 lookfor_filter["name"] = site["netmap-use"]
2865 if "netmap-create" in site:
2866 create_network = True
2867 net_vim_name = net_name
2868 if site["netmap-create"]:
2869 net_vim_name = site["netmap-create"]
2870 elif sce_net["external"]:
2871 if sce_net['vim_id'] != None:
tierno868220c2017-09-26 00:11:05 +02002872 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
tiernobe41e222016-09-02 15:16:13 +02002873 create_network = False
2874 lookfor_network = True
2875 lookfor_filter["id"] = sce_net['vim_id']
tierno868220c2017-09-26 00:11:05 +02002876 filter_text = "vim_id '{}' datacenter_netmap name '{}'. Try to reload vims with "\
2877 "datacenter-net-update".format(sce_net['vim_id'], sce_net["name"])
2878 # look for network at datacenter and return error
tiernobe41e222016-09-02 15:16:13 +02002879 else:
tierno868220c2017-09-26 00:11:05 +02002880 # 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 +02002881 create_network = True
2882 lookfor_network = True
2883 lookfor_filter["name"] = sce_net["name"]
2884 net_vim_name = sce_net["name"]
2885 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01002886 else:
tiernobe41e222016-09-02 15:16:13 +02002887 net_vim_name = net_name
2888 create_network = True
2889 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01002890
tiernof1450872017-10-17 23:15:08 +02002891 task_extra = {}
2892 if create_network:
2893 task_action = "CREATE"
2894 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None))
2895 if lookfor_network:
2896 task_extra["find"] = (lookfor_filter,)
tierno868220c2017-09-26 00:11:05 +02002897 elif lookfor_network:
2898 task_action = "FIND"
tiernof1450872017-10-17 23:15:08 +02002899 task_extra["params"] = (lookfor_filter,)
tierno42026a02017-02-10 15:13:40 +01002900
tierno8e690322017-08-10 15:58:50 +02002901 # fill database content
2902 net_uuid = str(uuid4())
2903 uuid_list.append(net_uuid)
2904 sce_net2instance[sce_net['uuid']][datacenter_id] = net_uuid
2905 db_net = {
2906 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02002907 'vim_net_id': None,
tierno8e690322017-08-10 15:58:50 +02002908 "instance_scenario_id": instance_uuid,
2909 "sce_net_id": sce_net["uuid"],
2910 "created": create_network,
2911 'datacenter_id': datacenter_id,
2912 'datacenter_tenant_id': myvim_thread_id,
2913 'status': 'BUILD' if create_network else "ACTIVE"
2914 }
2915 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02002916 db_vim_action = {
2917 "instance_action_id": instance_action_id,
2918 "status": "SCHEDULED",
2919 "task_index": task_index,
2920 "datacenter_vim_id": myvim_thread_id,
2921 "action": task_action,
2922 "item": "instance_nets",
2923 "item_id": net_uuid,
tiernof1450872017-10-17 23:15:08 +02002924 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
tierno868220c2017-09-26 00:11:05 +02002925 }
2926 net2task_id['scenario'][sce_net['uuid']][datacenter_id] = task_index
2927 task_index += 1
2928 db_vim_actions.append(db_vim_action)
2929
tierno8e690322017-08-10 15:58:50 +02002930 if 'ip_profile' in sce_net:
2931 db_ip_profile={
2932 'instance_net_id': net_uuid,
2933 'ip_version': sce_net['ip_profile']['ip_version'],
2934 'subnet_address': sce_net['ip_profile']['subnet_address'],
2935 'gateway_address': sce_net['ip_profile']['gateway_address'],
2936 'dns_address': sce_net['ip_profile']['dns_address'],
2937 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
2938 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
2939 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
2940 }
2941 db_ip_profiles.append(db_ip_profile)
2942
tiernob3d36742017-03-03 23:51:05 +01002943 # 2. Creating new nets (vnf internal nets) in the VIM"
mirabal29356312017-07-27 12:21:22 +02002944 # For each vnf net, we create it and we add it to instanceNetlist.
tierno7edb6752016-03-21 17:37:52 +01002945 for sce_vnf in scenarioDict['vnfs']:
2946 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02002947 if sce_vnf.get("datacenter"):
tiernobe41e222016-09-02 15:16:13 +02002948 datacenter_id = sce_vnf["datacenter"]
tierno868220c2017-09-26 00:11:05 +02002949 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
tiernobe41e222016-09-02 15:16:13 +02002950 else:
tiernobe41e222016-09-02 15:16:13 +02002951 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002952 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tierno868220c2017-09-26 00:11:05 +02002953 descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
tierno7edb6752016-03-21 17:37:52 +01002954 net_name = descriptor_net.get("name")
2955 if not net_name:
tierno868220c2017-09-26 00:11:05 +02002956 net_name = "{}.{}".format(instance_name, net["name"])
2957 net_name = net_name[:255] # limit length
tierno7edb6752016-03-21 17:37:52 +01002958 net_type = net['type']
tierno868220c2017-09-26 00:11:05 +02002959
tierno8e690322017-08-10 15:58:50 +02002960 if sce_vnf['uuid'] not in vnf_net2instance:
2961 vnf_net2instance[sce_vnf['uuid']] = {}
tierno868220c2017-09-26 00:11:05 +02002962 if sce_vnf['uuid'] not in net2task_id:
2963 net2task_id[sce_vnf['uuid']] = {}
2964 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
tierno66345bc2016-09-26 11:37:55 +02002965
tierno8e690322017-08-10 15:58:50 +02002966 # fill database content
2967 net_uuid = str(uuid4())
2968 uuid_list.append(net_uuid)
2969 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
2970 db_net = {
2971 "uuid": net_uuid,
tierno868220c2017-09-26 00:11:05 +02002972 'vim_net_id': None,
tierno8e690322017-08-10 15:58:50 +02002973 "instance_scenario_id": instance_uuid,
2974 "net_id": net["uuid"],
2975 "created": True,
2976 'datacenter_id': datacenter_id,
2977 'datacenter_tenant_id': myvim_thread_id,
2978 }
2979 db_instance_nets.append(db_net)
tierno868220c2017-09-26 00:11:05 +02002980
2981 db_vim_action = {
2982 "instance_action_id": instance_action_id,
2983 "task_index": task_index,
2984 "datacenter_vim_id": myvim_thread_id,
2985 "status": "SCHEDULED",
2986 "action": "CREATE",
2987 "item": "instance_nets",
2988 "item_id": net_uuid,
2989 "extra": yaml.safe_dump({"params": (net_name, net_type, net.get('ip_profile',None))},
2990 default_flow_style=True, width=256)
2991 }
2992 task_index += 1
2993 db_vim_actions.append(db_vim_action)
2994
tierno8e690322017-08-10 15:58:50 +02002995 if 'ip_profile' in net:
2996 db_ip_profile = {
2997 'instance_net_id': net_uuid,
2998 'ip_version': net['ip_profile']['ip_version'],
2999 'subnet_address': net['ip_profile']['subnet_address'],
3000 'gateway_address': net['ip_profile']['gateway_address'],
3001 'dns_address': net['ip_profile']['dns_address'],
3002 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3003 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3004 'dhcp_count': net['ip_profile']['dhcp_count'],
3005 }
3006 db_ip_profiles.append(db_ip_profile)
3007
tierno868220c2017-09-26 00:11:05 +02003008 # print "vnf_net2instance:"
3009 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01003010
tiernob3d36742017-03-03 23:51:05 +01003011 # 3. Creating new vm instances in the VIM
tierno868220c2017-09-26 00:11:05 +02003012 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3013 sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
garciadeblasacd4e782017-07-23 19:44:55 +02003014 for sce_vnf in sce_vnf_list:
tierno5a3273c2017-08-29 11:43:46 +02003015 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02003016 for vm in sce_vnf['vms']:
3017 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02003018 if vm_av and vm_av not in vnf_availability_zones:
3019 vnf_availability_zones.append(vm_av)
mirabal29356312017-07-27 12:21:22 +02003020
3021 # check if there is enough availability zones available at vim level.
tierno5a3273c2017-08-29 11:43:46 +02003022 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3023 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
3024 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
mirabal29356312017-07-27 12:21:22 +02003025
tiernobe41e222016-09-02 15:16:13 +02003026 if sce_vnf.get("datacenter"):
3027 vim = myvims[ sce_vnf["datacenter"] ]
tierno867ffe92017-03-27 12:50:34 +02003028 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"] ]
tiernobe41e222016-09-02 15:16:13 +02003029 datacenter_id = sce_vnf["datacenter"]
3030 else:
3031 vim = myvims[ default_datacenter_id ]
tierno867ffe92017-03-27 12:50:34 +02003032 myvim_thread_id = myvim_threads_id[ default_datacenter_id ]
tiernobe41e222016-09-02 15:16:13 +02003033 datacenter_id = default_datacenter_id
mirabal29356312017-07-27 12:21:22 +02003034 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003035 i = 0
mirabal29356312017-07-27 12:21:22 +02003036
tierno8e690322017-08-10 15:58:50 +02003037 vnf_uuid = str(uuid4())
3038 uuid_list.append(vnf_uuid)
3039 db_instance_vnf = {
3040 'uuid': vnf_uuid,
3041 'instance_scenario_id': instance_uuid,
3042 'vnf_id': sce_vnf['vnf_id'],
3043 'sce_vnf_id': sce_vnf['uuid'],
3044 'datacenter_id': datacenter_id,
3045 'datacenter_tenant_id': myvim_thread_id,
3046 }
3047 db_instance_vnfs.append(db_instance_vnf)
3048
tierno7edb6752016-03-21 17:37:52 +01003049 for vm in sce_vnf['vms']:
tierno7edb6752016-03-21 17:37:52 +01003050 myVMDict = {}
tierno8e690322017-08-10 15:58:50 +02003051 myVMDict['name'] = "{}.{}.{}".format(instance_name[:64], sce_vnf['name'][:64], vm["name"][:64])
tierno7edb6752016-03-21 17:37:52 +01003052 myVMDict['description'] = myVMDict['name'][0:99]
3053# if not startvms:
3054# myVMDict['start'] = "no"
tierno868220c2017-09-26 00:11:05 +02003055 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
tierno7edb6752016-03-21 17:37:52 +01003056 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02003057 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00003058 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01003059 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01003060
tierno868220c2017-09-26 00:11:05 +02003061 # create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02003062 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01003063 if flavor_dict['extended']!=None:
tierno868220c2017-09-26 00:11:05 +02003064 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
montesmoreno0c8def02016-12-22 12:16:23 +00003065 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3066
tierno868220c2017-09-26 00:11:05 +02003067 # Obtain information for additional disks
montesmoreno0c8def02016-12-22 12:16:23 +00003068 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id})
3069 if not extended_flavor_dict:
3070 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
3071 return
3072
tierno868220c2017-09-26 00:11:05 +02003073 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
montesmoreno0c8def02016-12-22 12:16:23 +00003074 myVMDict['disks'] = None
3075 extended_info = extended_flavor_dict[0]['extended']
3076 if extended_info != None:
3077 extended_flavor_dict_yaml = yaml.load(extended_info)
3078 if 'disks' in extended_flavor_dict_yaml:
3079 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
3080
tierno7edb6752016-03-21 17:37:52 +01003081 vm['vim_flavor_id'] = flavor_id
tierno7edb6752016-03-21 17:37:52 +01003082 myVMDict['imageRef'] = vm['vim_image_id']
3083 myVMDict['flavorRef'] = vm['vim_flavor_id']
mirabal29356312017-07-27 12:21:22 +02003084 myVMDict['availability_zone'] = vm.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01003085 myVMDict['networks'] = []
tierno868220c2017-09-26 00:11:05 +02003086 task_depends_on = []
3087 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno8e690322017-08-10 15:58:50 +02003088 db_vm_ifaces = []
tierno7edb6752016-03-21 17:37:52 +01003089 for iface in vm['interfaces']:
3090 netDict = {}
3091 if iface['type']=="data":
3092 netDict['type'] = iface['model']
3093 elif "model" in iface and iface["model"]!=None:
3094 netDict['model']=iface['model']
tierno868220c2017-09-26 00:11:05 +02003095 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3096 # is obtained from iterface table model
3097 # discover type of interface looking at flavor
tierno7edb6752016-03-21 17:37:52 +01003098 for numa in flavor_dict.get('extended',{}).get('numas',[]):
3099 for flavor_iface in numa.get('interfaces',[]):
3100 if flavor_iface.get('name') == iface['internal_name']:
3101 if flavor_iface['dedicated'] == 'yes':
3102 netDict['type']="PF" #passthrough
3103 elif flavor_iface['dedicated'] == 'no':
3104 netDict['type']="VF" #siov
3105 elif flavor_iface['dedicated'] == 'yes:sriov':
3106 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
3107 netDict["mac_address"] = flavor_iface.get("mac_address")
3108 break;
3109 netDict["use"]=iface['type']
3110 if netDict["use"]=="data" and not netDict.get("type"):
3111 #print "netDict", netDict
3112 #print "iface", iface
3113 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'])
3114 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02003115 raise NfvoException(e_text + "After database migration some information is not available. \
3116 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01003117 else:
tiernoae4a8d12016-07-08 12:30:39 +02003118 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01003119 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
3120 netDict["type"]="virtual"
3121 if "vpci" in iface and iface["vpci"] is not None:
3122 netDict['vpci'] = iface['vpci']
3123 if "mac" in iface and iface["mac"] is not None:
3124 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00003125 if "port-security" in iface and iface["port-security"] is not None:
3126 netDict['port_security'] = iface['port-security']
3127 if "floating-ip" in iface and iface["floating-ip"] is not None:
3128 netDict['floating_ip'] = iface['floating-ip']
tierno7edb6752016-03-21 17:37:52 +01003129 netDict['name'] = iface['internal_name']
3130 if iface['net_id'] is None:
3131 for vnf_iface in sce_vnf["interfaces"]:
tierno868220c2017-09-26 00:11:05 +02003132 # print iface
3133 # print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01003134 if vnf_iface['interface_id']==iface['uuid']:
tierno868220c2017-09-26 00:11:05 +02003135 netDict['net_id'] = "TASK-{}".format(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id])
tierno8e690322017-08-10 15:58:50 +02003136 instance_net_id = sce_net2instance[ vnf_iface['sce_net_id'] ][datacenter_id]
tierno868220c2017-09-26 00:11:05 +02003137 task_depends_on.append(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id])
tierno7edb6752016-03-21 17:37:52 +01003138 break
3139 else:
tierno868220c2017-09-26 00:11:05 +02003140 netDict['net_id'] = "TASK-{}".format(net2task_id[ sce_vnf['uuid'] ][ iface['net_id'] ])
tierno8e690322017-08-10 15:58:50 +02003141 instance_net_id = vnf_net2instance[ sce_vnf['uuid'] ][ iface['net_id'] ]
tierno868220c2017-09-26 00:11:05 +02003142 task_depends_on.append(net2task_id[sce_vnf['uuid'] ][ iface['net_id']])
3143 # skip bridge ifaces not connected to any net
3144 if 'net_id' not in netDict or netDict['net_id']==None:
3145 continue
tierno7edb6752016-03-21 17:37:52 +01003146 myVMDict['networks'].append(netDict)
tierno8e690322017-08-10 15:58:50 +02003147 db_vm_iface={
3148 # "uuid"
3149 # 'instance_vm_id': instance_vm_uuid,
3150 "instance_net_id": instance_net_id,
3151 'interface_id': iface['uuid'],
3152 # 'vim_interface_id': ,
3153 'type': 'external' if iface['external_name'] is not None else 'internal',
3154 'ip_address': iface.get('ip_address'),
3155 'floating_ip': int(iface.get('floating-ip', False)),
3156 'port_security': int(iface.get('port-security', True))
3157 }
3158 db_vm_ifaces.append(db_vm_iface)
3159 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3160 # print myVMDict['name']
3161 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3162 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3163 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tierno36c0b172017-01-12 18:32:28 +01003164 if vm.get("boot_data"):
3165 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config)
3166 else:
3167 cloud_config_vm = cloud_config
tierno5a3273c2017-08-29 11:43:46 +02003168 if myVMDict.get('availability_zone'):
3169 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02003170 else:
tierno5a3273c2017-08-29 11:43:46 +02003171 av_index = None
tierno8e690322017-08-10 15:58:50 +02003172 for vm_index in range(0, vm.get('count', 1)):
3173 vm_index_name = ""
3174 if vm.get('count', 1) > 1:
3175 vm_index_name += "." + chr(97 + vm_index)
tierno868220c2017-09-26 00:11:05 +02003176 task_params = (myVMDict['name']+vm_index_name, myVMDict['description'], myVMDict.get('start', None),
3177 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3178 myVMDict['disks'], av_index, vnf_availability_zones)
tierno8e690322017-08-10 15:58:50 +02003179 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3180 for net in myVMDict['networks']:
3181 if "vim_id" in net:
3182 for iface in vm['interfaces']:
3183 if net["name"]==iface["internal_name"]:
3184 iface["vim_id"]=net["vim_id"]
3185 break
3186 vm_uuid = str(uuid4())
3187 uuid_list.append(vm_uuid)
3188 db_vm = {
3189 "uuid": vm_uuid,
3190 'instance_vnf_id': vnf_uuid,
tierno868220c2017-09-26 00:11:05 +02003191 #TODO delete "vim_vm_id": vm_id,
tierno8e690322017-08-10 15:58:50 +02003192 "vm_id": vm["uuid"],
3193 # "status":
3194 }
3195 db_instance_vms.append(db_vm)
tierno868220c2017-09-26 00:11:05 +02003196
3197 iface_index = 0
tierno8e690322017-08-10 15:58:50 +02003198 for db_vm_iface in db_vm_ifaces:
3199 iface_uuid = str(uuid4())
3200 uuid_list.append(iface_uuid)
3201 db_vm_iface_instance = {
3202 "uuid": iface_uuid,
3203 "instance_vm_id": vm_uuid
3204 }
3205 db_vm_iface_instance.update(db_vm_iface)
3206 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3207 ip = db_vm_iface_instance.get("ip_address")
3208 i = ip.rfind(".")
3209 if i > 0:
3210 try:
3211 i += 1
3212 ip = ip[i:] + str(int(ip[:i]) +1)
3213 db_vm_iface_instance["ip_address"] = ip
3214 except:
3215 db_vm_iface_instance["ip_address"] = None
3216 db_instance_interfaces.append(db_vm_iface_instance)
tierno868220c2017-09-26 00:11:05 +02003217 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3218 iface_index += 1
3219
3220 db_vim_action = {
3221 "instance_action_id": instance_action_id,
3222 "task_index": task_index,
3223 "datacenter_vim_id": myvim_thread_id,
3224 "action": "CREATE",
3225 "status": "SCHEDULED",
3226 "item": "instance_vms",
3227 "item_id": vm_uuid,
3228 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3229 default_flow_style=True, width=256)
3230 }
3231 task_index += 1
3232 db_vim_actions.append(db_vim_action)
tierno8e690322017-08-10 15:58:50 +02003233
tierno867ffe92017-03-27 12:50:34 +02003234 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02003235
tierno868220c2017-09-26 00:11:05 +02003236 db_instance_action["number_tasks"] = task_index
tierno8e690322017-08-10 15:58:50 +02003237 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3238 db_instance_scenario['datacenter_id'] = default_datacenter_id
3239 db_tables=[
3240 {"instance_scenarios": db_instance_scenario},
3241 {"instance_vnfs": db_instance_vnfs},
3242 {"instance_nets": db_instance_nets},
3243 {"ip_profiles": db_ip_profiles},
3244 {"instance_vms": db_instance_vms},
3245 {"instance_interfaces": db_instance_interfaces},
tierno868220c2017-09-26 00:11:05 +02003246 {"instance_actions": db_instance_action},
3247 {"vim_actions": db_vim_actions}
tierno8e690322017-08-10 15:58:50 +02003248 ]
3249
tierno868220c2017-09-26 00:11:05 +02003250 logger.debug("create_instance done DB tables: %s",
tierno8e690322017-08-10 15:58:50 +02003251 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3252 mydb.new_rows(db_tables, uuid_list)
tierno868220c2017-09-26 00:11:05 +02003253 for myvim_thread_id in myvim_threads_id.values():
3254 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
tierno867ffe92017-03-27 12:50:34 +02003255
tierno868220c2017-09-26 00:11:05 +02003256 returned_instance = mydb.get_instance_scenario(instance_uuid)
3257 returned_instance["action_id"] = instance_action_id
3258 return returned_instance
3259 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02003260 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02003261 if isinstance(e, db_base_Exception):
3262 error_text = "database Exception"
3263 elif isinstance(e, vimconn.vimconnException):
3264 error_text = "VIM Exception"
3265 else:
3266 error_text = "Exception"
3267 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
tierno868220c2017-09-26 00:11:05 +02003268 # logger.error("create_instance: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02003269 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01003270
tiernob3d36742017-03-03 23:51:05 +01003271
tierno7edb6752016-03-21 17:37:52 +01003272def delete_instance(mydb, tenant_id, instance_id):
tierno868220c2017-09-26 00:11:05 +02003273 # print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003274 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tierno868220c2017-09-26 00:11:05 +02003275 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01003276 tenant_id = instanceDict["tenant_id"]
tierno868220c2017-09-26 00:11:05 +02003277 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01003278
tierno868220c2017-09-26 00:11:05 +02003279 # 1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02003280 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003281
tierno868220c2017-09-26 00:11:05 +02003282 # 2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00003283 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01003284 myvims = {}
3285 myvim_threads = {}
tierno868220c2017-09-26 00:11:05 +02003286 vimthread_affected = {}
tierno3fcfdb72017-10-24 07:48:24 +02003287 net2vm_dependencies = {}
tierno7edb6752016-03-21 17:37:52 +01003288
tierno868220c2017-09-26 00:11:05 +02003289 task_index = 0
3290 instance_action_id = get_task_id()
3291 db_vim_actions = []
3292 db_instance_action = {
3293 "uuid": instance_action_id, # same uuid for the instance and the action on create
3294 "tenant_id": tenant_id,
3295 "instance_id": instance_id,
3296 "description": "DELETE",
3297 # "number_tasks": 0 # filled bellow
3298 }
3299
3300 # 2.1 deleting VMs
3301 # vm_fail_list=[]
tierno7edb6752016-03-21 17:37:52 +01003302 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00003303 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tierno868220c2017-09-26 00:11:05 +02003304 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
tiernoa2793912016-10-04 08:15:08 +00003305 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01003306 try:
tierno867ffe92017-03-27 12:50:34 +02003307 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01003308 except NfvoException as e:
3309 logger.error(str(e))
3310 myvim_thread = None
3311 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00003312 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
3313 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
3314 if len(vims) == 0:
3315 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
3316 sce_vnf["datacenter_tenant_id"]))
3317 myvims[datacenter_key] = None
3318 else:
3319 myvims[datacenter_key] = vims.values()[0]
3320 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01003321 myvim_thread = myvim_threads[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01003322 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00003323 if not myvim:
3324 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
3325 continue
tierno3fcfdb72017-10-24 07:48:24 +02003326 db_vim_action = {
3327 "instance_action_id": instance_action_id,
3328 "task_index": task_index,
3329 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
3330 "action": "DELETE",
3331 "status": "SCHEDULED",
3332 "item": "instance_vms",
3333 "item_id": vm["uuid"],
3334 "extra": yaml.safe_dump({"params": vm["interfaces"]},
3335 default_flow_style=True, width=256)
3336 }
3337 db_vim_actions.append(db_vim_action)
3338 for interface in vm["interfaces"]:
3339 if not interface.get("instance_net_id"):
3340 continue
3341 if interface["instance_net_id"] not in net2vm_dependencies:
3342 net2vm_dependencies[interface["instance_net_id"]] = []
3343 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
3344 task_index += 1
tierno42026a02017-02-10 15:13:40 +01003345
tierno868220c2017-09-26 00:11:05 +02003346 # 2.2 deleting NETS
3347 # net_fail_list=[]
tierno7edb6752016-03-21 17:37:52 +01003348 for net in instanceDict['nets']:
tierno868220c2017-09-26 00:11:05 +02003349 vimthread_affected[net["datacenter_tenant_id"]] = None
tiernoa2793912016-10-04 08:15:08 +00003350 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
3351 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01003352 try:
tierno867ffe92017-03-27 12:50:34 +02003353 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01003354 except NfvoException as e:
3355 logger.error(str(e))
3356 myvim_thread = None
3357 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00003358 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
3359 datacenter_tenant_id=net["datacenter_tenant_id"])
3360 if len(vims) == 0:
3361 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
3362 myvims[datacenter_key] = None
3363 else:
3364 myvims[datacenter_key] = vims.values()[0]
3365 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01003366 myvim_thread = myvim_threads[datacenter_key]
tiernoa2793912016-10-04 08:15:08 +00003367
tierno7edb6752016-03-21 17:37:52 +01003368 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00003369 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 +01003370 continue
tierno3fcfdb72017-10-24 07:48:24 +02003371 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
3372 if net2vm_dependencies.get(net["uuid"]):
3373 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
3374 db_vim_action = {
3375 "instance_action_id": instance_action_id,
3376 "task_index": task_index,
3377 "datacenter_vim_id": net["datacenter_tenant_id"],
3378 "action": "DELETE",
3379 "status": "SCHEDULED",
3380 "item": "instance_nets",
3381 "item_id": net["uuid"],
3382 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3383 }
3384 task_index += 1
3385 db_vim_actions.append(db_vim_action)
tierno868220c2017-09-26 00:11:05 +02003386
3387 db_instance_action["number_tasks"] = task_index
3388 db_tables = [
3389 {"instance_actions": db_instance_action},
3390 {"vim_actions": db_vim_actions}
3391 ]
3392
3393 logger.debug("delete_instance done DB tables: %s",
3394 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
3395 mydb.new_rows(db_tables, ())
3396 for myvim_thread_id in vimthread_affected.keys():
3397 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
3398
tiernob3d36742017-03-03 23:51:05 +01003399 if len(error_msg) > 0:
tierno868220c2017-09-26 00:11:05 +02003400 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
3401 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
tierno7edb6752016-03-21 17:37:52 +01003402 else:
tierno868220c2017-09-26 00:11:05 +02003403 return "action_id={} instance {} deleted".format(instance_action_id, message)
tierno7edb6752016-03-21 17:37:52 +01003404
tiernob3d36742017-03-03 23:51:05 +01003405
tierno7edb6752016-03-21 17:37:52 +01003406def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
3407 '''Refreshes a scenario instance. It modifies instanceDict'''
3408 '''Returns:
3409 - 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
3410 - error_msg
3411 '''
tierno867ffe92017-03-27 12:50:34 +02003412 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
3413 # #print "nfvo.refresh_instance begins"
3414 # #print json.dumps(instanceDict, indent=4)
3415 #
3416 # #print "Getting the VIM URL and the VIM tenant_id"
3417 # myvims={}
3418 #
3419 # # 1. Getting VIM vm and net list
3420 # vms_updated = [] #List of VM instance uuids in openmano that were updated
3421 # vms_notupdated=[]
3422 # vm_list = {}
3423 # for sce_vnf in instanceDict['vnfs']:
3424 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
3425 # if datacenter_key not in vm_list:
3426 # vm_list[datacenter_key] = []
3427 # if datacenter_key not in myvims:
3428 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
3429 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
3430 # if len(vims) == 0:
3431 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
3432 # myvims[datacenter_key] = None
3433 # else:
3434 # myvims[datacenter_key] = vims.values()[0]
3435 # for vm in sce_vnf['vms']:
3436 # vm_list[datacenter_key].append(vm['vim_vm_id'])
3437 # vms_notupdated.append(vm["uuid"])
3438 #
3439 # nets_updated = [] #List of VM instance uuids in openmano that were updated
3440 # nets_notupdated=[]
3441 # net_list = {}
3442 # for net in instanceDict['nets']:
3443 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
3444 # if datacenter_key not in net_list:
3445 # net_list[datacenter_key] = []
3446 # if datacenter_key not in myvims:
3447 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
3448 # datacenter_tenant_id=net["datacenter_tenant_id"])
3449 # if len(vims) == 0:
3450 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
3451 # myvims[datacenter_key] = None
3452 # else:
3453 # myvims[datacenter_key] = vims.values()[0]
3454 #
3455 # net_list[datacenter_key].append(net['vim_net_id'])
3456 # nets_notupdated.append(net["uuid"])
3457 #
3458 # # 1. Getting the status of all VMs
3459 # vm_dict={}
3460 # for datacenter_key in myvims:
3461 # if not vm_list.get(datacenter_key):
3462 # continue
3463 # failed = True
3464 # failed_message=""
3465 # if not myvims[datacenter_key]:
3466 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
3467 # else:
3468 # try:
3469 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
3470 # failed = False
3471 # except vimconn.vimconnException as e:
3472 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
3473 # failed_message = str(e)
3474 # if failed:
3475 # for vm in vm_list[datacenter_key]:
3476 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
3477 #
3478 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
3479 # for sce_vnf in instanceDict['vnfs']:
3480 # for vm in sce_vnf['vms']:
3481 # vm_id = vm['vim_vm_id']
3482 # interfaces = vm_dict[vm_id].pop('interfaces', [])
3483 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
3484 # has_mgmt_iface = False
3485 # for iface in vm["interfaces"]:
3486 # if iface["type"]=="mgmt":
3487 # has_mgmt_iface = True
3488 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
3489 # vm_dict[vm_id]['status'] = "ACTIVE"
3490 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
3491 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
3492 # 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'):
3493 # vm['status'] = vm_dict[vm_id]['status']
3494 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
3495 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
3496 # # 2.1. Update in openmano DB the VMs whose status changed
3497 # try:
3498 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
3499 # vms_notupdated.remove(vm["uuid"])
3500 # if updates>0:
3501 # vms_updated.append(vm["uuid"])
3502 # except db_base_Exception as e:
3503 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
3504 # # 2.2. Update in openmano DB the interface VMs
3505 # for interface in interfaces:
3506 # #translate from vim_net_id to instance_net_id
3507 # network_id_list=[]
3508 # for net in instanceDict['nets']:
3509 # if net["vim_net_id"] == interface["vim_net_id"]:
3510 # network_id_list.append(net["uuid"])
3511 # if not network_id_list:
3512 # continue
3513 # del interface["vim_net_id"]
3514 # try:
3515 # for network_id in network_id_list:
3516 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
3517 # except db_base_Exception as e:
3518 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
3519 #
3520 # # 3. Getting the status of all nets
3521 # net_dict = {}
3522 # for datacenter_key in myvims:
3523 # if not net_list.get(datacenter_key):
3524 # continue
3525 # failed = True
3526 # failed_message = ""
3527 # if not myvims[datacenter_key]:
3528 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
3529 # else:
3530 # try:
3531 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
3532 # failed = False
3533 # except vimconn.vimconnException as e:
3534 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
3535 # failed_message = str(e)
3536 # if failed:
3537 # for net in net_list[datacenter_key]:
3538 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
3539 #
3540 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
3541 # # TODO: update nets inside a vnf
3542 # for net in instanceDict['nets']:
3543 # net_id = net['vim_net_id']
3544 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
3545 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
3546 # 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'):
3547 # net['status'] = net_dict[net_id]['status']
3548 # net['error_msg'] = net_dict[net_id].get('error_msg')
3549 # net['vim_info'] = net_dict[net_id].get('vim_info')
3550 # # 5.1. Update in openmano DB the nets whose status changed
3551 # try:
3552 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
3553 # nets_notupdated.remove(net["uuid"])
3554 # if updated>0:
3555 # nets_updated.append(net["uuid"])
3556 # except db_base_Exception as e:
3557 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
3558 #
3559 # # Returns appropriate output
3560 # #print "nfvo.refresh_instance finishes"
3561 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
3562 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01003563 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02003564 # if len(vms_notupdated)+len(nets_notupdated)>0:
3565 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
3566 # 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 +01003567
tiernoae4a8d12016-07-08 12:30:39 +02003568 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01003569
3570def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02003571 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02003572 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01003573 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
3574
tiernoae4a8d12016-07-08 12:30:39 +02003575 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02003576 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
3577 if len(vims) == 0:
3578 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01003579 myvim = vims.values()[0]
tierno42026a02017-02-10 15:13:40 +01003580
tierno868220c2017-09-26 00:11:05 +02003581 if action_dict.get("create-vdu"):
3582 for vdu in action_dict["create-vdu"]:
3583 vdu_id = vdu.get("vdu-id")
3584 vdu_count = vdu.get("count", 1)
3585 # get from database TODO
3586 # insert tasks TODO
3587 pass
tierno7edb6752016-03-21 17:37:52 +01003588
3589 input_vnfs = action_dict.pop("vnfs", [])
3590 input_vms = action_dict.pop("vms", [])
3591 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
3592 vm_result = {}
3593 vm_error = 0
3594 vm_ok = 0
3595 for sce_vnf in instanceDict['vnfs']:
3596 for vm in sce_vnf['vms']:
3597 if not action_over_all:
3598 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
tierno868220c2017-09-26 00:11:05 +02003599 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
tierno7edb6752016-03-21 17:37:52 +01003600 continue
tiernoae4a8d12016-07-08 12:30:39 +02003601 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02003602 if "add_public_key" in action_dict:
3603 mgmt_access = {}
3604 if sce_vnf.get('mgmt_access'):
3605 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
3606 ssh_access = mgmt_access['config-access']['ssh-access']
3607 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
tierno42026a02017-02-10 15:13:40 +01003608 try:
gcalvinoe580c7d2017-09-22 14:09:51 +02003609 if ssh_access['required'] and ssh_access['default-user']:
3610 if 'ip_address' in vm:
3611 mgmt_ip = vm['ip_address'].split(';')
3612 password = mgmt_access['config-access'].get('password')
3613 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
3614 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
3615 action_dict['add_public_key'],
3616 password=password, ro_key=priv_RO_key)
3617 else:
3618 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
3619 HTTP_Internal_Server_Error)
3620 except KeyError:
3621 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
3622 HTTP_Internal_Server_Error)
3623 else:
3624 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
3625 HTTP_Internal_Server_Error)
3626 else:
3627 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
3628 if "console" in action_dict:
3629 if not global_config["http_console_proxy"]:
tierno20fc2a22016-08-19 17:02:35 +02003630 vm_result[ vm['uuid'] ] = {"vim_result": 200,
3631 "description": "{protocol}//{ip}:{port}/{suffix}".format(
3632 protocol=data["protocol"],
gcalvinoe580c7d2017-09-22 14:09:51 +02003633 ip = data["server"],
3634 port = data["port"],
tierno20fc2a22016-08-19 17:02:35 +02003635 suffix = data["suffix"]),
3636 "name":vm['name']
3637 }
3638 vm_ok +=1
gcalvinoe580c7d2017-09-22 14:09:51 +02003639 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
3640 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
3641 "description": "this console is only reachable by local interface",
3642 "name":vm['name']
3643 }
tierno20fc2a22016-08-19 17:02:35 +02003644 vm_error+=1
gcalvinoe580c7d2017-09-22 14:09:51 +02003645 else:
3646 #print "console data", data
3647 try:
3648 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
3649 vm_result[ vm['uuid'] ] = {"vim_result": 200,
3650 "description": "{protocol}//{ip}:{port}/{suffix}".format(
3651 protocol=data["protocol"],
3652 ip = global_config["http_console_host"],
3653 port = console_thread.port,
3654 suffix = data["suffix"]),
3655 "name":vm['name']
3656 }
3657 vm_ok +=1
3658 except NfvoException as e:
3659 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
3660 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02003661
gcalvinoe580c7d2017-09-22 14:09:51 +02003662 else:
3663 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
3664 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02003665 except vimconn.vimconnException as e:
3666 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
3667 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01003668
3669 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02003670 return vm_result
tierno7edb6752016-03-21 17:37:52 +01003671 else:
tierno351863c2016-07-23 01:46:03 +02003672 return vm_result
tierno42026a02017-02-10 15:13:40 +01003673
tierno868220c2017-09-26 00:11:05 +02003674def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
3675 filter={}
3676 if nfvo_tenant and nfvo_tenant != "any":
3677 filter["tenant_id"] = nfvo_tenant
3678 if instance_id and instance_id != "any":
3679 filter["instance_id"] = instance_id
3680 if action_id:
3681 filter["uuid"] = action_id
3682 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
3683 if not rows and action_id:
3684 raise NfvoException("Not found any action with this criteria", HTTP_Not_Found)
3685 return {"ations": rows}
3686
tiernob3d36742017-03-03 23:51:05 +01003687
tierno7edb6752016-03-21 17:37:52 +01003688def create_or_use_console_proxy_thread(console_server, console_port):
3689 #look for a non-used port
3690 console_thread_key = console_server + ":" + str(console_port)
3691 if console_thread_key in global_config["console_thread"]:
3692 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02003693 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01003694
tierno7edb6752016-03-21 17:37:52 +01003695 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02003696 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01003697 if port in global_config["console_ports"]:
3698 continue
3699 try:
3700 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
3701 clithread.start()
3702 global_config["console_thread"][console_thread_key] = clithread
3703 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02003704 return clithread
tierno7edb6752016-03-21 17:37:52 +01003705 except cli.ConsoleProxyExceptionPortUsed as e:
3706 #port used, try with onoher
3707 continue
3708 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02003709 raise NfvoException(str(e), HTTP_Bad_Request)
3710 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01003711
tiernob3d36742017-03-03 23:51:05 +01003712
tierno7edb6752016-03-21 17:37:52 +01003713def check_tenant(mydb, tenant_id):
3714 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02003715 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
3716 if not tenant:
3717 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
3718 return
tierno7edb6752016-03-21 17:37:52 +01003719
3720def new_tenant(mydb, tenant_dict):
tierno7edb6752016-03-21 17:37:52 +01003721
gcalvinoe580c7d2017-09-22 14:09:51 +02003722 tenant_uuid = str(uuid4())
3723 tenant_dict['uuid'] = tenant_uuid
3724 try:
3725 pub_key, priv_key = create_RO_keypair(tenant_uuid)
3726 tenant_dict['RO_pub_key'] = pub_key
3727 tenant_dict['encrypted_RO_priv_key'] = priv_key
gcalvinoc62cfa52017-10-05 18:21:25 +02003728 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
gcalvinoe580c7d2017-09-22 14:09:51 +02003729 except db_base_Exception as e:
3730 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), HTTP_Internal_Server_Error)
3731 return tenant_uuid
tiernob3d36742017-03-03 23:51:05 +01003732
tierno7edb6752016-03-21 17:37:52 +01003733def delete_tenant(mydb, tenant):
3734 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01003735
tiernof97fd272016-07-11 14:32:37 +02003736 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
3737 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
3738 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01003739
tiernob3d36742017-03-03 23:51:05 +01003740
tierno7edb6752016-03-21 17:37:52 +01003741def new_datacenter(mydb, datacenter_descriptor):
3742 if "config" in datacenter_descriptor:
3743 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02003744 #Check that datacenter-type is correct
3745 datacenter_type = datacenter_descriptor.get("type", "openvim");
3746 module_info = None
3747 try:
3748 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02003749 pkg = __import__("osm_ro." + module)
3750 vim_conn = getattr(pkg, module)
3751 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02003752 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02003753 # if module_info and module_info[0]:
3754 # file.close(module_info[0])
tierno3ae39742016-09-07 12:17:51 +02003755 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01003756
gcalvinoc62cfa52017-10-05 18:21:25 +02003757 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
tiernof97fd272016-07-11 14:32:37 +02003758 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003759
tiernob3d36742017-03-03 23:51:05 +01003760
tierno7edb6752016-03-21 17:37:52 +01003761def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02003762 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02003763 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02003764
3765 # edit data
tiernof97fd272016-07-11 14:32:37 +02003766 datacenter_id = datacenter['uuid']
3767 where={'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02003768 remove_port_mapping = False
tierno7edb6752016-03-21 17:37:52 +01003769 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02003770 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01003771 try:
3772 new_config_dict = datacenter_descriptor["config"]
3773 #delete null fields
3774 to_delete=[]
3775 for k in new_config_dict:
tierno8fe7a492017-07-11 13:50:04 +02003776 if new_config_dict[k] == None:
tierno7edb6752016-03-21 17:37:52 +01003777 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02003778 if k == 'sdn-controller':
3779 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01003780
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003781 config_text = datacenter.get("config")
3782 if not config_text:
3783 config_text = '{}'
3784 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01003785 config_dict.update(new_config_dict)
3786 #delete null fields
3787 for k in to_delete:
3788 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02003789 except Exception as e:
3790 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02003791 if config_dict:
3792 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
3793 else:
3794 datacenter_descriptor["config"] = None
3795 if remove_port_mapping:
3796 try:
3797 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
3798 except ovimException as e:
3799 logger.error("Error deleting datacenter-port-mapping " + str(e))
3800
tiernof97fd272016-07-11 14:32:37 +02003801 mydb.update_rows('datacenters', datacenter_descriptor, where)
3802 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003803
tiernob3d36742017-03-03 23:51:05 +01003804
tierno7edb6752016-03-21 17:37:52 +01003805def delete_datacenter(mydb, datacenter):
3806 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02003807 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
3808 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02003809 try:
3810 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
3811 except ovimException as e:
3812 logger.error("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02003813 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01003814
tiernob3d36742017-03-03 23:51:05 +01003815
tierno8008c3a2016-10-13 15:34:28 +00003816def 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 +02003817 # get datacenter info
tierno0ea2a7e2017-10-18 00:06:26 +02003818 try:
3819 datacenter_id = get_datacenter_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003820
tierno0ea2a7e2017-10-18 00:06:26 +02003821 create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
tierno42026a02017-02-10 15:13:40 +01003822
tierno0ea2a7e2017-10-18 00:06:26 +02003823 # get nfvo_tenant info
3824 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
3825 if vim_tenant_name==None:
3826 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01003827
tierno0ea2a7e2017-10-18 00:06:26 +02003828 #check that this association does not exist before
3829 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
3830 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
3831 if len(tenants_datacenters)>0:
3832 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01003833
tierno0ea2a7e2017-10-18 00:06:26 +02003834 vim_tenant_id_exist_atdb=False
3835 if not create_vim_tenant:
3836 where_={"datacenter_id": datacenter_id}
3837 if vim_tenant_id!=None:
3838 where_["vim_tenant_id"] = vim_tenant_id
3839 if vim_tenant_name!=None:
3840 where_["vim_tenant_name"] = vim_tenant_name
3841 #check if vim_tenant_id is already at database
3842 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
3843 if len(datacenter_tenants_dict)>=1:
3844 datacenter_tenants_dict = datacenter_tenants_dict[0]
3845 vim_tenant_id_exist_atdb=True
3846 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
3847 else: #result=0
3848 datacenter_tenants_dict = {}
3849 #insert at table datacenter_tenants
3850 else: #if vim_tenant_id==None:
3851 #create tenant at VIM if not provided
3852 try:
3853 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
3854 vim_passwd=vim_password)
3855 datacenter_name = myvim["name"]
3856 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
3857 except vimconn.vimconnException as e:
3858 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 +01003859 datacenter_tenants_dict = {}
tierno0ea2a7e2017-10-18 00:06:26 +02003860 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01003861
tierno0ea2a7e2017-10-18 00:06:26 +02003862 #fill datacenter_tenants table
3863 if not vim_tenant_id_exist_atdb:
3864 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
3865 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
3866 datacenter_tenants_dict["user"] = vim_username
3867 datacenter_tenants_dict["passwd"] = vim_password
3868 datacenter_tenants_dict["datacenter_id"] = datacenter_id
3869 if config:
3870 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
3871 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
3872 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01003873
tierno0ea2a7e2017-10-18 00:06:26 +02003874 #fill tenants_datacenters table
3875 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
3876 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
3877 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
3878 # create thread
3879 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id) # reload data
3880 datacenter_name = myvim["name"]
3881 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
3882 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
3883 db=db, db_lock=db_lock, ovim=ovim)
3884 new_thread.start()
3885 thread_id = datacenter_tenants_dict["uuid"]
3886 vim_threads["running"][thread_id] = new_thread
3887 return datacenter_id
3888 except vimconn.vimconnException as e:
3889 raise NfvoException(str(e), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01003890
tierno99314902017-04-26 13:23:09 +02003891
3892def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
3893 vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003894 #Obtain the data of this datacenter_tenant_id
3895 vim_data = mydb.get_rows(
3896 SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",
3897 "datacenter_tenants.passwd", "datacenter_tenants.config"),
3898 FROM="datacenter_tenants JOIN tenants_datacenters ON datacenter_tenants.uuid=tenants_datacenters.datacenter_tenant_id",
3899 WHERE={"tenants_datacenters.nfvo_tenant_id": nfvo_tenant,
3900 "tenants_datacenters.datacenter_id": datacenter_id})
3901
3902 logger.debug(str(vim_data))
3903 if len(vim_data) < 1:
3904 raise NfvoException("Datacenter {} is not attached for tenant {}".format(datacenter_id, nfvo_tenant), HTTP_Conflict)
3905
3906 v = vim_data[0]
3907 if v['config']:
3908 v['config'] = yaml.load(v['config'])
3909
3910 if vim_tenant_id:
3911 v['vim_tenant_id'] = vim_tenant_id
3912 if vim_tenant_name:
3913 v['vim_tenant_name'] = vim_tenant_name
3914 if vim_username:
3915 v['user'] = vim_username
3916 if vim_password:
3917 v['passwd'] = vim_password
3918 if config:
3919 if not v['config']:
3920 v['config'] = {}
3921 v['config'].update(config)
3922
3923 logger.debug(str(v))
3924 deassociate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'])
3925 associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'], vim_tenant_name=v['vim_tenant_name'],
3926 vim_username=v['user'], vim_password=v['passwd'], config=v['config'])
3927
3928 return datacenter_id
tiernob3d36742017-03-03 23:51:05 +01003929
tierno7edb6752016-03-21 17:37:52 +01003930def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
tierno7edb6752016-03-21 17:37:52 +01003931 #get nfvo_tenant info
3932 if not tenant_id or tenant_id=="any":
3933 tenant_uuid = None
3934 else:
tiernof97fd272016-07-11 14:32:37 +02003935 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003936 tenant_uuid = tenant_dict['uuid']
3937
tierno0ea2a7e2017-10-18 00:06:26 +02003938 datacenter_id = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003939 #check that this association exist before
tierno0ea2a7e2017-10-18 00:06:26 +02003940 tenants_datacenter_dict={"datacenter_id": datacenter_id }
tierno7edb6752016-03-21 17:37:52 +01003941 if tenant_uuid:
3942 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02003943 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
3944 if len(tenant_datacenter_list)==0 and tenant_uuid:
3945 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01003946
3947 #delete this association
tiernof97fd272016-07-11 14:32:37 +02003948 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01003949
3950 #get vim_tenant info and deletes
3951 warning=''
3952 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02003953 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
3954 #try to delete vim:tenant
3955 try:
3956 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
3957 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01003958 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01003959 try:
tierno0ea2a7e2017-10-18 00:06:26 +02003960 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02003961 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
3962 except vimconn.vimconnException as e:
3963 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
3964 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02003965 except db_base_Exception as e:
3966 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01003967 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02003968 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tierno42026a02017-02-10 15:13:40 +01003969 thread = vim_threads["running"][thread_id]
tierno868220c2017-09-26 00:11:05 +02003970 thread.insert_task("exit")
tierno42026a02017-02-10 15:13:40 +01003971 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02003972 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01003973
tiernob3d36742017-03-03 23:51:05 +01003974
tierno7edb6752016-03-21 17:37:52 +01003975def datacenter_action(mydb, tenant_id, datacenter, action_dict):
3976 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01003977 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003978 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003979
3980 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02003981 try:
tiernof97fd272016-07-11 14:32:37 +02003982 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02003983 #print content
3984 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003985 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
3986 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01003987 #update nets Change from VIM format to NFVO format
3988 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02003989 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01003990 net_nfvo={'datacenter_id': datacenter_id}
3991 net_nfvo['name'] = net['name']
3992 #net_nfvo['description']= net['name']
3993 net_nfvo['vim_net_id'] = net['id']
3994 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
3995 net_nfvo['shared'] = net['shared']
3996 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
3997 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02003998 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
3999 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
4000 return inserted
tierno7edb6752016-03-21 17:37:52 +01004001 elif 'net-edit' in action_dict:
4002 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02004003 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01004004 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01004005 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02004006 return result
tierno7edb6752016-03-21 17:37:52 +01004007 elif 'net-delete' in action_dict:
4008 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02004009 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01004010 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01004011 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02004012 return result
tierno7edb6752016-03-21 17:37:52 +01004013
4014 else:
tiernof97fd272016-07-11 14:32:37 +02004015 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01004016
tiernob3d36742017-03-03 23:51:05 +01004017
tierno7edb6752016-03-21 17:37:52 +01004018def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
4019 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004020 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004021
tierno42fcc3b2016-07-06 17:20:40 +02004022 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01004023 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01004024 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02004025 return result
tierno7edb6752016-03-21 17:37:52 +01004026
tiernob3d36742017-03-03 23:51:05 +01004027
tierno7edb6752016-03-21 17:37:52 +01004028def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
4029 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004030 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004031 filter_dict={}
4032 if action_dict:
4033 action_dict = action_dict["netmap"]
4034 if 'vim_id' in action_dict:
4035 filter_dict["id"] = action_dict['vim_id']
4036 if 'vim_name' in action_dict:
4037 filter_dict["name"] = action_dict['vim_name']
4038 else:
4039 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01004040
tiernoae4a8d12016-07-08 12:30:39 +02004041 try:
tiernof97fd272016-07-11 14:32:37 +02004042 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02004043 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004044 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
4045 raise NfvoException(str(e), HTTP_Internal_Server_Error)
4046 if len(vim_nets)>1 and action_dict:
4047 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
4048 elif len(vim_nets)==0: # and action_dict:
4049 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01004050 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02004051 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01004052 net_nfvo={'datacenter_id': datacenter_id}
4053 if action_dict and "name" in action_dict:
4054 net_nfvo['name'] = action_dict['name']
4055 else:
4056 net_nfvo['name'] = net['name']
4057 #net_nfvo['description']= net['name']
4058 net_nfvo['vim_net_id'] = net['id']
4059 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
4060 net_nfvo['shared'] = net['shared']
4061 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02004062 try:
4063 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01004064 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02004065 net_nfvo["uuid"] = net_id
4066 except db_base_Exception as e:
4067 if action_dict:
4068 raise
4069 else:
4070 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01004071 net_list.append(net_nfvo)
4072 return net_list
tierno7edb6752016-03-21 17:37:52 +01004073
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004074def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
4075 # obtain all network data
4076 try:
4077 if utils.check_valid_uuid(network_id):
4078 filter_dict = {"id": network_id}
4079 else:
4080 filter_dict = {"name": network_id}
4081
4082 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4083 network = myvim.get_network_list(filter_dict=filter_dict)
4084 except vimconn.vimconnException as e:
tiernof1ba57e2017-09-07 12:23:19 +02004085 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 +02004086
4087 # ensure the network is defined
4088 if len(network) == 0:
4089 raise NfvoException("Network {} is not present in the system".format(network_id),
4090 HTTP_Bad_Request)
4091
4092 # ensure there is only one network with the provided name
4093 if len(network) > 1:
4094 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), HTTP_Bad_Request)
4095
4096 # ensure it is a dataplane network
4097 if network[0]['type'] != 'data':
4098 return None
4099
4100 # ensure we use the id
4101 network_id = network[0]['id']
4102
4103 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
4104 # and with instance_scenario_id==NULL
4105 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
4106 search_dict = {'vim_net_id': network_id}
4107
4108 try:
4109 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
4110 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
4111 except db_base_Exception as e:
4112 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
4113 network_id) + str(e), HTTP_Internal_Server_Error)
4114
4115 sdn_net_counter = 0
4116 for net in result:
4117 if net['sdn_net_id'] != None:
4118 sdn_net_counter+=1
4119 sdn_net_id = net['sdn_net_id']
4120
4121 if sdn_net_counter == 0:
4122 return None
4123 elif sdn_net_counter == 1:
4124 return sdn_net_id
4125 else:
4126 raise NfvoException("More than one SDN network is associated to vim network {}".format(
4127 network_id), HTTP_Internal_Server_Error)
4128
4129def get_sdn_controller_id(mydb, datacenter):
4130 # Obtain sdn controller id
4131 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
4132 if not config:
4133 return None
4134
4135 return yaml.load(config).get('sdn-controller')
4136
4137def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
4138 try:
4139 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4140 if not sdn_network_id:
4141 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), HTTP_Internal_Server_Error)
4142
4143 #Obtain sdn controller id
4144 controller_id = get_sdn_controller_id(mydb, datacenter)
4145 if not controller_id:
4146 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), HTTP_Internal_Server_Error)
4147
4148 #Obtain sdn controller info
4149 sdn_controller = ovim.show_of_controller(controller_id)
4150
4151 port_data = {
4152 'name': 'external_port',
4153 'net_id': sdn_network_id,
4154 'ofc_id': controller_id,
4155 'switch_dpid': sdn_controller['dpid'],
4156 'switch_port': descriptor['port']
4157 }
4158
4159 if 'vlan' in descriptor:
4160 port_data['vlan'] = descriptor['vlan']
4161 if 'mac' in descriptor:
4162 port_data['mac'] = descriptor['mac']
4163
4164 result = ovim.new_port(port_data)
4165 except ovimException as e:
4166 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
4167 sdn_network_id, network_id) + str(e), HTTP_Internal_Server_Error)
4168 except db_base_Exception as e:
4169 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
4170 network_id) + str(e), HTTP_Internal_Server_Error)
4171
4172 return 'Port uuid: '+ result
4173
4174def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
4175 if port_id:
4176 filter = {'uuid': port_id}
4177 else:
4178 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4179 if not sdn_network_id:
4180 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
4181 HTTP_Internal_Server_Error)
4182 #in case no port_id is specified only ports marked as 'external_port' will be detached
4183 filter = {'name': 'external_port', 'net_id': sdn_network_id}
4184
4185 try:
4186 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
4187 except ovimException as e:
4188 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4189 HTTP_Internal_Server_Error)
4190
4191 if len(port_list) == 0:
4192 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
4193 HTTP_Bad_Request)
4194
4195 port_uuid_list = []
4196 for port in port_list:
4197 try:
4198 port_uuid_list.append(port['uuid'])
4199 ovim.delete_port(port['uuid'])
4200 except ovimException as e:
4201 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), HTTP_Internal_Server_Error)
4202
4203 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01004204
tierno7edb6752016-03-21 17:37:52 +01004205def vim_action_get(mydb, tenant_id, datacenter, item, name):
4206 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004207 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01004208 filter_dict={}
4209 if name:
tierno42fcc3b2016-07-06 17:20:40 +02004210 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01004211 filter_dict["id"] = name
4212 else:
4213 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02004214 try:
4215 if item=="networks":
4216 #filter_dict['tenant_id'] = myvim['tenant_id']
4217 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004218
4219 if len(content) == 0:
4220 raise NfvoException("Network {} is not present in the system. ".format(name),
4221 HTTP_Bad_Request)
4222
4223 #Update the networks with the attached ports
4224 for net in content:
4225 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
4226 if sdn_network_id != None:
4227 try:
4228 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
4229 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
4230 except ovimException as e:
4231 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), HTTP_Internal_Server_Error)
4232 #Remove field name and if port name is external_port save it as 'type'
4233 for port in port_list:
4234 if port['name'] == 'external_port':
4235 port['type'] = "External"
4236 del port['name']
4237 net['sdn_network_id'] = sdn_network_id
4238 net['sdn_attached_ports'] = port_list
4239
tiernoae4a8d12016-07-08 12:30:39 +02004240 elif item=="tenants":
4241 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01004242 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004243
tierno4540ea52017-01-18 17:44:32 +01004244 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02004245 else:
tiernof97fd272016-07-11 14:32:37 +02004246 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02004247 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02004248 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02004249 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02004250 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02004251 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 +02004252 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02004253 else:
tiernof97fd272016-07-11 14:32:37 +02004254 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02004255 except vimconn.vimconnException as e:
4256 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02004257 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01004258
tiernob3d36742017-03-03 23:51:05 +01004259
tierno7edb6752016-03-21 17:37:52 +01004260def vim_action_delete(mydb, tenant_id, datacenter, item, name):
4261 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02004262 if tenant_id == "any":
4263 tenant_id=None
4264
tiernoa2793912016-10-04 08:15:08 +00004265 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02004266 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02004267 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
4268 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02004269 items = content.values()[0]
4270 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02004271 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02004272 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02004273 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02004274 else: # it is a dict
4275 item_id = items["id"]
4276 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01004277
tiernoae4a8d12016-07-08 12:30:39 +02004278 try:
4279 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004280 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
4281 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
4282 if sdn_network_id != None:
4283 #Delete any port attachment to this network
4284 try:
4285 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
4286 except ovimException as e:
4287 raise NfvoException(
4288 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4289 HTTP_Internal_Server_Error)
4290
4291 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
4292 for port in port_list:
4293 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
4294
4295 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
4296 try:
4297 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
4298 except db_base_Exception as e:
4299 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
4300 str(e), HTTP_Internal_Server_Error)
4301
4302 #Delete the SDN network
4303 try:
4304 ovim.delete_network(sdn_network_id)
4305 except ovimException as e:
4306 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
4307 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
4308 HTTP_Internal_Server_Error)
4309
tiernoae4a8d12016-07-08 12:30:39 +02004310 content = myvim.delete_network(item_id)
4311 elif item=="tenants":
4312 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01004313 elif item == "images":
4314 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02004315 else:
tierno42026a02017-02-10 15:13:40 +01004316 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02004317 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004318 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
4319 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02004320
tiernof97fd272016-07-11 14:32:37 +02004321 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01004322
tiernob3d36742017-03-03 23:51:05 +01004323
tierno7edb6752016-03-21 17:37:52 +01004324def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
4325 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00004326 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02004327 if tenant_id == "any":
4328 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00004329 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02004330 try:
4331 if item=="networks":
4332 net = descriptor["network"]
4333 net_name = net.pop("name")
4334 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02004335 net_public = net.pop("shared", False)
4336 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01004337 net_vlan = net.pop("vlan", None)
4338 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 +02004339
4340 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
4341 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
4342 try:
4343 sdn_network = {}
4344 sdn_network['vlan'] = net_vlan
4345 sdn_network['type'] = net_type
4346 sdn_network['name'] = net_name
4347 ovim_content = ovim.new_network(sdn_network)
4348 except ovimException as e:
4349 self.logger.error("ovimException creating SDN network={} ".format(
4350 sdn_network) + str(e), exc_info=True)
4351 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
4352 HTTP_Internal_Server_Error)
4353
4354 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
4355 # use instance_scenario_id=None to distinguish from real instaces of nets
4356 correspondence = {'instance_scenario_id': None, 'sdn_net_id': ovim_content, 'vim_net_id': content}
4357 #obtain datacenter_tenant_id
4358 correspondence['datacenter_tenant_id'] = mydb.get_rows(SELECT=('uuid',), FROM='datacenter_tenants', WHERE={'datacenter_id': datacenter})[0]['uuid']
4359
4360 try:
4361 mydb.new_row('instance_nets', correspondence, add_uuid=True)
4362 except db_base_Exception as e:
4363 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
4364 str(e), HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02004365 elif item=="tenants":
4366 tenant = descriptor["tenant"]
4367 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
4368 else:
tierno42026a02017-02-10 15:13:40 +01004369 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02004370 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02004371 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02004372
tierno7edb6752016-03-21 17:37:52 +01004373 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004374
4375def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004376 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004377 logger.debug('New SDN controller created with uuid {}'.format(data))
4378 return data
4379
4380def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004381 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004382 msg = 'SDN controller {} updated'.format(data)
4383 logger.debug(msg)
4384 return msg
4385
4386def sdn_controller_list(mydb, tenant_id, controller_id=None):
4387 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004388 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004389 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004390 data = ovim.show_of_controller(controller_id)
4391
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004392 msg = 'SDN controller list:\n {}'.format(data)
4393 logger.debug(msg)
4394 return data
4395
4396def sdn_controller_delete(mydb, tenant_id, controller_id):
4397 select_ = ('uuid', 'config')
4398 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
4399 for datacenter in datacenters:
4400 if datacenter['config']:
4401 config = yaml.load(datacenter['config'])
4402 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
4403 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), HTTP_Conflict)
4404
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004405 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004406 msg = 'SDN controller {} deleted'.format(data)
4407 logger.debug(msg)
4408 return msg
4409
4410def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
4411 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
4412 if len(controller) < 1:
4413 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), HTTP_Not_Found)
4414
4415 try:
4416 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
4417 except:
4418 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), HTTP_Bad_Request)
4419
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004420 sdn_controller = ovim.show_of_controller(sdn_controller_id)
4421 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004422
4423 maps = list()
4424 for compute_node in sdn_port_mapping:
4425 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
4426 element = dict()
4427 element["compute_node"] = compute_node["compute_node"]
4428 for port in compute_node["ports"]:
4429 element["pci"] = port.get("pci")
4430 element["switch_port"] = port.get("switch_port")
4431 element["switch_mac"] = port.get("switch_mac")
4432 if not element["pci"] or not (element["switch_port"] or element["switch_mac"]):
4433 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
4434 " or 'switch_mac'", HTTP_Bad_Request)
4435 maps.append(dict(element))
4436
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004437 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 +01004438
4439def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02004440 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004441
4442 result = {
4443 "sdn-controller": None,
4444 "datacenter-id": datacenter_id,
4445 "dpid": None,
4446 "ports_mapping": list()
4447 }
4448
4449 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
4450 if datacenter['config']:
4451 config = yaml.load(datacenter['config'])
4452 if 'sdn-controller' in config:
4453 controller_id = config['sdn-controller']
4454 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
4455 result["sdn-controller"] = controller_id
4456 result["dpid"] = sdn_controller["dpid"]
4457
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02004458 if result["sdn-controller"] == None:
4459 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), HTTP_Bad_Request)
4460 if result["dpid"] == None:
4461 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
4462 HTTP_Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01004463
4464 if len(maps) == 0:
4465 return result
4466
4467 ports_correspondence_dict = dict()
4468 for link in maps:
4469 if result["sdn-controller"] != link["ofc_id"]:
4470 raise NfvoException("The sdn-controller specified for different port mappings differ", HTTP_Internal_Server_Error)
4471 if result["dpid"] != link["switch_dpid"]:
4472 raise NfvoException("The dpid specified for different port mappings differ", HTTP_Internal_Server_Error)
4473 element = dict()
4474 element["pci"] = link["pci"]
4475 if link["switch_port"]:
4476 element["switch_port"] = link["switch_port"]
4477 if link["switch_mac"]:
4478 element["switch_mac"] = link["switch_mac"]
4479
4480 if not link["compute_node"] in ports_correspondence_dict:
4481 content = dict()
4482 content["compute_node"] = link["compute_node"]
4483 content["ports"] = list()
4484 ports_correspondence_dict[link["compute_node"]] = content
4485
4486 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
4487
4488 for key in sorted(ports_correspondence_dict):
4489 result["ports_mapping"].append(ports_correspondence_dict[key])
4490
4491 return result
4492
4493def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02004494 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
gcalvinoe580c7d2017-09-22 14:09:51 +02004495
4496def create_RO_keypair(tenant_id):
4497 """
4498 Creates a public / private keys for a RO tenant and returns their values
4499 Params:
4500 tenant_id: ID of the tenant
4501 Return:
4502 public_key: Public key for the RO tenant
4503 private_key: Encrypted private key for RO tenant
4504 """
4505
4506 bits = 2048
4507 key = RSA.generate(bits)
4508 try:
4509 public_key = key.publickey().exportKey('OpenSSH')
4510 if isinstance(public_key, ValueError):
4511 raise NfvoException("Unable to create public key: {}".format(public_key), HTTP_Internal_Server_Error)
4512 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
4513 except (ValueError, NameError) as e:
4514 raise NfvoException("Unable to create private key: {}".format(e), HTTP_Internal_Server_Error)
4515 return public_key, private_key
4516
4517def decrypt_key (key, tenant_id):
4518 """
4519 Decrypts an encrypted RSA key
4520 Params:
4521 key: Private key to be decrypted
4522 tenant_id: ID of the tenant
4523 Return:
4524 unencrypted_key: Unencrypted private key for RO tenant
4525 """
4526 try:
4527 key = RSA.importKey(key,tenant_id)
4528 unencrypted_key = key.exportKey('PEM')
4529 if isinstance(unencrypted_key, ValueError):
4530 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), HTTP_Internal_Server_Error)
4531 except ValueError as e:
4532 raise NfvoException("Unable to decrypt the private key: {}".format(e), HTTP_Internal_Server_Error)
4533 return unencrypted_key