blob: 8f105c32e97e83029253e192fac07a1fd8cc6553 [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
tiernof97fd272016-07-11 14:32:37 +020041from db_base import db_base_Exception
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010042
tiernob3d36742017-03-03 23:51:05 +010043import nfvo_db
44from threading import Lock
45from time import time
tierno01b3e172017-04-21 10:52:34 +020046from lib_osm_openvim import ovim as ovim_module
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +020047from lib_osm_openvim.ovim import ovimException
tierno7edb6752016-03-21 17:37:52 +010048
49global global_config
50global vimconn_imported
tierno73ad9e42016-09-12 18:11:11 +020051global logger
montesmoreno0c8def02016-12-22 12:16:23 +000052global default_volume_size
53default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010054global ovim
55ovim = None
tiernoc5651792017-03-27 10:50:43 +020056global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020057
tierno42026a02017-02-10 15:13:40 +010058vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
59vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010060vim_persistent_info = {}
tierno73ad9e42016-09-12 18:11:11 +020061logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010062task_lock = Lock()
tierno867ffe92017-03-27 12:50:34 +020063global_instance_tasks = {}
tiernob3d36742017-03-03 23:51:05 +010064last_task_id = 0.0
65db=None
66db_lock=Lock()
tierno7edb6752016-03-21 17:37:52 +010067
68class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020069 def __init__(self, message, http_code):
70 self.http_code = http_code
71 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010072
73
tiernob3d36742017-03-03 23:51:05 +010074def get_task_id():
75 global last_task_id
76 task_id = time()
77 if task_id <= last_task_id:
78 task_id = last_task_id + 0.000001
79 last_task_id = task_id
80 return "TASK.{:.6f}".format(task_id)
81
82
tierno867ffe92017-03-27 12:50:34 +020083def new_task(name, params, depends=None):
tiernob3d36742017-03-03 23:51:05 +010084 task_id = get_task_id()
85 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
86 if depends:
87 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +010088 return task
89
90
91def is_task_id(id):
92 return True if id[:5] == "TASK." else False
93
94
tierno42026a02017-02-10 15:13:40 +010095def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
96 name = datacenter_name[:16]
97 if name not in vim_threads["names"]:
98 vim_threads["names"].append(name)
99 return name
tiernob3d36742017-03-03 23:51:05 +0100100 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100101 if name not in vim_threads["names"]:
102 vim_threads["names"].append(name)
103 return name
104 name = datacenter_id + "-" + tenant_id
105 vim_threads["names"].append(name)
106 return name
107
108
109def start_service(mydb):
tiernob3d36742017-03-03 23:51:05 +0100110 global db, global_config
111 db = nfvo_db.nfvo_db()
112 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 +0100113 global ovim
114
115 # Initialize openvim for SDN control
116 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
117 # TODO: review ovim.py to delete not needed configuration
118 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200119 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100120 'network_vlan_range_start': 1000,
121 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200122 'db_name': global_config["db_ovim_name"],
123 'db_host': global_config["db_ovim_host"],
124 'db_user': global_config["db_ovim_user"],
125 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100126 'bridge_ifaces': {},
127 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100128 'network_type': 'bridge',
129 #TODO: log_level_of should not be needed. To be modified in ovim
130 'log_level_of': 'DEBUG'
131 }
tierno42026a02017-02-10 15:13:40 +0100132 try:
tierno46df9672017-05-26 13:12:21 +0200133 ovim = ovim_module.ovim(ovim_configuration)
134 ovim.start_service()
135
136 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
137 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
138 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
139 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
140 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
141 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100142 vims = mydb.get_rows(FROM=from_, SELECT=select_)
143 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200144 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
145 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100146 if vim["config"]:
147 extra.update(yaml.load(vim["config"]))
148 if vim.get('dt_config'):
149 extra.update(yaml.load(vim["dt_config"]))
150 if vim["type"] not in vimconn_imported:
151 module_info=None
152 try:
153 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200154 pkg = __import__("osm_ro." + module)
155 vim_conn = getattr(pkg, module)
156 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
157 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100158 vimconn_imported[vim["type"]] = vim_conn
159 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200160 # if module_info and module_info[0]:
161 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200162 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
tiernob3d36742017-03-03 23:51:05 +0100163 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100164
tierno867ffe92017-03-27 12:50:34 +0200165 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100166 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100167 try:
168 #if not tenant:
169 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
170 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100171 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
172 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
173 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
174 user=vim['user'], passwd=vim['passwd'],
175 config=extra, persistent_info=vim_persistent_info[thread_id]
176 )
tierno42026a02017-02-10 15:13:40 +0100177 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200178 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
179 HTTP_Internal_Server_Error)
180 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
181 vim['vim_tenant_id'])
tiernob3d36742017-03-03 23:51:05 +0100182 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200183 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100184 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100185 vim_threads["running"][thread_id] = new_thread
186 except db_base_Exception as e:
187 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200188 except ovim_module.ovimException as e:
189 message = str(e)
190 if message[:22] == "DATABASE wrong version":
191 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
192 "at host {dbhost}".format(
193 msg=message[22:-3], dbname=global_config["db_ovim_name"],
194 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
195 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
196 raise NfvoException(message, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100197
tierno867ffe92017-03-27 12:50:34 +0200198
tierno42026a02017-02-10 15:13:40 +0100199def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200200 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100201 if ovim:
202 ovim.stop_service()
tierno42026a02017-02-10 15:13:40 +0100203 for thread_id,thread in vim_threads["running"].items():
tierno867ffe92017-03-27 12:50:34 +0200204 thread.insert_task(new_task("exit", None))
tierno42026a02017-02-10 15:13:40 +0100205 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100206 vim_threads["running"] = {}
tiernoc5651792017-03-27 10:50:43 +0200207 if global_config and global_config.get("console_thread"):
208 for thread in global_config["console_thread"]:
209 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100210
tierno6ddeded2017-05-16 15:40:26 +0200211def get_version():
212 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
213 global_config["version_date"] ))
214
tierno42026a02017-02-10 15:13:40 +0100215
tierno7edb6752016-03-21 17:37:52 +0100216def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
217 '''Obtain flavorList
218 return result, content:
219 <0, error_text upon error
220 nb_records, flavor_list on success
221 '''
222 WHERE_dict={}
223 WHERE_dict['vnf_id'] = vnf_id
224 if nfvo_tenant is not None:
225 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100226
tierno7edb6752016-03-21 17:37:52 +0100227 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
228 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200229 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
230 #print "get_flavor_list result:", result
231 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100232 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200233 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100234 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200235 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100236
tiernob3d36742017-03-03 23:51:05 +0100237
tierno7edb6752016-03-21 17:37:52 +0100238def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
239 '''Obtain imageList
240 return result, content:
241 <0, error_text upon error
242 nb_records, flavor_list on success
243 '''
244 WHERE_dict={}
245 WHERE_dict['vnf_id'] = vnf_id
246 if nfvo_tenant is not None:
247 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100248
tierno7edb6752016-03-21 17:37:52 +0100249 #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 +0200250 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 +0100251 imageList=[]
tiernof97fd272016-07-11 14:32:37 +0200252 for image in images:
tierno7edb6752016-03-21 17:37:52 +0100253 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +0200254 return imageList
tierno7edb6752016-03-21 17:37:52 +0100255
tiernob3d36742017-03-03 23:51:05 +0100256
tiernoa2793912016-10-04 08:15:08 +0000257def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
258 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None):
tierno7edb6752016-03-21 17:37:52 +0100259 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100260 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100261 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200262 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100263 '''
264 WHERE_dict={}
265 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
266 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000267 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100268 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
269 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000270 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
271 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100272 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 +0000273 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 +0100274 '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 +0000275 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100276 else:
277 from_ = 'datacenters as d'
278 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200279 try:
280 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
281 vim_dict={}
282 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200283 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
284 'datacenter_id': vim.get('datacenter_id')}
tierno8008c3a2016-10-13 15:34:28 +0000285 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200286 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000287 if vim.get('dt_config'):
288 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200289 if vim["type"] not in vimconn_imported:
290 module_info=None
291 try:
292 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200293 pkg = __import__("osm_ro." + module)
294 vim_conn = getattr(pkg, module)
295 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
296 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200297 vimconn_imported[vim["type"]] = vim_conn
298 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200299 # if module_info and module_info[0]:
300 # file.close(module_info[0])
tiernof97fd272016-07-11 14:32:37 +0200301 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
302 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100303
tierno7edb6752016-03-21 17:37:52 +0100304 try:
tierno867ffe92017-03-27 12:50:34 +0200305 if 'datacenter_tenant_id' in vim:
306 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100307 if thread_id not in vim_persistent_info:
308 vim_persistent_info[thread_id] = {}
309 persistent_info = vim_persistent_info[thread_id]
310 else:
311 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200312 #if not tenant:
313 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
314 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
315 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100316 tenant_id=vim.get('vim_tenant_id',vim_tenant),
317 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100318 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200319 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100320 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200321 )
322 except Exception as e:
323 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
324 return vim_dict
325 except db_base_Exception as e:
326 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100327
tiernob3d36742017-03-03 23:51:05 +0100328
tierno7edb6752016-03-21 17:37:52 +0100329def rollback(mydb, vims, rollback_list):
330 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100331 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100332 for i in range(len(rollback_list)-1, -1, -1):
333 item = rollback_list[i]
334 if item["where"]=="vim":
335 if item["vim_id"] not in vims:
336 continue
tierno56d73d22017-08-02 13:53:02 +0200337 if is_task_id(item["uuid"]):
338 continue
339 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200340 try:
341 if item["what"]=="image":
342 vim.delete_image(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200343 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200344 elif item["what"]=="flavor":
345 vim.delete_flavor(item["uuid"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200346 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200347 elif item["what"]=="network":
348 vim.delete_network(item["uuid"])
349 elif item["what"]=="vm":
350 vim.delete_vminstance(item["uuid"])
351 except vimconn.vimconnException as e:
352 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
353 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200354 except db_base_Exception as e:
355 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 +0100356
tierno7edb6752016-03-21 17:37:52 +0100357 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200358 try:
359 if item["what"]=="image":
360 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
361 elif item["what"]=="flavor":
362 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
363 except db_base_Exception as e:
364 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
365 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100366 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100367 return True," Rollback successful."
368 else:
369 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100370
tiernob3d36742017-03-03 23:51:05 +0100371
tiernoafed5f12017-01-26 17:57:43 +0100372def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100373 global global_config
tierno42026a02017-02-10 15:13:40 +0100374 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100375 vnfc_interfaces={}
376 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100377 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100378 #dataplane interfaces
379 for numa in vnfc.get("numas",() ):
380 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100381 if interface["name"] in name_dict:
382 raise NfvoException(
383 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
384 vnfc["name"], interface["name"]),
385 HTTP_Bad_Request)
386 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100387 #bridge interfaces
388 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100389 if interface["name"] in name_dict:
390 raise NfvoException(
391 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
392 vnfc["name"], interface["name"]),
393 HTTP_Bad_Request)
394 name_dict[ interface["name"] ] = "overlay"
395 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100396 # check bood-data info
397 if "boot-data" in vnfc:
398 # check that user-data is incompatible with users and config-files
399 if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
400 raise NfvoException(
401 "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
402 HTTP_Bad_Request)
403
tierno7edb6752016-03-21 17:37:52 +0100404 #check if the info in external_connections matches with the one in the vnfcs
405 name_list=[]
406 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
407 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100408 raise NfvoException(
409 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
410 external_connection["name"]),
411 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100412 name_list.append(external_connection["name"])
413 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100414 raise NfvoException(
415 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
416 external_connection["name"], external_connection["VNFC"]),
417 HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100418
tierno7edb6752016-03-21 17:37:52 +0100419 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100420 raise NfvoException(
421 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
422 external_connection["name"],
423 external_connection["local_iface_name"]),
424 HTTP_Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100425
tierno7edb6752016-03-21 17:37:52 +0100426 #check if the info in internal_connections matches with the one in the vnfcs
427 name_list=[]
428 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
429 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100430 raise NfvoException(
431 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
432 internal_connection["name"]),
433 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100434 name_list.append(internal_connection["name"])
435 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100436
437 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
438 raise NfvoException(
439 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
440 internal_connection["name"],
441 'ptp' if vnf_descriptor_version==1 else 'e-line',
442 'data' if vnf_descriptor_version==1 else "e-lan"),
443 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100444 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100445 vnf = port["VNFC"]
446 iface = port["local_iface_name"]
447 if vnf not in vnfc_interfaces:
448 raise NfvoException(
449 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
450 internal_connection["name"], vnf),
451 HTTP_Bad_Request)
452 if iface not in vnfc_interfaces[ vnf ]:
453 raise NfvoException(
454 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
455 internal_connection["name"], iface),
456 HTTP_Bad_Request)
457 return -HTTP_Bad_Request,
458 if vnf_descriptor_version==1 and "type" not in internal_connection:
459 if vnfc_interfaces[vnf][iface] == "overlay":
460 internal_connection["type"] = "bridge"
461 else:
462 internal_connection["type"] = "data"
463 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
464 if vnfc_interfaces[vnf][iface] == "overlay":
465 internal_connection["implementation"] = "overlay"
466 else:
467 internal_connection["implementation"] = "underlay"
468 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
469 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
470 raise NfvoException(
471 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
472 internal_connection["name"],
473 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
474 'data' if vnf_descriptor_version==1 else 'underlay'),
475 HTTP_Bad_Request)
476 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
477 vnfc_interfaces[vnf][iface] == "underlay":
478 raise NfvoException(
479 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
480 internal_connection["name"], iface,
481 'data' if vnf_descriptor_version==1 else 'underlay',
482 'bridge' if vnf_descriptor_version==1 else 'overlay'),
483 HTTP_Bad_Request)
484
tierno7edb6752016-03-21 17:37:52 +0100485
tierno56d73d22017-08-02 13:53:02 +0200486def 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 +0100487 #look if image exist
488 if only_create_at_vim:
489 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000490 if return_on_error == None:
491 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100492 else:
garciadeblas14480452017-01-10 13:08:07 +0100493 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200494 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
495 else:
496 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200497 if len(images)>=1:
498 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100499 else:
garciadeblas14480452017-01-10 13:08:07 +0100500 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100501 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200502 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
503 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100504 }
garciadeblas14480452017-01-10 13:08:07 +0100505 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200506 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
507 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100508 #create image at every vim
509 for vim_id,vim in vims.iteritems():
510 image_created="false"
511 #look at database
tiernof97fd272016-07-11 14:32:37 +0200512 image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100513 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200514 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200515 if image_dict['location'] is not None:
516 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
517 else:
garciadeblas30833382017-01-09 09:46:31 +0100518 filter_dict = {}
519 filter_dict['name'] = image_dict['universal_name']
520 if image_dict.get('checksum') != None:
521 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000522 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200523 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100524 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200525 if len(vim_images) > 1:
garciadeblas3fa2c052017-01-05 12:00:08 +0100526 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), HTTP_Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000527 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100528 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200529 else:
garciadeblas14480452017-01-10 13:08:07 +0100530 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
531 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200532
tiernoae4a8d12016-07-08 12:30:39 +0200533 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100534 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100535 try:
garciadeblas14480452017-01-10 13:08:07 +0100536 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
537 if image_dict['location']:
538 image_vim_id = vim.new_image(image_dict)
539 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
540 image_created="true"
541 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100542 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
543 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200544 except vimconn.vimconnException as e:
545 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100546 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200547 raise
tierno5e91eb82016-10-04 09:39:07 +0000548 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100549 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200550 continue
551 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000552 if return_on_error:
553 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
554 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200555 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000556 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100557 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200558 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200559 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100560 #add new vim_id at datacenters_images
561 mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created})
562 elif image_db[0]["vim_id"]!=image_vim_id:
563 #modify existing vim_id at datacenters_images
564 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno42026a02017-02-10 15:13:40 +0100565
tiernof97fd272016-07-11 14:32:37 +0200566 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100567
tiernob3d36742017-03-03 23:51:05 +0100568
tierno5e91eb82016-10-04 09:39:07 +0000569def 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 +0100570 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
571 'ram':flavor_dict.get('ram'),
572 'vcpus':flavor_dict.get('vcpus'),
573 }
574 if 'extended' in flavor_dict and flavor_dict['extended']==None:
575 del flavor_dict['extended']
576 if 'extended' in flavor_dict:
577 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
578
579 #look if flavor exist
580 if only_create_at_vim:
581 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000582 if return_on_error == None:
583 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100584 else:
tiernof97fd272016-07-11 14:32:37 +0200585 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
586 if len(flavors)>=1:
587 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100588 else:
589 #create flavor
590 #create one by one the images of aditional disks
591 dev_image_list=[] #list of images
592 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
593 dev_nb=0
594 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200595 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100596 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200597 image_dict={}
598 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
599 image_dict['universal_name']=device.get('image name')
600 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
601 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100602 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200603 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100604 image_metadata_dict = device.get('image metadata', None)
605 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100606 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100607 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
608 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200609 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
610 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100611 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100612 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100613 temp_flavor_dict['name'] = flavor_dict['name']
614 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200615 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
616 flavor_mano_id= content
617 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100618 #create flavor at every vim
619 if 'uuid' in flavor_dict:
620 del flavor_dict['uuid']
621 flavor_vim_id=None
622 for vim_id,vim in vims.items():
623 flavor_created="false"
624 #look at database
tiernof97fd272016-07-11 14:32:37 +0200625 flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100626 #look at VIM if this flavor exist SKIPPED
627 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
628 #if res_vim < 0:
629 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
630 # continue
631 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100632
tierno7edb6752016-03-21 17:37:52 +0100633 #Create the flavor in VIM
634 #Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000635 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100636 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
637 #make a copy of original devices
638 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000639
tierno7edb6752016-03-21 17:37:52 +0100640 for device in flavor_dict["extended"].get("devices",[]):
641 dev={}
642 dev.update(device)
643 devices_original.append(dev)
644 if 'image' in device:
645 del device['image']
646 if 'image metadata' in device:
647 del device['image metadata']
648 dev_nb=0
649 for index in range(0,len(devices_original)) :
650 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000651 if "image" not in device and "image name" not in device:
652 if 'size' in device:
653 disk_list.append({'size': device.get('size', default_volume_size)})
tierno7edb6752016-03-21 17:37:52 +0100654 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200655 image_dict={}
656 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
657 image_dict['universal_name']=device.get('image name')
658 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
659 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100660 #image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200661 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100662 image_metadata_dict = device.get('image metadata', None)
663 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100664 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100665 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
666 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200667 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 +0100668 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200669 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 +0000670
671 #save disk information (image must be based on and size
672 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
673
tierno7edb6752016-03-21 17:37:52 +0100674 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
675 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200676 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100677 #check that this vim_id exist in VIM, if not create
678 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200679 try:
680 vim.get_flavor(flavor_vim_id)
681 continue #flavor exist
682 except vimconn.vimconnException:
683 pass
tierno7edb6752016-03-21 17:37:52 +0100684 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200685 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
686 try:
tiernocf157a82017-01-30 14:07:06 +0100687 flavor_vim_id = None
688 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
689 flavor_create="false"
690 except vimconn.vimconnException as e:
691 pass
692 try:
693 if not flavor_vim_id:
694 flavor_vim_id = vim.new_flavor(flavor_dict)
695 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
696 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200697 except vimconn.vimconnException as e:
698 if return_on_error:
699 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200700 raise
tiernoae4a8d12016-07-08 12:30:39 +0200701 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000702 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200703 continue
tierno7edb6752016-03-21 17:37:52 +0100704 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200705 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100706 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000707 extended_devices_yaml = None
708 if len(disk_list) > 0:
709 extended_devices = dict()
710 extended_devices['disks'] = disk_list
711 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
712 mydb.new_row('datacenters_flavors',
713 {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id,
714 'created':flavor_created,'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100715 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
716 #modify existing vim_id at datacenters_flavors
717 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno42026a02017-02-10 15:13:40 +0100718
tiernof97fd272016-07-11 14:32:37 +0200719 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100720
tiernob3d36742017-03-03 23:51:05 +0100721
tierno7edb6752016-03-21 17:37:52 +0100722def new_vnf(mydb, tenant_id, vnf_descriptor):
723 global global_config
tierno42026a02017-02-10 15:13:40 +0100724
tierno7edb6752016-03-21 17:37:52 +0100725 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +0100726 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +0100727 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +0100728 vims = {}
tierno7edb6752016-03-21 17:37:52 +0100729 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +0100730 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100731 if "tenant_id" in vnf_descriptor["vnf"]:
732 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200733 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
734 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100735 else:
736 vnf_descriptor['vnf']['tenant_id'] = tenant_id
737 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +0100738 if global_config["auto_push_VNF_to_VIMs"]:
739 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100740
741 # Step 4. Review the descriptor and add missing fields
742 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +0200743 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +0100744 vnf_name = vnf_descriptor['vnf']['name']
745 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
746 if "physical" in vnf_descriptor['vnf']:
747 del vnf_descriptor['vnf']['physical']
748 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +0100749
tierno42026a02017-02-10 15:13:40 +0100750 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200751 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
752 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +0100753
tierno7edb6752016-03-21 17:37:52 +0100754 #For each VNFC, we add it to the VNFCDict and we create a flavor.
755 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
756 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +0100757 try:
tiernof97fd272016-07-11 14:32:37 +0200758 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100759 for vnfc in vnf_descriptor['vnf']['VNFC']:
760 VNFCitem={}
761 VNFCitem["name"] = vnfc['name']
762 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +0100763
tiernof97fd272016-07-11 14:32:37 +0200764 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +0100765
tierno7edb6752016-03-21 17:37:52 +0100766 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200767 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 +0100768 myflavorDict["description"] = VNFCitem["description"]
769 myflavorDict["ram"] = vnfc.get("ram", 0)
770 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
771 myflavorDict["disk"] = vnfc.get("disk", 1)
772 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +0100773
tierno7edb6752016-03-21 17:37:52 +0100774 devices = vnfc.get("devices")
775 if devices != None:
776 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +0100777
tierno7edb6752016-03-21 17:37:52 +0100778 # TODO:
779 # 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 +0100780 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
781
tierno7edb6752016-03-21 17:37:52 +0100782 # Previous code has been commented
783 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
784 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
785 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
786 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
787 #else:
788 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
789 # if result2:
790 # print "Error creating flavor: unknown processor model. Rollback successful."
791 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
792 # else:
793 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
794 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +0100795
tierno7edb6752016-03-21 17:37:52 +0100796 if 'numas' in vnfc and len(vnfc['numas'])>0:
797 myflavorDict['extended']['numas'] = vnfc['numas']
798
799 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +0100800
tierno7edb6752016-03-21 17:37:52 +0100801 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200802 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +0100803
tiernof97fd272016-07-11 14:32:37 +0200804 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100805 VNFCitem["flavor_id"] = flavor_id
806 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +0100807
tiernof97fd272016-07-11 14:32:37 +0200808 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100809 # Step 6.3 New images are created in the VIM
810 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +0100811 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +0100812 #In case this integration is made, the VNFCDict might become a VNFClist.
813 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +0200814 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200815 image_dict={}
816 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
817 image_dict['universal_name']=vnfc.get('image name')
818 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
819 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100820 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200821 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100822 image_metadata_dict = vnfc.get('image metadata', None)
823 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100824 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +0100825 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
826 image_dict['metadata']=image_metadata_str
827 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +0200828 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
829 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +0100830 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200831 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno36c0b172017-01-12 18:32:28 +0100832 if vnfc.get("boot-data"):
833 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +0100834
tierno42026a02017-02-10 15:13:40 +0100835
tiernof97fd272016-07-11 14:32:37 +0200836 # Step 7. Storing the VNF descriptor in the repository
837 if "descriptor" not in vnf_descriptor["vnf"]:
838 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +0100839
tiernof97fd272016-07-11 14:32:37 +0200840 # Step 8. Adding the VNF to the NFVO DB
841 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
842 return vnf_id
843 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +0100844 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +0200845 if isinstance(e, db_base_Exception):
846 error_text = "Exception at database"
847 elif isinstance(e, KeyError):
848 error_text = "KeyError exception "
849 e.http_code = HTTP_Internal_Server_Error
850 else:
851 error_text = "Exception at VIM"
852 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
853 #logger.error("start_scenario %s", error_text)
854 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +0100855
tiernob3d36742017-03-03 23:51:05 +0100856
garciadeblas9f8456e2016-09-05 05:02:59 +0200857def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
858 global global_config
tierno42026a02017-02-10 15:13:40 +0100859
garciadeblas9f8456e2016-09-05 05:02:59 +0200860 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +0100861 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +0200862 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +0100863 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +0200864 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +0100865 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +0200866 if "tenant_id" in vnf_descriptor["vnf"]:
867 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
868 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
869 HTTP_Unauthorized)
870 else:
871 vnf_descriptor['vnf']['tenant_id'] = tenant_id
872 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +0100873 if global_config["auto_push_VNF_to_VIMs"]:
874 vims = get_vim(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +0200875
876 # Step 4. Review the descriptor and add missing fields
877 #print vnf_descriptor
878 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
879 vnf_name = vnf_descriptor['vnf']['name']
880 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
881 if "physical" in vnf_descriptor['vnf']:
882 del vnf_descriptor['vnf']['physical']
883 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +0100884
tierno42026a02017-02-10 15:13:40 +0100885 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +0200886 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
887 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +0100888
garciadeblas9f8456e2016-09-05 05:02:59 +0200889 #For each VNFC, we add it to the VNFCDict and we create a flavor.
890 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
891 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
892 try:
893 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
894 for vnfc in vnf_descriptor['vnf']['VNFC']:
895 VNFCitem={}
896 VNFCitem["name"] = vnfc['name']
897 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +0100898
garciadeblas9f8456e2016-09-05 05:02:59 +0200899 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +0100900
garciadeblas9f8456e2016-09-05 05:02:59 +0200901 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200902 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 +0200903 myflavorDict["description"] = VNFCitem["description"]
904 myflavorDict["ram"] = vnfc.get("ram", 0)
905 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
906 myflavorDict["disk"] = vnfc.get("disk", 1)
907 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +0100908
garciadeblas9f8456e2016-09-05 05:02:59 +0200909 devices = vnfc.get("devices")
910 if devices != None:
911 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +0100912
garciadeblas9f8456e2016-09-05 05:02:59 +0200913 # TODO:
914 # 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 +0100915 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
916
garciadeblas9f8456e2016-09-05 05:02:59 +0200917 # Previous code has been commented
918 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
919 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
920 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
921 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
922 #else:
923 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
924 # if result2:
925 # print "Error creating flavor: unknown processor model. Rollback successful."
926 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
927 # else:
928 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
929 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +0100930
garciadeblas9f8456e2016-09-05 05:02:59 +0200931 if 'numas' in vnfc and len(vnfc['numas'])>0:
932 myflavorDict['extended']['numas'] = vnfc['numas']
933
934 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +0100935
garciadeblas9f8456e2016-09-05 05:02:59 +0200936 # Step 6.2 New flavors are created in the VIM
937 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
938
939 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
940 VNFCitem["flavor_id"] = flavor_id
941 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +0100942
garciadeblas9f8456e2016-09-05 05:02:59 +0200943 logger.debug("Creating new images in the VIM for each VNFC")
944 # Step 6.3 New images are created in the VIM
945 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +0100946 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +0200947 #In case this integration is made, the VNFCDict might become a VNFClist.
948 for vnfc in vnf_descriptor['vnf']['VNFC']:
949 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200950 image_dict={}
951 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
952 image_dict['universal_name']=vnfc.get('image name')
953 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
954 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100955 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200956 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +0200957 image_metadata_dict = vnfc.get('image metadata', None)
958 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100959 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +0200960 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
961 image_dict['metadata']=image_metadata_str
962 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
963 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
964 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
965 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200966 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno36c0b172017-01-12 18:32:28 +0100967 if vnfc.get("boot-data"):
968 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +0200969
garciadeblas9f8456e2016-09-05 05:02:59 +0200970 # Step 7. Storing the VNF descriptor in the repository
971 if "descriptor" not in vnf_descriptor["vnf"]:
972 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +0100973
garciadeblas9f8456e2016-09-05 05:02:59 +0200974 # Step 8. Adding the VNF to the NFVO DB
975 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
976 return vnf_id
977 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
978 _, message = rollback(mydb, vims, rollback_list)
979 if isinstance(e, db_base_Exception):
980 error_text = "Exception at database"
981 elif isinstance(e, KeyError):
982 error_text = "KeyError exception "
983 e.http_code = HTTP_Internal_Server_Error
984 else:
985 error_text = "Exception at VIM"
986 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
987 #logger.error("start_scenario %s", error_text)
988 raise NfvoException(error_text, e.http_code)
989
tiernob3d36742017-03-03 23:51:05 +0100990
tierno7edb6752016-03-21 17:37:52 +0100991def get_vnf_id(mydb, tenant_id, vnf_id):
992 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +0100993 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100994 #obtain data
995 where_or = {}
996 if tenant_id != "any":
997 where_or["tenant_id"] = tenant_id
998 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +0100999 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1000
tiernof97fd272016-07-11 14:32:37 +02001001 vnf_id=vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +01001002 filter_keys = ('uuid','name','description','public', "tenant_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001003 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001004 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1005 data={'vnf' : filtered_content}
1006 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001007 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tierno36c0b172017-01-12 18:32:28 +01001008 SELECT=('vms.uuid as uuid','vms.name as name', 'vms.description as description', 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001009 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001010 if len(content)==0:
1011 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001012 # change boot_data into boot-data
1013 for vm in content:
1014 if vm.get("boot_data"):
1015 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1016 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001017
1018 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001019 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001020
tierno7edb6752016-03-21 17:37:52 +01001021 #GET NET
tierno42026a02017-02-10 15:13:40 +01001022 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001023 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1024 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001025 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001026
1027 #GET ip-profile for each net
1028 for net in data['vnf']['nets']:
1029 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1030 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1031 WHERE={'net_id': net["uuid"]} )
1032 if len(ipprofiles)==1:
1033 net["ip_profile"] = ipprofiles[0]
1034 elif len(ipprofiles)>1:
1035 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 +01001036
1037
garciadeblas9f8456e2016-09-05 05:02:59 +02001038 #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 +01001039
garciadeblas9f8456e2016-09-05 05:02:59 +02001040 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001041 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 +01001042 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1043 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno42026a02017-02-10 15:13:40 +01001044 WHERE={'vnfs.uuid': vnf_id},
tierno7edb6752016-03-21 17:37:52 +01001045 WHERE_NOT={'interfaces.external_name': None} )
1046 #print content
tiernof97fd272016-07-11 14:32:37 +02001047 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001048
tiernof97fd272016-07-11 14:32:37 +02001049 return data
tierno7edb6752016-03-21 17:37:52 +01001050
1051
1052def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1053 # Check tenant exist
1054 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001055 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001056 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +02001057 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001058 else:
1059 vims={}
1060
1061 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1062 where_or = {}
1063 if tenant_id != "any":
1064 where_or["tenant_id"] = tenant_id
1065 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001066 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 +02001067 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001068
tierno7edb6752016-03-21 17:37:52 +01001069 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001070 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001071 if len(flavorList)==0:
1072 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001073
tiernof97fd272016-07-11 14:32:37 +02001074 imageList = get_imagelist(mydb, vnf_id)
1075 if len(imageList)==0:
1076 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001077
tiernof97fd272016-07-11 14:32:37 +02001078 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1079 if deleted == 0:
1080 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno42026a02017-02-10 15:13:40 +01001081
tierno7edb6752016-03-21 17:37:52 +01001082 undeletedItems = []
1083 for flavor in flavorList:
1084 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001085 try:
1086 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1087 if len(c) > 0:
1088 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1089 continue
1090 #flavor not used, must be deleted
1091 #delelte at VIM
1092 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +01001093 for flavor_vim in c:
1094 if flavor_vim["datacenter_id"] not in vims:
1095 continue
1096 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
1097 continue
1098 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001099 try:
1100 myvim.delete_flavor(flavor_vim["vim_id"])
1101 except vimconn.vimconnNotFoundException as e:
1102 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
1103 except vimconn.vimconnException as e:
1104 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1105 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
1106 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001107 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1108 mydb.delete_row_by_id('flavors', flavor)
1109 except db_base_Exception as e:
1110 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +01001111 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +02001112
tierno42026a02017-02-10 15:13:40 +01001113
tierno7edb6752016-03-21 17:37:52 +01001114 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001115 try:
1116 #check if image is used by other vnf
1117 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
1118 if len(c) > 0:
1119 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1120 continue
1121 #image not used, must be deleted
1122 #delelte at VIM
1123 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001124 for image_vim in c:
1125 if image_vim["datacenter_id"] not in vims:
1126 continue
1127 if image_vim['created']=='false': #skip this image because not created by openmano
1128 continue
1129 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001130 try:
1131 myvim.delete_image(image_vim["vim_id"])
1132 except vimconn.vimconnNotFoundException as e:
1133 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1134 except vimconn.vimconnException as e:
1135 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1136 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1137 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001138 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1139 mydb.delete_row_by_id('images', image)
1140 except db_base_Exception as e:
1141 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001142 undeletedItems.append("image %s" % image)
1143
tiernof97fd272016-07-11 14:32:37 +02001144 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001145 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001146 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001147
tiernob3d36742017-03-03 23:51:05 +01001148
tierno7edb6752016-03-21 17:37:52 +01001149def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1150 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1151 if result < 0:
1152 return result, vims
1153 elif result == 0:
1154 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
1155 myvim = vims.values()[0]
1156 result,servers = myvim.get_hosts_info()
1157 if result < 0:
1158 return result, servers
1159 topology = {'name':myvim['name'] , 'servers': servers}
1160 return result, topology
1161
tiernob3d36742017-03-03 23:51:05 +01001162
tierno7edb6752016-03-21 17:37:52 +01001163def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001164 vims = get_vim(mydb, nfvo_tenant_id)
1165 if len(vims) == 0:
1166 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
1167 elif len(vims)>1:
1168 #print "nfvo.datacenter_action() error. Several datacenters found"
1169 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001170 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001171 try:
1172 hosts = myvim.get_hosts()
1173 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001174
tiernof97fd272016-07-11 14:32:37 +02001175 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1176 for host in hosts:
1177 server={'name':host['name'], 'vms':[]}
1178 for vm in host['instances']:
1179 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001180 try:
tiernof97fd272016-07-11 14:32:37 +02001181 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1182 WHERE={'vim_vm_id':vm['id']} )
1183 if len(c) == 0:
1184 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1185 continue
1186 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001187
tiernof97fd272016-07-11 14:32:37 +02001188 except db_base_Exception as e:
1189 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1190 datacenter['Datacenters'][0]['servers'].append(server)
1191 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001192
tiernof97fd272016-07-11 14:32:37 +02001193 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1194 return datacenter
1195 except vimconn.vimconnException as e:
1196 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001197
tiernob3d36742017-03-03 23:51:05 +01001198
tierno7edb6752016-03-21 17:37:52 +01001199def new_scenario(mydb, tenant_id, topo):
1200
1201# result, vims = get_vim(mydb, tenant_id)
1202# if result < 0:
1203# return result, vims
1204#1: parse input
1205 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001206 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001207 if "tenant_id" in topo:
1208 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001209 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
1210 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001211 else:
1212 tenant_id=None
1213
tierno42026a02017-02-10 15:13:40 +01001214#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001215 vnfs={}
1216 other_nets={} #external_networks, bridge_networks and data_networkds
1217 nodes = topo['topology']['nodes']
1218 for k in nodes.keys():
1219 if nodes[k]['type'] == 'VNF':
1220 vnfs[k] = nodes[k]
1221 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001222 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001223 other_nets[k] = nodes[k]
1224 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001225 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001226 other_nets[k] = nodes[k]
1227 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001228
tierno7edb6752016-03-21 17:37:52 +01001229
1230#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1231 for name,vnf in vnfs.items():
tiernocea279c2016-07-18 12:36:49 +02001232 where={}
1233 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001234 error_text = ""
1235 error_pos = "'topology':'nodes':'" + name + "'"
1236 if 'vnf_id' in vnf:
1237 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001238 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001239 if 'VNF model' in vnf:
1240 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001241 where['name'] = vnf['VNF model']
1242 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +02001243 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001244
tiernocea279c2016-07-18 12:36:49 +02001245 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1246 FROM='vnfs',
tierno42026a02017-02-10 15:13:40 +01001247 WHERE=where,
tiernocea279c2016-07-18 12:36:49 +02001248 WHERE_OR=where_or,
1249 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001250 if len(vnf_db)==0:
1251 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1252 elif len(vnf_db)>1:
1253 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001254 vnf['uuid']=vnf_db[0]['uuid']
1255 vnf['description']=vnf_db[0]['description']
1256 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001257 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1258 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
tierno7edb6752016-03-21 17:37:52 +01001259 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001260 for ext_iface in ext_ifaces:
1261 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1262
1263#1.4 get list of connections
1264 conections = topo['topology']['connections']
1265 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001266 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001267 for k in conections.keys():
1268 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1269 ifaces_list = conections[k]['nodes'].items()
1270 elif type(conections[k]['nodes'])==list: #list with dictionary
1271 ifaces_list=[]
1272 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1273 for k2 in conection_pair_list:
1274 ifaces_list += k2
1275
1276 con_type = conections[k].get("type", "link")
1277 if con_type != "link":
1278 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001279 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001280 other_nets[k] = {'external': False}
1281 if conections[k].get("graph"):
1282 other_nets[k]["graph"] = conections[k]["graph"]
1283 ifaces_list.append( (k, None) )
1284
tierno42026a02017-02-10 15:13:40 +01001285
tierno7edb6752016-03-21 17:37:52 +01001286 if con_type == "external_network":
1287 other_nets[k]['external'] = True
1288 if conections[k].get("model"):
1289 other_nets[k]["model"] = conections[k]["model"]
1290 else:
1291 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001292 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001293 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001294
tiernoefd80c92016-09-16 14:17:46 +02001295 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001296 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)
1297 #print set(ifaces_list)
1298 #check valid VNF and iface names
1299 for iface in ifaces_list:
1300 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001301 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1302 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001303 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001304 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1305 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001306
1307#1.5 unify connections from the pair list to a consolidated list
1308 index=0
1309 while index < len(conections_list):
1310 index2 = index+1
1311 while index2 < len(conections_list):
1312 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1313 conections_list[index] |= conections_list[index2]
1314 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001315 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001316 else:
1317 index2 += 1
1318 conections_list[index] = list(conections_list[index]) # from set to list again
1319 index += 1
1320 #for k in conections_list:
1321 # print k
tierno42026a02017-02-10 15:13:40 +01001322
tierno7edb6752016-03-21 17:37:52 +01001323
1324
1325#1.6 Delete non external nets
1326# for k in other_nets.keys():
1327# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1328# for con in conections_list:
1329# delete_indexes=[]
1330# for index in range(0,len(con)):
1331# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1332# for index in delete_indexes:
1333# del con[index]
1334# del other_nets[k]
1335#1.7: Check external_ports are present at database table datacenter_nets
1336 for k,net in other_nets.items():
1337 error_pos = "'topology':'nodes':'" + k + "'"
1338 if net['external']==False:
1339 if 'name' not in net:
1340 net['name']=k
1341 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001342 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001343 if net['model']=='bridge_net':
1344 net['type']='bridge';
1345 elif net['model']=='dataplane_net':
1346 net['type']='data';
1347 else:
tiernof97fd272016-07-11 14:32:37 +02001348 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001349 else: #external
1350#IF we do not want to check that external network exist at datacenter
1351 pass
tierno42026a02017-02-10 15:13:40 +01001352#ELSE
tierno7edb6752016-03-21 17:37:52 +01001353# error_text = ""
1354# WHERE_={}
1355# if 'net_id' in net:
1356# error_text += " 'net_id' " + net['net_id']
1357# WHERE_['uuid'] = net['net_id']
1358# if 'model' in net:
1359# error_text += " 'model' " + net['model']
1360# WHERE_['name'] = net['model']
1361# if len(WHERE_) == 0:
1362# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1363# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1364# FROM='datacenter_nets', WHERE=WHERE_ )
1365# if r<0:
1366# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1367# elif r==0:
1368# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1369# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1370# elif r>1:
tierno42026a02017-02-10 15:13:40 +01001371# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1372# 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 +01001373# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01001374#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001375 net_list={}
1376 net_nb=0 #Number of nets
1377 for con in conections_list:
1378 #check if this is connected to a external net
1379 other_net_index=-1
1380 #print
1381 #print "con", con
1382 for index in range(0,len(con)):
1383 #check if this is connected to a external net
1384 for net_key in other_nets.keys():
1385 if con[index][0]==net_key:
1386 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01001387 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 +02001388 #print "nfvo.new_scenario " + error_text
1389 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001390 else:
1391 other_net_index = index
1392 net_target = net_key
1393 break
1394 #print "other_net_index", other_net_index
1395 try:
1396 if other_net_index>=0:
1397 del con[other_net_index]
1398#IF we do not want to check that external network exist at datacenter
1399 if other_nets[net_target]['external'] :
1400 if "name" not in other_nets[net_target]:
1401 other_nets[net_target]['name'] = other_nets[net_target]['model']
1402 if other_nets[net_target]["type"] == "external_network":
1403 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1404 other_nets[net_target]["type"] = "data"
1405 else:
1406 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01001407#ELSE
tierno7edb6752016-03-21 17:37:52 +01001408# if other_nets[net_target]['external'] :
1409# 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
1410# if type_=='data' and other_nets[net_target]['type']=="ptp":
1411# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1412# print "nfvo.new_scenario " + error_text
1413# return -HTTP_Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01001414#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001415 for iface in con:
1416 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1417 else:
1418 #create a net
1419 net_type_bridge=False
1420 net_type_data=False
1421 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01001422 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02001423 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01001424 'external':False}
tierno7edb6752016-03-21 17:37:52 +01001425 for iface in con:
1426 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1427 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1428 if iface_type=='mgmt' or iface_type=='bridge':
1429 net_type_bridge = True
1430 else:
1431 net_type_data = True
1432 if net_type_bridge and net_type_data:
1433 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 +02001434 #print "nfvo.new_scenario " + error_text
1435 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001436 elif net_type_bridge:
1437 type_='bridge'
1438 else:
1439 type_='data' if len(con)>2 else 'ptp'
1440 net_list[net_target]['type'] = type_
1441 net_nb+=1
1442 except Exception:
1443 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001444 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01001445 #raise e
tiernof97fd272016-07-11 14:32:37 +02001446 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001447
1448#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01001449 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02001450 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01001451 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01001452 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02001453 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01001454 add_mgmt_net = False
1455 for vnf in vnfs.values():
1456 for iface in vnf['ifaces'].values():
1457 if iface['type']=='mgmt' and 'net_key' not in iface:
1458 #iface not connected
1459 iface['net_key'] = 'mgmt'
1460 add_mgmt_net = True
1461 if add_mgmt_net and 'mgmt' not in net_list:
1462 net_list['mgmt']=mgmt_net[0]
1463 net_list['mgmt']['external']=True
1464 net_list['mgmt']['graph']={'visible':False}
1465
1466 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001467 #print
1468 #print 'net_list', net_list
1469 #print
1470 #print 'vnfs', vnfs
1471 #print
tierno7edb6752016-03-21 17:37:52 +01001472
1473#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001474 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001475 'tenant_id':tenant_id, 'name':topo['name'],
1476 'description':topo.get('description',topo['name']),
1477 'public': topo.get('public', False)
1478 })
tierno42026a02017-02-10 15:13:40 +01001479
tiernof97fd272016-07-11 14:32:37 +02001480 return c
tierno7edb6752016-03-21 17:37:52 +01001481
tiernob3d36742017-03-03 23:51:05 +01001482
tierno5bb59dc2017-02-13 14:53:54 +01001483def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
1484 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02001485 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001486 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001487 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001488 if "tenant_id" in scenario:
1489 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01001490 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001491 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1492 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001493 else:
1494 tenant_id=None
1495
tierno5bb59dc2017-02-13 14:53:54 +01001496 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01001497 for name,vnf in scenario["vnfs"].iteritems():
tiernocea279c2016-07-18 12:36:49 +02001498 where={}
1499 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001500 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001501 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01001502 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001503 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001504 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001505 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001506 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001507 where['name'] = vnf['vnf_name']
1508 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001509 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01001510 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02001511 FROM='vnfs',
1512 WHERE=where,
1513 WHERE_OR=where_or,
1514 WHERE_AND_OR="AND")
tierno5bb59dc2017-02-13 14:53:54 +01001515 if len(vnf_db) == 0:
tiernof97fd272016-07-11 14:32:37 +02001516 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01001517 elif len(vnf_db) > 1:
tiernof97fd272016-07-11 14:32:37 +02001518 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01001519 vnf['uuid'] = vnf_db[0]['uuid']
1520 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01001521 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01001522 # get external interfaces
1523 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
1524 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1525 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name': None} )
tierno7edb6752016-03-21 17:37:52 +01001526 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01001527 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
1528 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01001529
tierno5bb59dc2017-02-13 14:53:54 +01001530 # 2: Insert net_key and ip_address at every vnf interface
1531 for net_name, net in scenario["networks"].items():
1532 net_type_bridge = False
1533 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01001534 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01001535 if version == "0.2":
1536 temp_dict = iface_dict
1537 ip_address = None
1538 elif version == "0.3":
1539 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
1540 ip_address = iface_dict.get('ip_address', None)
1541 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01001542 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01001543 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
1544 net_name, vnf)
1545 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001546 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001547 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01001548 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
1549 .format(net_name, iface)
1550 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001551 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001552 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01001553 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
1554 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
1555 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001556 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001557 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01001558 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01001559 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01001560 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01001561 net_type_bridge = True
1562 else:
1563 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01001564
tierno7edb6752016-03-21 17:37:52 +01001565 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01001566 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
1567 .format(net_name)
1568 # logger.debug("nfvo.new_scenario " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001569 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001570 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01001571 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01001572 else:
tierno5bb59dc2017-02-13 14:53:54 +01001573 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
1574
1575 if net.get("implementation"): # for v0.3
1576 if type_ == "bridge" and net["implementation"] == "underlay":
1577 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
1578 "'network':'{}'".format(net_name)
1579 # logger.debug(error_text)
1580 raise NfvoException(error_text, HTTP_Bad_Request)
1581 elif type_ != "bridge" and net["implementation"] == "overlay":
1582 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
1583 "'network':'{}'".format(net_name)
1584 # logger.debug(error_text)
1585 raise NfvoException(error_text, HTTP_Bad_Request)
1586 net.pop("implementation")
1587 if "type" in net and version == "0.3": # for v0.3
1588 if type_ == "data" and net["type"] == "e-line":
1589 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
1590 "'e-line' at 'network':'{}'".format(net_name)
1591 # logger.debug(error_text)
1592 raise NfvoException(error_text, HTTP_Bad_Request)
1593 elif type_ == "ptp" and net["type"] == "e-lan":
1594 type_ = "data"
1595
tierno7edb6752016-03-21 17:37:52 +01001596 net['type'] = type_
1597 net['name'] = net_name
1598 net['external'] = net.get('external', False)
1599
tierno5bb59dc2017-02-13 14:53:54 +01001600 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01001601 scenario["nets"] = scenario["networks"]
1602 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01001603 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02001604 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01001605
tiernob3d36742017-03-03 23:51:05 +01001606
tierno7edb6752016-03-21 17:37:52 +01001607def edit_scenario(mydb, tenant_id, scenario_id, data):
1608 data["uuid"] = scenario_id
1609 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001610 c = mydb.edit_scenario( data )
1611 return c
tierno7edb6752016-03-21 17:37:52 +01001612
tiernob3d36742017-03-03 23:51:05 +01001613
tierno7edb6752016-03-21 17:37:52 +01001614def 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 +02001615 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00001616 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
1617 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02001618 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001619 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00001620
tierno7edb6752016-03-21 17:37:52 +01001621 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001622 try:
1623 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tiernof97fd272016-07-11 14:32:37 +02001624 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00001625 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02001626 scenarioDict['datacenter_id'] = datacenter_id
1627 #print '================scenarioDict======================='
1628 #print json.dumps(scenarioDict, indent=4)
1629 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01001630
tiernoae4a8d12016-07-08 12:30:39 +02001631 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
1632 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001633
tiernoae4a8d12016-07-08 12:30:39 +02001634 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1635 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01001636
tiernoae4a8d12016-07-08 12:30:39 +02001637 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
1638 for sce_net in scenarioDict['nets']:
1639 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01001640
tiernoae4a8d12016-07-08 12:30:39 +02001641 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01001642 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02001643 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01001644 myNetDict = {}
1645 myNetDict["name"] = myNetName
1646 myNetDict["type"] = myNetType
1647 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001648 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01001649 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02001650 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001651 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02001652 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02001653 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001654 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
1655 sce_net['vim_id'] = network_id
1656 auxNetDict['scenario'][sce_net['uuid']] = network_id
1657 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001658 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001659 else:
1660 if sce_net['vim_id'] == None:
1661 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
1662 _, message = rollback(mydb, vims, rollbackList)
1663 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02001664 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02001665 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
1666 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01001667
tiernoae4a8d12016-07-08 12:30:39 +02001668 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
1669 #For each vnf net, we create it and we add it to instanceNetlist.
1670 for sce_vnf in scenarioDict['vnfs']:
1671 for net in sce_vnf['nets']:
1672 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01001673
tiernoae4a8d12016-07-08 12:30:39 +02001674 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
1675 myNetName = myNetName[0:255] #limit length
1676 myNetType = net['type']
1677 myNetDict = {}
1678 myNetDict["name"] = myNetName
1679 myNetDict["type"] = myNetType
1680 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001681 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02001682 #print myNetDict
1683 #TODO:
1684 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02001685 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001686 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
1687 net['vim_id'] = network_id
1688 if sce_vnf['uuid'] not in auxNetDict:
1689 auxNetDict[sce_vnf['uuid']] = {}
1690 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1691 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001692 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01001693
tiernoae4a8d12016-07-08 12:30:39 +02001694 #print "auxNetDict:"
1695 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001696
tiernoae4a8d12016-07-08 12:30:39 +02001697 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
1698 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
1699 i = 0
1700 for sce_vnf in scenarioDict['vnfs']:
1701 for vm in sce_vnf['vms']:
1702 i += 1
1703 myVMDict = {}
1704 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01001705 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02001706 #myVMDict['description'] = vm['description']
1707 myVMDict['description'] = myVMDict['name'][0:99]
1708 if not startvms:
1709 myVMDict['start'] = "no"
1710 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1711 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01001712
tiernoae4a8d12016-07-08 12:30:39 +02001713 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001714 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01001715 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001716 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01001717
tiernoae4a8d12016-07-08 12:30:39 +02001718 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001719 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001720 if flavor_dict['extended']!=None:
1721 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01001722 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001723 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01001724
1725
tiernoae4a8d12016-07-08 12:30:39 +02001726 myVMDict['imageRef'] = vm['vim_image_id']
1727 myVMDict['flavorRef'] = vm['vim_flavor_id']
1728 myVMDict['networks'] = []
1729 for iface in vm['interfaces']:
1730 netDict = {}
1731 if iface['type']=="data":
1732 netDict['type'] = iface['model']
1733 elif "model" in iface and iface["model"]!=None:
1734 netDict['model']=iface['model']
1735 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1736 #discover type of interface looking at flavor
1737 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1738 for flavor_iface in numa.get('interfaces',[]):
1739 if flavor_iface.get('name') == iface['internal_name']:
1740 if flavor_iface['dedicated'] == 'yes':
1741 netDict['type']="PF" #passthrough
1742 elif flavor_iface['dedicated'] == 'no':
1743 netDict['type']="VF" #siov
1744 elif flavor_iface['dedicated'] == 'yes:sriov':
1745 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1746 netDict["mac_address"] = flavor_iface.get("mac_address")
1747 break;
1748 netDict["use"]=iface['type']
1749 if netDict["use"]=="data" and not netDict.get("type"):
1750 #print "netDict", netDict
1751 #print "iface", iface
1752 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'])
1753 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02001754 raise NfvoException(e_text + "After database migration some information is not available. \
1755 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02001756 else:
tiernof97fd272016-07-11 14:32:37 +02001757 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02001758 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1759 netDict["type"]="virtual"
1760 if "vpci" in iface and iface["vpci"] is not None:
1761 netDict['vpci'] = iface['vpci']
1762 if "mac" in iface and iface["mac"] is not None:
1763 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001764 if "port-security" in iface and iface["port-security"] is not None:
1765 netDict['port_security'] = iface['port-security']
1766 if "floating-ip" in iface and iface["floating-ip"] is not None:
1767 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02001768 netDict['name'] = iface['internal_name']
1769 if iface['net_id'] is None:
1770 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001771 #print iface
1772 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02001773 if vnf_iface['interface_id']==iface['uuid']:
1774 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
1775 break
1776 else:
1777 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1778 #skip bridge ifaces not connected to any net
1779 #if 'net_id' not in netDict or netDict['net_id']==None:
1780 # continue
1781 myVMDict['networks'].append(netDict)
1782 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1783 #print myVMDict['name']
1784 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1785 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1786 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1787 vm_id = myvim.new_vminstance(myVMDict['name'],myVMDict['description'],myVMDict.get('start', None),
1788 myVMDict['imageRef'],myVMDict['flavorRef'],myVMDict['networks'])
1789 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
1790 vm['vim_id'] = vm_id
1791 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1792 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1793 for net in myVMDict['networks']:
1794 if "vim_id" in net:
1795 for iface in vm['interfaces']:
1796 if net["name"]==iface["internal_name"]:
1797 iface["vim_id"]=net["vim_id"]
1798 break
tierno42026a02017-02-10 15:13:40 +01001799
tiernoae4a8d12016-07-08 12:30:39 +02001800 logger.debug("start scenario Deployment done")
1801 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
1802 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001803 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
1804 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01001805
tiernof97fd272016-07-11 14:32:37 +02001806 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001807 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001808 if isinstance(e, db_base_Exception):
1809 error_text = "Exception at database"
1810 else:
1811 error_text = "Exception at VIM"
1812 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1813 #logger.error("start_scenario %s", error_text)
1814 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001815
tiernob3d36742017-03-03 23:51:05 +01001816
tierno36c0b172017-01-12 18:32:28 +01001817def unify_cloud_config(cloud_config_preserve, cloud_config):
1818 ''' join the cloud config information into cloud_config_preserve.
1819 In case of conflict cloud_config_preserve preserves
1820 None is admited
1821 '''
1822 if not cloud_config_preserve and not cloud_config:
1823 return None
1824
1825 new_cloud_config = {"key-pairs":[], "users":[]}
1826 # key-pairs
1827 if cloud_config_preserve:
1828 for key in cloud_config_preserve.get("key-pairs", () ):
1829 if key not in new_cloud_config["key-pairs"]:
1830 new_cloud_config["key-pairs"].append(key)
1831 if cloud_config:
1832 for key in cloud_config.get("key-pairs", () ):
1833 if key not in new_cloud_config["key-pairs"]:
1834 new_cloud_config["key-pairs"].append(key)
1835 if not new_cloud_config["key-pairs"]:
1836 del new_cloud_config["key-pairs"]
1837
1838 # users
1839 if cloud_config:
1840 new_cloud_config["users"] += cloud_config.get("users", () )
1841 if cloud_config_preserve:
1842 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02001843 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01001844 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02001845 for index0 in range(0,len(users)):
1846 if index0 in index_to_delete:
1847 continue
1848 for index1 in range(index0+1,len(users)):
1849 if index1 in index_to_delete:
1850 continue
1851 if users[index0]["name"] == users[index1]["name"]:
1852 index_to_delete.append(index1)
1853 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01001854 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02001855 users[index0]["key-pairs"] = [key]
1856 elif key not in users[index0]["key-pairs"]:
1857 users[index0]["key-pairs"].append(key)
1858 index_to_delete.sort(reverse=True)
1859 for index in index_to_delete:
1860 del users[index]
tierno36c0b172017-01-12 18:32:28 +01001861 if not new_cloud_config["users"]:
1862 del new_cloud_config["users"]
1863
1864 #boot-data-drive
1865 if cloud_config and cloud_config.get("boot-data-drive") != None:
1866 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
1867 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
1868 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
1869
1870 # user-data
1871 if cloud_config and cloud_config.get("user-data") != None:
1872 new_cloud_config["user-data"] = cloud_config["user-data"]
1873 if cloud_config_preserve and cloud_config_preserve.get("user-data") != None:
1874 new_cloud_config["user-data"] = cloud_config_preserve["user-data"]
1875
1876 # config files
1877 new_cloud_config["config-files"] = []
1878 if cloud_config and cloud_config.get("config-files") != None:
1879 new_cloud_config["config-files"] += cloud_config["config-files"]
1880 if cloud_config_preserve:
1881 for file in cloud_config_preserve.get("config-files", ()):
1882 for index in range(0, len(new_cloud_config["config-files"])):
1883 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
1884 new_cloud_config["config-files"][index] = file
1885 break
1886 else:
1887 new_cloud_config["config-files"].append(file)
1888 if not new_cloud_config["config-files"]:
1889 del new_cloud_config["config-files"]
1890 return new_cloud_config
1891
1892
tierno867ffe92017-03-27 12:50:34 +02001893def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01001894 datacenter_id = None
1895 datacenter_name = None
1896 thread = None
tierno867ffe92017-03-27 12:50:34 +02001897 try:
1898 if datacenter_tenant_id:
1899 thread_id = datacenter_tenant_id
1900 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01001901 else:
tierno867ffe92017-03-27 12:50:34 +02001902 where_={"td.nfvo_tenant_id": tenant_id}
1903 if datacenter_id_name:
1904 if utils.check_valid_uuid(datacenter_id_name):
1905 datacenter_id = datacenter_id_name
1906 where_["dt.datacenter_id"] = datacenter_id
1907 else:
1908 datacenter_name = datacenter_id_name
1909 where_["d.name"] = datacenter_name
1910 if datacenter_tenant_id:
1911 where_["dt.uuid"] = datacenter_tenant_id
1912 datacenters = mydb.get_rows(
1913 SELECT=("dt.uuid as datacenter_tenant_id",),
1914 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
1915 "join datacenters as d on d.uuid=dt.datacenter_id",
1916 WHERE=where_)
1917 if len(datacenters) > 1:
1918 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1919 elif datacenters:
1920 thread_id = datacenters[0]["datacenter_tenant_id"]
1921 thread = vim_threads["running"].get(thread_id)
1922 if not thread:
1923 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1924 return thread_id, thread
1925 except db_base_Exception as e:
1926 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02001927
tiernof5755962017-07-13 15:44:34 +02001928
tiernoa2793912016-10-04 08:15:08 +00001929def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02001930 datacenter_id = None
1931 datacenter_name = None
1932 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01001933 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02001934 datacenter_id = datacenter_id_name
1935 else:
1936 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00001937 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02001938 if len(vims) == 0:
1939 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1940 elif len(vims)>1:
1941 #print "nfvo.datacenter_action() error. Several datacenters found"
1942 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1943 return vims.keys()[0], vims.values()[0]
1944
tiernob3d36742017-03-03 23:51:05 +01001945
garciadeblas9f8456e2016-09-05 05:02:59 +02001946def update(d, u):
1947 '''Takes dict d and updates it with the values in dict u.'''
1948 '''It merges all depth levels'''
1949 for k, v in u.iteritems():
1950 if isinstance(v, collections.Mapping):
1951 r = update(d.get(k, {}), v)
1952 d[k] = r
1953 else:
1954 d[k] = u[k]
1955 return d
1956
tiernob3d36742017-03-03 23:51:05 +01001957
tierno7edb6752016-03-21 17:37:52 +01001958def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01001959 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
1960 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01001961 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01001962
tiernobe41e222016-09-02 15:16:13 +02001963 #find main datacenter
1964 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02001965 myvim_threads_id = {}
1966 instance_tasks={}
1967 tasks_to_launch={}
tierno7edb6752016-03-21 17:37:52 +01001968 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02001969 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
1970 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02001971 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
1972 tasks_to_launch[myvim_threads_id[default_datacenter_id]] = []
tierno392f2852016-05-13 12:28:55 +02001973 #myvim_tenant = myvim['tenant_id']
tiernobe41e222016-09-02 15:16:13 +02001974# default_datacenter_name = vim['name']
tierno7edb6752016-03-21 17:37:52 +01001975 rollbackList=[]
tierno42026a02017-02-10 15:13:40 +01001976
tiernoae4a8d12016-07-08 12:30:39 +02001977 #print "Checking that the scenario exists and getting the scenario dictionary"
tiernobe41e222016-09-02 15:16:13 +02001978 scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id)
tierno42026a02017-02-10 15:13:40 +01001979
garciadeblasbb6a1ed2016-09-30 14:02:09 +00001980 #logger.debug(">>>>>>> Dictionaries before merging")
1981 #logger.debug(">>>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
1982 #logger.debug(">>>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01001983
tiernobe41e222016-09-02 15:16:13 +02001984 scenarioDict['datacenter_id'] = default_datacenter_id
garciadeblas9f8456e2016-09-05 05:02:59 +02001985
tierno7edb6752016-03-21 17:37:52 +01001986 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1987 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01001988
1989 logger.debug("Creating instance from scenario-dict:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) #TODO remove
tierno7edb6752016-03-21 17:37:52 +01001990 instance_name = instance_dict["name"]
1991 instance_description = instance_dict.get("description")
1992 try:
tiernob3d36742017-03-03 23:51:05 +01001993 # 0 check correct parameters
tiernobe41e222016-09-02 15:16:13 +02001994 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
tiernob3d36742017-03-03 23:51:05 +01001995 found = False
tierno7edb6752016-03-21 17:37:52 +01001996 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02001997 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01001998 found = True
1999 break
2000 if not found:
tiernobe41e222016-09-02 15:16:13 +02002001 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request)
2002 if "sites" not in net_instance_desc:
2003 net_instance_desc["sites"] = [ {} ]
2004 site_without_datacenter_field = False
2005 for site in net_instance_desc["sites"]:
2006 if site.get("datacenter"):
2007 if site["datacenter"] not in myvims:
2008 #Add this datacenter to myvims
2009 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
2010 myvims[d] = v
tierno867ffe92017-03-27 12:50:34 +02002011 myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, site["datacenter"])
2012 tasks_to_launch[myvim_threads_id[d]] = []
tiernob3d36742017-03-03 23:51:05 +01002013 site["datacenter"] = d #change name to id
tiernobe41e222016-09-02 15:16:13 +02002014 else:
2015 if site_without_datacenter_field:
2016 raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
2017 site_without_datacenter_field = True
tiernob3d36742017-03-03 23:51:05 +01002018 site["datacenter"] = default_datacenter_id #change name to id
tierno42026a02017-02-10 15:13:40 +01002019
tiernobe41e222016-09-02 15:16:13 +02002020 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01002021 found=False
2022 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02002023 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01002024 found = True
2025 break
2026 if not found:
tiernobe41e222016-09-02 15:16:13 +02002027 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
2028 if "datacenter" in vnf_instance_desc:
tiernob3d36742017-03-03 23:51:05 +01002029 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02002030 if vnf_instance_desc["datacenter"] not in myvims:
2031 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
2032 myvims[d] = v
tierno867ffe92017-03-27 12:50:34 +02002033 myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
2034 tasks_to_launch[myvim_threads_id[d]] = []
tiernoa2793912016-10-04 08:15:08 +00002035 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01002036
tiernoa4e1a6e2016-08-31 14:19:40 +02002037 #0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01002038 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02002039
2040 #0.2 merge instance information into scenario
2041 #Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
2042 #However, this is not possible yet.
2043 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
2044 for scenario_net in scenarioDict['nets']:
2045 if net_name == scenario_net["name"]:
2046 if 'ip-profile' in net_instance_desc:
tierno455612d2017-05-30 16:40:10 +02002047 # translate from input format to database format
2048 ipprofile_in = net_instance_desc['ip-profile']
2049 ipprofile_db = {}
2050 ipprofile_db['subnet_address'] = ipprofile_in.get('subnet-address')
2051 ipprofile_db['ip_version'] = ipprofile_in.get('ip-version', 'IPv4')
2052 ipprofile_db['gateway_address'] = ipprofile_in.get('gateway-address')
2053 ipprofile_db['dns_address'] = ipprofile_in.get('dns-address')
2054 if isinstance(ipprofile_db['dns_address'], (list, tuple)):
2055 ipprofile_db['dns_address'] = ";".join(ipprofile_db['dns_address'])
2056 if 'dhcp' in ipprofile_in:
2057 ipprofile_db['dhcp_start_address'] = ipprofile_in['dhcp'].get('start-address')
2058 ipprofile_db['dhcp_enabled'] = ipprofile_in['dhcp'].get('enabled', True)
2059 ipprofile_db['dhcp_count'] = ipprofile_in['dhcp'].get('count' )
garciadeblasedca7b32016-09-29 14:01:52 +00002060 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02002061 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00002062 else:
tierno455612d2017-05-30 16:40:10 +02002063 update(scenario_net['ip_profile'], ipprofile_db)
tiernoe6c58ce2016-09-14 16:02:49 +02002064 for interface in net_instance_desc.get('interfaces', () ):
garciadeblas9f8456e2016-09-05 05:02:59 +02002065 if 'ip_address' in interface:
2066 for vnf in scenarioDict['vnfs']:
2067 if interface['vnf'] == vnf['name']:
2068 for vnf_interface in vnf['interfaces']:
2069 if interface['vnf_interface'] == vnf_interface['external_name']:
2070 vnf_interface['ip_address']=interface['ip_address']
2071
garciadeblasbb6a1ed2016-09-30 14:02:09 +00002072 #logger.debug(">>>>>>>> Merged dictionary")
tierno4319dad2016-09-05 12:11:11 +02002073 logger.debug("Creating instance scenario-dict MERGED:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
garciadeblas9f8456e2016-09-05 05:02:59 +02002074
tierno42026a02017-02-10 15:13:40 +01002075
tiernob3d36742017-03-03 23:51:05 +01002076 # 1. Creating new nets (sce_nets) in the VIM"
tierno7edb6752016-03-21 17:37:52 +01002077 for sce_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02002078 sce_net["vim_id_sites"]={}
tierno7edb6752016-03-21 17:37:52 +01002079 descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{})
tiernobe41e222016-09-02 15:16:13 +02002080 net_name = descriptor_net.get("vim-network-name")
2081 auxNetDict['scenario'][sce_net['uuid']] = {}
2082
2083 sites = descriptor_net.get("sites", [ {} ])
2084 for site in sites:
2085 if site.get("datacenter"):
2086 vim = myvims[ site["datacenter"] ]
2087 datacenter_id = site["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02002088 myvim_thread_id = myvim_threads_id[ site["datacenter"] ]
tierno7edb6752016-03-21 17:37:52 +01002089 else:
tiernobe41e222016-09-02 15:16:13 +02002090 vim = myvims[ default_datacenter_id ]
2091 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002092 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tiernobe41e222016-09-02 15:16:13 +02002093 net_type = sce_net['type']
2094 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True
2095 if sce_net["external"]:
2096 if not net_name:
tierno42026a02017-02-10 15:13:40 +01002097 net_name = sce_net["name"]
tiernobe41e222016-09-02 15:16:13 +02002098 if "netmap-use" in site or "netmap-create" in site:
2099 create_network = False
2100 lookfor_network = False
2101 if "netmap-use" in site:
2102 lookfor_network = True
2103 if utils.check_valid_uuid(site["netmap-use"]):
2104 filter_text = "scenario id '%s'" % site["netmap-use"]
2105 lookfor_filter["id"] = site["netmap-use"]
tierno42026a02017-02-10 15:13:40 +01002106 else:
tiernobe41e222016-09-02 15:16:13 +02002107 filter_text = "scenario name '%s'" % site["netmap-use"]
2108 lookfor_filter["name"] = site["netmap-use"]
2109 if "netmap-create" in site:
2110 create_network = True
2111 net_vim_name = net_name
2112 if site["netmap-create"]:
2113 net_vim_name = site["netmap-create"]
tierno42026a02017-02-10 15:13:40 +01002114
tiernobe41e222016-09-02 15:16:13 +02002115 elif sce_net['vim_id'] != None:
2116 #there is a netmap at datacenter_nets database #TODO REVISE!!!!
2117 create_network = False
2118 lookfor_network = True
2119 lookfor_filter["id"] = sce_net['vim_id']
2120 filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"])
2121 #look for network at datacenter and return error
2122 else:
2123 #There is not a netmap, look at datacenter for a net with this name and create if not found
2124 create_network = True
2125 lookfor_network = True
2126 lookfor_filter["name"] = sce_net["name"]
2127 net_vim_name = sce_net["name"]
2128 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01002129 else:
tiernobe41e222016-09-02 15:16:13 +02002130 if not net_name:
2131 net_name = "%s.%s" %(instance_name, sce_net["name"])
2132 net_name = net_name[:255] #limit length
2133 net_vim_name = net_name
2134 create_network = True
2135 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01002136
tiernobe41e222016-09-02 15:16:13 +02002137 if lookfor_network:
2138 vim_nets = vim.get_network_list(filter_dict=lookfor_filter)
2139 if len(vim_nets) > 1:
2140 raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request )
2141 elif len(vim_nets) == 0:
2142 if not create_network:
2143 raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request )
2144 else:
2145 sce_net["vim_id_sites"][datacenter_id] = vim_nets[0]['id']
tiernobe41e222016-09-02 15:16:13 +02002146 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id']
2147 create_network = False
2148 if create_network:
2149 #if network is not external
tiernob3d36742017-03-03 23:51:05 +01002150 task = new_task("new-net", (net_vim_name, net_type, sce_net.get('ip_profile',None)))
tierno867ffe92017-03-27 12:50:34 +02002151 task_id = task["id"]
tiernob3d36742017-03-03 23:51:05 +01002152 instance_tasks[task_id] = task
tierno867ffe92017-03-27 12:50:34 +02002153 tasks_to_launch[myvim_thread_id].append(task)
tiernob3d36742017-03-03 23:51:05 +01002154 #network_id = vim.new_network(net_vim_name, net_type, sce_net.get('ip_profile',None))
2155 sce_net["vim_id_sites"][datacenter_id] = task_id
2156 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = task_id
2157 rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':task_id})
tierno66345bc2016-09-26 11:37:55 +02002158 sce_net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002159
tiernob3d36742017-03-03 23:51:05 +01002160 # 2. Creating new nets (vnf internal nets) in the VIM"
tierno7edb6752016-03-21 17:37:52 +01002161 #For each vnf net, we create it and we add it to instanceNetlist.
2162 for sce_vnf in scenarioDict['vnfs']:
2163 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02002164 if sce_vnf.get("datacenter"):
2165 vim = myvims[ sce_vnf["datacenter"] ]
2166 datacenter_id = sce_vnf["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02002167 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"]]
tiernobe41e222016-09-02 15:16:13 +02002168 else:
2169 vim = myvims[ default_datacenter_id ]
2170 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002171 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01002172 descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{})
2173 net_name = descriptor_net.get("name")
2174 if not net_name:
2175 net_name = "%s.%s" %(instance_name, net["name"])
2176 net_name = net_name[:255] #limit length
2177 net_type = net['type']
tiernob3d36742017-03-03 23:51:05 +01002178 task = new_task("new-net", (net_name, net_type, net.get('ip_profile',None)))
tierno867ffe92017-03-27 12:50:34 +02002179 task_id = task["id"]
tiernob3d36742017-03-03 23:51:05 +01002180 instance_tasks[task_id] = task
tierno867ffe92017-03-27 12:50:34 +02002181 tasks_to_launch[myvim_thread_id].append(task)
tiernob3d36742017-03-03 23:51:05 +01002182 # network_id = vim.new_network(net_name, net_type, net.get('ip_profile',None))
2183 net['vim_id'] = task_id
tierno7edb6752016-03-21 17:37:52 +01002184 if sce_vnf['uuid'] not in auxNetDict:
2185 auxNetDict[sce_vnf['uuid']] = {}
tiernob3d36742017-03-03 23:51:05 +01002186 auxNetDict[sce_vnf['uuid']][net['uuid']] = task_id
2187 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':task_id})
tierno66345bc2016-09-26 11:37:55 +02002188 net["created"] = True
2189
tierno42026a02017-02-10 15:13:40 +01002190
tiernoae4a8d12016-07-08 12:30:39 +02002191 #print "auxNetDict:"
2192 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002193
tiernob3d36742017-03-03 23:51:05 +01002194 # 3. Creating new vm instances in the VIM
tiernoae4a8d12016-07-08 12:30:39 +02002195 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
garciadeblasacd4e782017-07-23 19:44:55 +02002196 sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
2197 #for sce_vnf in scenarioDict['vnfs']:
2198 for sce_vnf in sce_vnf_list:
tiernobe41e222016-09-02 15:16:13 +02002199 if sce_vnf.get("datacenter"):
2200 vim = myvims[ sce_vnf["datacenter"] ]
tierno867ffe92017-03-27 12:50:34 +02002201 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"] ]
tiernobe41e222016-09-02 15:16:13 +02002202 datacenter_id = sce_vnf["datacenter"]
2203 else:
2204 vim = myvims[ default_datacenter_id ]
tierno867ffe92017-03-27 12:50:34 +02002205 myvim_thread_id = myvim_threads_id[ default_datacenter_id ]
tiernobe41e222016-09-02 15:16:13 +02002206 datacenter_id = default_datacenter_id
2207 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002208 i = 0
2209 for vm in sce_vnf['vms']:
2210 i += 1
2211 myVMDict = {}
tiernoae65a482016-11-24 16:20:05 +01002212 myVMDict['name'] = "{}.{}.{}".format(instance_name,sce_vnf['name'],chr(96+i))
tierno7edb6752016-03-21 17:37:52 +01002213 myVMDict['description'] = myVMDict['name'][0:99]
2214# if not startvms:
2215# myVMDict['start'] = "no"
2216 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2217 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002218 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00002219 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01002220 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002221
tierno7edb6752016-03-21 17:37:52 +01002222 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002223 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01002224 if flavor_dict['extended']!=None:
2225 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
montesmoreno0c8def02016-12-22 12:16:23 +00002226 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
2227
montesmoreno0c8def02016-12-22 12:16:23 +00002228 #Obtain information for additional disks
2229 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id})
2230 if not extended_flavor_dict:
2231 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
2232 return
2233
2234 #extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
2235 myVMDict['disks'] = None
2236 extended_info = extended_flavor_dict[0]['extended']
2237 if extended_info != None:
2238 extended_flavor_dict_yaml = yaml.load(extended_info)
2239 if 'disks' in extended_flavor_dict_yaml:
2240 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
2241
tierno7edb6752016-03-21 17:37:52 +01002242 vm['vim_flavor_id'] = flavor_id
tierno7edb6752016-03-21 17:37:52 +01002243 myVMDict['imageRef'] = vm['vim_image_id']
2244 myVMDict['flavorRef'] = vm['vim_flavor_id']
2245 myVMDict['networks'] = []
tiernob3d36742017-03-03 23:51:05 +01002246 task_depends = {}
tiernoa2793912016-10-04 08:15:08 +00002247 #TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno7edb6752016-03-21 17:37:52 +01002248 for iface in vm['interfaces']:
2249 netDict = {}
2250 if iface['type']=="data":
2251 netDict['type'] = iface['model']
2252 elif "model" in iface and iface["model"]!=None:
2253 netDict['model']=iface['model']
2254 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2255 #discover type of interface looking at flavor
2256 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2257 for flavor_iface in numa.get('interfaces',[]):
2258 if flavor_iface.get('name') == iface['internal_name']:
2259 if flavor_iface['dedicated'] == 'yes':
2260 netDict['type']="PF" #passthrough
2261 elif flavor_iface['dedicated'] == 'no':
2262 netDict['type']="VF" #siov
2263 elif flavor_iface['dedicated'] == 'yes:sriov':
2264 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2265 netDict["mac_address"] = flavor_iface.get("mac_address")
2266 break;
2267 netDict["use"]=iface['type']
2268 if netDict["use"]=="data" and not netDict.get("type"):
2269 #print "netDict", netDict
2270 #print "iface", iface
2271 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'])
2272 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02002273 raise NfvoException(e_text + "After database migration some information is not available. \
2274 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002275 else:
tiernoae4a8d12016-07-08 12:30:39 +02002276 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002277 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2278 netDict["type"]="virtual"
2279 if "vpci" in iface and iface["vpci"] is not None:
2280 netDict['vpci'] = iface['vpci']
2281 if "mac" in iface and iface["mac"] is not None:
2282 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002283 if "port-security" in iface and iface["port-security"] is not None:
2284 netDict['port_security'] = iface['port-security']
2285 if "floating-ip" in iface and iface["floating-ip"] is not None:
2286 netDict['floating_ip'] = iface['floating-ip']
tierno7edb6752016-03-21 17:37:52 +01002287 netDict['name'] = iface['internal_name']
2288 if iface['net_id'] is None:
2289 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002290 #print iface
2291 #print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01002292 if vnf_iface['interface_id']==iface['uuid']:
tiernobe41e222016-09-02 15:16:13 +02002293 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01002294 break
2295 else:
2296 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
tierno867ffe92017-03-27 12:50:34 +02002297 if netDict.get('net_id') and is_task_id(netDict['net_id']):
tiernob3d36742017-03-03 23:51:05 +01002298 task_depends[netDict['net_id']] = instance_tasks[netDict['net_id']]
tierno7edb6752016-03-21 17:37:52 +01002299 #skip bridge ifaces not connected to any net
2300 #if 'net_id' not in netDict or netDict['net_id']==None:
2301 # continue
2302 myVMDict['networks'].append(netDict)
tiernoae4a8d12016-07-08 12:30:39 +02002303 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2304 #print myVMDict['name']
2305 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2306 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2307 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tierno36c0b172017-01-12 18:32:28 +01002308 if vm.get("boot_data"):
2309 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config)
2310 else:
2311 cloud_config_vm = cloud_config
tiernob3d36742017-03-03 23:51:05 +01002312 task = new_task("new-vm", (myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
2313 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
2314 cloud_config_vm, myVMDict['disks']), depends=task_depends)
tierno867ffe92017-03-27 12:50:34 +02002315 instance_tasks[task["id"]] = task
2316 tasks_to_launch[myvim_thread_id].append(task)
2317 vm_id = task["id"]
tierno7edb6752016-03-21 17:37:52 +01002318 vm['vim_id'] = vm_id
2319 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2320 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2321 for net in myVMDict['networks']:
2322 if "vim_id" in net:
2323 for iface in vm['interfaces']:
2324 if net["name"]==iface["internal_name"]:
2325 iface["vim_id"]=net["vim_id"]
2326 break
tierno867ffe92017-03-27 12:50:34 +02002327 scenarioDict["datacenter2tenant"] = myvim_threads_id
tiernoa2793912016-10-04 08:15:08 +00002328 logger.debug("create_instance Deployment done scenarioDict: %s",
2329 yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False) )
tiernof97fd272016-07-11 14:32:37 +02002330 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_name, instance_description, scenarioDict)
tierno867ffe92017-03-27 12:50:34 +02002331 for myvim_thread_id,task_list in tasks_to_launch.items():
2332 for task in task_list:
2333 vim_threads["running"][myvim_thread_id].insert_task(task)
2334
2335 global_instance_tasks[instance_id] = instance_tasks
2336 # Update database with those ended instance_tasks
2337 # for task in instance_tasks.values():
2338 # if task["status"] == "ok":
2339 # if task["name"] == "new-vm":
2340 # mydb.update_rows("instance_vms", UPDATE={"vim_vm_id": task["result"]},
2341 # WHERE={"vim_vm_id": task["id"]})
2342 # elif task["name"] == "new-net":
2343 # mydb.update_rows("instance_nets", UPDATE={"vim_net_id": task["result"]},
2344 # WHERE={"vim_net_id": task["id"]})
tiernof97fd272016-07-11 14:32:37 +02002345 return mydb.get_instance_scenario(instance_id)
2346 except (NfvoException, vimconn.vimconnException,db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02002347 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002348 if isinstance(e, db_base_Exception):
2349 error_text = "database Exception"
2350 elif isinstance(e, vimconn.vimconnException):
2351 error_text = "VIM Exception"
2352 else:
2353 error_text = "Exception"
2354 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2355 #logger.error("create_instance: %s", error_text)
2356 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01002357
tiernob3d36742017-03-03 23:51:05 +01002358
tierno7edb6752016-03-21 17:37:52 +01002359def delete_instance(mydb, tenant_id, instance_id):
tiernoae4a8d12016-07-08 12:30:39 +02002360 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002361 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +02002362 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01002363 tenant_id = instanceDict["tenant_id"]
tiernoae4a8d12016-07-08 12:30:39 +02002364 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01002365
tiernoa2793912016-10-04 08:15:08 +00002366 #1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02002367 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002368
2369 #2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00002370 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01002371 myvims = {}
2372 myvim_threads = {}
tierno7edb6752016-03-21 17:37:52 +01002373
2374 #2.1 deleting VMs
2375 #vm_fail_list=[]
2376 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002377 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2378 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01002379 try:
tierno867ffe92017-03-27 12:50:34 +02002380 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01002381 except NfvoException as e:
2382 logger.error(str(e))
2383 myvim_thread = None
2384 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00002385 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
2386 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2387 if len(vims) == 0:
2388 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
2389 sce_vnf["datacenter_tenant_id"]))
2390 myvims[datacenter_key] = None
2391 else:
2392 myvims[datacenter_key] = vims.values()[0]
2393 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01002394 myvim_thread = myvim_threads[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01002395 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002396 if not myvim:
2397 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
2398 continue
tiernoae4a8d12016-07-08 12:30:39 +02002399 try:
tiernob3d36742017-03-03 23:51:05 +01002400 task=None
2401 if is_task_id(vm['vim_vm_id']):
2402 task_id = vm['vim_vm_id']
tierno867ffe92017-03-27 12:50:34 +02002403 old_task = global_instance_tasks[instance_id].get(task_id)
tiernob3d36742017-03-03 23:51:05 +01002404 if not old_task:
2405 error_msg += "\n VM was scheduled for create, but task {} is not found".format(task_id)
2406 continue
2407 with task_lock:
2408 if old_task["status"] == "enqueued":
2409 old_task["status"] = "deleted"
2410 elif old_task["status"] == "error":
2411 continue
2412 elif old_task["status"] == "processing":
tierno867ffe92017-03-27 12:50:34 +02002413 task = new_task("del-vm", (task_id, vm["interfaces"]), depends={task_id: old_task})
tiernob3d36742017-03-03 23:51:05 +01002414 else: #ok
tierno867ffe92017-03-27 12:50:34 +02002415 task = new_task("del-vm", (old_task["result"], vm["interfaces"]))
tiernob3d36742017-03-03 23:51:05 +01002416 else:
tierno867ffe92017-03-27 12:50:34 +02002417 task = new_task("del-vm", (vm['vim_vm_id'], vm["interfaces"]) )
tiernob3d36742017-03-03 23:51:05 +01002418 if task:
2419 myvim_thread.insert_task(task)
tiernoae4a8d12016-07-08 12:30:39 +02002420 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002421 error_msg+="\n VM VIM_id={} not found at datacenter={}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
tiernoae4a8d12016-07-08 12:30:39 +02002422 logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found",
2423 vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'])
2424 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002425 error_msg+="\n VM VIM_id={} at datacenter={} Error: {} {}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"], e.http_code, str(e))
2426 logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM_id '%s', from VNF_id '%s': %s",
tiernoae4a8d12016-07-08 12:30:39 +02002427 e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e))
tierno42026a02017-02-10 15:13:40 +01002428
tierno7edb6752016-03-21 17:37:52 +01002429 #2.2 deleting NETS
2430 #net_fail_list=[]
2431 for net in instanceDict['nets']:
tierno66345bc2016-09-26 11:37:55 +02002432 if not net['created']:
tierno7edb6752016-03-21 17:37:52 +01002433 continue #skip not created nets
tiernoa2793912016-10-04 08:15:08 +00002434 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2435 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01002436 try:
tierno867ffe92017-03-27 12:50:34 +02002437 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01002438 except NfvoException as e:
2439 logger.error(str(e))
2440 myvim_thread = None
2441 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00002442 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
2443 datacenter_tenant_id=net["datacenter_tenant_id"])
2444 if len(vims) == 0:
2445 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2446 myvims[datacenter_key] = None
2447 else:
2448 myvims[datacenter_key] = vims.values()[0]
2449 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01002450 myvim_thread = myvim_threads[datacenter_key]
tiernoa2793912016-10-04 08:15:08 +00002451
tierno7edb6752016-03-21 17:37:52 +01002452 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00002453 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 +01002454 continue
tiernoae4a8d12016-07-08 12:30:39 +02002455 try:
tiernob3d36742017-03-03 23:51:05 +01002456 task = None
2457 if is_task_id(net['vim_net_id']):
2458 task_id = net['vim_net_id']
tierno867ffe92017-03-27 12:50:34 +02002459 old_task = global_instance_tasks[instance_id].get(task_id)
tiernob3d36742017-03-03 23:51:05 +01002460 if not old_task:
2461 error_msg += "\n NET was scheduled for create, but task {} is not found".format(task_id)
2462 continue
2463 with task_lock:
2464 if old_task["status"] == "enqueued":
2465 old_task["status"] = "deleted"
2466 elif old_task["status"] == "error":
2467 continue
2468 elif old_task["status"] == "processing":
2469 task = new_task("del-net", task_id, depends={task_id: old_task})
2470 else: # ok
2471 task = new_task("del-net", old_task["result"])
2472 else:
tierno867ffe92017-03-27 12:50:34 +02002473 task = new_task("del-net", (net['vim_net_id'], net['sdn_net_id']))
tiernob3d36742017-03-03 23:51:05 +01002474 if task:
2475 myvim_thread.insert_task(task)
tiernoae4a8d12016-07-08 12:30:39 +02002476 except vimconn.vimconnNotFoundException as e:
tiernob3d36742017-03-03 23:51:05 +01002477 error_msg += "\n NET VIM_id={} not found at datacenter={}".format(net['vim_net_id'], net["datacenter_id"])
tiernoa2793912016-10-04 08:15:08 +00002478 logger.warn("NET '%s', VIM_id '%s', from VNF_net_id '%s' not found",
tiernob3d36742017-03-03 23:51:05 +01002479 net['uuid'], net['vim_net_id'], str(net['vnf_net_id']))
tiernoae4a8d12016-07-08 12:30:39 +02002480 except vimconn.vimconnException as e:
tiernob3d36742017-03-03 23:51:05 +01002481 error_msg += "\n NET VIM_id={} at datacenter={} Error: {} {}".format(net['vim_net_id'],
2482 net["datacenter_id"],
2483 e.http_code, str(e))
tiernoa2793912016-10-04 08:15:08 +00002484 logger.error("Error %d deleting NET '%s', VIM_id '%s', from VNF_net_id '%s': %s",
tiernob3d36742017-03-03 23:51:05 +01002485 e.http_code, net['uuid'], net['vim_net_id'], str(net['vnf_net_id']), str(e))
2486 if len(error_msg) > 0:
tiernof97fd272016-07-11 14:32:37 +02002487 return 'instance ' + message + ' deleted but some elements could not be deleted, or already deleted (error: 404) from VIM: ' + error_msg
tierno7edb6752016-03-21 17:37:52 +01002488 else:
tiernof97fd272016-07-11 14:32:37 +02002489 return 'instance ' + message + ' deleted'
tierno7edb6752016-03-21 17:37:52 +01002490
tiernob3d36742017-03-03 23:51:05 +01002491
tierno7edb6752016-03-21 17:37:52 +01002492def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
2493 '''Refreshes a scenario instance. It modifies instanceDict'''
2494 '''Returns:
2495 - 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
2496 - error_msg
2497 '''
tierno867ffe92017-03-27 12:50:34 +02002498 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
2499 # #print "nfvo.refresh_instance begins"
2500 # #print json.dumps(instanceDict, indent=4)
2501 #
2502 # #print "Getting the VIM URL and the VIM tenant_id"
2503 # myvims={}
2504 #
2505 # # 1. Getting VIM vm and net list
2506 # vms_updated = [] #List of VM instance uuids in openmano that were updated
2507 # vms_notupdated=[]
2508 # vm_list = {}
2509 # for sce_vnf in instanceDict['vnfs']:
2510 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2511 # if datacenter_key not in vm_list:
2512 # vm_list[datacenter_key] = []
2513 # if datacenter_key not in myvims:
2514 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
2515 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2516 # if len(vims) == 0:
2517 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
2518 # myvims[datacenter_key] = None
2519 # else:
2520 # myvims[datacenter_key] = vims.values()[0]
2521 # for vm in sce_vnf['vms']:
2522 # vm_list[datacenter_key].append(vm['vim_vm_id'])
2523 # vms_notupdated.append(vm["uuid"])
2524 #
2525 # nets_updated = [] #List of VM instance uuids in openmano that were updated
2526 # nets_notupdated=[]
2527 # net_list = {}
2528 # for net in instanceDict['nets']:
2529 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2530 # if datacenter_key not in net_list:
2531 # net_list[datacenter_key] = []
2532 # if datacenter_key not in myvims:
2533 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
2534 # datacenter_tenant_id=net["datacenter_tenant_id"])
2535 # if len(vims) == 0:
2536 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2537 # myvims[datacenter_key] = None
2538 # else:
2539 # myvims[datacenter_key] = vims.values()[0]
2540 #
2541 # net_list[datacenter_key].append(net['vim_net_id'])
2542 # nets_notupdated.append(net["uuid"])
2543 #
2544 # # 1. Getting the status of all VMs
2545 # vm_dict={}
2546 # for datacenter_key in myvims:
2547 # if not vm_list.get(datacenter_key):
2548 # continue
2549 # failed = True
2550 # failed_message=""
2551 # if not myvims[datacenter_key]:
2552 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2553 # else:
2554 # try:
2555 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
2556 # failed = False
2557 # except vimconn.vimconnException as e:
2558 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
2559 # failed_message = str(e)
2560 # if failed:
2561 # for vm in vm_list[datacenter_key]:
2562 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2563 #
2564 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
2565 # for sce_vnf in instanceDict['vnfs']:
2566 # for vm in sce_vnf['vms']:
2567 # vm_id = vm['vim_vm_id']
2568 # interfaces = vm_dict[vm_id].pop('interfaces', [])
2569 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
2570 # has_mgmt_iface = False
2571 # for iface in vm["interfaces"]:
2572 # if iface["type"]=="mgmt":
2573 # has_mgmt_iface = True
2574 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
2575 # vm_dict[vm_id]['status'] = "ACTIVE"
2576 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
2577 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
2578 # 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'):
2579 # vm['status'] = vm_dict[vm_id]['status']
2580 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
2581 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
2582 # # 2.1. Update in openmano DB the VMs whose status changed
2583 # try:
2584 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
2585 # vms_notupdated.remove(vm["uuid"])
2586 # if updates>0:
2587 # vms_updated.append(vm["uuid"])
2588 # except db_base_Exception as e:
2589 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
2590 # # 2.2. Update in openmano DB the interface VMs
2591 # for interface in interfaces:
2592 # #translate from vim_net_id to instance_net_id
2593 # network_id_list=[]
2594 # for net in instanceDict['nets']:
2595 # if net["vim_net_id"] == interface["vim_net_id"]:
2596 # network_id_list.append(net["uuid"])
2597 # if not network_id_list:
2598 # continue
2599 # del interface["vim_net_id"]
2600 # try:
2601 # for network_id in network_id_list:
2602 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
2603 # except db_base_Exception as e:
2604 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
2605 #
2606 # # 3. Getting the status of all nets
2607 # net_dict = {}
2608 # for datacenter_key in myvims:
2609 # if not net_list.get(datacenter_key):
2610 # continue
2611 # failed = True
2612 # failed_message = ""
2613 # if not myvims[datacenter_key]:
2614 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2615 # else:
2616 # try:
2617 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
2618 # failed = False
2619 # except vimconn.vimconnException as e:
2620 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
2621 # failed_message = str(e)
2622 # if failed:
2623 # for net in net_list[datacenter_key]:
2624 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2625 #
2626 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
2627 # # TODO: update nets inside a vnf
2628 # for net in instanceDict['nets']:
2629 # net_id = net['vim_net_id']
2630 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
2631 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
2632 # 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'):
2633 # net['status'] = net_dict[net_id]['status']
2634 # net['error_msg'] = net_dict[net_id].get('error_msg')
2635 # net['vim_info'] = net_dict[net_id].get('vim_info')
2636 # # 5.1. Update in openmano DB the nets whose status changed
2637 # try:
2638 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
2639 # nets_notupdated.remove(net["uuid"])
2640 # if updated>0:
2641 # nets_updated.append(net["uuid"])
2642 # except db_base_Exception as e:
2643 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
2644 #
2645 # # Returns appropriate output
2646 # #print "nfvo.refresh_instance finishes"
2647 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
2648 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01002649 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02002650 # if len(vms_notupdated)+len(nets_notupdated)>0:
2651 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
2652 # 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 +01002653
tiernoae4a8d12016-07-08 12:30:39 +02002654 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01002655
tiernob3d36742017-03-03 23:51:05 +01002656
tierno7edb6752016-03-21 17:37:52 +01002657def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02002658 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002659 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002660 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
2661
tiernoae4a8d12016-07-08 12:30:39 +02002662 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02002663 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
2664 if len(vims) == 0:
2665 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002666 myvim = vims.values()[0]
tierno42026a02017-02-10 15:13:40 +01002667
tierno7edb6752016-03-21 17:37:52 +01002668
2669 input_vnfs = action_dict.pop("vnfs", [])
2670 input_vms = action_dict.pop("vms", [])
2671 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
2672 vm_result = {}
2673 vm_error = 0
2674 vm_ok = 0
2675 for sce_vnf in instanceDict['vnfs']:
2676 for vm in sce_vnf['vms']:
2677 if not action_over_all:
2678 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
2679 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
2680 continue
tiernoae4a8d12016-07-08 12:30:39 +02002681 try:
2682 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
tierno7edb6752016-03-21 17:37:52 +01002683 if "console" in action_dict:
tierno20fc2a22016-08-19 17:02:35 +02002684 if not global_config["http_console_proxy"]:
2685 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2686 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2687 protocol=data["protocol"],
2688 ip = data["server"],
2689 port = data["port"],
2690 suffix = data["suffix"]),
2691 "name":vm['name']
2692 }
2693 vm_ok +=1
2694 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
tierno7edb6752016-03-21 17:37:52 +01002695 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
2696 "description": "this console is only reachable by local interface",
2697 "name":vm['name']
2698 }
2699 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02002700 else:
tierno7edb6752016-03-21 17:37:52 +01002701 #print "console data", data
tierno42026a02017-02-10 15:13:40 +01002702 try:
tierno20fc2a22016-08-19 17:02:35 +02002703 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
2704 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2705 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2706 protocol=data["protocol"],
2707 ip = global_config["http_console_host"],
2708 port = console_thread.port,
2709 suffix = data["suffix"]),
2710 "name":vm['name']
2711 }
2712 vm_ok +=1
2713 except NfvoException as e:
2714 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2715 vm_error+=1
2716
tierno7edb6752016-03-21 17:37:52 +01002717 else:
tiernof97fd272016-07-11 14:32:37 +02002718 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
tierno7edb6752016-03-21 17:37:52 +01002719 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02002720 except vimconn.vimconnException as e:
2721 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2722 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01002723
2724 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02002725 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002726 else:
tierno351863c2016-07-23 01:46:03 +02002727 return vm_result
tierno42026a02017-02-10 15:13:40 +01002728
tiernob3d36742017-03-03 23:51:05 +01002729
tierno7edb6752016-03-21 17:37:52 +01002730def create_or_use_console_proxy_thread(console_server, console_port):
2731 #look for a non-used port
2732 console_thread_key = console_server + ":" + str(console_port)
2733 if console_thread_key in global_config["console_thread"]:
2734 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02002735 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01002736
tierno7edb6752016-03-21 17:37:52 +01002737 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02002738 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01002739 if port in global_config["console_ports"]:
2740 continue
2741 try:
2742 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
2743 clithread.start()
2744 global_config["console_thread"][console_thread_key] = clithread
2745 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02002746 return clithread
tierno7edb6752016-03-21 17:37:52 +01002747 except cli.ConsoleProxyExceptionPortUsed as e:
2748 #port used, try with onoher
2749 continue
2750 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02002751 raise NfvoException(str(e), HTTP_Bad_Request)
2752 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002753
tiernob3d36742017-03-03 23:51:05 +01002754
tierno7edb6752016-03-21 17:37:52 +01002755def check_tenant(mydb, tenant_id):
2756 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02002757 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
2758 if not tenant:
2759 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
2760 return
tierno7edb6752016-03-21 17:37:52 +01002761
tiernob3d36742017-03-03 23:51:05 +01002762
tierno7edb6752016-03-21 17:37:52 +01002763def new_tenant(mydb, tenant_dict):
tiernof97fd272016-07-11 14:32:37 +02002764 tenant_id = mydb.new_row("nfvo_tenants", tenant_dict, add_uuid=True)
2765 return tenant_id
tierno7edb6752016-03-21 17:37:52 +01002766
tiernob3d36742017-03-03 23:51:05 +01002767
tierno7edb6752016-03-21 17:37:52 +01002768def delete_tenant(mydb, tenant):
2769 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01002770
tiernof97fd272016-07-11 14:32:37 +02002771 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
2772 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
2773 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01002774
tiernob3d36742017-03-03 23:51:05 +01002775
tierno7edb6752016-03-21 17:37:52 +01002776def new_datacenter(mydb, datacenter_descriptor):
2777 if "config" in datacenter_descriptor:
2778 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02002779 #Check that datacenter-type is correct
2780 datacenter_type = datacenter_descriptor.get("type", "openvim");
2781 module_info = None
2782 try:
2783 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02002784 pkg = __import__("osm_ro." + module)
2785 vim_conn = getattr(pkg, module)
2786 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02002787 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02002788 # if module_info and module_info[0]:
2789 # file.close(module_info[0])
tierno3ae39742016-09-07 12:17:51 +02002790 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01002791
tiernof97fd272016-07-11 14:32:37 +02002792 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
2793 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002794
tiernob3d36742017-03-03 23:51:05 +01002795
tierno7edb6752016-03-21 17:37:52 +01002796def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02002797 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02002798 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02002799
2800 # edit data
tiernof97fd272016-07-11 14:32:37 +02002801 datacenter_id = datacenter['uuid']
2802 where={'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02002803 remove_port_mapping = False
tierno7edb6752016-03-21 17:37:52 +01002804 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02002805 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01002806 try:
2807 new_config_dict = datacenter_descriptor["config"]
2808 #delete null fields
2809 to_delete=[]
2810 for k in new_config_dict:
tierno8fe7a492017-07-11 13:50:04 +02002811 if new_config_dict[k] == None:
tierno7edb6752016-03-21 17:37:52 +01002812 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02002813 if k == 'sdn-controller':
2814 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01002815
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01002816 config_text = datacenter.get("config")
2817 if not config_text:
2818 config_text = '{}'
2819 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01002820 config_dict.update(new_config_dict)
2821 #delete null fields
2822 for k in to_delete:
2823 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02002824 except Exception as e:
2825 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02002826 if config_dict:
2827 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
2828 else:
2829 datacenter_descriptor["config"] = None
2830 if remove_port_mapping:
2831 try:
2832 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
2833 except ovimException as e:
2834 logger.error("Error deleting datacenter-port-mapping " + str(e))
2835
tiernof97fd272016-07-11 14:32:37 +02002836 mydb.update_rows('datacenters', datacenter_descriptor, where)
2837 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002838
tiernob3d36742017-03-03 23:51:05 +01002839
tierno7edb6752016-03-21 17:37:52 +01002840def delete_datacenter(mydb, datacenter):
2841 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002842 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
2843 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02002844 try:
2845 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
2846 except ovimException as e:
2847 logger.error("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02002848 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01002849
tiernob3d36742017-03-03 23:51:05 +01002850
tierno8008c3a2016-10-13 15:34:28 +00002851def associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter, vim_tenant_id=None, vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
tierno7edb6752016-03-21 17:37:52 +01002852 #get datacenter info
Vance Shipleyc24b4e22017-05-12 02:34:53 +05302853 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username, vim_passwd=vim_password)
tierno42026a02017-02-10 15:13:40 +01002854 datacenter_name = myvim["name"]
tierno7edb6752016-03-21 17:37:52 +01002855
tierno42026a02017-02-10 15:13:40 +01002856 create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
2857
2858 # get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02002859 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002860 if vim_tenant_name==None:
2861 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01002862
tierno7edb6752016-03-21 17:37:52 +01002863 #check that this association does not exist before
2864 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernof97fd272016-07-11 14:32:37 +02002865 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2866 if len(tenants_datacenters)>0:
2867 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002868
2869 vim_tenant_id_exist_atdb=False
2870 if not create_vim_tenant:
2871 where_={"datacenter_id": datacenter_id}
2872 if vim_tenant_id!=None:
2873 where_["vim_tenant_id"] = vim_tenant_id
2874 if vim_tenant_name!=None:
2875 where_["vim_tenant_name"] = vim_tenant_name
2876 #check if vim_tenant_id is already at database
tiernof97fd272016-07-11 14:32:37 +02002877 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
2878 if len(datacenter_tenants_dict)>=1:
tierno7edb6752016-03-21 17:37:52 +01002879 datacenter_tenants_dict = datacenter_tenants_dict[0]
2880 vim_tenant_id_exist_atdb=True
2881 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
2882 else: #result=0
2883 datacenter_tenants_dict = {}
2884 #insert at table datacenter_tenants
2885 else: #if vim_tenant_id==None:
2886 #create tenant at VIM if not provided
tiernoae4a8d12016-07-08 12:30:39 +02002887 try:
2888 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
2889 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02002890 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 +01002891 datacenter_tenants_dict = {}
2892 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01002893
tierno7edb6752016-03-21 17:37:52 +01002894 #fill datacenter_tenants table
2895 if not vim_tenant_id_exist_atdb:
tierno42026a02017-02-10 15:13:40 +01002896 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
tierno7edb6752016-03-21 17:37:52 +01002897 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
tierno42026a02017-02-10 15:13:40 +01002898 datacenter_tenants_dict["user"] = vim_username
2899 datacenter_tenants_dict["passwd"] = vim_password
2900 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tierno8008c3a2016-10-13 15:34:28 +00002901 if config:
2902 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
tiernof97fd272016-07-11 14:32:37 +02002903 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01002904 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01002905
tierno7edb6752016-03-21 17:37:52 +01002906 #fill tenants_datacenters table
tierno99314902017-04-26 13:23:09 +02002907 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
2908 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
tiernof97fd272016-07-11 14:32:37 +02002909 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tierno42026a02017-02-10 15:13:40 +01002910 # create thread
2911 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id) # reload data
2912 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tierno99314902017-04-26 13:23:09 +02002913 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
2914 db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +01002915 new_thread.start()
tierno867ffe92017-03-27 12:50:34 +02002916 thread_id = datacenter_tenants_dict["uuid"]
tiernob3d36742017-03-03 23:51:05 +01002917 vim_threads["running"][thread_id] = new_thread
tiernof97fd272016-07-11 14:32:37 +02002918 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002919
tierno99314902017-04-26 13:23:09 +02002920
2921def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
2922 vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01002923 #Obtain the data of this datacenter_tenant_id
2924 vim_data = mydb.get_rows(
2925 SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",
2926 "datacenter_tenants.passwd", "datacenter_tenants.config"),
2927 FROM="datacenter_tenants JOIN tenants_datacenters ON datacenter_tenants.uuid=tenants_datacenters.datacenter_tenant_id",
2928 WHERE={"tenants_datacenters.nfvo_tenant_id": nfvo_tenant,
2929 "tenants_datacenters.datacenter_id": datacenter_id})
2930
2931 logger.debug(str(vim_data))
2932 if len(vim_data) < 1:
2933 raise NfvoException("Datacenter {} is not attached for tenant {}".format(datacenter_id, nfvo_tenant), HTTP_Conflict)
2934
2935 v = vim_data[0]
2936 if v['config']:
2937 v['config'] = yaml.load(v['config'])
2938
2939 if vim_tenant_id:
2940 v['vim_tenant_id'] = vim_tenant_id
2941 if vim_tenant_name:
2942 v['vim_tenant_name'] = vim_tenant_name
2943 if vim_username:
2944 v['user'] = vim_username
2945 if vim_password:
2946 v['passwd'] = vim_password
2947 if config:
2948 if not v['config']:
2949 v['config'] = {}
2950 v['config'].update(config)
2951
2952 logger.debug(str(v))
2953 deassociate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'])
2954 associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'], vim_tenant_name=v['vim_tenant_name'],
2955 vim_username=v['user'], vim_password=v['passwd'], config=v['config'])
2956
2957 return datacenter_id
tiernob3d36742017-03-03 23:51:05 +01002958
tierno7edb6752016-03-21 17:37:52 +01002959def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
2960 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00002961 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter)
tierno7edb6752016-03-21 17:37:52 +01002962
2963 #get nfvo_tenant info
2964 if not tenant_id or tenant_id=="any":
2965 tenant_uuid = None
2966 else:
tiernof97fd272016-07-11 14:32:37 +02002967 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002968 tenant_uuid = tenant_dict['uuid']
2969
2970 #check that this association exist before
2971 tenants_datacenter_dict={"datacenter_id":datacenter_id }
2972 if tenant_uuid:
2973 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02002974 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
2975 if len(tenant_datacenter_list)==0 and tenant_uuid:
2976 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002977
2978 #delete this association
tiernof97fd272016-07-11 14:32:37 +02002979 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01002980
2981 #get vim_tenant info and deletes
2982 warning=''
2983 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02002984 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2985 #try to delete vim:tenant
2986 try:
2987 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
2988 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01002989 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01002990 try:
tiernoae4a8d12016-07-08 12:30:39 +02002991 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
2992 except vimconn.vimconnException as e:
2993 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
2994 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02002995 except db_base_Exception as e:
2996 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01002997 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02002998 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tierno42026a02017-02-10 15:13:40 +01002999 thread = vim_threads["running"][thread_id]
tierno867ffe92017-03-27 12:50:34 +02003000 thread.insert_task(new_task("exit", None))
tierno42026a02017-02-10 15:13:40 +01003001 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02003002 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01003003
tiernob3d36742017-03-03 23:51:05 +01003004
tierno7edb6752016-03-21 17:37:52 +01003005def datacenter_action(mydb, tenant_id, datacenter, action_dict):
3006 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01003007 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003008 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003009
3010 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02003011 try:
tiernof97fd272016-07-11 14:32:37 +02003012 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02003013 #print content
3014 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003015 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
3016 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01003017 #update nets Change from VIM format to NFVO format
3018 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02003019 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01003020 net_nfvo={'datacenter_id': datacenter_id}
3021 net_nfvo['name'] = net['name']
3022 #net_nfvo['description']= net['name']
3023 net_nfvo['vim_net_id'] = net['id']
3024 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
3025 net_nfvo['shared'] = net['shared']
3026 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
3027 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02003028 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
3029 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
3030 return inserted
tierno7edb6752016-03-21 17:37:52 +01003031 elif 'net-edit' in action_dict:
3032 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02003033 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01003034 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01003035 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02003036 return result
tierno7edb6752016-03-21 17:37:52 +01003037 elif 'net-delete' in action_dict:
3038 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02003039 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01003040 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01003041 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02003042 return result
tierno7edb6752016-03-21 17:37:52 +01003043
3044 else:
tiernof97fd272016-07-11 14:32:37 +02003045 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01003046
tiernob3d36742017-03-03 23:51:05 +01003047
tierno7edb6752016-03-21 17:37:52 +01003048def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
3049 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003050 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003051
tierno42fcc3b2016-07-06 17:20:40 +02003052 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01003053 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01003054 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02003055 return result
tierno7edb6752016-03-21 17:37:52 +01003056
tiernob3d36742017-03-03 23:51:05 +01003057
tierno7edb6752016-03-21 17:37:52 +01003058def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
3059 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003060 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003061 filter_dict={}
3062 if action_dict:
3063 action_dict = action_dict["netmap"]
3064 if 'vim_id' in action_dict:
3065 filter_dict["id"] = action_dict['vim_id']
3066 if 'vim_name' in action_dict:
3067 filter_dict["name"] = action_dict['vim_name']
3068 else:
3069 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01003070
tiernoae4a8d12016-07-08 12:30:39 +02003071 try:
tiernof97fd272016-07-11 14:32:37 +02003072 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02003073 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003074 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
3075 raise NfvoException(str(e), HTTP_Internal_Server_Error)
3076 if len(vim_nets)>1 and action_dict:
3077 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
3078 elif len(vim_nets)==0: # and action_dict:
3079 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01003080 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02003081 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01003082 net_nfvo={'datacenter_id': datacenter_id}
3083 if action_dict and "name" in action_dict:
3084 net_nfvo['name'] = action_dict['name']
3085 else:
3086 net_nfvo['name'] = net['name']
3087 #net_nfvo['description']= net['name']
3088 net_nfvo['vim_net_id'] = net['id']
3089 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
3090 net_nfvo['shared'] = net['shared']
3091 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02003092 try:
3093 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01003094 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02003095 net_nfvo["uuid"] = net_id
3096 except db_base_Exception as e:
3097 if action_dict:
3098 raise
3099 else:
3100 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01003101 net_list.append(net_nfvo)
3102 return net_list
tierno7edb6752016-03-21 17:37:52 +01003103
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003104def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
3105 # obtain all network data
3106 try:
3107 if utils.check_valid_uuid(network_id):
3108 filter_dict = {"id": network_id}
3109 else:
3110 filter_dict = {"name": network_id}
3111
3112 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3113 network = myvim.get_network_list(filter_dict=filter_dict)
3114 except vimconn.vimconnException as e:
3115 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
3116 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
3117
3118 # ensure the network is defined
3119 if len(network) == 0:
3120 raise NfvoException("Network {} is not present in the system".format(network_id),
3121 HTTP_Bad_Request)
3122
3123 # ensure there is only one network with the provided name
3124 if len(network) > 1:
3125 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), HTTP_Bad_Request)
3126
3127 # ensure it is a dataplane network
3128 if network[0]['type'] != 'data':
3129 return None
3130
3131 # ensure we use the id
3132 network_id = network[0]['id']
3133
3134 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
3135 # and with instance_scenario_id==NULL
3136 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
3137 search_dict = {'vim_net_id': network_id}
3138
3139 try:
3140 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
3141 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
3142 except db_base_Exception as e:
3143 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
3144 network_id) + str(e), HTTP_Internal_Server_Error)
3145
3146 sdn_net_counter = 0
3147 for net in result:
3148 if net['sdn_net_id'] != None:
3149 sdn_net_counter+=1
3150 sdn_net_id = net['sdn_net_id']
3151
3152 if sdn_net_counter == 0:
3153 return None
3154 elif sdn_net_counter == 1:
3155 return sdn_net_id
3156 else:
3157 raise NfvoException("More than one SDN network is associated to vim network {}".format(
3158 network_id), HTTP_Internal_Server_Error)
3159
3160def get_sdn_controller_id(mydb, datacenter):
3161 # Obtain sdn controller id
3162 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
3163 if not config:
3164 return None
3165
3166 return yaml.load(config).get('sdn-controller')
3167
3168def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
3169 try:
3170 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
3171 if not sdn_network_id:
3172 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), HTTP_Internal_Server_Error)
3173
3174 #Obtain sdn controller id
3175 controller_id = get_sdn_controller_id(mydb, datacenter)
3176 if not controller_id:
3177 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), HTTP_Internal_Server_Error)
3178
3179 #Obtain sdn controller info
3180 sdn_controller = ovim.show_of_controller(controller_id)
3181
3182 port_data = {
3183 'name': 'external_port',
3184 'net_id': sdn_network_id,
3185 'ofc_id': controller_id,
3186 'switch_dpid': sdn_controller['dpid'],
3187 'switch_port': descriptor['port']
3188 }
3189
3190 if 'vlan' in descriptor:
3191 port_data['vlan'] = descriptor['vlan']
3192 if 'mac' in descriptor:
3193 port_data['mac'] = descriptor['mac']
3194
3195 result = ovim.new_port(port_data)
3196 except ovimException as e:
3197 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
3198 sdn_network_id, network_id) + str(e), HTTP_Internal_Server_Error)
3199 except db_base_Exception as e:
3200 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
3201 network_id) + str(e), HTTP_Internal_Server_Error)
3202
3203 return 'Port uuid: '+ result
3204
3205def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
3206 if port_id:
3207 filter = {'uuid': port_id}
3208 else:
3209 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
3210 if not sdn_network_id:
3211 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
3212 HTTP_Internal_Server_Error)
3213 #in case no port_id is specified only ports marked as 'external_port' will be detached
3214 filter = {'name': 'external_port', 'net_id': sdn_network_id}
3215
3216 try:
3217 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
3218 except ovimException as e:
3219 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
3220 HTTP_Internal_Server_Error)
3221
3222 if len(port_list) == 0:
3223 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
3224 HTTP_Bad_Request)
3225
3226 port_uuid_list = []
3227 for port in port_list:
3228 try:
3229 port_uuid_list.append(port['uuid'])
3230 ovim.delete_port(port['uuid'])
3231 except ovimException as e:
3232 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), HTTP_Internal_Server_Error)
3233
3234 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01003235
tierno7edb6752016-03-21 17:37:52 +01003236def vim_action_get(mydb, tenant_id, datacenter, item, name):
3237 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003238 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003239 filter_dict={}
3240 if name:
tierno42fcc3b2016-07-06 17:20:40 +02003241 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01003242 filter_dict["id"] = name
3243 else:
3244 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02003245 try:
3246 if item=="networks":
3247 #filter_dict['tenant_id'] = myvim['tenant_id']
3248 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003249
3250 if len(content) == 0:
3251 raise NfvoException("Network {} is not present in the system. ".format(name),
3252 HTTP_Bad_Request)
3253
3254 #Update the networks with the attached ports
3255 for net in content:
3256 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
3257 if sdn_network_id != None:
3258 try:
3259 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
3260 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
3261 except ovimException as e:
3262 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), HTTP_Internal_Server_Error)
3263 #Remove field name and if port name is external_port save it as 'type'
3264 for port in port_list:
3265 if port['name'] == 'external_port':
3266 port['type'] = "External"
3267 del port['name']
3268 net['sdn_network_id'] = sdn_network_id
3269 net['sdn_attached_ports'] = port_list
3270
tiernoae4a8d12016-07-08 12:30:39 +02003271 elif item=="tenants":
3272 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01003273 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003274
tierno4540ea52017-01-18 17:44:32 +01003275 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02003276 else:
tiernof97fd272016-07-11 14:32:37 +02003277 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02003278 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02003279 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02003280 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02003281 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02003282 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 +02003283 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02003284 else:
tiernof97fd272016-07-11 14:32:37 +02003285 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02003286 except vimconn.vimconnException as e:
3287 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02003288 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01003289
tiernob3d36742017-03-03 23:51:05 +01003290
tierno7edb6752016-03-21 17:37:52 +01003291def vim_action_delete(mydb, tenant_id, datacenter, item, name):
3292 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02003293 if tenant_id == "any":
3294 tenant_id=None
3295
tiernoa2793912016-10-04 08:15:08 +00003296 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02003297 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02003298 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
3299 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02003300 items = content.values()[0]
3301 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02003302 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02003303 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02003304 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02003305 else: # it is a dict
3306 item_id = items["id"]
3307 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01003308
tiernoae4a8d12016-07-08 12:30:39 +02003309 try:
3310 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003311 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
3312 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
3313 if sdn_network_id != None:
3314 #Delete any port attachment to this network
3315 try:
3316 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
3317 except ovimException as e:
3318 raise NfvoException(
3319 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
3320 HTTP_Internal_Server_Error)
3321
3322 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
3323 for port in port_list:
3324 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
3325
3326 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
3327 try:
3328 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
3329 except db_base_Exception as e:
3330 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
3331 str(e), HTTP_Internal_Server_Error)
3332
3333 #Delete the SDN network
3334 try:
3335 ovim.delete_network(sdn_network_id)
3336 except ovimException as e:
3337 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
3338 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
3339 HTTP_Internal_Server_Error)
3340
tiernoae4a8d12016-07-08 12:30:39 +02003341 content = myvim.delete_network(item_id)
3342 elif item=="tenants":
3343 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01003344 elif item == "images":
3345 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02003346 else:
tierno42026a02017-02-10 15:13:40 +01003347 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02003348 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003349 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
3350 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02003351
tiernof97fd272016-07-11 14:32:37 +02003352 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01003353
tiernob3d36742017-03-03 23:51:05 +01003354
tierno7edb6752016-03-21 17:37:52 +01003355def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
3356 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003357 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02003358 if tenant_id == "any":
3359 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00003360 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02003361 try:
3362 if item=="networks":
3363 net = descriptor["network"]
3364 net_name = net.pop("name")
3365 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02003366 net_public = net.pop("shared", False)
3367 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01003368 net_vlan = net.pop("vlan", None)
3369 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 +02003370
3371 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
3372 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
3373 try:
3374 sdn_network = {}
3375 sdn_network['vlan'] = net_vlan
3376 sdn_network['type'] = net_type
3377 sdn_network['name'] = net_name
3378 ovim_content = ovim.new_network(sdn_network)
3379 except ovimException as e:
3380 self.logger.error("ovimException creating SDN network={} ".format(
3381 sdn_network) + str(e), exc_info=True)
3382 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
3383 HTTP_Internal_Server_Error)
3384
3385 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
3386 # use instance_scenario_id=None to distinguish from real instaces of nets
3387 correspondence = {'instance_scenario_id': None, 'sdn_net_id': ovim_content, 'vim_net_id': content}
3388 #obtain datacenter_tenant_id
3389 correspondence['datacenter_tenant_id'] = mydb.get_rows(SELECT=('uuid',), FROM='datacenter_tenants', WHERE={'datacenter_id': datacenter})[0]['uuid']
3390
3391 try:
3392 mydb.new_row('instance_nets', correspondence, add_uuid=True)
3393 except db_base_Exception as e:
3394 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
3395 str(e), HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02003396 elif item=="tenants":
3397 tenant = descriptor["tenant"]
3398 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
3399 else:
tierno42026a02017-02-10 15:13:40 +01003400 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02003401 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003402 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02003403
tierno7edb6752016-03-21 17:37:52 +01003404 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003405
3406def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003407 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003408 logger.debug('New SDN controller created with uuid {}'.format(data))
3409 return data
3410
3411def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003412 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003413 msg = 'SDN controller {} updated'.format(data)
3414 logger.debug(msg)
3415 return msg
3416
3417def sdn_controller_list(mydb, tenant_id, controller_id=None):
3418 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003419 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003420 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003421 data = ovim.show_of_controller(controller_id)
3422
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003423 msg = 'SDN controller list:\n {}'.format(data)
3424 logger.debug(msg)
3425 return data
3426
3427def sdn_controller_delete(mydb, tenant_id, controller_id):
3428 select_ = ('uuid', 'config')
3429 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
3430 for datacenter in datacenters:
3431 if datacenter['config']:
3432 config = yaml.load(datacenter['config'])
3433 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
3434 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), HTTP_Conflict)
3435
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003436 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003437 msg = 'SDN controller {} deleted'.format(data)
3438 logger.debug(msg)
3439 return msg
3440
3441def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
3442 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
3443 if len(controller) < 1:
3444 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), HTTP_Not_Found)
3445
3446 try:
3447 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
3448 except:
3449 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), HTTP_Bad_Request)
3450
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003451 sdn_controller = ovim.show_of_controller(sdn_controller_id)
3452 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003453
3454 maps = list()
3455 for compute_node in sdn_port_mapping:
3456 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
3457 element = dict()
3458 element["compute_node"] = compute_node["compute_node"]
3459 for port in compute_node["ports"]:
3460 element["pci"] = port.get("pci")
3461 element["switch_port"] = port.get("switch_port")
3462 element["switch_mac"] = port.get("switch_mac")
3463 if not element["pci"] or not (element["switch_port"] or element["switch_mac"]):
3464 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
3465 " or 'switch_mac'", HTTP_Bad_Request)
3466 maps.append(dict(element))
3467
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003468 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 +01003469
3470def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003471 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003472
3473 result = {
3474 "sdn-controller": None,
3475 "datacenter-id": datacenter_id,
3476 "dpid": None,
3477 "ports_mapping": list()
3478 }
3479
3480 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
3481 if datacenter['config']:
3482 config = yaml.load(datacenter['config'])
3483 if 'sdn-controller' in config:
3484 controller_id = config['sdn-controller']
3485 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
3486 result["sdn-controller"] = controller_id
3487 result["dpid"] = sdn_controller["dpid"]
3488
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003489 if result["sdn-controller"] == None:
3490 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), HTTP_Bad_Request)
3491 if result["dpid"] == None:
3492 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
3493 HTTP_Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003494
3495 if len(maps) == 0:
3496 return result
3497
3498 ports_correspondence_dict = dict()
3499 for link in maps:
3500 if result["sdn-controller"] != link["ofc_id"]:
3501 raise NfvoException("The sdn-controller specified for different port mappings differ", HTTP_Internal_Server_Error)
3502 if result["dpid"] != link["switch_dpid"]:
3503 raise NfvoException("The dpid specified for different port mappings differ", HTTP_Internal_Server_Error)
3504 element = dict()
3505 element["pci"] = link["pci"]
3506 if link["switch_port"]:
3507 element["switch_port"] = link["switch_port"]
3508 if link["switch_mac"]:
3509 element["switch_mac"] = link["switch_mac"]
3510
3511 if not link["compute_node"] in ports_correspondence_dict:
3512 content = dict()
3513 content["compute_node"] = link["compute_node"]
3514 content["ports"] = list()
3515 ports_correspondence_dict[link["compute_node"]] = content
3516
3517 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
3518
3519 for key in sorted(ports_correspondence_dict):
3520 result["ports_mapping"].append(ports_correspondence_dict[key])
3521
3522 return result
3523
3524def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02003525 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})