blob: 8b6a2e1390963d3442891d1302b929a0224ed17b [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
tierno8e690322017-08-10 15:58:50 +020041from uuid import uuid4
tiernof97fd272016-07-11 14:32:37 +020042from db_base import db_base_Exception
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010043
tiernob3d36742017-03-03 23:51:05 +010044import nfvo_db
45from threading import Lock
46from time import time
tierno01b3e172017-04-21 10:52:34 +020047from lib_osm_openvim import ovim as ovim_module
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +020048from lib_osm_openvim.ovim import ovimException
tierno7edb6752016-03-21 17:37:52 +010049
50global global_config
51global vimconn_imported
tierno73ad9e42016-09-12 18:11:11 +020052global logger
montesmoreno0c8def02016-12-22 12:16:23 +000053global default_volume_size
54default_volume_size = '5' #size in GB
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +010055global ovim
56ovim = None
tiernoc5651792017-03-27 10:50:43 +020057global_config = None
tiernoae4a8d12016-07-08 12:30:39 +020058
tierno42026a02017-02-10 15:13:40 +010059vimconn_imported = {} # dictionary with VIM type as key, loaded module as value
60vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
tiernob3d36742017-03-03 23:51:05 +010061vim_persistent_info = {}
tierno73ad9e42016-09-12 18:11:11 +020062logger = logging.getLogger('openmano.nfvo')
tiernob3d36742017-03-03 23:51:05 +010063task_lock = Lock()
tierno867ffe92017-03-27 12:50:34 +020064global_instance_tasks = {}
tiernob3d36742017-03-03 23:51:05 +010065last_task_id = 0.0
66db=None
67db_lock=Lock()
tierno7edb6752016-03-21 17:37:52 +010068
69class NfvoException(Exception):
tiernoae4a8d12016-07-08 12:30:39 +020070 def __init__(self, message, http_code):
71 self.http_code = http_code
72 Exception.__init__(self, message)
tierno7edb6752016-03-21 17:37:52 +010073
74
tiernob3d36742017-03-03 23:51:05 +010075def get_task_id():
76 global last_task_id
77 task_id = time()
78 if task_id <= last_task_id:
79 task_id = last_task_id + 0.000001
80 last_task_id = task_id
81 return "TASK.{:.6f}".format(task_id)
82
83
tierno867ffe92017-03-27 12:50:34 +020084def new_task(name, params, depends=None):
tiernob3d36742017-03-03 23:51:05 +010085 task_id = get_task_id()
86 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
87 if depends:
88 task["depends"] = depends
tiernob3d36742017-03-03 23:51:05 +010089 return task
90
91
92def is_task_id(id):
93 return True if id[:5] == "TASK." else False
94
95
tierno42026a02017-02-10 15:13:40 +010096def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id):
97 name = datacenter_name[:16]
98 if name not in vim_threads["names"]:
99 vim_threads["names"].append(name)
100 return name
tiernob3d36742017-03-03 23:51:05 +0100101 name = datacenter_name[:16] + "." + tenant_name[:16]
tierno42026a02017-02-10 15:13:40 +0100102 if name not in vim_threads["names"]:
103 vim_threads["names"].append(name)
104 return name
105 name = datacenter_id + "-" + tenant_id
106 vim_threads["names"].append(name)
107 return name
108
109
110def start_service(mydb):
tiernob3d36742017-03-03 23:51:05 +0100111 global db, global_config
112 db = nfvo_db.nfvo_db()
113 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 +0100114 global ovim
115
116 # Initialize openvim for SDN control
117 # TODO: Avoid static configuration by adding new parameters to openmanod.cfg
118 # TODO: review ovim.py to delete not needed configuration
119 ovim_configuration = {
tierno639520f2017-04-05 19:55:36 +0200120 'logger_name': 'openmano.ovim',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100121 'network_vlan_range_start': 1000,
122 'network_vlan_range_end': 4096,
tierno639520f2017-04-05 19:55:36 +0200123 'db_name': global_config["db_ovim_name"],
124 'db_host': global_config["db_ovim_host"],
125 'db_user': global_config["db_ovim_user"],
126 'db_passwd': global_config["db_ovim_passwd"],
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100127 'bridge_ifaces': {},
128 'mode': 'normal',
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100129 'network_type': 'bridge',
130 #TODO: log_level_of should not be needed. To be modified in ovim
131 'log_level_of': 'DEBUG'
132 }
tierno42026a02017-02-10 15:13:40 +0100133 try:
tierno46df9672017-05-26 13:12:21 +0200134 ovim = ovim_module.ovim(ovim_configuration)
135 ovim.start_service()
136
137 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
138 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
139 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
140 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
141 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
142 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
tierno42026a02017-02-10 15:13:40 +0100143 vims = mydb.get_rows(FROM=from_, SELECT=select_)
144 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200145 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
146 'datacenter_id': vim.get('datacenter_id')}
tierno42026a02017-02-10 15:13:40 +0100147 if vim["config"]:
148 extra.update(yaml.load(vim["config"]))
149 if vim.get('dt_config'):
150 extra.update(yaml.load(vim["dt_config"]))
151 if vim["type"] not in vimconn_imported:
152 module_info=None
153 try:
154 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200155 pkg = __import__("osm_ro." + module)
156 vim_conn = getattr(pkg, module)
157 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
158 # vim_conn = imp.load_module(vim["type"], *module_info)
tierno42026a02017-02-10 15:13:40 +0100159 vimconn_imported[vim["type"]] = vim_conn
160 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200161 # if module_info and module_info[0]:
162 # file.close(module_info[0])
tiernocdee8cc2017-04-25 13:42:06 +0200163 raise NfvoException("Unknown vim type '{}'. Cannot open file '{}.py'; {}: {}".format(
tiernob3d36742017-03-03 23:51:05 +0100164 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100165
tierno867ffe92017-03-27 12:50:34 +0200166 thread_id = vim['datacenter_tenant_id']
tiernob3d36742017-03-03 23:51:05 +0100167 vim_persistent_info[thread_id] = {}
tierno42026a02017-02-10 15:13:40 +0100168 try:
169 #if not tenant:
170 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
171 myvim = vimconn_imported[ vim["type"] ].vimconnector(
tiernob3d36742017-03-03 23:51:05 +0100172 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
173 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
174 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
175 user=vim['user'], passwd=vim['passwd'],
176 config=extra, persistent_info=vim_persistent_info[thread_id]
177 )
tierno42026a02017-02-10 15:13:40 +0100178 except Exception as e:
tierno46df9672017-05-26 13:12:21 +0200179 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
180 HTTP_Internal_Server_Error)
181 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['vim_tenant_id'], vim['vim_tenant_name'],
182 vim['vim_tenant_id'])
tiernob3d36742017-03-03 23:51:05 +0100183 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, vim['datacenter_name'],
tierno867ffe92017-03-27 12:50:34 +0200184 vim['datacenter_tenant_id'], db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +0100185 new_thread.start()
tierno42026a02017-02-10 15:13:40 +0100186 vim_threads["running"][thread_id] = new_thread
187 except db_base_Exception as e:
188 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno46df9672017-05-26 13:12:21 +0200189 except ovim_module.ovimException as e:
190 message = str(e)
191 if message[:22] == "DATABASE wrong version":
192 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
193 "at host {dbhost}".format(
194 msg=message[22:-3], dbname=global_config["db_ovim_name"],
195 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
196 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
197 raise NfvoException(message, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100198
tierno867ffe92017-03-27 12:50:34 +0200199
tierno42026a02017-02-10 15:13:40 +0100200def stop_service():
tiernoc5651792017-03-27 10:50:43 +0200201 global ovim, global_config
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +0100202 if ovim:
203 ovim.stop_service()
tierno42026a02017-02-10 15:13:40 +0100204 for thread_id,thread in vim_threads["running"].items():
tierno867ffe92017-03-27 12:50:34 +0200205 thread.insert_task(new_task("exit", None))
tierno42026a02017-02-10 15:13:40 +0100206 vim_threads["deleting"][thread_id] = thread
tiernob3d36742017-03-03 23:51:05 +0100207 vim_threads["running"] = {}
tiernoc5651792017-03-27 10:50:43 +0200208 if global_config and global_config.get("console_thread"):
209 for thread in global_config["console_thread"]:
210 thread.terminate = True
tiernob3d36742017-03-03 23:51:05 +0100211
tierno6ddeded2017-05-16 15:40:26 +0200212def get_version():
213 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
214 global_config["version_date"] ))
215
tierno42026a02017-02-10 15:13:40 +0100216
tierno7edb6752016-03-21 17:37:52 +0100217def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
218 '''Obtain flavorList
219 return result, content:
220 <0, error_text upon error
221 nb_records, flavor_list on success
222 '''
223 WHERE_dict={}
224 WHERE_dict['vnf_id'] = vnf_id
225 if nfvo_tenant is not None:
226 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100227
tierno7edb6752016-03-21 17:37:52 +0100228 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
229 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
tiernof97fd272016-07-11 14:32:37 +0200230 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
231 #print "get_flavor_list result:", result
232 #print "get_flavor_list content:", content
tierno7edb6752016-03-21 17:37:52 +0100233 flavorList=[]
tiernof97fd272016-07-11 14:32:37 +0200234 for flavor in flavors:
tierno7edb6752016-03-21 17:37:52 +0100235 flavorList.append(flavor['flavor_id'])
tiernof97fd272016-07-11 14:32:37 +0200236 return flavorList
tierno7edb6752016-03-21 17:37:52 +0100237
tiernob3d36742017-03-03 23:51:05 +0100238
tierno7edb6752016-03-21 17:37:52 +0100239def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
240 '''Obtain imageList
241 return result, content:
242 <0, error_text upon error
243 nb_records, flavor_list on success
244 '''
245 WHERE_dict={}
246 WHERE_dict['vnf_id'] = vnf_id
247 if nfvo_tenant is not None:
248 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
tierno42026a02017-02-10 15:13:40 +0100249
tierno7edb6752016-03-21 17:37:52 +0100250 #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 +0200251 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 +0100252 imageList=[]
tiernof97fd272016-07-11 14:32:37 +0200253 for image in images:
tierno7edb6752016-03-21 17:37:52 +0100254 imageList.append(image['image_id'])
tiernof97fd272016-07-11 14:32:37 +0200255 return imageList
tierno7edb6752016-03-21 17:37:52 +0100256
tiernob3d36742017-03-03 23:51:05 +0100257
tiernoa2793912016-10-04 08:15:08 +0000258def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
259 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None):
tierno7edb6752016-03-21 17:37:52 +0100260 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
tierno42026a02017-02-10 15:13:40 +0100261 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
tierno7edb6752016-03-21 17:37:52 +0100262 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
tiernobe41e222016-09-02 15:16:13 +0200263 raise exception upon error
tierno7edb6752016-03-21 17:37:52 +0100264 '''
265 WHERE_dict={}
266 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
267 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
tiernoa2793912016-10-04 08:15:08 +0000268 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
tierno7edb6752016-03-21 17:37:52 +0100269 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
270 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
tiernoa2793912016-10-04 08:15:08 +0000271 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
272 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
tierno7edb6752016-03-21 17:37:52 +0100273 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 +0000274 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 +0100275 '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 +0000276 'user','passwd', 'dt.config as dt_config')
tierno7edb6752016-03-21 17:37:52 +0100277 else:
278 from_ = 'datacenters as d'
279 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
tiernof97fd272016-07-11 14:32:37 +0200280 try:
281 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
282 vim_dict={}
283 for vim in vims:
tierno867ffe92017-03-27 12:50:34 +0200284 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
285 'datacenter_id': vim.get('datacenter_id')}
tierno8008c3a2016-10-13 15:34:28 +0000286 if vim["config"]:
tiernof97fd272016-07-11 14:32:37 +0200287 extra.update(yaml.load(vim["config"]))
tierno8008c3a2016-10-13 15:34:28 +0000288 if vim.get('dt_config'):
289 extra.update(yaml.load(vim["dt_config"]))
tiernof97fd272016-07-11 14:32:37 +0200290 if vim["type"] not in vimconn_imported:
291 module_info=None
292 try:
293 module = "vimconn_" + vim["type"]
tierno361275f2017-04-25 16:24:34 +0200294 pkg = __import__("osm_ro." + module)
295 vim_conn = getattr(pkg, module)
296 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
297 # vim_conn = imp.load_module(vim["type"], *module_info)
tiernof97fd272016-07-11 14:32:37 +0200298 vimconn_imported[vim["type"]] = vim_conn
299 except (IOError, ImportError) as e:
tierno361275f2017-04-25 16:24:34 +0200300 # if module_info and module_info[0]:
301 # file.close(module_info[0])
tiernof97fd272016-07-11 14:32:37 +0200302 raise NfvoException("Unknown vim type '{}'. Can not open file '{}.py'; {}: {}".format(
303 vim["type"], module, type(e).__name__, str(e)), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100304
tierno7edb6752016-03-21 17:37:52 +0100305 try:
tierno867ffe92017-03-27 12:50:34 +0200306 if 'datacenter_tenant_id' in vim:
307 thread_id = vim["datacenter_tenant_id"]
tiernob3d36742017-03-03 23:51:05 +0100308 if thread_id not in vim_persistent_info:
309 vim_persistent_info[thread_id] = {}
310 persistent_info = vim_persistent_info[thread_id]
311 else:
312 persistent_info = {}
tiernof97fd272016-07-11 14:32:37 +0200313 #if not tenant:
314 # return -HTTP_Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
315 vim_dict[ vim['datacenter_id'] ] = vimconn_imported[ vim["type"] ].vimconnector(
316 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
tiernob3d36742017-03-03 23:51:05 +0100317 tenant_id=vim.get('vim_tenant_id',vim_tenant),
318 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
tierno42026a02017-02-10 15:13:40 +0100319 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
tierno3ae39742016-09-07 12:17:51 +0200320 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
tiernob3d36742017-03-03 23:51:05 +0100321 config=extra, persistent_info=persistent_info
tiernof97fd272016-07-11 14:32:37 +0200322 )
323 except Exception as e:
324 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), HTTP_Internal_Server_Error)
325 return vim_dict
326 except db_base_Exception as e:
327 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
tierno42026a02017-02-10 15:13:40 +0100328
tiernob3d36742017-03-03 23:51:05 +0100329
tierno7edb6752016-03-21 17:37:52 +0100330def rollback(mydb, vims, rollback_list):
331 undeleted_items=[]
tierno42026a02017-02-10 15:13:40 +0100332 #delete things by reverse order
tierno7edb6752016-03-21 17:37:52 +0100333 for i in range(len(rollback_list)-1, -1, -1):
334 item = rollback_list[i]
335 if item["where"]=="vim":
336 if item["vim_id"] not in vims:
337 continue
tierno56d73d22017-08-02 13:53:02 +0200338 if is_task_id(item["uuid"]):
339 continue
340 vim = vims[item["vim_id"]]
tiernoae4a8d12016-07-08 12:30:39 +0200341 try:
342 if item["what"]=="image":
343 vim.delete_image(item["uuid"])
tiernof97fd272016-07-11 14:32:37 +0200344 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200345 elif item["what"]=="flavor":
346 vim.delete_flavor(item["uuid"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200347 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]})
tiernoae4a8d12016-07-08 12:30:39 +0200348 elif item["what"]=="network":
349 vim.delete_network(item["uuid"])
350 elif item["what"]=="vm":
351 vim.delete_vminstance(item["uuid"])
352 except vimconn.vimconnException as e:
353 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
354 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
tiernof97fd272016-07-11 14:32:37 +0200355 except db_base_Exception as e:
356 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 +0100357
tierno7edb6752016-03-21 17:37:52 +0100358 else: # where==mano
tiernof97fd272016-07-11 14:32:37 +0200359 try:
360 if item["what"]=="image":
361 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
362 elif item["what"]=="flavor":
363 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
364 except db_base_Exception as e:
365 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
366 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
tierno42026a02017-02-10 15:13:40 +0100367 if len(undeleted_items)==0:
tierno7edb6752016-03-21 17:37:52 +0100368 return True," Rollback successful."
369 else:
370 return False," Rollback fails to delete: " + str(undeleted_items)
tierno42026a02017-02-10 15:13:40 +0100371
tiernob3d36742017-03-03 23:51:05 +0100372
tiernoafed5f12017-01-26 17:57:43 +0100373def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
tierno7edb6752016-03-21 17:37:52 +0100374 global global_config
tierno42026a02017-02-10 15:13:40 +0100375 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
tierno7edb6752016-03-21 17:37:52 +0100376 vnfc_interfaces={}
377 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
tiernoafed5f12017-01-26 17:57:43 +0100378 name_dict = {}
tierno7edb6752016-03-21 17:37:52 +0100379 #dataplane interfaces
380 for numa in vnfc.get("numas",() ):
381 for interface in numa.get("interfaces",()):
tiernoafed5f12017-01-26 17:57:43 +0100382 if interface["name"] in name_dict:
383 raise NfvoException(
384 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
385 vnfc["name"], interface["name"]),
386 HTTP_Bad_Request)
387 name_dict[ interface["name"] ] = "underlay"
tierno7edb6752016-03-21 17:37:52 +0100388 #bridge interfaces
389 for interface in vnfc.get("bridge-ifaces",() ):
tiernoafed5f12017-01-26 17:57:43 +0100390 if interface["name"] in name_dict:
391 raise NfvoException(
392 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
393 vnfc["name"], interface["name"]),
394 HTTP_Bad_Request)
395 name_dict[ interface["name"] ] = "overlay"
396 vnfc_interfaces[ vnfc["name"] ] = name_dict
tierno36c0b172017-01-12 18:32:28 +0100397 # check bood-data info
tierno40e1bce2017-08-09 09:12:04 +0200398 # if "boot-data" in vnfc:
399 # # check that user-data is incompatible with users and config-files
400 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
401 # raise NfvoException(
402 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
403 # HTTP_Bad_Request)
tierno36c0b172017-01-12 18:32:28 +0100404
tierno7edb6752016-03-21 17:37:52 +0100405 #check if the info in external_connections matches with the one in the vnfcs
406 name_list=[]
407 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
408 if external_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100409 raise NfvoException(
410 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
411 external_connection["name"]),
412 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100413 name_list.append(external_connection["name"])
414 if external_connection["VNFC"] not in vnfc_interfaces:
tiernoafed5f12017-01-26 17:57:43 +0100415 raise NfvoException(
416 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
417 external_connection["name"], external_connection["VNFC"]),
418 HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +0100419
tierno7edb6752016-03-21 17:37:52 +0100420 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
tiernoafed5f12017-01-26 17:57:43 +0100421 raise NfvoException(
422 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
423 external_connection["name"],
424 external_connection["local_iface_name"]),
425 HTTP_Bad_Request )
tierno42026a02017-02-10 15:13:40 +0100426
tierno7edb6752016-03-21 17:37:52 +0100427 #check if the info in internal_connections matches with the one in the vnfcs
428 name_list=[]
429 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
430 if internal_connection["name"] in name_list:
tiernoafed5f12017-01-26 17:57:43 +0100431 raise NfvoException(
432 "Error at vnf:internal-connections:name, value '%s' already used as an internal-connection".format(
433 internal_connection["name"]),
434 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100435 name_list.append(internal_connection["name"])
436 #We should check that internal-connections of type "ptp" have only 2 elements
tiernoafed5f12017-01-26 17:57:43 +0100437
438 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
439 raise NfvoException(
440 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
441 internal_connection["name"],
442 'ptp' if vnf_descriptor_version==1 else 'e-line',
443 'data' if vnf_descriptor_version==1 else "e-lan"),
444 HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100445 for port in internal_connection["elements"]:
tiernoafed5f12017-01-26 17:57:43 +0100446 vnf = port["VNFC"]
447 iface = port["local_iface_name"]
448 if vnf not in vnfc_interfaces:
449 raise NfvoException(
450 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
451 internal_connection["name"], vnf),
452 HTTP_Bad_Request)
453 if iface not in vnfc_interfaces[ vnf ]:
454 raise NfvoException(
455 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
456 internal_connection["name"], iface),
457 HTTP_Bad_Request)
458 return -HTTP_Bad_Request,
459 if vnf_descriptor_version==1 and "type" not in internal_connection:
460 if vnfc_interfaces[vnf][iface] == "overlay":
461 internal_connection["type"] = "bridge"
462 else:
463 internal_connection["type"] = "data"
464 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
465 if vnfc_interfaces[vnf][iface] == "overlay":
466 internal_connection["implementation"] = "overlay"
467 else:
468 internal_connection["implementation"] = "underlay"
469 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
470 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
471 raise NfvoException(
472 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
473 internal_connection["name"],
474 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
475 'data' if vnf_descriptor_version==1 else 'underlay'),
476 HTTP_Bad_Request)
477 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
478 vnfc_interfaces[vnf][iface] == "underlay":
479 raise NfvoException(
480 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
481 internal_connection["name"], iface,
482 'data' if vnf_descriptor_version==1 else 'underlay',
483 'bridge' if vnf_descriptor_version==1 else 'overlay'),
484 HTTP_Bad_Request)
485
tierno7edb6752016-03-21 17:37:52 +0100486
tierno56d73d22017-08-02 13:53:02 +0200487def 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 +0100488 #look if image exist
489 if only_create_at_vim:
490 image_mano_id = image_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000491 if return_on_error == None:
492 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100493 else:
garciadeblas14480452017-01-10 13:08:07 +0100494 if image_dict['location']:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200495 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
496 else:
497 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
tiernof97fd272016-07-11 14:32:37 +0200498 if len(images)>=1:
499 image_mano_id = images[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100500 else:
garciadeblas14480452017-01-10 13:08:07 +0100501 #create image in MANO DB
tierno7edb6752016-03-21 17:37:52 +0100502 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
garciadeblasb69fa9f2016-09-28 12:04:10 +0200503 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
504 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
tierno7edb6752016-03-21 17:37:52 +0100505 }
garciadeblas14480452017-01-10 13:08:07 +0100506 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
tiernof97fd272016-07-11 14:32:37 +0200507 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
508 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100509 #create image at every vim
510 for vim_id,vim in vims.iteritems():
511 image_created="false"
512 #look at database
tiernof97fd272016-07-11 14:32:37 +0200513 image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100514 #look at VIM if this image exist
tiernoae4a8d12016-07-08 12:30:39 +0200515 try:
garciadeblasb69fa9f2016-09-28 12:04:10 +0200516 if image_dict['location'] is not None:
517 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
518 else:
garciadeblas30833382017-01-09 09:46:31 +0100519 filter_dict = {}
520 filter_dict['name'] = image_dict['universal_name']
521 if image_dict.get('checksum') != None:
522 filter_dict['checksum'] = image_dict['checksum']
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000523 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200524 vim_images = vim.get_image_list(filter_dict)
garciadeblas14480452017-01-10 13:08:07 +0100525 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200526 if len(vim_images) > 1:
garciadeblas3fa2c052017-01-05 12:00:08 +0100527 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), HTTP_Conflict)
garciadeblasbb6a1ed2016-09-30 14:02:09 +0000528 elif len(vim_images) == 0:
garciadeblas3fa2c052017-01-05 12:00:08 +0100529 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
garciadeblasb69fa9f2016-09-28 12:04:10 +0200530 else:
garciadeblas14480452017-01-10 13:08:07 +0100531 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
532 image_vim_id = vim_images[0]['id']
garciadeblasb69fa9f2016-09-28 12:04:10 +0200533
tiernoae4a8d12016-07-08 12:30:39 +0200534 except vimconn.vimconnNotFoundException as e:
garciadeblas14480452017-01-10 13:08:07 +0100535 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
tierno42026a02017-02-10 15:13:40 +0100536 try:
garciadeblas14480452017-01-10 13:08:07 +0100537 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
538 if image_dict['location']:
539 image_vim_id = vim.new_image(image_dict)
540 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
541 image_created="true"
542 else:
garciadeblasb6153a22017-02-06 15:38:33 +0100543 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
544 raise vimconn.vimconnException(str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200545 except vimconn.vimconnException as e:
546 if return_on_error:
garciadeblas14480452017-01-10 13:08:07 +0100547 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200548 raise
tierno5e91eb82016-10-04 09:39:07 +0000549 image_vim_id = None
garciadeblas14480452017-01-10 13:08:07 +0100550 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
tiernoae4a8d12016-07-08 12:30:39 +0200551 continue
552 except vimconn.vimconnException as e:
tierno5e91eb82016-10-04 09:39:07 +0000553 if return_on_error:
554 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
555 raise
garciadeblasb69fa9f2016-09-28 12:04:10 +0200556 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
tierno5e91eb82016-10-04 09:39:07 +0000557 image_vim_id = None
garciadeblas30833382017-01-09 09:46:31 +0100558 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200559 #if we reach here, the image has been created or existed
tiernof97fd272016-07-11 14:32:37 +0200560 if len(image_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100561 #add new vim_id at datacenters_images
562 mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created})
563 elif image_db[0]["vim_id"]!=image_vim_id:
564 #modify existing vim_id at datacenters_images
565 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 +0100566
tiernof97fd272016-07-11 14:32:37 +0200567 return image_vim_id if only_create_at_vim else image_mano_id
tierno7edb6752016-03-21 17:37:52 +0100568
tiernob3d36742017-03-03 23:51:05 +0100569
tierno5e91eb82016-10-04 09:39:07 +0000570def 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 +0100571 temp_flavor_dict= {'disk':flavor_dict.get('disk',1),
572 'ram':flavor_dict.get('ram'),
573 'vcpus':flavor_dict.get('vcpus'),
574 }
575 if 'extended' in flavor_dict and flavor_dict['extended']==None:
576 del flavor_dict['extended']
577 if 'extended' in flavor_dict:
578 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
579
580 #look if flavor exist
581 if only_create_at_vim:
582 flavor_mano_id = flavor_dict['uuid']
tierno5e91eb82016-10-04 09:39:07 +0000583 if return_on_error == None:
584 return_on_error = True
tierno7edb6752016-03-21 17:37:52 +0100585 else:
tiernof97fd272016-07-11 14:32:37 +0200586 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
587 if len(flavors)>=1:
588 flavor_mano_id = flavors[0]['uuid']
tierno7edb6752016-03-21 17:37:52 +0100589 else:
590 #create flavor
591 #create one by one the images of aditional disks
592 dev_image_list=[] #list of images
593 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
594 dev_nb=0
595 for device in flavor_dict['extended'].get('devices',[]):
garciadeblas41f18be2016-10-04 09:09:58 +0200596 if "image" not in device and "image name" not in device:
tierno7edb6752016-03-21 17:37:52 +0100597 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200598 image_dict={}
599 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
600 image_dict['universal_name']=device.get('image name')
601 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
602 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100603 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200604 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100605 image_metadata_dict = device.get('image metadata', None)
606 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100607 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100608 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
609 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200610 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
611 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
tierno7edb6752016-03-21 17:37:52 +0100612 dev_image_list.append(image_id)
tierno42026a02017-02-10 15:13:40 +0100613 dev_nb += 1
tierno7edb6752016-03-21 17:37:52 +0100614 temp_flavor_dict['name'] = flavor_dict['name']
615 temp_flavor_dict['description'] = flavor_dict.get('description',None)
tiernof97fd272016-07-11 14:32:37 +0200616 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
617 flavor_mano_id= content
618 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100619 #create flavor at every vim
620 if 'uuid' in flavor_dict:
621 del flavor_dict['uuid']
622 flavor_vim_id=None
623 for vim_id,vim in vims.items():
624 flavor_created="false"
625 #look at database
tiernof97fd272016-07-11 14:32:37 +0200626 flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id})
tierno7edb6752016-03-21 17:37:52 +0100627 #look at VIM if this flavor exist SKIPPED
628 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
629 #if res_vim < 0:
630 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
631 # continue
632 #elif res_vim==0:
tierno42026a02017-02-10 15:13:40 +0100633
tierno7edb6752016-03-21 17:37:52 +0100634 #Create the flavor in VIM
635 #Translate images at devices from MANO id to VIM id
montesmoreno0c8def02016-12-22 12:16:23 +0000636 disk_list = []
tierno7edb6752016-03-21 17:37:52 +0100637 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
638 #make a copy of original devices
639 devices_original=[]
montesmoreno0c8def02016-12-22 12:16:23 +0000640
tierno7edb6752016-03-21 17:37:52 +0100641 for device in flavor_dict["extended"].get("devices",[]):
642 dev={}
643 dev.update(device)
644 devices_original.append(dev)
645 if 'image' in device:
646 del device['image']
647 if 'image metadata' in device:
648 del device['image metadata']
649 dev_nb=0
650 for index in range(0,len(devices_original)) :
651 device=devices_original[index]
montesmoreno0c8def02016-12-22 12:16:23 +0000652 if "image" not in device and "image name" not in device:
653 if 'size' in device:
654 disk_list.append({'size': device.get('size', default_volume_size)})
tierno7edb6752016-03-21 17:37:52 +0100655 continue
garciadeblasb69fa9f2016-09-28 12:04:10 +0200656 image_dict={}
657 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
658 image_dict['universal_name']=device.get('image name')
659 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
660 image_dict['location']=device.get('image')
garciadeblas14480452017-01-10 13:08:07 +0100661 #image_dict['new_location']=device.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200662 image_dict['checksum']=device.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100663 image_metadata_dict = device.get('image metadata', None)
664 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100665 if image_metadata_dict != None:
tierno7edb6752016-03-21 17:37:52 +0100666 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
667 image_dict['metadata']=image_metadata_str
tiernof97fd272016-07-11 14:32:37 +0200668 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 +0100669 image_dict["uuid"]=image_mano_id
tiernof97fd272016-07-11 14:32:37 +0200670 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 +0000671
672 #save disk information (image must be based on and size
673 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
674
tierno7edb6752016-03-21 17:37:52 +0100675 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
676 dev_nb += 1
tiernof97fd272016-07-11 14:32:37 +0200677 if len(flavor_db)>0:
tierno7edb6752016-03-21 17:37:52 +0100678 #check that this vim_id exist in VIM, if not create
679 flavor_vim_id=flavor_db[0]["vim_id"]
tiernoae4a8d12016-07-08 12:30:39 +0200680 try:
681 vim.get_flavor(flavor_vim_id)
682 continue #flavor exist
683 except vimconn.vimconnException:
684 pass
tierno7edb6752016-03-21 17:37:52 +0100685 #create flavor at vim
tiernoae4a8d12016-07-08 12:30:39 +0200686 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
687 try:
tiernocf157a82017-01-30 14:07:06 +0100688 flavor_vim_id = None
689 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
690 flavor_create="false"
691 except vimconn.vimconnException as e:
692 pass
693 try:
694 if not flavor_vim_id:
695 flavor_vim_id = vim.new_flavor(flavor_dict)
696 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
697 flavor_created="true"
tiernoae4a8d12016-07-08 12:30:39 +0200698 except vimconn.vimconnException as e:
699 if return_on_error:
700 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tiernof97fd272016-07-11 14:32:37 +0200701 raise
tiernoae4a8d12016-07-08 12:30:39 +0200702 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
tierno5e91eb82016-10-04 09:39:07 +0000703 flavor_vim_id = None
tiernoae4a8d12016-07-08 12:30:39 +0200704 continue
tierno7edb6752016-03-21 17:37:52 +0100705 #if reach here the flavor has been create or exist
tiernof97fd272016-07-11 14:32:37 +0200706 if len(flavor_db)==0:
tierno7edb6752016-03-21 17:37:52 +0100707 #add new vim_id at datacenters_flavors
montesmoreno0c8def02016-12-22 12:16:23 +0000708 extended_devices_yaml = None
709 if len(disk_list) > 0:
710 extended_devices = dict()
711 extended_devices['disks'] = disk_list
712 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
713 mydb.new_row('datacenters_flavors',
714 {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id,
715 'created':flavor_created,'extended': extended_devices_yaml})
tierno7edb6752016-03-21 17:37:52 +0100716 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
717 #modify existing vim_id at datacenters_flavors
718 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 +0100719
tiernof97fd272016-07-11 14:32:37 +0200720 return flavor_vim_id if only_create_at_vim else flavor_mano_id
tierno7edb6752016-03-21 17:37:52 +0100721
tiernob3d36742017-03-03 23:51:05 +0100722
tierno7edb6752016-03-21 17:37:52 +0100723def new_vnf(mydb, tenant_id, vnf_descriptor):
724 global global_config
tierno42026a02017-02-10 15:13:40 +0100725
tierno7edb6752016-03-21 17:37:52 +0100726 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +0100727 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
tierno7edb6752016-03-21 17:37:52 +0100728 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +0100729 vims = {}
tierno7edb6752016-03-21 17:37:52 +0100730 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +0100731 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100732 if "tenant_id" in vnf_descriptor["vnf"]:
733 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +0200734 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
735 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +0100736 else:
737 vnf_descriptor['vnf']['tenant_id'] = tenant_id
738 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +0100739 if global_config["auto_push_VNF_to_VIMs"]:
740 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100741
742 # Step 4. Review the descriptor and add missing fields
743 #print vnf_descriptor
tiernof97fd272016-07-11 14:32:37 +0200744 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
tierno7edb6752016-03-21 17:37:52 +0100745 vnf_name = vnf_descriptor['vnf']['name']
746 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
747 if "physical" in vnf_descriptor['vnf']:
748 del vnf_descriptor['vnf']['physical']
749 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +0100750
tierno42026a02017-02-10 15:13:40 +0100751 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200752 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
753 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +0100754
tierno7edb6752016-03-21 17:37:52 +0100755 #For each VNFC, we add it to the VNFCDict and we create a flavor.
756 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
757 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
tierno7edb6752016-03-21 17:37:52 +0100758 try:
tiernof97fd272016-07-11 14:32:37 +0200759 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100760 for vnfc in vnf_descriptor['vnf']['VNFC']:
761 VNFCitem={}
762 VNFCitem["name"] = vnfc['name']
mirabal29356312017-07-27 12:21:22 +0200763 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +0100764 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +0100765
tiernof97fd272016-07-11 14:32:37 +0200766 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +0100767
tierno7edb6752016-03-21 17:37:52 +0100768 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200769 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 +0100770 myflavorDict["description"] = VNFCitem["description"]
771 myflavorDict["ram"] = vnfc.get("ram", 0)
772 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
773 myflavorDict["disk"] = vnfc.get("disk", 1)
774 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +0100775
tierno7edb6752016-03-21 17:37:52 +0100776 devices = vnfc.get("devices")
777 if devices != None:
778 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +0100779
tierno7edb6752016-03-21 17:37:52 +0100780 # TODO:
781 # 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 +0100782 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
783
tierno7edb6752016-03-21 17:37:52 +0100784 # Previous code has been commented
785 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
786 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
787 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
788 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
789 #else:
790 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
791 # if result2:
792 # print "Error creating flavor: unknown processor model. Rollback successful."
793 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
794 # else:
795 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
796 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +0100797
tierno7edb6752016-03-21 17:37:52 +0100798 if 'numas' in vnfc and len(vnfc['numas'])>0:
799 myflavorDict['extended']['numas'] = vnfc['numas']
800
801 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +0100802
tierno7edb6752016-03-21 17:37:52 +0100803 # Step 6.2 New flavors are created in the VIM
tiernof97fd272016-07-11 14:32:37 +0200804 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
tierno7edb6752016-03-21 17:37:52 +0100805
tiernof97fd272016-07-11 14:32:37 +0200806 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
tierno7edb6752016-03-21 17:37:52 +0100807 VNFCitem["flavor_id"] = flavor_id
808 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +0100809
tiernof97fd272016-07-11 14:32:37 +0200810 logger.debug("Creating new images in the VIM for each VNFC")
tierno7edb6752016-03-21 17:37:52 +0100811 # Step 6.3 New images are created in the VIM
812 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +0100813 #This "for" loop might be integrated with the previous one
tierno7edb6752016-03-21 17:37:52 +0100814 #In case this integration is made, the VNFCDict might become a VNFClist.
815 for vnfc in vnf_descriptor['vnf']['VNFC']:
tiernof97fd272016-07-11 14:32:37 +0200816 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200817 image_dict={}
818 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
819 image_dict['universal_name']=vnfc.get('image name')
820 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
821 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100822 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200823 image_dict['checksum']=vnfc.get('image checksum')
tierno7edb6752016-03-21 17:37:52 +0100824 image_metadata_dict = vnfc.get('image metadata', None)
825 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100826 if image_metadata_dict is not None:
tierno7edb6752016-03-21 17:37:52 +0100827 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
828 image_dict['metadata']=image_metadata_str
829 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
tiernof97fd272016-07-11 14:32:37 +0200830 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
831 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
tierno7edb6752016-03-21 17:37:52 +0100832 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200833 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +0200834 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +0100835 if vnfc.get("boot-data"):
836 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
tierno7edb6752016-03-21 17:37:52 +0100837
tierno42026a02017-02-10 15:13:40 +0100838
tiernof97fd272016-07-11 14:32:37 +0200839 # Step 7. Storing the VNF descriptor in the repository
840 if "descriptor" not in vnf_descriptor["vnf"]:
841 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +0100842
tiernof97fd272016-07-11 14:32:37 +0200843 # Step 8. Adding the VNF to the NFVO DB
844 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
845 return vnf_id
846 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
tierno7edb6752016-03-21 17:37:52 +0100847 _, message = rollback(mydb, vims, rollback_list)
tiernof97fd272016-07-11 14:32:37 +0200848 if isinstance(e, db_base_Exception):
849 error_text = "Exception at database"
850 elif isinstance(e, KeyError):
851 error_text = "KeyError exception "
852 e.http_code = HTTP_Internal_Server_Error
853 else:
854 error_text = "Exception at VIM"
855 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
856 #logger.error("start_scenario %s", error_text)
857 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +0100858
tiernob3d36742017-03-03 23:51:05 +0100859
garciadeblas9f8456e2016-09-05 05:02:59 +0200860def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
861 global global_config
tierno42026a02017-02-10 15:13:40 +0100862
garciadeblas9f8456e2016-09-05 05:02:59 +0200863 # Step 1. Check the VNF descriptor
tiernoafed5f12017-01-26 17:57:43 +0100864 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
garciadeblas9f8456e2016-09-05 05:02:59 +0200865 # Step 2. Check tenant exist
tiernod29b1d32017-01-25 11:02:52 +0100866 vims = {}
garciadeblas9f8456e2016-09-05 05:02:59 +0200867 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +0100868 check_tenant(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +0200869 if "tenant_id" in vnf_descriptor["vnf"]:
870 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
871 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
872 HTTP_Unauthorized)
873 else:
874 vnf_descriptor['vnf']['tenant_id'] = tenant_id
875 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernod29b1d32017-01-25 11:02:52 +0100876 if global_config["auto_push_VNF_to_VIMs"]:
877 vims = get_vim(mydb, tenant_id)
garciadeblas9f8456e2016-09-05 05:02:59 +0200878
879 # Step 4. Review the descriptor and add missing fields
880 #print vnf_descriptor
881 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
882 vnf_name = vnf_descriptor['vnf']['name']
883 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
884 if "physical" in vnf_descriptor['vnf']:
885 del vnf_descriptor['vnf']['physical']
886 #print vnf_descriptor
tiernoafed5f12017-01-26 17:57:43 +0100887
tierno42026a02017-02-10 15:13:40 +0100888 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
garciadeblas9f8456e2016-09-05 05:02:59 +0200889 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
890 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
tierno42026a02017-02-10 15:13:40 +0100891
garciadeblas9f8456e2016-09-05 05:02:59 +0200892 #For each VNFC, we add it to the VNFCDict and we create a flavor.
893 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
894 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
895 try:
896 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
897 for vnfc in vnf_descriptor['vnf']['VNFC']:
898 VNFCitem={}
899 VNFCitem["name"] = vnfc['name']
900 VNFCitem["description"] = vnfc.get("description", 'VM %s of the VNF %s' %(vnfc['name'],vnf_name))
tierno42026a02017-02-10 15:13:40 +0100901
garciadeblas9f8456e2016-09-05 05:02:59 +0200902 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
tierno42026a02017-02-10 15:13:40 +0100903
garciadeblas9f8456e2016-09-05 05:02:59 +0200904 myflavorDict = {}
garciadeblasb69fa9f2016-09-28 12:04:10 +0200905 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 +0200906 myflavorDict["description"] = VNFCitem["description"]
907 myflavorDict["ram"] = vnfc.get("ram", 0)
908 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
909 myflavorDict["disk"] = vnfc.get("disk", 1)
910 myflavorDict["extended"] = {}
tierno42026a02017-02-10 15:13:40 +0100911
garciadeblas9f8456e2016-09-05 05:02:59 +0200912 devices = vnfc.get("devices")
913 if devices != None:
914 myflavorDict["extended"]["devices"] = devices
tierno42026a02017-02-10 15:13:40 +0100915
garciadeblas9f8456e2016-09-05 05:02:59 +0200916 # TODO:
917 # 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 +0100918 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
919
garciadeblas9f8456e2016-09-05 05:02:59 +0200920 # Previous code has been commented
921 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
922 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
923 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
924 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
925 #else:
926 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
927 # if result2:
928 # print "Error creating flavor: unknown processor model. Rollback successful."
929 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
930 # else:
931 # return -HTTP_Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
932 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
tierno42026a02017-02-10 15:13:40 +0100933
garciadeblas9f8456e2016-09-05 05:02:59 +0200934 if 'numas' in vnfc and len(vnfc['numas'])>0:
935 myflavorDict['extended']['numas'] = vnfc['numas']
936
937 #print myflavorDict
tierno42026a02017-02-10 15:13:40 +0100938
garciadeblas9f8456e2016-09-05 05:02:59 +0200939 # Step 6.2 New flavors are created in the VIM
940 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
941
942 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
943 VNFCitem["flavor_id"] = flavor_id
944 VNFCDict[vnfc['name']] = VNFCitem
tierno42026a02017-02-10 15:13:40 +0100945
garciadeblas9f8456e2016-09-05 05:02:59 +0200946 logger.debug("Creating new images in the VIM for each VNFC")
947 # Step 6.3 New images are created in the VIM
948 #For each VNFC, we must create the appropriate image.
tierno42026a02017-02-10 15:13:40 +0100949 #This "for" loop might be integrated with the previous one
garciadeblas9f8456e2016-09-05 05:02:59 +0200950 #In case this integration is made, the VNFCDict might become a VNFClist.
951 for vnfc in vnf_descriptor['vnf']['VNFC']:
952 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
garciadeblasb69fa9f2016-09-28 12:04:10 +0200953 image_dict={}
954 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
955 image_dict['universal_name']=vnfc.get('image name')
956 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
957 image_dict['location']=vnfc.get('VNFC image')
garciadeblas14480452017-01-10 13:08:07 +0100958 #image_dict['new_location']=vnfc.get('image location')
garciadeblasb69fa9f2016-09-28 12:04:10 +0200959 image_dict['checksum']=vnfc.get('image checksum')
garciadeblas9f8456e2016-09-05 05:02:59 +0200960 image_metadata_dict = vnfc.get('image metadata', None)
961 image_metadata_str = None
tierno42026a02017-02-10 15:13:40 +0100962 if image_metadata_dict is not None:
garciadeblas9f8456e2016-09-05 05:02:59 +0200963 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
964 image_dict['metadata']=image_metadata_str
965 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
966 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
967 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
968 VNFCDict[vnfc['name']]["image_id"] = image_id
garciadeblasb69fa9f2016-09-28 12:04:10 +0200969 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
tierno8e690322017-08-10 15:58:50 +0200970 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
tierno36c0b172017-01-12 18:32:28 +0100971 if vnfc.get("boot-data"):
972 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +0200973
garciadeblas9f8456e2016-09-05 05:02:59 +0200974 # Step 7. Storing the VNF descriptor in the repository
975 if "descriptor" not in vnf_descriptor["vnf"]:
976 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +0100977
garciadeblas9f8456e2016-09-05 05:02:59 +0200978 # Step 8. Adding the VNF to the NFVO DB
979 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
980 return vnf_id
981 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
982 _, message = rollback(mydb, vims, rollback_list)
983 if isinstance(e, db_base_Exception):
984 error_text = "Exception at database"
985 elif isinstance(e, KeyError):
986 error_text = "KeyError exception "
987 e.http_code = HTTP_Internal_Server_Error
988 else:
989 error_text = "Exception at VIM"
990 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
991 #logger.error("start_scenario %s", error_text)
992 raise NfvoException(error_text, e.http_code)
993
tiernob3d36742017-03-03 23:51:05 +0100994
tierno7edb6752016-03-21 17:37:52 +0100995def get_vnf_id(mydb, tenant_id, vnf_id):
996 #check valid tenant_id
tierno42026a02017-02-10 15:13:40 +0100997 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +0100998 #obtain data
999 where_or = {}
1000 if tenant_id != "any":
1001 where_or["tenant_id"] = tenant_id
1002 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001003 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1004
tiernof97fd272016-07-11 14:32:37 +02001005 vnf_id=vnf["uuid"]
tierno7edb6752016-03-21 17:37:52 +01001006 filter_keys = ('uuid','name','description','public', "tenant_id", "created_at")
tiernof97fd272016-07-11 14:32:37 +02001007 filtered_content = dict( (k,v) for k,v in vnf.iteritems() if k in filter_keys )
tierno7edb6752016-03-21 17:37:52 +01001008 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1009 data={'vnf' : filtered_content}
1010 #GET VM
tiernof97fd272016-07-11 14:32:37 +02001011 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
tierno36c0b172017-01-12 18:32:28 +01001012 SELECT=('vms.uuid as uuid','vms.name as name', 'vms.description as description', 'boot_data'),
tierno7edb6752016-03-21 17:37:52 +01001013 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001014 if len(content)==0:
1015 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno36c0b172017-01-12 18:32:28 +01001016 # change boot_data into boot-data
1017 for vm in content:
1018 if vm.get("boot_data"):
1019 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1020 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +01001021
1022 data['vnf']['VNFC'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001023 #TODO: GET all the information from a VNFC and include it in the output.
tierno42026a02017-02-10 15:13:40 +01001024
tierno7edb6752016-03-21 17:37:52 +01001025 #GET NET
tierno42026a02017-02-10 15:13:40 +01001026 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
tierno7edb6752016-03-21 17:37:52 +01001027 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1028 WHERE={'vnfs.uuid': vnf_id} )
tiernof97fd272016-07-11 14:32:37 +02001029 data['vnf']['nets'] = content
garciadeblas9f8456e2016-09-05 05:02:59 +02001030
1031 #GET ip-profile for each net
1032 for net in data['vnf']['nets']:
1033 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1034 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1035 WHERE={'net_id': net["uuid"]} )
1036 if len(ipprofiles)==1:
1037 net["ip_profile"] = ipprofiles[0]
1038 elif len(ipprofiles)>1:
1039 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 +01001040
1041
garciadeblas9f8456e2016-09-05 05:02:59 +02001042 #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 +01001043
garciadeblas9f8456e2016-09-05 05:02:59 +02001044 #GET External Interfaces
tiernof97fd272016-07-11 14:32:37 +02001045 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 +01001046 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1047 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
tierno42026a02017-02-10 15:13:40 +01001048 WHERE={'vnfs.uuid': vnf_id},
tierno7edb6752016-03-21 17:37:52 +01001049 WHERE_NOT={'interfaces.external_name': None} )
1050 #print content
tiernof97fd272016-07-11 14:32:37 +02001051 data['vnf']['external-connections'] = content
tierno42026a02017-02-10 15:13:40 +01001052
tiernof97fd272016-07-11 14:32:37 +02001053 return data
tierno7edb6752016-03-21 17:37:52 +01001054
1055
1056def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1057 # Check tenant exist
1058 if tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +02001059 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001060 # Get the URL of the VIM from the nfvo_tenant and the datacenter
tiernof97fd272016-07-11 14:32:37 +02001061 vims = get_vim(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001062 else:
1063 vims={}
1064
1065 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1066 where_or = {}
1067 if tenant_id != "any":
1068 where_or["tenant_id"] = tenant_id
1069 where_or["public"] = True
tierno42026a02017-02-10 15:13:40 +01001070 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 +02001071 vnf_id = vnf["uuid"]
tierno42026a02017-02-10 15:13:40 +01001072
tierno7edb6752016-03-21 17:37:52 +01001073 # "Getting the list of flavors and tenants of the VNF"
tierno42026a02017-02-10 15:13:40 +01001074 flavorList = get_flavorlist(mydb, vnf_id)
tiernof97fd272016-07-11 14:32:37 +02001075 if len(flavorList)==0:
1076 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001077
tiernof97fd272016-07-11 14:32:37 +02001078 imageList = get_imagelist(mydb, vnf_id)
1079 if len(imageList)==0:
1080 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
tierno42026a02017-02-10 15:13:40 +01001081
tiernof97fd272016-07-11 14:32:37 +02001082 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1083 if deleted == 0:
1084 raise NfvoException("vnf '{}' not found".format(vnf_id), HTTP_Not_Found)
tierno42026a02017-02-10 15:13:40 +01001085
tierno7edb6752016-03-21 17:37:52 +01001086 undeletedItems = []
1087 for flavor in flavorList:
1088 #check if flavor is used by other vnf
tiernof97fd272016-07-11 14:32:37 +02001089 try:
1090 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1091 if len(c) > 0:
1092 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1093 continue
1094 #flavor not used, must be deleted
1095 #delelte at VIM
1096 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor})
tierno7edb6752016-03-21 17:37:52 +01001097 for flavor_vim in c:
1098 if flavor_vim["datacenter_id"] not in vims:
1099 continue
1100 if flavor_vim['created']=='false': #skip this flavor because not created by openmano
1101 continue
1102 myvim=vims[ flavor_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001103 try:
1104 myvim.delete_flavor(flavor_vim["vim_id"])
1105 except vimconn.vimconnNotFoundException as e:
1106 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"], flavor_vim["datacenter_id"] )
1107 except vimconn.vimconnException as e:
1108 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1109 flavor_vim["vim_id"], flavor_vim["datacenter_id"], type(e).__name__, str(e))
1110 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"], flavor_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001111 #delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1112 mydb.delete_row_by_id('flavors', flavor)
1113 except db_base_Exception as e:
1114 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
tierno7edb6752016-03-21 17:37:52 +01001115 undeletedItems.append("flavor %s" % flavor)
tiernof97fd272016-07-11 14:32:37 +02001116
tierno42026a02017-02-10 15:13:40 +01001117
tierno7edb6752016-03-21 17:37:52 +01001118 for image in imageList:
tiernof97fd272016-07-11 14:32:37 +02001119 try:
1120 #check if image is used by other vnf
1121 c = mydb.get_rows(FROM='vms', WHERE={'image_id':image} )
1122 if len(c) > 0:
1123 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1124 continue
1125 #image not used, must be deleted
1126 #delelte at VIM
1127 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
tierno7edb6752016-03-21 17:37:52 +01001128 for image_vim in c:
1129 if image_vim["datacenter_id"] not in vims:
1130 continue
1131 if image_vim['created']=='false': #skip this image because not created by openmano
1132 continue
1133 myvim=vims[ image_vim["datacenter_id"] ]
tiernoae4a8d12016-07-08 12:30:39 +02001134 try:
1135 myvim.delete_image(image_vim["vim_id"])
1136 except vimconn.vimconnNotFoundException as e:
1137 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1138 except vimconn.vimconnException as e:
1139 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1140 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1141 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
tiernof97fd272016-07-11 14:32:37 +02001142 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1143 mydb.delete_row_by_id('images', image)
1144 except db_base_Exception as e:
1145 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
tierno7edb6752016-03-21 17:37:52 +01001146 undeletedItems.append("image %s" % image)
1147
tiernof97fd272016-07-11 14:32:37 +02001148 return vnf_id + " " + vnf["name"]
tierno42026a02017-02-10 15:13:40 +01001149 #if undeletedItems:
tiernof97fd272016-07-11 14:32:37 +02001150 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
tierno7edb6752016-03-21 17:37:52 +01001151
tiernob3d36742017-03-03 23:51:05 +01001152
tierno7edb6752016-03-21 17:37:52 +01001153def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1154 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1155 if result < 0:
1156 return result, vims
1157 elif result == 0:
1158 return -HTTP_Not_Found, "datacenter '%s' not found" % datacenter_name
1159 myvim = vims.values()[0]
1160 result,servers = myvim.get_hosts_info()
1161 if result < 0:
1162 return result, servers
1163 topology = {'name':myvim['name'] , 'servers': servers}
1164 return result, topology
1165
tiernob3d36742017-03-03 23:51:05 +01001166
tierno7edb6752016-03-21 17:37:52 +01001167def get_hosts(mydb, nfvo_tenant_id):
tiernof97fd272016-07-11 14:32:37 +02001168 vims = get_vim(mydb, nfvo_tenant_id)
1169 if len(vims) == 0:
1170 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), HTTP_Not_Found)
1171 elif len(vims)>1:
1172 #print "nfvo.datacenter_action() error. Several datacenters found"
1173 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001174 myvim = vims.values()[0]
tiernof97fd272016-07-11 14:32:37 +02001175 try:
1176 hosts = myvim.get_hosts()
1177 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
tierno7edb6752016-03-21 17:37:52 +01001178
tiernof97fd272016-07-11 14:32:37 +02001179 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1180 for host in hosts:
1181 server={'name':host['name'], 'vms':[]}
1182 for vm in host['instances']:
1183 #get internal name and model
tierno42026a02017-02-10 15:13:40 +01001184 try:
tiernof97fd272016-07-11 14:32:37 +02001185 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1186 WHERE={'vim_vm_id':vm['id']} )
1187 if len(c) == 0:
1188 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1189 continue
1190 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
tierno42026a02017-02-10 15:13:40 +01001191
tiernof97fd272016-07-11 14:32:37 +02001192 except db_base_Exception as e:
1193 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1194 datacenter['Datacenters'][0]['servers'].append(server)
1195 #return -400, "en construccion"
tierno42026a02017-02-10 15:13:40 +01001196
tiernof97fd272016-07-11 14:32:37 +02001197 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1198 return datacenter
1199 except vimconn.vimconnException as e:
1200 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001201
tiernob3d36742017-03-03 23:51:05 +01001202
tierno7edb6752016-03-21 17:37:52 +01001203def new_scenario(mydb, tenant_id, topo):
1204
1205# result, vims = get_vim(mydb, tenant_id)
1206# if result < 0:
1207# return result, vims
1208#1: parse input
1209 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001210 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001211 if "tenant_id" in topo:
1212 if topo["tenant_id"] != tenant_id:
tiernof97fd272016-07-11 14:32:37 +02001213 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
1214 HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001215 else:
1216 tenant_id=None
1217
tierno42026a02017-02-10 15:13:40 +01001218#1.1: get VNFs and external_networks (other_nets).
tierno7edb6752016-03-21 17:37:52 +01001219 vnfs={}
1220 other_nets={} #external_networks, bridge_networks and data_networkds
1221 nodes = topo['topology']['nodes']
1222 for k in nodes.keys():
1223 if nodes[k]['type'] == 'VNF':
1224 vnfs[k] = nodes[k]
1225 vnfs[k]['ifaces'] = {}
tierno42026a02017-02-10 15:13:40 +01001226 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
tierno7edb6752016-03-21 17:37:52 +01001227 other_nets[k] = nodes[k]
1228 other_nets[k]['external']=True
tierno42026a02017-02-10 15:13:40 +01001229 elif nodes[k]['type'] == 'network':
tierno7edb6752016-03-21 17:37:52 +01001230 other_nets[k] = nodes[k]
1231 other_nets[k]['external']=False
tierno42026a02017-02-10 15:13:40 +01001232
tierno7edb6752016-03-21 17:37:52 +01001233
1234#1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1235 for name,vnf in vnfs.items():
tiernocea279c2016-07-18 12:36:49 +02001236 where={}
1237 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001238 error_text = ""
1239 error_pos = "'topology':'nodes':'" + name + "'"
1240 if 'vnf_id' in vnf:
1241 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001242 where['uuid'] = vnf['vnf_id']
tierno7edb6752016-03-21 17:37:52 +01001243 if 'VNF model' in vnf:
1244 error_text += " 'VNF model' " + vnf['VNF model']
tiernocea279c2016-07-18 12:36:49 +02001245 where['name'] = vnf['VNF model']
1246 if len(where) == 0:
tiernof97fd272016-07-11 14:32:37 +02001247 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01001248
tiernocea279c2016-07-18 12:36:49 +02001249 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1250 FROM='vnfs',
tierno42026a02017-02-10 15:13:40 +01001251 WHERE=where,
tiernocea279c2016-07-18 12:36:49 +02001252 WHERE_OR=where_or,
1253 WHERE_AND_OR="AND")
tiernof97fd272016-07-11 14:32:37 +02001254 if len(vnf_db)==0:
1255 raise NfvoException("unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
1256 elif len(vnf_db)>1:
1257 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01001258 vnf['uuid']=vnf_db[0]['uuid']
1259 vnf['description']=vnf_db[0]['description']
1260 #get external interfaces
tierno42026a02017-02-10 15:13:40 +01001261 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1262 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 +01001263 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name':None} )
tierno7edb6752016-03-21 17:37:52 +01001264 for ext_iface in ext_ifaces:
1265 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1266
1267#1.4 get list of connections
1268 conections = topo['topology']['connections']
1269 conections_list = []
tiernoefd80c92016-09-16 14:17:46 +02001270 conections_list_name = []
tierno7edb6752016-03-21 17:37:52 +01001271 for k in conections.keys():
1272 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1273 ifaces_list = conections[k]['nodes'].items()
1274 elif type(conections[k]['nodes'])==list: #list with dictionary
1275 ifaces_list=[]
1276 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1277 for k2 in conection_pair_list:
1278 ifaces_list += k2
1279
1280 con_type = conections[k].get("type", "link")
1281 if con_type != "link":
1282 if k in other_nets:
tiernof97fd272016-07-11 14:32:37 +02001283 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001284 other_nets[k] = {'external': False}
1285 if conections[k].get("graph"):
1286 other_nets[k]["graph"] = conections[k]["graph"]
1287 ifaces_list.append( (k, None) )
1288
tierno42026a02017-02-10 15:13:40 +01001289
tierno7edb6752016-03-21 17:37:52 +01001290 if con_type == "external_network":
1291 other_nets[k]['external'] = True
1292 if conections[k].get("model"):
1293 other_nets[k]["model"] = conections[k]["model"]
1294 else:
1295 other_nets[k]["model"] = k
tierno42026a02017-02-10 15:13:40 +01001296 if con_type == "dataplane_net" or con_type == "bridge_net":
tierno7edb6752016-03-21 17:37:52 +01001297 other_nets[k]["model"] = con_type
tierno42026a02017-02-10 15:13:40 +01001298
tiernoefd80c92016-09-16 14:17:46 +02001299 conections_list_name.append(k)
tierno7edb6752016-03-21 17:37:52 +01001300 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)
1301 #print set(ifaces_list)
1302 #check valid VNF and iface names
1303 for iface in ifaces_list:
1304 if iface[0] not in vnfs and iface[0] not in other_nets :
tiernof97fd272016-07-11 14:32:37 +02001305 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
1306 str(k), iface[0]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001307 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
tiernof97fd272016-07-11 14:32:37 +02001308 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
1309 str(k), iface[0], iface[1]), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001310
1311#1.5 unify connections from the pair list to a consolidated list
1312 index=0
1313 while index < len(conections_list):
1314 index2 = index+1
1315 while index2 < len(conections_list):
1316 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
1317 conections_list[index] |= conections_list[index2]
1318 del conections_list[index2]
tiernoefd80c92016-09-16 14:17:46 +02001319 del conections_list_name[index2]
tierno7edb6752016-03-21 17:37:52 +01001320 else:
1321 index2 += 1
1322 conections_list[index] = list(conections_list[index]) # from set to list again
1323 index += 1
1324 #for k in conections_list:
1325 # print k
tierno42026a02017-02-10 15:13:40 +01001326
tierno7edb6752016-03-21 17:37:52 +01001327
1328
1329#1.6 Delete non external nets
1330# for k in other_nets.keys():
1331# if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
1332# for con in conections_list:
1333# delete_indexes=[]
1334# for index in range(0,len(con)):
1335# if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
1336# for index in delete_indexes:
1337# del con[index]
1338# del other_nets[k]
1339#1.7: Check external_ports are present at database table datacenter_nets
1340 for k,net in other_nets.items():
1341 error_pos = "'topology':'nodes':'" + k + "'"
1342 if net['external']==False:
1343 if 'name' not in net:
1344 net['name']=k
1345 if 'model' not in net:
tiernof97fd272016-07-11 14:32:37 +02001346 raise NfvoException("needed a 'model' at " + error_pos, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001347 if net['model']=='bridge_net':
1348 net['type']='bridge';
1349 elif net['model']=='dataplane_net':
1350 net['type']='data';
1351 else:
tiernof97fd272016-07-11 14:32:37 +02001352 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001353 else: #external
1354#IF we do not want to check that external network exist at datacenter
1355 pass
tierno42026a02017-02-10 15:13:40 +01001356#ELSE
tierno7edb6752016-03-21 17:37:52 +01001357# error_text = ""
1358# WHERE_={}
1359# if 'net_id' in net:
1360# error_text += " 'net_id' " + net['net_id']
1361# WHERE_['uuid'] = net['net_id']
1362# if 'model' in net:
1363# error_text += " 'model' " + net['model']
1364# WHERE_['name'] = net['model']
1365# if len(WHERE_) == 0:
1366# return -HTTP_Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
1367# r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
1368# FROM='datacenter_nets', WHERE=WHERE_ )
1369# if r<0:
1370# print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
1371# elif r==0:
1372# print "nfvo.new_scenario Error" +error_text+ " is not present at database"
1373# return -HTTP_Bad_Request, "unknown " +error_text+ " at " + error_pos
1374# elif r>1:
tierno42026a02017-02-10 15:13:40 +01001375# print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
1376# 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 +01001377# other_nets[k].update(net_db[0])
tierno42026a02017-02-10 15:13:40 +01001378#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001379 net_list={}
1380 net_nb=0 #Number of nets
1381 for con in conections_list:
1382 #check if this is connected to a external net
1383 other_net_index=-1
1384 #print
1385 #print "con", con
1386 for index in range(0,len(con)):
1387 #check if this is connected to a external net
1388 for net_key in other_nets.keys():
1389 if con[index][0]==net_key:
1390 if other_net_index>=0:
tierno42026a02017-02-10 15:13:40 +01001391 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 +02001392 #print "nfvo.new_scenario " + error_text
1393 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001394 else:
1395 other_net_index = index
1396 net_target = net_key
1397 break
1398 #print "other_net_index", other_net_index
1399 try:
1400 if other_net_index>=0:
1401 del con[other_net_index]
1402#IF we do not want to check that external network exist at datacenter
1403 if other_nets[net_target]['external'] :
1404 if "name" not in other_nets[net_target]:
1405 other_nets[net_target]['name'] = other_nets[net_target]['model']
1406 if other_nets[net_target]["type"] == "external_network":
1407 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
1408 other_nets[net_target]["type"] = "data"
1409 else:
1410 other_nets[net_target]["type"] = "bridge"
tierno42026a02017-02-10 15:13:40 +01001411#ELSE
tierno7edb6752016-03-21 17:37:52 +01001412# if other_nets[net_target]['external'] :
1413# 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
1414# if type_=='data' and other_nets[net_target]['type']=="ptp":
1415# error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
1416# print "nfvo.new_scenario " + error_text
1417# return -HTTP_Bad_Request, error_text
tierno42026a02017-02-10 15:13:40 +01001418#ENDIF
tierno7edb6752016-03-21 17:37:52 +01001419 for iface in con:
1420 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1421 else:
1422 #create a net
1423 net_type_bridge=False
1424 net_type_data=False
1425 net_target = "__-__net"+str(net_nb)
tierno42026a02017-02-10 15:13:40 +01001426 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
tiernoefd80c92016-09-16 14:17:46 +02001427 'description':"net-%s in scenario %s" %(net_nb,topo['name']),
tierno42026a02017-02-10 15:13:40 +01001428 'external':False}
tierno7edb6752016-03-21 17:37:52 +01001429 for iface in con:
1430 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
1431 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
1432 if iface_type=='mgmt' or iface_type=='bridge':
1433 net_type_bridge = True
1434 else:
1435 net_type_data = True
1436 if net_type_bridge and net_type_data:
1437 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 +02001438 #print "nfvo.new_scenario " + error_text
1439 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001440 elif net_type_bridge:
1441 type_='bridge'
1442 else:
1443 type_='data' if len(con)>2 else 'ptp'
1444 net_list[net_target]['type'] = type_
1445 net_nb+=1
1446 except Exception:
1447 error_text = "Error connection node %s : %s does not match any VNF or interface" % (iface[0], iface[1])
tiernof97fd272016-07-11 14:32:37 +02001448 #print "nfvo.new_scenario " + error_text
tierno7edb6752016-03-21 17:37:52 +01001449 #raise e
tiernof97fd272016-07-11 14:32:37 +02001450 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001451
1452#1.8: Connect to management net all not already connected interfaces of type 'mgmt'
tierno42026a02017-02-10 15:13:40 +01001453 #1.8.1 obtain management net
tiernof97fd272016-07-11 14:32:37 +02001454 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
tierno7edb6752016-03-21 17:37:52 +01001455 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
tierno42026a02017-02-10 15:13:40 +01001456 #1.8.2 check all interfaces from all vnfs
tiernof97fd272016-07-11 14:32:37 +02001457 if len(mgmt_net)>0:
tierno7edb6752016-03-21 17:37:52 +01001458 add_mgmt_net = False
1459 for vnf in vnfs.values():
1460 for iface in vnf['ifaces'].values():
1461 if iface['type']=='mgmt' and 'net_key' not in iface:
1462 #iface not connected
1463 iface['net_key'] = 'mgmt'
1464 add_mgmt_net = True
1465 if add_mgmt_net and 'mgmt' not in net_list:
1466 net_list['mgmt']=mgmt_net[0]
1467 net_list['mgmt']['external']=True
1468 net_list['mgmt']['graph']={'visible':False}
1469
1470 net_list.update(other_nets)
tiernof97fd272016-07-11 14:32:37 +02001471 #print
1472 #print 'net_list', net_list
1473 #print
1474 #print 'vnfs', vnfs
1475 #print
tierno7edb6752016-03-21 17:37:52 +01001476
1477#2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
tiernof97fd272016-07-11 14:32:37 +02001478 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
tierno392f2852016-05-13 12:28:55 +02001479 'tenant_id':tenant_id, 'name':topo['name'],
1480 'description':topo.get('description',topo['name']),
1481 'public': topo.get('public', False)
1482 })
tierno42026a02017-02-10 15:13:40 +01001483
tiernof97fd272016-07-11 14:32:37 +02001484 return c
tierno7edb6752016-03-21 17:37:52 +01001485
tiernob3d36742017-03-03 23:51:05 +01001486
tierno5bb59dc2017-02-13 14:53:54 +01001487def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
1488 """ This creates a new scenario for version 0.2 and 0.3"""
tierno392f2852016-05-13 12:28:55 +02001489 scenario = scenario_dict["scenario"]
tierno7edb6752016-03-21 17:37:52 +01001490 if tenant_id != "any":
tierno42026a02017-02-10 15:13:40 +01001491 check_tenant(mydb, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01001492 if "tenant_id" in scenario:
1493 if scenario["tenant_id"] != tenant_id:
tierno5bb59dc2017-02-13 14:53:54 +01001494 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
tiernof97fd272016-07-11 14:32:37 +02001495 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
1496 scenario["tenant_id"], tenant_id), HTTP_Unauthorized)
tierno7edb6752016-03-21 17:37:52 +01001497 else:
1498 tenant_id=None
1499
tierno5bb59dc2017-02-13 14:53:54 +01001500 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
tierno7edb6752016-03-21 17:37:52 +01001501 for name,vnf in scenario["vnfs"].iteritems():
tiernocea279c2016-07-18 12:36:49 +02001502 where={}
1503 where_or={"tenant_id": tenant_id, 'public': "true"}
tierno7edb6752016-03-21 17:37:52 +01001504 error_text = ""
garciadeblas71781ea2016-09-19 14:41:59 +02001505 error_pos = "'scenario':'vnfs':'" + name + "'"
tierno7edb6752016-03-21 17:37:52 +01001506 if 'vnf_id' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001507 error_text += " 'vnf_id' " + vnf['vnf_id']
tiernocea279c2016-07-18 12:36:49 +02001508 where['uuid'] = vnf['vnf_id']
tierno392f2852016-05-13 12:28:55 +02001509 if 'vnf_name' in vnf:
tierno5bb59dc2017-02-13 14:53:54 +01001510 error_text += " 'vnf_name' " + vnf['vnf_name']
tiernocea279c2016-07-18 12:36:49 +02001511 where['name'] = vnf['vnf_name']
1512 if len(where) == 0:
garciadeblas71781ea2016-09-19 14:41:59 +02001513 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, HTTP_Bad_Request)
tierno5bb59dc2017-02-13 14:53:54 +01001514 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
tiernocea279c2016-07-18 12:36:49 +02001515 FROM='vnfs',
1516 WHERE=where,
1517 WHERE_OR=where_or,
1518 WHERE_AND_OR="AND")
tierno5bb59dc2017-02-13 14:53:54 +01001519 if len(vnf_db) == 0:
tiernof97fd272016-07-11 14:32:37 +02001520 raise NfvoException("Unknown" + error_text + " at " + error_pos, HTTP_Not_Found)
tierno5bb59dc2017-02-13 14:53:54 +01001521 elif len(vnf_db) > 1:
tiernof97fd272016-07-11 14:32:37 +02001522 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", HTTP_Conflict)
tierno5bb59dc2017-02-13 14:53:54 +01001523 vnf['uuid'] = vnf_db[0]['uuid']
1524 vnf['description'] = vnf_db[0]['description']
tierno7edb6752016-03-21 17:37:52 +01001525 vnf['ifaces'] = {}
tierno5bb59dc2017-02-13 14:53:54 +01001526 # get external interfaces
1527 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
1528 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1529 WHERE={'vnfs.uuid':vnf['uuid']}, WHERE_NOT={'external_name': None} )
tierno7edb6752016-03-21 17:37:52 +01001530 for ext_iface in ext_ifaces:
tierno5bb59dc2017-02-13 14:53:54 +01001531 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
1532 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
tierno7edb6752016-03-21 17:37:52 +01001533
tierno5bb59dc2017-02-13 14:53:54 +01001534 # 2: Insert net_key and ip_address at every vnf interface
1535 for net_name, net in scenario["networks"].items():
1536 net_type_bridge = False
1537 net_type_data = False
tierno7edb6752016-03-21 17:37:52 +01001538 for iface_dict in net["interfaces"]:
tierno5bb59dc2017-02-13 14:53:54 +01001539 if version == "0.2":
1540 temp_dict = iface_dict
1541 ip_address = None
1542 elif version == "0.3":
1543 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
1544 ip_address = iface_dict.get('ip_address', None)
1545 for vnf, iface in temp_dict.items():
tierno7edb6752016-03-21 17:37:52 +01001546 if vnf not in scenario["vnfs"]:
tierno5bb59dc2017-02-13 14:53:54 +01001547 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
1548 net_name, vnf)
1549 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001550 raise NfvoException(error_text, HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01001551 if iface not in scenario["vnfs"][vnf]['ifaces']:
tierno5bb59dc2017-02-13 14:53:54 +01001552 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
1553 .format(net_name, iface)
1554 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001555 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001556 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
tierno5bb59dc2017-02-13 14:53:54 +01001557 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
1558 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
1559 # logger.debug("nfvo.new_scenario_v02 " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001560 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001561 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
tierno5bb59dc2017-02-13 14:53:54 +01001562 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
tierno7edb6752016-03-21 17:37:52 +01001563 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
tierno5bb59dc2017-02-13 14:53:54 +01001564 if iface_type == 'mgmt' or iface_type == 'bridge':
tierno7edb6752016-03-21 17:37:52 +01001565 net_type_bridge = True
1566 else:
1567 net_type_data = True
tierno5bb59dc2017-02-13 14:53:54 +01001568
tierno7edb6752016-03-21 17:37:52 +01001569 if net_type_bridge and net_type_data:
tierno5bb59dc2017-02-13 14:53:54 +01001570 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
1571 .format(net_name)
1572 # logger.debug("nfvo.new_scenario " + error_text)
tiernof97fd272016-07-11 14:32:37 +02001573 raise NfvoException(error_text, HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001574 elif net_type_bridge:
tierno5bb59dc2017-02-13 14:53:54 +01001575 type_ = 'bridge'
tierno7edb6752016-03-21 17:37:52 +01001576 else:
tierno5bb59dc2017-02-13 14:53:54 +01001577 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
1578
1579 if net.get("implementation"): # for v0.3
1580 if type_ == "bridge" and net["implementation"] == "underlay":
1581 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
1582 "'network':'{}'".format(net_name)
1583 # logger.debug(error_text)
1584 raise NfvoException(error_text, HTTP_Bad_Request)
1585 elif type_ != "bridge" and net["implementation"] == "overlay":
1586 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
1587 "'network':'{}'".format(net_name)
1588 # logger.debug(error_text)
1589 raise NfvoException(error_text, HTTP_Bad_Request)
1590 net.pop("implementation")
1591 if "type" in net and version == "0.3": # for v0.3
1592 if type_ == "data" and net["type"] == "e-line":
1593 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
1594 "'e-line' at 'network':'{}'".format(net_name)
1595 # logger.debug(error_text)
1596 raise NfvoException(error_text, HTTP_Bad_Request)
1597 elif type_ == "ptp" and net["type"] == "e-lan":
1598 type_ = "data"
1599
tierno7edb6752016-03-21 17:37:52 +01001600 net['type'] = type_
1601 net['name'] = net_name
1602 net['external'] = net.get('external', False)
1603
tierno5bb59dc2017-02-13 14:53:54 +01001604 # 3: insert at database
tierno7edb6752016-03-21 17:37:52 +01001605 scenario["nets"] = scenario["networks"]
1606 scenario['tenant_id'] = tenant_id
tierno5bb59dc2017-02-13 14:53:54 +01001607 scenario_id = mydb.new_scenario(scenario)
tiernof97fd272016-07-11 14:32:37 +02001608 return scenario_id
tierno7edb6752016-03-21 17:37:52 +01001609
tiernob3d36742017-03-03 23:51:05 +01001610
tierno7edb6752016-03-21 17:37:52 +01001611def edit_scenario(mydb, tenant_id, scenario_id, data):
1612 data["uuid"] = scenario_id
1613 data["tenant_id"] = tenant_id
tiernof97fd272016-07-11 14:32:37 +02001614 c = mydb.edit_scenario( data )
1615 return c
tierno7edb6752016-03-21 17:37:52 +01001616
tiernob3d36742017-03-03 23:51:05 +01001617
tierno7edb6752016-03-21 17:37:52 +01001618def 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 +02001619 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernoa2793912016-10-04 08:15:08 +00001620 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
1621 vims = {datacenter_id: myvim}
tierno392f2852016-05-13 12:28:55 +02001622 myvim_tenant = myvim['tenant_id']
tierno7edb6752016-03-21 17:37:52 +01001623 datacenter_name = myvim['name']
tiernoa2793912016-10-04 08:15:08 +00001624
tierno7edb6752016-03-21 17:37:52 +01001625 rollbackList=[]
tiernoae4a8d12016-07-08 12:30:39 +02001626 try:
1627 #print "Checking that the scenario_id exists and getting the scenario dictionary"
tiernof97fd272016-07-11 14:32:37 +02001628 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id)
tiernoa2793912016-10-04 08:15:08 +00001629 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
tiernoae4a8d12016-07-08 12:30:39 +02001630 scenarioDict['datacenter_id'] = datacenter_id
1631 #print '================scenarioDict======================='
1632 #print json.dumps(scenarioDict, indent=4)
1633 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
tierno42026a02017-02-10 15:13:40 +01001634
tiernoae4a8d12016-07-08 12:30:39 +02001635 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
1636 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001637
tiernoae4a8d12016-07-08 12:30:39 +02001638 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
1639 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01001640
tiernoae4a8d12016-07-08 12:30:39 +02001641 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
1642 for sce_net in scenarioDict['nets']:
1643 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
tierno42026a02017-02-10 15:13:40 +01001644
tiernoae4a8d12016-07-08 12:30:39 +02001645 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
tierno7edb6752016-03-21 17:37:52 +01001646 myNetName = myNetName[0:255] #limit length
tiernoae4a8d12016-07-08 12:30:39 +02001647 myNetType = sce_net['type']
tierno7edb6752016-03-21 17:37:52 +01001648 myNetDict = {}
1649 myNetDict["name"] = myNetName
1650 myNetDict["type"] = myNetType
1651 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001652 myNetIPProfile = sce_net.get('ip_profile', None)
tierno7edb6752016-03-21 17:37:52 +01001653 #TODO:
tiernoae4a8d12016-07-08 12:30:39 +02001654 #We should use the dictionary as input parameter for new_network
tiernof97fd272016-07-11 14:32:37 +02001655 #print myNetDict
tiernoae4a8d12016-07-08 12:30:39 +02001656 if not sce_net["external"]:
garciadeblas9f8456e2016-09-05 05:02:59 +02001657 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001658 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
1659 sce_net['vim_id'] = network_id
1660 auxNetDict['scenario'][sce_net['uuid']] = network_id
1661 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001662 sce_net["created"] = True
tiernoae4a8d12016-07-08 12:30:39 +02001663 else:
1664 if sce_net['vim_id'] == None:
1665 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
1666 _, message = rollback(mydb, vims, rollbackList)
1667 logger.error("nfvo.start_scenario: %s", error_text)
tiernof97fd272016-07-11 14:32:37 +02001668 raise NfvoException(error_text, HTTP_Bad_Request)
tiernoae4a8d12016-07-08 12:30:39 +02001669 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
1670 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
tierno42026a02017-02-10 15:13:40 +01001671
tiernoae4a8d12016-07-08 12:30:39 +02001672 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
1673 #For each vnf net, we create it and we add it to instanceNetlist.
mirabal29356312017-07-27 12:21:22 +02001674
tiernoae4a8d12016-07-08 12:30:39 +02001675 for sce_vnf in scenarioDict['vnfs']:
1676 for net in sce_vnf['nets']:
1677 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
tierno42026a02017-02-10 15:13:40 +01001678
tiernoae4a8d12016-07-08 12:30:39 +02001679 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
1680 myNetName = myNetName[0:255] #limit length
1681 myNetType = net['type']
1682 myNetDict = {}
1683 myNetDict["name"] = myNetName
1684 myNetDict["type"] = myNetType
1685 myNetDict["tenant_id"] = myvim_tenant
garciadeblas9f8456e2016-09-05 05:02:59 +02001686 myNetIPProfile = net.get('ip_profile', None)
tiernoae4a8d12016-07-08 12:30:39 +02001687 #print myNetDict
1688 #TODO:
1689 #We should use the dictionary as input parameter for new_network
garciadeblas9f8456e2016-09-05 05:02:59 +02001690 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
tiernoae4a8d12016-07-08 12:30:39 +02001691 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
1692 net['vim_id'] = network_id
1693 if sce_vnf['uuid'] not in auxNetDict:
1694 auxNetDict[sce_vnf['uuid']] = {}
1695 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
1696 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
tierno66345bc2016-09-26 11:37:55 +02001697 net["created"] = True
tierno42026a02017-02-10 15:13:40 +01001698
tiernoae4a8d12016-07-08 12:30:39 +02001699 #print "auxNetDict:"
1700 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01001701
tiernoae4a8d12016-07-08 12:30:39 +02001702 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
1703 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
1704 i = 0
1705 for sce_vnf in scenarioDict['vnfs']:
tierno5a3273c2017-08-29 11:43:46 +02001706 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02001707 for vm in sce_vnf['vms']:
1708 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02001709 if vm_av and vm_av not in vnf_availability_zones:
1710 vnf_availability_zones.append(vm_av)
1711
1712 # check if there is enough availability zones available at vim level.
1713 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
1714 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
1715 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
1716
tiernoae4a8d12016-07-08 12:30:39 +02001717 for vm in sce_vnf['vms']:
1718 i += 1
1719 myVMDict = {}
1720 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
tiernoae65a482016-11-24 16:20:05 +01001721 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
tiernoae4a8d12016-07-08 12:30:39 +02001722 #myVMDict['description'] = vm['description']
1723 myVMDict['description'] = myVMDict['name'][0:99]
1724 if not startvms:
1725 myVMDict['start'] = "no"
1726 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
1727 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
tierno42026a02017-02-10 15:13:40 +01001728
tiernoae4a8d12016-07-08 12:30:39 +02001729 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001730 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno42026a02017-02-10 15:13:40 +01001731 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001732 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01001733
tiernoae4a8d12016-07-08 12:30:39 +02001734 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02001735 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tiernoae4a8d12016-07-08 12:30:39 +02001736 if flavor_dict['extended']!=None:
1737 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
tierno42026a02017-02-10 15:13:40 +01001738 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
tiernoae4a8d12016-07-08 12:30:39 +02001739 vm['vim_flavor_id'] = flavor_id
tierno42026a02017-02-10 15:13:40 +01001740
1741
tiernoae4a8d12016-07-08 12:30:39 +02001742 myVMDict['imageRef'] = vm['vim_image_id']
1743 myVMDict['flavorRef'] = vm['vim_flavor_id']
1744 myVMDict['networks'] = []
1745 for iface in vm['interfaces']:
1746 netDict = {}
1747 if iface['type']=="data":
1748 netDict['type'] = iface['model']
1749 elif "model" in iface and iface["model"]!=None:
1750 netDict['model']=iface['model']
1751 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
1752 #discover type of interface looking at flavor
1753 for numa in flavor_dict.get('extended',{}).get('numas',[]):
1754 for flavor_iface in numa.get('interfaces',[]):
1755 if flavor_iface.get('name') == iface['internal_name']:
1756 if flavor_iface['dedicated'] == 'yes':
1757 netDict['type']="PF" #passthrough
1758 elif flavor_iface['dedicated'] == 'no':
1759 netDict['type']="VF" #siov
1760 elif flavor_iface['dedicated'] == 'yes:sriov':
1761 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
1762 netDict["mac_address"] = flavor_iface.get("mac_address")
1763 break;
1764 netDict["use"]=iface['type']
1765 if netDict["use"]=="data" and not netDict.get("type"):
1766 #print "netDict", netDict
1767 #print "iface", iface
1768 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'])
1769 if flavor_dict.get('extended')==None:
tiernof97fd272016-07-11 14:32:37 +02001770 raise NfvoException(e_text + "After database migration some information is not available. \
1771 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tiernoae4a8d12016-07-08 12:30:39 +02001772 else:
tiernof97fd272016-07-11 14:32:37 +02001773 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02001774 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
1775 netDict["type"]="virtual"
1776 if "vpci" in iface and iface["vpci"] is not None:
1777 netDict['vpci'] = iface['vpci']
1778 if "mac" in iface and iface["mac"] is not None:
1779 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00001780 if "port-security" in iface and iface["port-security"] is not None:
1781 netDict['port_security'] = iface['port-security']
1782 if "floating-ip" in iface and iface["floating-ip"] is not None:
1783 netDict['floating_ip'] = iface['floating-ip']
tiernoae4a8d12016-07-08 12:30:39 +02001784 netDict['name'] = iface['internal_name']
1785 if iface['net_id'] is None:
1786 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02001787 #print iface
1788 #print vnf_iface
tiernoae4a8d12016-07-08 12:30:39 +02001789 if vnf_iface['interface_id']==iface['uuid']:
1790 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
1791 break
1792 else:
1793 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
1794 #skip bridge ifaces not connected to any net
1795 #if 'net_id' not in netDict or netDict['net_id']==None:
1796 # continue
1797 myVMDict['networks'].append(netDict)
1798 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
1799 #print myVMDict['name']
1800 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
1801 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
1802 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
mirabal29356312017-07-27 12:21:22 +02001803
1804 if 'availability_zone' in myVMDict:
tierno5a3273c2017-08-29 11:43:46 +02001805 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02001806 else:
tierno5a3273c2017-08-29 11:43:46 +02001807 av_index = None
mirabal29356312017-07-27 12:21:22 +02001808
1809 vm_id = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
1810 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
tierno5a3273c2017-08-29 11:43:46 +02001811 availability_zone_index=av_index,
1812 availability_zone_list=vnf_availability_zones)
tiernoae4a8d12016-07-08 12:30:39 +02001813 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
1814 vm['vim_id'] = vm_id
1815 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
1816 #put interface uuid back to scenario[vnfs][vms[[interfaces]
1817 for net in myVMDict['networks']:
1818 if "vim_id" in net:
1819 for iface in vm['interfaces']:
1820 if net["name"]==iface["internal_name"]:
1821 iface["vim_id"]=net["vim_id"]
1822 break
tierno42026a02017-02-10 15:13:40 +01001823
tiernoae4a8d12016-07-08 12:30:39 +02001824 logger.debug("start scenario Deployment done")
1825 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
1826 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
tiernof97fd272016-07-11 14:32:37 +02001827 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
1828 return mydb.get_instance_scenario(instance_id)
tierno42026a02017-02-10 15:13:40 +01001829
tiernof97fd272016-07-11 14:32:37 +02001830 except (db_base_Exception, vimconn.vimconnException) as e:
tiernoae4a8d12016-07-08 12:30:39 +02001831 _, message = rollback(mydb, vims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02001832 if isinstance(e, db_base_Exception):
1833 error_text = "Exception at database"
1834 else:
1835 error_text = "Exception at VIM"
1836 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1837 #logger.error("start_scenario %s", error_text)
1838 raise NfvoException(error_text, e.http_code)
tierno7edb6752016-03-21 17:37:52 +01001839
tiernob3d36742017-03-03 23:51:05 +01001840
tierno36c0b172017-01-12 18:32:28 +01001841def unify_cloud_config(cloud_config_preserve, cloud_config):
tierno40e1bce2017-08-09 09:12:04 +02001842 """ join the cloud config information into cloud_config_preserve.
tierno36c0b172017-01-12 18:32:28 +01001843 In case of conflict cloud_config_preserve preserves
tierno40e1bce2017-08-09 09:12:04 +02001844 None is allowed
1845 """
tierno36c0b172017-01-12 18:32:28 +01001846 if not cloud_config_preserve and not cloud_config:
1847 return None
1848
1849 new_cloud_config = {"key-pairs":[], "users":[]}
1850 # key-pairs
1851 if cloud_config_preserve:
1852 for key in cloud_config_preserve.get("key-pairs", () ):
1853 if key not in new_cloud_config["key-pairs"]:
1854 new_cloud_config["key-pairs"].append(key)
1855 if cloud_config:
1856 for key in cloud_config.get("key-pairs", () ):
1857 if key not in new_cloud_config["key-pairs"]:
1858 new_cloud_config["key-pairs"].append(key)
1859 if not new_cloud_config["key-pairs"]:
1860 del new_cloud_config["key-pairs"]
1861
1862 # users
1863 if cloud_config:
1864 new_cloud_config["users"] += cloud_config.get("users", () )
1865 if cloud_config_preserve:
1866 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
tiernoa4e1a6e2016-08-31 14:19:40 +02001867 index_to_delete = []
tierno36c0b172017-01-12 18:32:28 +01001868 users = new_cloud_config.get("users", [])
tiernoa4e1a6e2016-08-31 14:19:40 +02001869 for index0 in range(0,len(users)):
1870 if index0 in index_to_delete:
1871 continue
1872 for index1 in range(index0+1,len(users)):
1873 if index1 in index_to_delete:
1874 continue
1875 if users[index0]["name"] == users[index1]["name"]:
1876 index_to_delete.append(index1)
1877 for key in users[index1].get("key-pairs",()):
tierno36c0b172017-01-12 18:32:28 +01001878 if "key-pairs" not in users[index0]:
tiernoa4e1a6e2016-08-31 14:19:40 +02001879 users[index0]["key-pairs"] = [key]
1880 elif key not in users[index0]["key-pairs"]:
1881 users[index0]["key-pairs"].append(key)
1882 index_to_delete.sort(reverse=True)
1883 for index in index_to_delete:
1884 del users[index]
tierno36c0b172017-01-12 18:32:28 +01001885 if not new_cloud_config["users"]:
1886 del new_cloud_config["users"]
1887
1888 #boot-data-drive
1889 if cloud_config and cloud_config.get("boot-data-drive") != None:
1890 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
1891 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
1892 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
1893
1894 # user-data
tierno40e1bce2017-08-09 09:12:04 +02001895 new_cloud_config["user-data"] = []
1896 if cloud_config and cloud_config.get("user-data"):
1897 if isinstance(cloud_config["user-data"], list):
1898 new_cloud_config["user-data"] += cloud_config["user-data"]
1899 else:
1900 new_cloud_config["user-data"].append(cloud_config["user-data"])
1901 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
1902 if isinstance(cloud_config_preserve["user-data"], list):
1903 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
1904 else:
1905 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
1906 if not new_cloud_config["user-data"]:
1907 del new_cloud_config["user-data"]
tierno36c0b172017-01-12 18:32:28 +01001908
1909 # config files
1910 new_cloud_config["config-files"] = []
1911 if cloud_config and cloud_config.get("config-files") != None:
1912 new_cloud_config["config-files"] += cloud_config["config-files"]
1913 if cloud_config_preserve:
1914 for file in cloud_config_preserve.get("config-files", ()):
1915 for index in range(0, len(new_cloud_config["config-files"])):
1916 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
1917 new_cloud_config["config-files"][index] = file
1918 break
1919 else:
1920 new_cloud_config["config-files"].append(file)
1921 if not new_cloud_config["config-files"]:
1922 del new_cloud_config["config-files"]
1923 return new_cloud_config
1924
1925
tierno867ffe92017-03-27 12:50:34 +02001926def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
tiernob3d36742017-03-03 23:51:05 +01001927 datacenter_id = None
1928 datacenter_name = None
1929 thread = None
tierno867ffe92017-03-27 12:50:34 +02001930 try:
1931 if datacenter_tenant_id:
1932 thread_id = datacenter_tenant_id
1933 thread = vim_threads["running"].get(datacenter_tenant_id)
tiernob3d36742017-03-03 23:51:05 +01001934 else:
tierno867ffe92017-03-27 12:50:34 +02001935 where_={"td.nfvo_tenant_id": tenant_id}
1936 if datacenter_id_name:
1937 if utils.check_valid_uuid(datacenter_id_name):
1938 datacenter_id = datacenter_id_name
1939 where_["dt.datacenter_id"] = datacenter_id
1940 else:
1941 datacenter_name = datacenter_id_name
1942 where_["d.name"] = datacenter_name
1943 if datacenter_tenant_id:
1944 where_["dt.uuid"] = datacenter_tenant_id
1945 datacenters = mydb.get_rows(
1946 SELECT=("dt.uuid as datacenter_tenant_id",),
1947 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
1948 "join datacenters as d on d.uuid=dt.datacenter_id",
1949 WHERE=where_)
1950 if len(datacenters) > 1:
1951 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1952 elif datacenters:
1953 thread_id = datacenters[0]["datacenter_tenant_id"]
1954 thread = vim_threads["running"].get(thread_id)
1955 if not thread:
1956 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1957 return thread_id, thread
1958 except db_base_Exception as e:
1959 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
tiernoa4e1a6e2016-08-31 14:19:40 +02001960
tiernof5755962017-07-13 15:44:34 +02001961
tiernoa2793912016-10-04 08:15:08 +00001962def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
tiernobe41e222016-09-02 15:16:13 +02001963 datacenter_id = None
1964 datacenter_name = None
1965 if datacenter_id_name:
tierno42026a02017-02-10 15:13:40 +01001966 if utils.check_valid_uuid(datacenter_id_name):
tiernobe41e222016-09-02 15:16:13 +02001967 datacenter_id = datacenter_id_name
1968 else:
1969 datacenter_name = datacenter_id_name
tiernoa2793912016-10-04 08:15:08 +00001970 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
tiernobe41e222016-09-02 15:16:13 +02001971 if len(vims) == 0:
1972 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
1973 elif len(vims)>1:
1974 #print "nfvo.datacenter_action() error. Several datacenters found"
1975 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
1976 return vims.keys()[0], vims.values()[0]
1977
tiernob3d36742017-03-03 23:51:05 +01001978
garciadeblas9f8456e2016-09-05 05:02:59 +02001979def update(d, u):
1980 '''Takes dict d and updates it with the values in dict u.'''
1981 '''It merges all depth levels'''
1982 for k, v in u.iteritems():
1983 if isinstance(v, collections.Mapping):
1984 r = update(d.get(k, {}), v)
1985 d[k] = r
1986 else:
1987 d[k] = u[k]
1988 return d
1989
tiernob3d36742017-03-03 23:51:05 +01001990
tierno7edb6752016-03-21 17:37:52 +01001991def create_instance(mydb, tenant_id, instance_dict):
tiernob3d36742017-03-03 23:51:05 +01001992 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
1993 # logger.debug("Creating instance...")
tierno7edb6752016-03-21 17:37:52 +01001994 scenario = instance_dict["scenario"]
tierno42026a02017-02-10 15:13:40 +01001995
tiernobe41e222016-09-02 15:16:13 +02001996 #find main datacenter
1997 myvims = {}
tierno867ffe92017-03-27 12:50:34 +02001998 myvim_threads_id = {}
1999 instance_tasks={}
2000 tasks_to_launch={}
tierno7edb6752016-03-21 17:37:52 +01002001 datacenter = instance_dict.get("datacenter")
tiernobe41e222016-09-02 15:16:13 +02002002 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
2003 myvims[default_datacenter_id] = vim
tierno867ffe92017-03-27 12:50:34 +02002004 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
2005 tasks_to_launch[myvim_threads_id[default_datacenter_id]] = []
tierno392f2852016-05-13 12:28:55 +02002006 #myvim_tenant = myvim['tenant_id']
tiernobe41e222016-09-02 15:16:13 +02002007# default_datacenter_name = vim['name']
tierno7edb6752016-03-21 17:37:52 +01002008 rollbackList=[]
tierno42026a02017-02-10 15:13:40 +01002009
tiernoae4a8d12016-07-08 12:30:39 +02002010 #print "Checking that the scenario exists and getting the scenario dictionary"
tiernobe41e222016-09-02 15:16:13 +02002011 scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id)
tierno42026a02017-02-10 15:13:40 +01002012
garciadeblasbb6a1ed2016-09-30 14:02:09 +00002013 #logger.debug(">>>>>>> Dictionaries before merging")
2014 #logger.debug(">>>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
2015 #logger.debug(">>>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
tierno42026a02017-02-10 15:13:40 +01002016
tierno8e690322017-08-10 15:58:50 +02002017 uuid_list = []
2018 instance_name = instance_dict["name"]
2019 instance_uuid = str(uuid4())
2020 uuid_list.append(instance_uuid)
2021 db_instance_scenario = {
2022 "uuid": instance_uuid,
2023 "name": instance_name,
2024 "tenant_id": tenant_id,
2025 "scenario_id": scenarioDict['uuid'],
2026 "datacenter_id": default_datacenter_id,
2027 # filled bellow 'datacenter_tenant_id'
2028 "description": instance_dict.get("description"),
2029 }
2030 db_ip_profiles=[]
2031 if scenarioDict.get("cloud-config"):
2032 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
2033 default_flow_style=True, width=256)
garciadeblas9f8456e2016-09-05 05:02:59 +02002034
tierno8e690322017-08-10 15:58:50 +02002035 vnf_net2instance = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2036 sce_net2instance = {}
tierno7edb6752016-03-21 17:37:52 +01002037 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2038 auxNetDict['scenario'] = {}
tierno42026a02017-02-10 15:13:40 +01002039
2040 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 +01002041 try:
tiernob3d36742017-03-03 23:51:05 +01002042 # 0 check correct parameters
tiernobe41e222016-09-02 15:16:13 +02002043 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
tiernob3d36742017-03-03 23:51:05 +01002044 found = False
tierno7edb6752016-03-21 17:37:52 +01002045 for scenario_net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +02002046 if net_name == scenario_net["name"]:
tierno7edb6752016-03-21 17:37:52 +01002047 found = True
2048 break
2049 if not found:
tiernobe41e222016-09-02 15:16:13 +02002050 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request)
2051 if "sites" not in net_instance_desc:
2052 net_instance_desc["sites"] = [ {} ]
2053 site_without_datacenter_field = False
2054 for site in net_instance_desc["sites"]:
2055 if site.get("datacenter"):
2056 if site["datacenter"] not in myvims:
2057 #Add this datacenter to myvims
2058 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
2059 myvims[d] = v
tierno867ffe92017-03-27 12:50:34 +02002060 myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, site["datacenter"])
2061 tasks_to_launch[myvim_threads_id[d]] = []
tiernob3d36742017-03-03 23:51:05 +01002062 site["datacenter"] = d #change name to id
tiernobe41e222016-09-02 15:16:13 +02002063 else:
2064 if site_without_datacenter_field:
2065 raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
2066 site_without_datacenter_field = True
tiernob3d36742017-03-03 23:51:05 +01002067 site["datacenter"] = default_datacenter_id #change name to id
tierno42026a02017-02-10 15:13:40 +01002068
tiernobe41e222016-09-02 15:16:13 +02002069 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
tierno7edb6752016-03-21 17:37:52 +01002070 found=False
2071 for scenario_vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +02002072 if vnf_name == scenario_vnf['name']:
tierno7edb6752016-03-21 17:37:52 +01002073 found = True
2074 break
2075 if not found:
tiernobe41e222016-09-02 15:16:13 +02002076 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
2077 if "datacenter" in vnf_instance_desc:
tiernob3d36742017-03-03 23:51:05 +01002078 # Add this datacenter to myvims
tiernobe41e222016-09-02 15:16:13 +02002079 if vnf_instance_desc["datacenter"] not in myvims:
2080 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
2081 myvims[d] = v
tierno867ffe92017-03-27 12:50:34 +02002082 myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
2083 tasks_to_launch[myvim_threads_id[d]] = []
tiernoa2793912016-10-04 08:15:08 +00002084 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
garciadeblas30833382017-01-09 09:46:31 +01002085
tiernoa4e1a6e2016-08-31 14:19:40 +02002086 #0.1 parse cloud-config parameters
tierno36c0b172017-01-12 18:32:28 +01002087 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
garciadeblas9f8456e2016-09-05 05:02:59 +02002088
2089 #0.2 merge instance information into scenario
2090 #Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
2091 #However, this is not possible yet.
2092 for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems():
2093 for scenario_net in scenarioDict['nets']:
2094 if net_name == scenario_net["name"]:
2095 if 'ip-profile' in net_instance_desc:
tierno455612d2017-05-30 16:40:10 +02002096 # translate from input format to database format
2097 ipprofile_in = net_instance_desc['ip-profile']
2098 ipprofile_db = {}
2099 ipprofile_db['subnet_address'] = ipprofile_in.get('subnet-address')
2100 ipprofile_db['ip_version'] = ipprofile_in.get('ip-version', 'IPv4')
2101 ipprofile_db['gateway_address'] = ipprofile_in.get('gateway-address')
2102 ipprofile_db['dns_address'] = ipprofile_in.get('dns-address')
2103 if isinstance(ipprofile_db['dns_address'], (list, tuple)):
2104 ipprofile_db['dns_address'] = ";".join(ipprofile_db['dns_address'])
2105 if 'dhcp' in ipprofile_in:
2106 ipprofile_db['dhcp_start_address'] = ipprofile_in['dhcp'].get('start-address')
2107 ipprofile_db['dhcp_enabled'] = ipprofile_in['dhcp'].get('enabled', True)
2108 ipprofile_db['dhcp_count'] = ipprofile_in['dhcp'].get('count' )
garciadeblasedca7b32016-09-29 14:01:52 +00002109 if 'ip_profile' not in scenario_net:
tierno455612d2017-05-30 16:40:10 +02002110 scenario_net['ip_profile'] = ipprofile_db
garciadeblasedca7b32016-09-29 14:01:52 +00002111 else:
tierno455612d2017-05-30 16:40:10 +02002112 update(scenario_net['ip_profile'], ipprofile_db)
tiernoe6c58ce2016-09-14 16:02:49 +02002113 for interface in net_instance_desc.get('interfaces', () ):
garciadeblas9f8456e2016-09-05 05:02:59 +02002114 if 'ip_address' in interface:
2115 for vnf in scenarioDict['vnfs']:
2116 if interface['vnf'] == vnf['name']:
2117 for vnf_interface in vnf['interfaces']:
2118 if interface['vnf_interface'] == vnf_interface['external_name']:
2119 vnf_interface['ip_address']=interface['ip_address']
2120
garciadeblasbb6a1ed2016-09-30 14:02:09 +00002121 #logger.debug(">>>>>>>> Merged dictionary")
tierno4319dad2016-09-05 12:11:11 +02002122 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 +02002123
tiernob3d36742017-03-03 23:51:05 +01002124 # 1. Creating new nets (sce_nets) in the VIM"
tierno8e690322017-08-10 15:58:50 +02002125 db_instance_nets = []
tierno7edb6752016-03-21 17:37:52 +01002126 for sce_net in scenarioDict['nets']:
tierno8e690322017-08-10 15:58:50 +02002127 descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{})
tiernobe41e222016-09-02 15:16:13 +02002128 net_name = descriptor_net.get("vim-network-name")
tierno8e690322017-08-10 15:58:50 +02002129 sce_net2instance[sce_net['uuid']] = {}
tiernobe41e222016-09-02 15:16:13 +02002130 auxNetDict['scenario'][sce_net['uuid']] = {}
2131
2132 sites = descriptor_net.get("sites", [ {} ])
2133 for site in sites:
2134 if site.get("datacenter"):
2135 vim = myvims[ site["datacenter"] ]
2136 datacenter_id = site["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02002137 myvim_thread_id = myvim_threads_id[ site["datacenter"] ]
tierno7edb6752016-03-21 17:37:52 +01002138 else:
tiernobe41e222016-09-02 15:16:13 +02002139 vim = myvims[ default_datacenter_id ]
2140 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002141 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tiernobe41e222016-09-02 15:16:13 +02002142 net_type = sce_net['type']
2143 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True
2144 if sce_net["external"]:
2145 if not net_name:
tierno42026a02017-02-10 15:13:40 +01002146 net_name = sce_net["name"]
tiernobe41e222016-09-02 15:16:13 +02002147 if "netmap-use" in site or "netmap-create" in site:
2148 create_network = False
2149 lookfor_network = False
2150 if "netmap-use" in site:
2151 lookfor_network = True
2152 if utils.check_valid_uuid(site["netmap-use"]):
2153 filter_text = "scenario id '%s'" % site["netmap-use"]
2154 lookfor_filter["id"] = site["netmap-use"]
tierno42026a02017-02-10 15:13:40 +01002155 else:
tiernobe41e222016-09-02 15:16:13 +02002156 filter_text = "scenario name '%s'" % site["netmap-use"]
2157 lookfor_filter["name"] = site["netmap-use"]
2158 if "netmap-create" in site:
2159 create_network = True
2160 net_vim_name = net_name
2161 if site["netmap-create"]:
2162 net_vim_name = site["netmap-create"]
tierno42026a02017-02-10 15:13:40 +01002163
tiernobe41e222016-09-02 15:16:13 +02002164 elif sce_net['vim_id'] != None:
2165 #there is a netmap at datacenter_nets database #TODO REVISE!!!!
2166 create_network = False
2167 lookfor_network = True
2168 lookfor_filter["id"] = sce_net['vim_id']
2169 filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"])
2170 #look for network at datacenter and return error
2171 else:
2172 #There is not a netmap, look at datacenter for a net with this name and create if not found
2173 create_network = True
2174 lookfor_network = True
2175 lookfor_filter["name"] = sce_net["name"]
2176 net_vim_name = sce_net["name"]
2177 filter_text = "scenario name '%s'" % sce_net["name"]
tierno7edb6752016-03-21 17:37:52 +01002178 else:
tiernobe41e222016-09-02 15:16:13 +02002179 if not net_name:
2180 net_name = "%s.%s" %(instance_name, sce_net["name"])
2181 net_name = net_name[:255] #limit length
2182 net_vim_name = net_name
2183 create_network = True
2184 lookfor_network = False
tierno42026a02017-02-10 15:13:40 +01002185
tiernobe41e222016-09-02 15:16:13 +02002186 if lookfor_network:
2187 vim_nets = vim.get_network_list(filter_dict=lookfor_filter)
2188 if len(vim_nets) > 1:
2189 raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request )
2190 elif len(vim_nets) == 0:
2191 if not create_network:
2192 raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request )
2193 else:
tierno8e690322017-08-10 15:58:50 +02002194 vim_id = vim_nets[0]['id']
tiernobe41e222016-09-02 15:16:13 +02002195 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id']
2196 create_network = False
2197 if create_network:
2198 #if network is not external
tiernob3d36742017-03-03 23:51:05 +01002199 task = new_task("new-net", (net_vim_name, net_type, sce_net.get('ip_profile',None)))
tierno867ffe92017-03-27 12:50:34 +02002200 task_id = task["id"]
tiernob3d36742017-03-03 23:51:05 +01002201 instance_tasks[task_id] = task
tierno867ffe92017-03-27 12:50:34 +02002202 tasks_to_launch[myvim_thread_id].append(task)
tiernob3d36742017-03-03 23:51:05 +01002203 #network_id = vim.new_network(net_vim_name, net_type, sce_net.get('ip_profile',None))
tierno8e690322017-08-10 15:58:50 +02002204 vim_id = task_id
tiernob3d36742017-03-03 23:51:05 +01002205 auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = task_id
2206 rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':task_id})
tierno66345bc2016-09-26 11:37:55 +02002207 sce_net["created"] = True
tierno42026a02017-02-10 15:13:40 +01002208
tierno8e690322017-08-10 15:58:50 +02002209 # fill database content
2210 net_uuid = str(uuid4())
2211 uuid_list.append(net_uuid)
2212 sce_net2instance[sce_net['uuid']][datacenter_id] = net_uuid
2213 db_net = {
2214 "uuid": net_uuid,
2215 'vim_net_id': vim_id,
2216 "instance_scenario_id": instance_uuid,
2217 "sce_net_id": sce_net["uuid"],
2218 "created": create_network,
2219 'datacenter_id': datacenter_id,
2220 'datacenter_tenant_id': myvim_thread_id,
2221 'status': 'BUILD' if create_network else "ACTIVE"
2222 }
2223 db_instance_nets.append(db_net)
2224 if 'ip_profile' in sce_net:
2225 db_ip_profile={
2226 'instance_net_id': net_uuid,
2227 'ip_version': sce_net['ip_profile']['ip_version'],
2228 'subnet_address': sce_net['ip_profile']['subnet_address'],
2229 'gateway_address': sce_net['ip_profile']['gateway_address'],
2230 'dns_address': sce_net['ip_profile']['dns_address'],
2231 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
2232 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
2233 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
2234 }
2235 db_ip_profiles.append(db_ip_profile)
2236
tiernob3d36742017-03-03 23:51:05 +01002237 # 2. Creating new nets (vnf internal nets) in the VIM"
mirabal29356312017-07-27 12:21:22 +02002238 # For each vnf net, we create it and we add it to instanceNetlist.
tierno7edb6752016-03-21 17:37:52 +01002239 for sce_vnf in scenarioDict['vnfs']:
2240 for net in sce_vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +02002241 if sce_vnf.get("datacenter"):
2242 vim = myvims[ sce_vnf["datacenter"] ]
2243 datacenter_id = sce_vnf["datacenter"]
tierno867ffe92017-03-27 12:50:34 +02002244 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"]]
tiernobe41e222016-09-02 15:16:13 +02002245 else:
2246 vim = myvims[ default_datacenter_id ]
2247 datacenter_id = default_datacenter_id
tierno867ffe92017-03-27 12:50:34 +02002248 myvim_thread_id = myvim_threads_id[default_datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01002249 descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{})
2250 net_name = descriptor_net.get("name")
2251 if not net_name:
2252 net_name = "%s.%s" %(instance_name, net["name"])
2253 net_name = net_name[:255] #limit length
2254 net_type = net['type']
tiernob3d36742017-03-03 23:51:05 +01002255 task = new_task("new-net", (net_name, net_type, net.get('ip_profile',None)))
tierno867ffe92017-03-27 12:50:34 +02002256 task_id = task["id"]
tiernob3d36742017-03-03 23:51:05 +01002257 instance_tasks[task_id] = task
tierno867ffe92017-03-27 12:50:34 +02002258 tasks_to_launch[myvim_thread_id].append(task)
tiernob3d36742017-03-03 23:51:05 +01002259 # network_id = vim.new_network(net_name, net_type, net.get('ip_profile',None))
tierno8e690322017-08-10 15:58:50 +02002260 vim_id = task_id
2261 if sce_vnf['uuid'] not in vnf_net2instance:
2262 vnf_net2instance[sce_vnf['uuid']] = {}
2263 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = task_id
tierno7edb6752016-03-21 17:37:52 +01002264 if sce_vnf['uuid'] not in auxNetDict:
2265 auxNetDict[sce_vnf['uuid']] = {}
tiernob3d36742017-03-03 23:51:05 +01002266 auxNetDict[sce_vnf['uuid']][net['uuid']] = task_id
2267 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':task_id})
tierno66345bc2016-09-26 11:37:55 +02002268 net["created"] = True
2269
tierno8e690322017-08-10 15:58:50 +02002270 # fill database content
2271 net_uuid = str(uuid4())
2272 uuid_list.append(net_uuid)
2273 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
2274 db_net = {
2275 "uuid": net_uuid,
2276 'vim_net_id': vim_id,
2277 "instance_scenario_id": instance_uuid,
2278 "net_id": net["uuid"],
2279 "created": True,
2280 'datacenter_id': datacenter_id,
2281 'datacenter_tenant_id': myvim_thread_id,
2282 }
2283 db_instance_nets.append(db_net)
2284 if 'ip_profile' in net:
2285 db_ip_profile = {
2286 'instance_net_id': net_uuid,
2287 'ip_version': net['ip_profile']['ip_version'],
2288 'subnet_address': net['ip_profile']['subnet_address'],
2289 'gateway_address': net['ip_profile']['gateway_address'],
2290 'dns_address': net['ip_profile']['dns_address'],
2291 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
2292 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
2293 'dhcp_count': net['ip_profile']['dhcp_count'],
2294 }
2295 db_ip_profiles.append(db_ip_profile)
2296
2297 #print "vnf_net2instance:"
2298 #print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
tierno42026a02017-02-10 15:13:40 +01002299
tiernob3d36742017-03-03 23:51:05 +01002300 # 3. Creating new vm instances in the VIM
tierno8e690322017-08-10 15:58:50 +02002301 db_instance_vnfs = []
2302 db_instance_vms = []
2303 db_instance_interfaces = []
tiernoae4a8d12016-07-08 12:30:39 +02002304 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
Adam Israel04f29112017-09-20 21:10:30 -04002305 sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
garciadeblasacd4e782017-07-23 19:44:55 +02002306 #for sce_vnf in scenarioDict['vnfs']:
2307 for sce_vnf in sce_vnf_list:
tierno5a3273c2017-08-29 11:43:46 +02002308 vnf_availability_zones = []
mirabal29356312017-07-27 12:21:22 +02002309 for vm in sce_vnf['vms']:
2310 vm_av = vm.get('availability_zone')
tierno5a3273c2017-08-29 11:43:46 +02002311 if vm_av and vm_av not in vnf_availability_zones:
2312 vnf_availability_zones.append(vm_av)
mirabal29356312017-07-27 12:21:22 +02002313
2314 # check if there is enough availability zones available at vim level.
tierno5a3273c2017-08-29 11:43:46 +02002315 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2316 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
2317 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
mirabal29356312017-07-27 12:21:22 +02002318
tiernobe41e222016-09-02 15:16:13 +02002319 if sce_vnf.get("datacenter"):
2320 vim = myvims[ sce_vnf["datacenter"] ]
tierno867ffe92017-03-27 12:50:34 +02002321 myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"] ]
tiernobe41e222016-09-02 15:16:13 +02002322 datacenter_id = sce_vnf["datacenter"]
2323 else:
2324 vim = myvims[ default_datacenter_id ]
tierno867ffe92017-03-27 12:50:34 +02002325 myvim_thread_id = myvim_threads_id[ default_datacenter_id ]
tiernobe41e222016-09-02 15:16:13 +02002326 datacenter_id = default_datacenter_id
mirabal29356312017-07-27 12:21:22 +02002327 sce_vnf["datacenter_id"] = datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002328 i = 0
mirabal29356312017-07-27 12:21:22 +02002329
tierno8e690322017-08-10 15:58:50 +02002330 vnf_uuid = str(uuid4())
2331 uuid_list.append(vnf_uuid)
2332 db_instance_vnf = {
2333 'uuid': vnf_uuid,
2334 'instance_scenario_id': instance_uuid,
2335 'vnf_id': sce_vnf['vnf_id'],
2336 'sce_vnf_id': sce_vnf['uuid'],
2337 'datacenter_id': datacenter_id,
2338 'datacenter_tenant_id': myvim_thread_id,
2339 }
2340 db_instance_vnfs.append(db_instance_vnf)
2341
tierno7edb6752016-03-21 17:37:52 +01002342 for vm in sce_vnf['vms']:
tierno7edb6752016-03-21 17:37:52 +01002343 myVMDict = {}
tierno8e690322017-08-10 15:58:50 +02002344 myVMDict['name'] = "{}.{}.{}".format(instance_name[:64], sce_vnf['name'][:64], vm["name"][:64])
tierno7edb6752016-03-21 17:37:52 +01002345 myVMDict['description'] = myVMDict['name'][0:99]
2346# if not startvms:
2347# myVMDict['start'] = "no"
2348 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2349 #create image at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002350 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
tierno5e91eb82016-10-04 09:39:07 +00002351 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
tierno7edb6752016-03-21 17:37:52 +01002352 vm['vim_image_id'] = image_id
tierno42026a02017-02-10 15:13:40 +01002353
tierno7edb6752016-03-21 17:37:52 +01002354 #create flavor at vim in case it not exist
tiernof97fd272016-07-11 14:32:37 +02002355 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
tierno7edb6752016-03-21 17:37:52 +01002356 if flavor_dict['extended']!=None:
2357 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
montesmoreno0c8def02016-12-22 12:16:23 +00002358 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
2359
montesmoreno0c8def02016-12-22 12:16:23 +00002360 #Obtain information for additional disks
2361 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id})
2362 if not extended_flavor_dict:
2363 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
2364 return
2365
2366 #extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
2367 myVMDict['disks'] = None
2368 extended_info = extended_flavor_dict[0]['extended']
2369 if extended_info != None:
2370 extended_flavor_dict_yaml = yaml.load(extended_info)
2371 if 'disks' in extended_flavor_dict_yaml:
2372 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
2373
tierno7edb6752016-03-21 17:37:52 +01002374 vm['vim_flavor_id'] = flavor_id
tierno7edb6752016-03-21 17:37:52 +01002375 myVMDict['imageRef'] = vm['vim_image_id']
2376 myVMDict['flavorRef'] = vm['vim_flavor_id']
mirabal29356312017-07-27 12:21:22 +02002377 myVMDict['availability_zone'] = vm.get('availability_zone')
tierno7edb6752016-03-21 17:37:52 +01002378 myVMDict['networks'] = []
tiernob3d36742017-03-03 23:51:05 +01002379 task_depends = {}
tiernoa2793912016-10-04 08:15:08 +00002380 #TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
tierno8e690322017-08-10 15:58:50 +02002381 db_vm_ifaces = []
tierno7edb6752016-03-21 17:37:52 +01002382 for iface in vm['interfaces']:
2383 netDict = {}
2384 if iface['type']=="data":
2385 netDict['type'] = iface['model']
2386 elif "model" in iface and iface["model"]!=None:
2387 netDict['model']=iface['model']
2388 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2389 #discover type of interface looking at flavor
2390 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2391 for flavor_iface in numa.get('interfaces',[]):
2392 if flavor_iface.get('name') == iface['internal_name']:
2393 if flavor_iface['dedicated'] == 'yes':
2394 netDict['type']="PF" #passthrough
2395 elif flavor_iface['dedicated'] == 'no':
2396 netDict['type']="VF" #siov
2397 elif flavor_iface['dedicated'] == 'yes:sriov':
2398 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2399 netDict["mac_address"] = flavor_iface.get("mac_address")
2400 break;
2401 netDict["use"]=iface['type']
2402 if netDict["use"]=="data" and not netDict.get("type"):
2403 #print "netDict", netDict
2404 #print "iface", iface
2405 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'])
2406 if flavor_dict.get('extended')==None:
tiernoae4a8d12016-07-08 12:30:39 +02002407 raise NfvoException(e_text + "After database migration some information is not available. \
2408 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002409 else:
tiernoae4a8d12016-07-08 12:30:39 +02002410 raise NfvoException(e_text, HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01002411 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2412 netDict["type"]="virtual"
2413 if "vpci" in iface and iface["vpci"] is not None:
2414 netDict['vpci'] = iface['vpci']
2415 if "mac" in iface and iface["mac"] is not None:
2416 netDict['mac_address'] = iface['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +00002417 if "port-security" in iface and iface["port-security"] is not None:
2418 netDict['port_security'] = iface['port-security']
2419 if "floating-ip" in iface and iface["floating-ip"] is not None:
2420 netDict['floating_ip'] = iface['floating-ip']
tierno7edb6752016-03-21 17:37:52 +01002421 netDict['name'] = iface['internal_name']
2422 if iface['net_id'] is None:
2423 for vnf_iface in sce_vnf["interfaces"]:
tiernof97fd272016-07-11 14:32:37 +02002424 #print iface
2425 #print vnf_iface
tierno7edb6752016-03-21 17:37:52 +01002426 if vnf_iface['interface_id']==iface['uuid']:
tiernobe41e222016-09-02 15:16:13 +02002427 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]
tierno8e690322017-08-10 15:58:50 +02002428 instance_net_id = sce_net2instance[ vnf_iface['sce_net_id'] ][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +01002429 break
2430 else:
2431 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
tierno8e690322017-08-10 15:58:50 +02002432 instance_net_id = vnf_net2instance[ sce_vnf['uuid'] ][ iface['net_id'] ]
tierno867ffe92017-03-27 12:50:34 +02002433 if netDict.get('net_id') and is_task_id(netDict['net_id']):
tiernob3d36742017-03-03 23:51:05 +01002434 task_depends[netDict['net_id']] = instance_tasks[netDict['net_id']]
tierno7edb6752016-03-21 17:37:52 +01002435 #skip bridge ifaces not connected to any net
2436 #if 'net_id' not in netDict or netDict['net_id']==None:
2437 # continue
2438 myVMDict['networks'].append(netDict)
tierno8e690322017-08-10 15:58:50 +02002439 db_vm_iface={
2440 # "uuid"
2441 # 'instance_vm_id': instance_vm_uuid,
2442 "instance_net_id": instance_net_id,
2443 'interface_id': iface['uuid'],
2444 # 'vim_interface_id': ,
2445 'type': 'external' if iface['external_name'] is not None else 'internal',
2446 'ip_address': iface.get('ip_address'),
2447 'floating_ip': int(iface.get('floating-ip', False)),
2448 'port_security': int(iface.get('port-security', True))
2449 }
2450 db_vm_ifaces.append(db_vm_iface)
2451 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2452 # print myVMDict['name']
2453 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2454 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2455 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
tierno36c0b172017-01-12 18:32:28 +01002456 if vm.get("boot_data"):
2457 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config)
2458 else:
2459 cloud_config_vm = cloud_config
tierno5a3273c2017-08-29 11:43:46 +02002460 if myVMDict.get('availability_zone'):
2461 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
mirabal29356312017-07-27 12:21:22 +02002462 else:
tierno5a3273c2017-08-29 11:43:46 +02002463 av_index = None
tierno8e690322017-08-10 15:58:50 +02002464 for vm_index in range(0, vm.get('count', 1)):
2465 vm_index_name = ""
2466 if vm.get('count', 1) > 1:
2467 vm_index_name += "." + chr(97 + vm_index)
2468 task = new_task("new-vm", (myVMDict['name']+vm_index_name, myVMDict['description'],
2469 myVMDict.get('start', None), myVMDict['imageRef'],
2470 myVMDict['flavorRef'], myVMDict['networks'],
2471 cloud_config_vm, myVMDict['disks'], av_index,
2472 vnf_availability_zones), depends=task_depends)
2473 instance_tasks[task["id"]] = task
2474 tasks_to_launch[myvim_thread_id].append(task)
2475 vm_id = task["id"]
2476 vm['vim_id'] = vm_id
2477 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2478 # put interface uuid back to scenario[vnfs][vms[[interfaces]
2479 for net in myVMDict['networks']:
2480 if "vim_id" in net:
2481 for iface in vm['interfaces']:
2482 if net["name"]==iface["internal_name"]:
2483 iface["vim_id"]=net["vim_id"]
2484 break
2485 vm_uuid = str(uuid4())
2486 uuid_list.append(vm_uuid)
2487 db_vm = {
2488 "uuid": vm_uuid,
2489 'instance_vnf_id': vnf_uuid,
2490 "vim_vm_id": vm_id,
2491 "vm_id": vm["uuid"],
2492 # "status":
2493 }
2494 db_instance_vms.append(db_vm)
2495 for db_vm_iface in db_vm_ifaces:
2496 iface_uuid = str(uuid4())
2497 uuid_list.append(iface_uuid)
2498 db_vm_iface_instance = {
2499 "uuid": iface_uuid,
2500 "instance_vm_id": vm_uuid
2501 }
2502 db_vm_iface_instance.update(db_vm_iface)
2503 if db_vm_iface_instance.get("ip_address"): # increment ip_address
2504 ip = db_vm_iface_instance.get("ip_address")
2505 i = ip.rfind(".")
2506 if i > 0:
2507 try:
2508 i += 1
2509 ip = ip[i:] + str(int(ip[:i]) +1)
2510 db_vm_iface_instance["ip_address"] = ip
2511 except:
2512 db_vm_iface_instance["ip_address"] = None
2513 db_instance_interfaces.append(db_vm_iface_instance)
2514
tierno867ffe92017-03-27 12:50:34 +02002515 scenarioDict["datacenter2tenant"] = myvim_threads_id
tierno8e690322017-08-10 15:58:50 +02002516
2517 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
2518 db_instance_scenario['datacenter_id'] = default_datacenter_id
2519 db_tables=[
2520 {"instance_scenarios": db_instance_scenario},
2521 {"instance_vnfs": db_instance_vnfs},
2522 {"instance_nets": db_instance_nets},
2523 {"ip_profiles": db_ip_profiles},
2524 {"instance_vms": db_instance_vms},
2525 {"instance_interfaces": db_instance_interfaces},
2526 ]
2527
tiernoa2793912016-10-04 08:15:08 +00002528 logger.debug("create_instance Deployment done scenarioDict: %s",
tierno8e690322017-08-10 15:58:50 +02002529 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2530 mydb.new_rows(db_tables, uuid_list)
tierno867ffe92017-03-27 12:50:34 +02002531 for myvim_thread_id,task_list in tasks_to_launch.items():
2532 for task in task_list:
2533 vim_threads["running"][myvim_thread_id].insert_task(task)
2534
tierno8e690322017-08-10 15:58:50 +02002535 global_instance_tasks[instance_uuid] = instance_tasks
tierno867ffe92017-03-27 12:50:34 +02002536 # Update database with those ended instance_tasks
2537 # for task in instance_tasks.values():
2538 # if task["status"] == "ok":
2539 # if task["name"] == "new-vm":
2540 # mydb.update_rows("instance_vms", UPDATE={"vim_vm_id": task["result"]},
2541 # WHERE={"vim_vm_id": task["id"]})
2542 # elif task["name"] == "new-net":
2543 # mydb.update_rows("instance_nets", UPDATE={"vim_net_id": task["result"]},
2544 # WHERE={"vim_net_id": task["id"]})
tierno8e690322017-08-10 15:58:50 +02002545 return mydb.get_instance_scenario(instance_uuid)
tiernof97fd272016-07-11 14:32:37 +02002546 except (NfvoException, vimconn.vimconnException,db_base_Exception) as e:
tiernobe41e222016-09-02 15:16:13 +02002547 message = rollback(mydb, myvims, rollbackList)
tiernof97fd272016-07-11 14:32:37 +02002548 if isinstance(e, db_base_Exception):
2549 error_text = "database Exception"
2550 elif isinstance(e, vimconn.vimconnException):
2551 error_text = "VIM Exception"
2552 else:
2553 error_text = "Exception"
2554 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2555 #logger.error("create_instance: %s", error_text)
2556 raise NfvoException(error_text, e.http_code)
tierno42026a02017-02-10 15:13:40 +01002557
tiernob3d36742017-03-03 23:51:05 +01002558
tierno7edb6752016-03-21 17:37:52 +01002559def delete_instance(mydb, tenant_id, instance_id):
tiernoae4a8d12016-07-08 12:30:39 +02002560 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002561 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
tiernoae4a8d12016-07-08 12:30:39 +02002562 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
tierno7edb6752016-03-21 17:37:52 +01002563 tenant_id = instanceDict["tenant_id"]
tiernoae4a8d12016-07-08 12:30:39 +02002564 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tierno7edb6752016-03-21 17:37:52 +01002565
tiernoa2793912016-10-04 08:15:08 +00002566 #1. Delete from Database
tiernof97fd272016-07-11 14:32:37 +02002567 message = mydb.delete_instance_scenario(instance_id, tenant_id)
tierno7edb6752016-03-21 17:37:52 +01002568
2569 #2. delete from VIM
tiernoa2793912016-10-04 08:15:08 +00002570 error_msg = ""
tiernob3d36742017-03-03 23:51:05 +01002571 myvims = {}
2572 myvim_threads = {}
tierno7edb6752016-03-21 17:37:52 +01002573
2574 #2.1 deleting VMs
2575 #vm_fail_list=[]
2576 for sce_vnf in instanceDict['vnfs']:
tiernoa2793912016-10-04 08:15:08 +00002577 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2578 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01002579 try:
tierno867ffe92017-03-27 12:50:34 +02002580 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01002581 except NfvoException as e:
2582 logger.error(str(e))
2583 myvim_thread = None
2584 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00002585 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
2586 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2587 if len(vims) == 0:
2588 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
2589 sce_vnf["datacenter_tenant_id"]))
2590 myvims[datacenter_key] = None
2591 else:
2592 myvims[datacenter_key] = vims.values()[0]
2593 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01002594 myvim_thread = myvim_threads[datacenter_key]
tierno7edb6752016-03-21 17:37:52 +01002595 for vm in sce_vnf['vms']:
tiernoa2793912016-10-04 08:15:08 +00002596 if not myvim:
2597 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
2598 continue
tiernoae4a8d12016-07-08 12:30:39 +02002599 try:
tiernob3d36742017-03-03 23:51:05 +01002600 task=None
2601 if is_task_id(vm['vim_vm_id']):
2602 task_id = vm['vim_vm_id']
tierno867ffe92017-03-27 12:50:34 +02002603 old_task = global_instance_tasks[instance_id].get(task_id)
tiernob3d36742017-03-03 23:51:05 +01002604 if not old_task:
2605 error_msg += "\n VM was scheduled for create, but task {} is not found".format(task_id)
2606 continue
2607 with task_lock:
2608 if old_task["status"] == "enqueued":
2609 old_task["status"] = "deleted"
2610 elif old_task["status"] == "error":
2611 continue
2612 elif old_task["status"] == "processing":
tierno867ffe92017-03-27 12:50:34 +02002613 task = new_task("del-vm", (task_id, vm["interfaces"]), depends={task_id: old_task})
tiernob3d36742017-03-03 23:51:05 +01002614 else: #ok
tierno867ffe92017-03-27 12:50:34 +02002615 task = new_task("del-vm", (old_task["result"], vm["interfaces"]))
tiernob3d36742017-03-03 23:51:05 +01002616 else:
tierno867ffe92017-03-27 12:50:34 +02002617 task = new_task("del-vm", (vm['vim_vm_id'], vm["interfaces"]) )
tiernob3d36742017-03-03 23:51:05 +01002618 if task:
2619 myvim_thread.insert_task(task)
tiernoae4a8d12016-07-08 12:30:39 +02002620 except vimconn.vimconnNotFoundException as e:
tiernoa2793912016-10-04 08:15:08 +00002621 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 +02002622 logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found",
2623 vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'])
2624 except vimconn.vimconnException as e:
tiernoa2793912016-10-04 08:15:08 +00002625 error_msg+="\n VM VIM_id={} at datacenter={} Error: {} {}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"], e.http_code, str(e))
2626 logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM_id '%s', from VNF_id '%s': %s",
tiernoae4a8d12016-07-08 12:30:39 +02002627 e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e))
tierno42026a02017-02-10 15:13:40 +01002628
tierno7edb6752016-03-21 17:37:52 +01002629 #2.2 deleting NETS
2630 #net_fail_list=[]
2631 for net in instanceDict['nets']:
tierno66345bc2016-09-26 11:37:55 +02002632 if not net['created']:
tierno7edb6752016-03-21 17:37:52 +01002633 continue #skip not created nets
tiernoa2793912016-10-04 08:15:08 +00002634 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2635 if datacenter_key not in myvims:
tiernob3d36742017-03-03 23:51:05 +01002636 try:
tierno867ffe92017-03-27 12:50:34 +02002637 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
tiernob3d36742017-03-03 23:51:05 +01002638 except NfvoException as e:
2639 logger.error(str(e))
2640 myvim_thread = None
2641 myvim_threads[datacenter_key] = myvim_thread
tiernoa2793912016-10-04 08:15:08 +00002642 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
2643 datacenter_tenant_id=net["datacenter_tenant_id"])
2644 if len(vims) == 0:
2645 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2646 myvims[datacenter_key] = None
2647 else:
2648 myvims[datacenter_key] = vims.values()[0]
2649 myvim = myvims[datacenter_key]
tiernob3d36742017-03-03 23:51:05 +01002650 myvim_thread = myvim_threads[datacenter_key]
tiernoa2793912016-10-04 08:15:08 +00002651
tierno7edb6752016-03-21 17:37:52 +01002652 if not myvim:
tiernoa2793912016-10-04 08:15:08 +00002653 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 +01002654 continue
tiernoae4a8d12016-07-08 12:30:39 +02002655 try:
tiernob3d36742017-03-03 23:51:05 +01002656 task = None
2657 if is_task_id(net['vim_net_id']):
2658 task_id = net['vim_net_id']
tierno867ffe92017-03-27 12:50:34 +02002659 old_task = global_instance_tasks[instance_id].get(task_id)
tiernob3d36742017-03-03 23:51:05 +01002660 if not old_task:
2661 error_msg += "\n NET was scheduled for create, but task {} is not found".format(task_id)
2662 continue
2663 with task_lock:
2664 if old_task["status"] == "enqueued":
2665 old_task["status"] = "deleted"
2666 elif old_task["status"] == "error":
2667 continue
2668 elif old_task["status"] == "processing":
2669 task = new_task("del-net", task_id, depends={task_id: old_task})
2670 else: # ok
2671 task = new_task("del-net", old_task["result"])
2672 else:
tierno867ffe92017-03-27 12:50:34 +02002673 task = new_task("del-net", (net['vim_net_id'], net['sdn_net_id']))
tiernob3d36742017-03-03 23:51:05 +01002674 if task:
2675 myvim_thread.insert_task(task)
tiernoae4a8d12016-07-08 12:30:39 +02002676 except vimconn.vimconnNotFoundException as e:
tiernob3d36742017-03-03 23:51:05 +01002677 error_msg += "\n NET VIM_id={} not found at datacenter={}".format(net['vim_net_id'], net["datacenter_id"])
tiernoa2793912016-10-04 08:15:08 +00002678 logger.warn("NET '%s', VIM_id '%s', from VNF_net_id '%s' not found",
tiernob3d36742017-03-03 23:51:05 +01002679 net['uuid'], net['vim_net_id'], str(net['vnf_net_id']))
tiernoae4a8d12016-07-08 12:30:39 +02002680 except vimconn.vimconnException as e:
tiernob3d36742017-03-03 23:51:05 +01002681 error_msg += "\n NET VIM_id={} at datacenter={} Error: {} {}".format(net['vim_net_id'],
2682 net["datacenter_id"],
2683 e.http_code, str(e))
tiernoa2793912016-10-04 08:15:08 +00002684 logger.error("Error %d deleting NET '%s', VIM_id '%s', from VNF_net_id '%s': %s",
tiernob3d36742017-03-03 23:51:05 +01002685 e.http_code, net['uuid'], net['vim_net_id'], str(net['vnf_net_id']), str(e))
2686 if len(error_msg) > 0:
tiernof97fd272016-07-11 14:32:37 +02002687 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 +01002688 else:
tiernof97fd272016-07-11 14:32:37 +02002689 return 'instance ' + message + ' deleted'
tierno7edb6752016-03-21 17:37:52 +01002690
tiernob3d36742017-03-03 23:51:05 +01002691
tierno7edb6752016-03-21 17:37:52 +01002692def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
2693 '''Refreshes a scenario instance. It modifies instanceDict'''
2694 '''Returns:
2695 - 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
2696 - error_msg
2697 '''
tierno867ffe92017-03-27 12:50:34 +02002698 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
2699 # #print "nfvo.refresh_instance begins"
2700 # #print json.dumps(instanceDict, indent=4)
2701 #
2702 # #print "Getting the VIM URL and the VIM tenant_id"
2703 # myvims={}
2704 #
2705 # # 1. Getting VIM vm and net list
2706 # vms_updated = [] #List of VM instance uuids in openmano that were updated
2707 # vms_notupdated=[]
2708 # vm_list = {}
2709 # for sce_vnf in instanceDict['vnfs']:
2710 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
2711 # if datacenter_key not in vm_list:
2712 # vm_list[datacenter_key] = []
2713 # if datacenter_key not in myvims:
2714 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
2715 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
2716 # if len(vims) == 0:
2717 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
2718 # myvims[datacenter_key] = None
2719 # else:
2720 # myvims[datacenter_key] = vims.values()[0]
2721 # for vm in sce_vnf['vms']:
2722 # vm_list[datacenter_key].append(vm['vim_vm_id'])
2723 # vms_notupdated.append(vm["uuid"])
2724 #
2725 # nets_updated = [] #List of VM instance uuids in openmano that were updated
2726 # nets_notupdated=[]
2727 # net_list = {}
2728 # for net in instanceDict['nets']:
2729 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
2730 # if datacenter_key not in net_list:
2731 # net_list[datacenter_key] = []
2732 # if datacenter_key not in myvims:
2733 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
2734 # datacenter_tenant_id=net["datacenter_tenant_id"])
2735 # if len(vims) == 0:
2736 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
2737 # myvims[datacenter_key] = None
2738 # else:
2739 # myvims[datacenter_key] = vims.values()[0]
2740 #
2741 # net_list[datacenter_key].append(net['vim_net_id'])
2742 # nets_notupdated.append(net["uuid"])
2743 #
2744 # # 1. Getting the status of all VMs
2745 # vm_dict={}
2746 # for datacenter_key in myvims:
2747 # if not vm_list.get(datacenter_key):
2748 # continue
2749 # failed = True
2750 # failed_message=""
2751 # if not myvims[datacenter_key]:
2752 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2753 # else:
2754 # try:
2755 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
2756 # failed = False
2757 # except vimconn.vimconnException as e:
2758 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
2759 # failed_message = str(e)
2760 # if failed:
2761 # for vm in vm_list[datacenter_key]:
2762 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2763 #
2764 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
2765 # for sce_vnf in instanceDict['vnfs']:
2766 # for vm in sce_vnf['vms']:
2767 # vm_id = vm['vim_vm_id']
2768 # interfaces = vm_dict[vm_id].pop('interfaces', [])
2769 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
2770 # has_mgmt_iface = False
2771 # for iface in vm["interfaces"]:
2772 # if iface["type"]=="mgmt":
2773 # has_mgmt_iface = True
2774 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
2775 # vm_dict[vm_id]['status'] = "ACTIVE"
2776 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
2777 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
2778 # 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'):
2779 # vm['status'] = vm_dict[vm_id]['status']
2780 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
2781 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
2782 # # 2.1. Update in openmano DB the VMs whose status changed
2783 # try:
2784 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
2785 # vms_notupdated.remove(vm["uuid"])
2786 # if updates>0:
2787 # vms_updated.append(vm["uuid"])
2788 # except db_base_Exception as e:
2789 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
2790 # # 2.2. Update in openmano DB the interface VMs
2791 # for interface in interfaces:
2792 # #translate from vim_net_id to instance_net_id
2793 # network_id_list=[]
2794 # for net in instanceDict['nets']:
2795 # if net["vim_net_id"] == interface["vim_net_id"]:
2796 # network_id_list.append(net["uuid"])
2797 # if not network_id_list:
2798 # continue
2799 # del interface["vim_net_id"]
2800 # try:
2801 # for network_id in network_id_list:
2802 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
2803 # except db_base_Exception as e:
2804 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
2805 #
2806 # # 3. Getting the status of all nets
2807 # net_dict = {}
2808 # for datacenter_key in myvims:
2809 # if not net_list.get(datacenter_key):
2810 # continue
2811 # failed = True
2812 # failed_message = ""
2813 # if not myvims[datacenter_key]:
2814 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
2815 # else:
2816 # try:
2817 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
2818 # failed = False
2819 # except vimconn.vimconnException as e:
2820 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
2821 # failed_message = str(e)
2822 # if failed:
2823 # for net in net_list[datacenter_key]:
2824 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
2825 #
2826 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
2827 # # TODO: update nets inside a vnf
2828 # for net in instanceDict['nets']:
2829 # net_id = net['vim_net_id']
2830 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
2831 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
2832 # 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'):
2833 # net['status'] = net_dict[net_id]['status']
2834 # net['error_msg'] = net_dict[net_id].get('error_msg')
2835 # net['vim_info'] = net_dict[net_id].get('vim_info')
2836 # # 5.1. Update in openmano DB the nets whose status changed
2837 # try:
2838 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
2839 # nets_notupdated.remove(net["uuid"])
2840 # if updated>0:
2841 # nets_updated.append(net["uuid"])
2842 # except db_base_Exception as e:
2843 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
2844 #
2845 # # Returns appropriate output
2846 # #print "nfvo.refresh_instance finishes"
2847 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
2848 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
tierno7edb6752016-03-21 17:37:52 +01002849 instance_id = instanceDict['uuid']
tierno867ffe92017-03-27 12:50:34 +02002850 # if len(vms_notupdated)+len(nets_notupdated)>0:
2851 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
2852 # 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 +01002853
tiernoae4a8d12016-07-08 12:30:39 +02002854 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
tierno7edb6752016-03-21 17:37:52 +01002855
tiernob3d36742017-03-03 23:51:05 +01002856
tierno7edb6752016-03-21 17:37:52 +01002857def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
tiernoae4a8d12016-07-08 12:30:39 +02002858 #print "Checking that the instance_id exists and getting the instance dictionary"
tiernof97fd272016-07-11 14:32:37 +02002859 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01002860 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
2861
tiernoae4a8d12016-07-08 12:30:39 +02002862 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
tiernof97fd272016-07-11 14:32:37 +02002863 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
2864 if len(vims) == 0:
2865 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01002866 myvim = vims.values()[0]
tierno42026a02017-02-10 15:13:40 +01002867
tierno7edb6752016-03-21 17:37:52 +01002868
2869 input_vnfs = action_dict.pop("vnfs", [])
2870 input_vms = action_dict.pop("vms", [])
2871 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
2872 vm_result = {}
2873 vm_error = 0
2874 vm_ok = 0
2875 for sce_vnf in instanceDict['vnfs']:
2876 for vm in sce_vnf['vms']:
2877 if not action_over_all:
2878 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
2879 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
2880 continue
tiernoae4a8d12016-07-08 12:30:39 +02002881 try:
2882 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
tierno7edb6752016-03-21 17:37:52 +01002883 if "console" in action_dict:
tierno20fc2a22016-08-19 17:02:35 +02002884 if not global_config["http_console_proxy"]:
2885 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2886 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2887 protocol=data["protocol"],
2888 ip = data["server"],
2889 port = data["port"],
2890 suffix = data["suffix"]),
2891 "name":vm['name']
2892 }
2893 vm_ok +=1
2894 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
tierno7edb6752016-03-21 17:37:52 +01002895 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
2896 "description": "this console is only reachable by local interface",
2897 "name":vm['name']
2898 }
2899 vm_error+=1
tierno20fc2a22016-08-19 17:02:35 +02002900 else:
tierno7edb6752016-03-21 17:37:52 +01002901 #print "console data", data
tierno42026a02017-02-10 15:13:40 +01002902 try:
tierno20fc2a22016-08-19 17:02:35 +02002903 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
2904 vm_result[ vm['uuid'] ] = {"vim_result": 200,
2905 "description": "{protocol}//{ip}:{port}/{suffix}".format(
2906 protocol=data["protocol"],
2907 ip = global_config["http_console_host"],
2908 port = console_thread.port,
2909 suffix = data["suffix"]),
2910 "name":vm['name']
2911 }
2912 vm_ok +=1
2913 except NfvoException as e:
2914 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2915 vm_error+=1
2916
tierno7edb6752016-03-21 17:37:52 +01002917 else:
tiernof97fd272016-07-11 14:32:37 +02002918 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
tierno7edb6752016-03-21 17:37:52 +01002919 vm_ok +=1
tiernoae4a8d12016-07-08 12:30:39 +02002920 except vimconn.vimconnException as e:
2921 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
2922 vm_error+=1
tierno7edb6752016-03-21 17:37:52 +01002923
2924 if vm_ok==0: #all goes wrong
tierno351863c2016-07-23 01:46:03 +02002925 return vm_result
tierno7edb6752016-03-21 17:37:52 +01002926 else:
tierno351863c2016-07-23 01:46:03 +02002927 return vm_result
tierno42026a02017-02-10 15:13:40 +01002928
tiernob3d36742017-03-03 23:51:05 +01002929
tierno7edb6752016-03-21 17:37:52 +01002930def create_or_use_console_proxy_thread(console_server, console_port):
2931 #look for a non-used port
2932 console_thread_key = console_server + ":" + str(console_port)
2933 if console_thread_key in global_config["console_thread"]:
2934 #global_config["console_thread"][console_thread_key].start_timeout()
tiernof97fd272016-07-11 14:32:37 +02002935 return global_config["console_thread"][console_thread_key]
tierno42026a02017-02-10 15:13:40 +01002936
tierno7edb6752016-03-21 17:37:52 +01002937 for port in global_config["console_port_iterator"]():
tierno20fc2a22016-08-19 17:02:35 +02002938 #print "create_or_use_console_proxy_thread() port:", port
tierno7edb6752016-03-21 17:37:52 +01002939 if port in global_config["console_ports"]:
2940 continue
2941 try:
2942 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
2943 clithread.start()
2944 global_config["console_thread"][console_thread_key] = clithread
2945 global_config["console_ports"][port] = console_thread_key
tiernof97fd272016-07-11 14:32:37 +02002946 return clithread
tierno7edb6752016-03-21 17:37:52 +01002947 except cli.ConsoleProxyExceptionPortUsed as e:
2948 #port used, try with onoher
2949 continue
2950 except cli.ConsoleProxyException as e:
tiernof97fd272016-07-11 14:32:37 +02002951 raise NfvoException(str(e), HTTP_Bad_Request)
2952 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01002953
tiernob3d36742017-03-03 23:51:05 +01002954
tierno7edb6752016-03-21 17:37:52 +01002955def check_tenant(mydb, tenant_id):
2956 '''check that tenant exists at database'''
tiernof97fd272016-07-11 14:32:37 +02002957 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
2958 if not tenant:
2959 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
2960 return
tierno7edb6752016-03-21 17:37:52 +01002961
tiernob3d36742017-03-03 23:51:05 +01002962
tierno7edb6752016-03-21 17:37:52 +01002963def new_tenant(mydb, tenant_dict):
tiernof97fd272016-07-11 14:32:37 +02002964 tenant_id = mydb.new_row("nfvo_tenants", tenant_dict, add_uuid=True)
2965 return tenant_id
tierno7edb6752016-03-21 17:37:52 +01002966
tiernob3d36742017-03-03 23:51:05 +01002967
tierno7edb6752016-03-21 17:37:52 +01002968def delete_tenant(mydb, tenant):
2969 #get nfvo_tenant info
tierno42026a02017-02-10 15:13:40 +01002970
tiernof97fd272016-07-11 14:32:37 +02002971 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
2972 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
2973 return tenant_dict['uuid'] + " " + tenant_dict["name"]
tierno7edb6752016-03-21 17:37:52 +01002974
tiernob3d36742017-03-03 23:51:05 +01002975
tierno7edb6752016-03-21 17:37:52 +01002976def new_datacenter(mydb, datacenter_descriptor):
2977 if "config" in datacenter_descriptor:
2978 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
tierno3ae39742016-09-07 12:17:51 +02002979 #Check that datacenter-type is correct
2980 datacenter_type = datacenter_descriptor.get("type", "openvim");
2981 module_info = None
2982 try:
2983 module = "vimconn_" + datacenter_type
tierno361275f2017-04-25 16:24:34 +02002984 pkg = __import__("osm_ro." + module)
2985 vim_conn = getattr(pkg, module)
2986 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
tierno3ae39742016-09-07 12:17:51 +02002987 except (IOError, ImportError):
tierno361275f2017-04-25 16:24:34 +02002988 # if module_info and module_info[0]:
2989 # file.close(module_info[0])
tierno3ae39742016-09-07 12:17:51 +02002990 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}'.py not installed".format(datacenter_type, module), HTTP_Bad_Request)
tierno42026a02017-02-10 15:13:40 +01002991
tiernof97fd272016-07-11 14:32:37 +02002992 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True)
2993 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01002994
tiernob3d36742017-03-03 23:51:05 +01002995
tierno7edb6752016-03-21 17:37:52 +01002996def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
tierno8fe7a492017-07-11 13:50:04 +02002997 # obtain data, check that only one exist
tiernof97fd272016-07-11 14:32:37 +02002998 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
tierno8fe7a492017-07-11 13:50:04 +02002999
3000 # edit data
tiernof97fd272016-07-11 14:32:37 +02003001 datacenter_id = datacenter['uuid']
3002 where={'uuid': datacenter['uuid']}
tierno8fe7a492017-07-11 13:50:04 +02003003 remove_port_mapping = False
tierno7edb6752016-03-21 17:37:52 +01003004 if "config" in datacenter_descriptor:
tierno8fe7a492017-07-11 13:50:04 +02003005 if datacenter_descriptor['config'] != None:
tierno7edb6752016-03-21 17:37:52 +01003006 try:
3007 new_config_dict = datacenter_descriptor["config"]
3008 #delete null fields
3009 to_delete=[]
3010 for k in new_config_dict:
tierno8fe7a492017-07-11 13:50:04 +02003011 if new_config_dict[k] == None:
tierno7edb6752016-03-21 17:37:52 +01003012 to_delete.append(k)
tierno8fe7a492017-07-11 13:50:04 +02003013 if k == 'sdn-controller':
3014 remove_port_mapping = True
tierno42026a02017-02-10 15:13:40 +01003015
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003016 config_text = datacenter.get("config")
3017 if not config_text:
3018 config_text = '{}'
3019 config_dict = yaml.load(config_text)
tierno7edb6752016-03-21 17:37:52 +01003020 config_dict.update(new_config_dict)
3021 #delete null fields
3022 for k in to_delete:
3023 del config_dict[k]
tiernof97fd272016-07-11 14:32:37 +02003024 except Exception as e:
3025 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
tierno8fe7a492017-07-11 13:50:04 +02003026 if config_dict:
3027 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
3028 else:
3029 datacenter_descriptor["config"] = None
3030 if remove_port_mapping:
3031 try:
3032 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
3033 except ovimException as e:
3034 logger.error("Error deleting datacenter-port-mapping " + str(e))
3035
tiernof97fd272016-07-11 14:32:37 +02003036 mydb.update_rows('datacenters', datacenter_descriptor, where)
3037 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003038
tiernob3d36742017-03-03 23:51:05 +01003039
tierno7edb6752016-03-21 17:37:52 +01003040def delete_datacenter(mydb, datacenter):
3041 #get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02003042 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
3043 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
tierno8fe7a492017-07-11 13:50:04 +02003044 try:
3045 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
3046 except ovimException as e:
3047 logger.error("Error deleting datacenter-port-mapping " + str(e))
tiernof97fd272016-07-11 14:32:37 +02003048 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
tierno7edb6752016-03-21 17:37:52 +01003049
tiernob3d36742017-03-03 23:51:05 +01003050
tierno8008c3a2016-10-13 15:34:28 +00003051def 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 +01003052 #get datacenter info
Vance Shipleyc24b4e22017-05-12 02:34:53 +05303053 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 +01003054 datacenter_name = myvim["name"]
tierno7edb6752016-03-21 17:37:52 +01003055
tierno42026a02017-02-10 15:13:40 +01003056 create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
3057
3058 # get nfvo_tenant info
tiernof97fd272016-07-11 14:32:37 +02003059 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
tierno7edb6752016-03-21 17:37:52 +01003060 if vim_tenant_name==None:
3061 vim_tenant_name=tenant_dict['name']
tierno42026a02017-02-10 15:13:40 +01003062
tierno7edb6752016-03-21 17:37:52 +01003063 #check that this association does not exist before
3064 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
tiernof97fd272016-07-11 14:32:37 +02003065 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
3066 if len(tenants_datacenters)>0:
3067 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
tierno7edb6752016-03-21 17:37:52 +01003068
3069 vim_tenant_id_exist_atdb=False
3070 if not create_vim_tenant:
3071 where_={"datacenter_id": datacenter_id}
3072 if vim_tenant_id!=None:
3073 where_["vim_tenant_id"] = vim_tenant_id
3074 if vim_tenant_name!=None:
3075 where_["vim_tenant_name"] = vim_tenant_name
3076 #check if vim_tenant_id is already at database
tiernof97fd272016-07-11 14:32:37 +02003077 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
3078 if len(datacenter_tenants_dict)>=1:
tierno7edb6752016-03-21 17:37:52 +01003079 datacenter_tenants_dict = datacenter_tenants_dict[0]
3080 vim_tenant_id_exist_atdb=True
3081 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
3082 else: #result=0
3083 datacenter_tenants_dict = {}
3084 #insert at table datacenter_tenants
3085 else: #if vim_tenant_id==None:
3086 #create tenant at VIM if not provided
tiernoae4a8d12016-07-08 12:30:39 +02003087 try:
3088 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
3089 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003090 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 +01003091 datacenter_tenants_dict = {}
3092 datacenter_tenants_dict["created"]="true"
tierno42026a02017-02-10 15:13:40 +01003093
tierno7edb6752016-03-21 17:37:52 +01003094 #fill datacenter_tenants table
3095 if not vim_tenant_id_exist_atdb:
tierno42026a02017-02-10 15:13:40 +01003096 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
tierno7edb6752016-03-21 17:37:52 +01003097 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
tierno42026a02017-02-10 15:13:40 +01003098 datacenter_tenants_dict["user"] = vim_username
3099 datacenter_tenants_dict["passwd"] = vim_password
3100 datacenter_tenants_dict["datacenter_id"] = datacenter_id
tierno8008c3a2016-10-13 15:34:28 +00003101 if config:
3102 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
tiernof97fd272016-07-11 14:32:37 +02003103 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01003104 datacenter_tenants_dict["uuid"] = id_
tierno42026a02017-02-10 15:13:40 +01003105
tierno7edb6752016-03-21 17:37:52 +01003106 #fill tenants_datacenters table
tierno99314902017-04-26 13:23:09 +02003107 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
3108 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
tiernof97fd272016-07-11 14:32:37 +02003109 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
tierno42026a02017-02-10 15:13:40 +01003110 # create thread
3111 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id) # reload data
3112 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
tierno99314902017-04-26 13:23:09 +02003113 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
3114 db=db, db_lock=db_lock, ovim=ovim)
tierno42026a02017-02-10 15:13:40 +01003115 new_thread.start()
tierno867ffe92017-03-27 12:50:34 +02003116 thread_id = datacenter_tenants_dict["uuid"]
tiernob3d36742017-03-03 23:51:05 +01003117 vim_threads["running"][thread_id] = new_thread
tiernof97fd272016-07-11 14:32:37 +02003118 return datacenter_id
tierno7edb6752016-03-21 17:37:52 +01003119
tierno99314902017-04-26 13:23:09 +02003120
3121def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
3122 vim_username=None, vim_password=None, config=None):
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003123 #Obtain the data of this datacenter_tenant_id
3124 vim_data = mydb.get_rows(
3125 SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",
3126 "datacenter_tenants.passwd", "datacenter_tenants.config"),
3127 FROM="datacenter_tenants JOIN tenants_datacenters ON datacenter_tenants.uuid=tenants_datacenters.datacenter_tenant_id",
3128 WHERE={"tenants_datacenters.nfvo_tenant_id": nfvo_tenant,
3129 "tenants_datacenters.datacenter_id": datacenter_id})
3130
3131 logger.debug(str(vim_data))
3132 if len(vim_data) < 1:
3133 raise NfvoException("Datacenter {} is not attached for tenant {}".format(datacenter_id, nfvo_tenant), HTTP_Conflict)
3134
3135 v = vim_data[0]
3136 if v['config']:
3137 v['config'] = yaml.load(v['config'])
3138
3139 if vim_tenant_id:
3140 v['vim_tenant_id'] = vim_tenant_id
3141 if vim_tenant_name:
3142 v['vim_tenant_name'] = vim_tenant_name
3143 if vim_username:
3144 v['user'] = vim_username
3145 if vim_password:
3146 v['passwd'] = vim_password
3147 if config:
3148 if not v['config']:
3149 v['config'] = {}
3150 v['config'].update(config)
3151
3152 logger.debug(str(v))
3153 deassociate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'])
3154 associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'], vim_tenant_name=v['vim_tenant_name'],
3155 vim_username=v['user'], vim_password=v['passwd'], config=v['config'])
3156
3157 return datacenter_id
tiernob3d36742017-03-03 23:51:05 +01003158
tierno7edb6752016-03-21 17:37:52 +01003159def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
3160 #get datacenter info
Adam Israel04f29112017-09-20 21:10:30 -04003161 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003162
3163 #get nfvo_tenant info
3164 if not tenant_id or tenant_id=="any":
3165 tenant_uuid = None
3166 else:
tiernof97fd272016-07-11 14:32:37 +02003167 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
tierno7edb6752016-03-21 17:37:52 +01003168 tenant_uuid = tenant_dict['uuid']
3169
3170 #check that this association exist before
3171 tenants_datacenter_dict={"datacenter_id":datacenter_id }
3172 if tenant_uuid:
3173 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
tiernof97fd272016-07-11 14:32:37 +02003174 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
3175 if len(tenant_datacenter_list)==0 and tenant_uuid:
3176 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01003177
3178 #delete this association
tiernof97fd272016-07-11 14:32:37 +02003179 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
tierno7edb6752016-03-21 17:37:52 +01003180
3181 #get vim_tenant info and deletes
3182 warning=''
3183 for tenant_datacenter_item in tenant_datacenter_list:
tiernof97fd272016-07-11 14:32:37 +02003184 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
3185 #try to delete vim:tenant
3186 try:
3187 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
3188 if vim_tenant_dict['created']=='true':
tierno7edb6752016-03-21 17:37:52 +01003189 #delete tenant at VIM if created by NFVO
tierno42026a02017-02-10 15:13:40 +01003190 try:
tiernoae4a8d12016-07-08 12:30:39 +02003191 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
3192 except vimconn.vimconnException as e:
3193 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
3194 logger.warn(warning)
tiernof97fd272016-07-11 14:32:37 +02003195 except db_base_Exception as e:
3196 logger.error("Cannot delete datacenter_tenants " + str(e))
tierno42026a02017-02-10 15:13:40 +01003197 pass # the error will be caused because dependencies, vim_tenant can not be deleted
tierno867ffe92017-03-27 12:50:34 +02003198 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
tierno42026a02017-02-10 15:13:40 +01003199 thread = vim_threads["running"][thread_id]
tierno867ffe92017-03-27 12:50:34 +02003200 thread.insert_task(new_task("exit", None))
tierno42026a02017-02-10 15:13:40 +01003201 vim_threads["deleting"][thread_id] = thread
tiernof97fd272016-07-11 14:32:37 +02003202 return "datacenter {} detached. {}".format(datacenter_id, warning)
tierno7edb6752016-03-21 17:37:52 +01003203
tiernob3d36742017-03-03 23:51:05 +01003204
tierno7edb6752016-03-21 17:37:52 +01003205def datacenter_action(mydb, tenant_id, datacenter, action_dict):
3206 #DEPRECATED
tierno42026a02017-02-10 15:13:40 +01003207 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003208 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003209
3210 if 'net-update' in action_dict:
tiernoae4a8d12016-07-08 12:30:39 +02003211 try:
tiernof97fd272016-07-11 14:32:37 +02003212 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
tiernoae4a8d12016-07-08 12:30:39 +02003213 #print content
3214 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003215 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
3216 raise NfvoException(str(e), HTTP_Internal_Server_Error)
tierno7edb6752016-03-21 17:37:52 +01003217 #update nets Change from VIM format to NFVO format
3218 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02003219 for net in nets:
tierno7edb6752016-03-21 17:37:52 +01003220 net_nfvo={'datacenter_id': datacenter_id}
3221 net_nfvo['name'] = net['name']
3222 #net_nfvo['description']= net['name']
3223 net_nfvo['vim_net_id'] = net['id']
3224 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
3225 net_nfvo['shared'] = net['shared']
3226 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
3227 net_list.append(net_nfvo)
tiernof97fd272016-07-11 14:32:37 +02003228 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
3229 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
3230 return inserted
tierno7edb6752016-03-21 17:37:52 +01003231 elif 'net-edit' in action_dict:
3232 net = action_dict['net-edit'].pop('net')
tierno42fcc3b2016-07-06 17:20:40 +02003233 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01003234 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
tierno7edb6752016-03-21 17:37:52 +01003235 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02003236 return result
tierno7edb6752016-03-21 17:37:52 +01003237 elif 'net-delete' in action_dict:
3238 net = action_dict['net-deelte'].get('net')
tierno42fcc3b2016-07-06 17:20:40 +02003239 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
tierno42026a02017-02-10 15:13:40 +01003240 result = mydb.delete_row(FROM='datacenter_nets',
tierno7edb6752016-03-21 17:37:52 +01003241 WHERE={'datacenter_id':datacenter_id, what: net})
tiernof97fd272016-07-11 14:32:37 +02003242 return result
tierno7edb6752016-03-21 17:37:52 +01003243
3244 else:
tiernof97fd272016-07-11 14:32:37 +02003245 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01003246
tiernob3d36742017-03-03 23:51:05 +01003247
tierno7edb6752016-03-21 17:37:52 +01003248def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
3249 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003250 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003251
tierno42fcc3b2016-07-06 17:20:40 +02003252 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
tierno42026a02017-02-10 15:13:40 +01003253 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
tierno7edb6752016-03-21 17:37:52 +01003254 WHERE={'datacenter_id':datacenter_id, what: netmap})
tiernof97fd272016-07-11 14:32:37 +02003255 return result
tierno7edb6752016-03-21 17:37:52 +01003256
tiernob3d36742017-03-03 23:51:05 +01003257
tierno7edb6752016-03-21 17:37:52 +01003258def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
3259 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003260 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003261 filter_dict={}
3262 if action_dict:
3263 action_dict = action_dict["netmap"]
3264 if 'vim_id' in action_dict:
3265 filter_dict["id"] = action_dict['vim_id']
3266 if 'vim_name' in action_dict:
3267 filter_dict["name"] = action_dict['vim_name']
3268 else:
3269 filter_dict["shared"] = True
tierno42026a02017-02-10 15:13:40 +01003270
tiernoae4a8d12016-07-08 12:30:39 +02003271 try:
tiernof97fd272016-07-11 14:32:37 +02003272 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02003273 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003274 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
3275 raise NfvoException(str(e), HTTP_Internal_Server_Error)
3276 if len(vim_nets)>1 and action_dict:
3277 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
3278 elif len(vim_nets)==0: # and action_dict:
3279 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +01003280 net_list=[]
tiernof97fd272016-07-11 14:32:37 +02003281 for net in vim_nets:
tierno7edb6752016-03-21 17:37:52 +01003282 net_nfvo={'datacenter_id': datacenter_id}
3283 if action_dict and "name" in action_dict:
3284 net_nfvo['name'] = action_dict['name']
3285 else:
3286 net_nfvo['name'] = net['name']
3287 #net_nfvo['description']= net['name']
3288 net_nfvo['vim_net_id'] = net['id']
3289 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
3290 net_nfvo['shared'] = net['shared']
3291 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
tiernof97fd272016-07-11 14:32:37 +02003292 try:
3293 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
tierno7edb6752016-03-21 17:37:52 +01003294 net_nfvo["status"] = "OK"
tiernof97fd272016-07-11 14:32:37 +02003295 net_nfvo["uuid"] = net_id
3296 except db_base_Exception as e:
3297 if action_dict:
3298 raise
3299 else:
3300 net_nfvo["status"] = "FAIL: " + str(e)
tierno42026a02017-02-10 15:13:40 +01003301 net_list.append(net_nfvo)
3302 return net_list
tierno7edb6752016-03-21 17:37:52 +01003303
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003304def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
3305 # obtain all network data
3306 try:
3307 if utils.check_valid_uuid(network_id):
3308 filter_dict = {"id": network_id}
3309 else:
3310 filter_dict = {"name": network_id}
3311
3312 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3313 network = myvim.get_network_list(filter_dict=filter_dict)
3314 except vimconn.vimconnException as e:
3315 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
3316 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
3317
3318 # ensure the network is defined
3319 if len(network) == 0:
3320 raise NfvoException("Network {} is not present in the system".format(network_id),
3321 HTTP_Bad_Request)
3322
3323 # ensure there is only one network with the provided name
3324 if len(network) > 1:
3325 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), HTTP_Bad_Request)
3326
3327 # ensure it is a dataplane network
3328 if network[0]['type'] != 'data':
3329 return None
3330
3331 # ensure we use the id
3332 network_id = network[0]['id']
3333
3334 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
3335 # and with instance_scenario_id==NULL
3336 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
3337 search_dict = {'vim_net_id': network_id}
3338
3339 try:
3340 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
3341 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
3342 except db_base_Exception as e:
3343 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
3344 network_id) + str(e), HTTP_Internal_Server_Error)
3345
3346 sdn_net_counter = 0
3347 for net in result:
3348 if net['sdn_net_id'] != None:
3349 sdn_net_counter+=1
3350 sdn_net_id = net['sdn_net_id']
3351
3352 if sdn_net_counter == 0:
3353 return None
3354 elif sdn_net_counter == 1:
3355 return sdn_net_id
3356 else:
3357 raise NfvoException("More than one SDN network is associated to vim network {}".format(
3358 network_id), HTTP_Internal_Server_Error)
3359
3360def get_sdn_controller_id(mydb, datacenter):
3361 # Obtain sdn controller id
3362 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
3363 if not config:
3364 return None
3365
3366 return yaml.load(config).get('sdn-controller')
3367
3368def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
3369 try:
3370 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
3371 if not sdn_network_id:
3372 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), HTTP_Internal_Server_Error)
3373
3374 #Obtain sdn controller id
3375 controller_id = get_sdn_controller_id(mydb, datacenter)
3376 if not controller_id:
3377 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), HTTP_Internal_Server_Error)
3378
3379 #Obtain sdn controller info
3380 sdn_controller = ovim.show_of_controller(controller_id)
3381
3382 port_data = {
3383 'name': 'external_port',
3384 'net_id': sdn_network_id,
3385 'ofc_id': controller_id,
3386 'switch_dpid': sdn_controller['dpid'],
3387 'switch_port': descriptor['port']
3388 }
3389
3390 if 'vlan' in descriptor:
3391 port_data['vlan'] = descriptor['vlan']
3392 if 'mac' in descriptor:
3393 port_data['mac'] = descriptor['mac']
3394
3395 result = ovim.new_port(port_data)
3396 except ovimException as e:
3397 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
3398 sdn_network_id, network_id) + str(e), HTTP_Internal_Server_Error)
3399 except db_base_Exception as e:
3400 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
3401 network_id) + str(e), HTTP_Internal_Server_Error)
3402
3403 return 'Port uuid: '+ result
3404
3405def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
3406 if port_id:
3407 filter = {'uuid': port_id}
3408 else:
3409 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
3410 if not sdn_network_id:
3411 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
3412 HTTP_Internal_Server_Error)
3413 #in case no port_id is specified only ports marked as 'external_port' will be detached
3414 filter = {'name': 'external_port', 'net_id': sdn_network_id}
3415
3416 try:
3417 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
3418 except ovimException as e:
3419 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
3420 HTTP_Internal_Server_Error)
3421
3422 if len(port_list) == 0:
3423 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
3424 HTTP_Bad_Request)
3425
3426 port_uuid_list = []
3427 for port in port_list:
3428 try:
3429 port_uuid_list.append(port['uuid'])
3430 ovim.delete_port(port['uuid'])
3431 except ovimException as e:
3432 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), HTTP_Internal_Server_Error)
3433
3434 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
tiernob3d36742017-03-03 23:51:05 +01003435
tierno7edb6752016-03-21 17:37:52 +01003436def vim_action_get(mydb, tenant_id, datacenter, item, name):
3437 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003438 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno7edb6752016-03-21 17:37:52 +01003439 filter_dict={}
3440 if name:
tierno42fcc3b2016-07-06 17:20:40 +02003441 if utils.check_valid_uuid(name):
tierno7edb6752016-03-21 17:37:52 +01003442 filter_dict["id"] = name
3443 else:
3444 filter_dict["name"] = name
tiernoae4a8d12016-07-08 12:30:39 +02003445 try:
3446 if item=="networks":
3447 #filter_dict['tenant_id'] = myvim['tenant_id']
3448 content = myvim.get_network_list(filter_dict=filter_dict)
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003449
3450 if len(content) == 0:
3451 raise NfvoException("Network {} is not present in the system. ".format(name),
3452 HTTP_Bad_Request)
3453
3454 #Update the networks with the attached ports
3455 for net in content:
3456 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
3457 if sdn_network_id != None:
3458 try:
3459 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
3460 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
3461 except ovimException as e:
3462 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), HTTP_Internal_Server_Error)
3463 #Remove field name and if port name is external_port save it as 'type'
3464 for port in port_list:
3465 if port['name'] == 'external_port':
3466 port['type'] = "External"
3467 del port['name']
3468 net['sdn_network_id'] = sdn_network_id
3469 net['sdn_attached_ports'] = port_list
3470
tiernoae4a8d12016-07-08 12:30:39 +02003471 elif item=="tenants":
3472 content = myvim.get_tenant_list(filter_dict=filter_dict)
tierno4540ea52017-01-18 17:44:32 +01003473 elif item == "images":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003474
tierno4540ea52017-01-18 17:44:32 +01003475 content = myvim.get_image_list(filter_dict=filter_dict)
tiernoae4a8d12016-07-08 12:30:39 +02003476 else:
tiernof97fd272016-07-11 14:32:37 +02003477 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernobe41e222016-09-02 15:16:13 +02003478 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
tiernoae4a8d12016-07-08 12:30:39 +02003479 if name and len(content)==1:
tiernof97fd272016-07-11 14:32:37 +02003480 return {item[:-1]: content[0]}
tiernoae4a8d12016-07-08 12:30:39 +02003481 elif name and len(content)==0:
tiernof97fd272016-07-11 14:32:37 +02003482 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 +02003483 datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02003484 else:
tiernof97fd272016-07-11 14:32:37 +02003485 return {item: content}
tiernoae4a8d12016-07-08 12:30:39 +02003486 except vimconn.vimconnException as e:
3487 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
tiernof97fd272016-07-11 14:32:37 +02003488 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
tierno42026a02017-02-10 15:13:40 +01003489
tiernob3d36742017-03-03 23:51:05 +01003490
tierno7edb6752016-03-21 17:37:52 +01003491def vim_action_delete(mydb, tenant_id, datacenter, item, name):
3492 #get datacenter info
tierno392f2852016-05-13 12:28:55 +02003493 if tenant_id == "any":
3494 tenant_id=None
3495
tiernoa2793912016-10-04 08:15:08 +00003496 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tierno392f2852016-05-13 12:28:55 +02003497 #get uuid name
tiernof97fd272016-07-11 14:32:37 +02003498 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
3499 logger.debug("vim_action_delete vim response: " + str(content))
tierno392f2852016-05-13 12:28:55 +02003500 items = content.values()[0]
3501 if type(items)==list and len(items)==0:
tiernof97fd272016-07-11 14:32:37 +02003502 raise NfvoException("Not found " + item, HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02003503 elif type(items)==list and len(items)>1:
tiernof97fd272016-07-11 14:32:37 +02003504 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
tierno392f2852016-05-13 12:28:55 +02003505 else: # it is a dict
3506 item_id = items["id"]
3507 item_name = str(items.get("name"))
tierno42026a02017-02-10 15:13:40 +01003508
tiernoae4a8d12016-07-08 12:30:39 +02003509 try:
3510 if item=="networks":
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003511 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
3512 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
3513 if sdn_network_id != None:
3514 #Delete any port attachment to this network
3515 try:
3516 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
3517 except ovimException as e:
3518 raise NfvoException(
3519 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
3520 HTTP_Internal_Server_Error)
3521
3522 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
3523 for port in port_list:
3524 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
3525
3526 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
3527 try:
3528 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
3529 except db_base_Exception as e:
3530 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
3531 str(e), HTTP_Internal_Server_Error)
3532
3533 #Delete the SDN network
3534 try:
3535 ovim.delete_network(sdn_network_id)
3536 except ovimException as e:
3537 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
3538 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
3539 HTTP_Internal_Server_Error)
3540
tiernoae4a8d12016-07-08 12:30:39 +02003541 content = myvim.delete_network(item_id)
3542 elif item=="tenants":
3543 content = myvim.delete_tenant(item_id)
tierno4540ea52017-01-18 17:44:32 +01003544 elif item == "images":
3545 content = myvim.delete_image(item_id)
tiernoae4a8d12016-07-08 12:30:39 +02003546 else:
tierno42026a02017-02-10 15:13:40 +01003547 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02003548 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003549 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
3550 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02003551
tiernof97fd272016-07-11 14:32:37 +02003552 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
tierno42026a02017-02-10 15:13:40 +01003553
tiernob3d36742017-03-03 23:51:05 +01003554
tierno7edb6752016-03-21 17:37:52 +01003555def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
3556 #get datacenter info
tiernoa2793912016-10-04 08:15:08 +00003557 logger.debug("vim_action_create descriptor %s", str(descriptor))
tierno392f2852016-05-13 12:28:55 +02003558 if tenant_id == "any":
3559 tenant_id=None
tiernoa2793912016-10-04 08:15:08 +00003560 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
tiernoae4a8d12016-07-08 12:30:39 +02003561 try:
3562 if item=="networks":
3563 net = descriptor["network"]
3564 net_name = net.pop("name")
3565 net_type = net.pop("type", "bridge")
garciadeblas9f8456e2016-09-05 05:02:59 +02003566 net_public = net.pop("shared", False)
3567 net_ipprofile = net.pop("ip_profile", None)
tiernoa7d34d02017-02-23 14:42:07 +01003568 net_vlan = net.pop("vlan", None)
3569 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 +02003570
3571 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
3572 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
3573 try:
3574 sdn_network = {}
3575 sdn_network['vlan'] = net_vlan
3576 sdn_network['type'] = net_type
3577 sdn_network['name'] = net_name
3578 ovim_content = ovim.new_network(sdn_network)
3579 except ovimException as e:
3580 self.logger.error("ovimException creating SDN network={} ".format(
3581 sdn_network) + str(e), exc_info=True)
3582 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
3583 HTTP_Internal_Server_Error)
3584
3585 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
3586 # use instance_scenario_id=None to distinguish from real instaces of nets
3587 correspondence = {'instance_scenario_id': None, 'sdn_net_id': ovim_content, 'vim_net_id': content}
3588 #obtain datacenter_tenant_id
3589 correspondence['datacenter_tenant_id'] = mydb.get_rows(SELECT=('uuid',), FROM='datacenter_tenants', WHERE={'datacenter_id': datacenter})[0]['uuid']
3590
3591 try:
3592 mydb.new_row('instance_nets', correspondence, add_uuid=True)
3593 except db_base_Exception as e:
3594 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
3595 str(e), HTTP_Internal_Server_Error)
tiernoae4a8d12016-07-08 12:30:39 +02003596 elif item=="tenants":
3597 tenant = descriptor["tenant"]
3598 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
3599 else:
tierno42026a02017-02-10 15:13:40 +01003600 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
tiernoae4a8d12016-07-08 12:30:39 +02003601 except vimconn.vimconnException as e:
tiernof97fd272016-07-11 14:32:37 +02003602 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
tiernoae4a8d12016-07-08 12:30:39 +02003603
tierno7edb6752016-03-21 17:37:52 +01003604 return vim_action_get(mydb, tenant_id, datacenter, item, content)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003605
3606def sdn_controller_create(mydb, tenant_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003607 data = ovim.new_of_controller(sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003608 logger.debug('New SDN controller created with uuid {}'.format(data))
3609 return data
3610
3611def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003612 data = ovim.edit_of_controller(controller_id, sdn_controller)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003613 msg = 'SDN controller {} updated'.format(data)
3614 logger.debug(msg)
3615 return msg
3616
3617def sdn_controller_list(mydb, tenant_id, controller_id=None):
3618 if controller_id == None:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003619 data = ovim.get_of_controllers()
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003620 else:
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003621 data = ovim.show_of_controller(controller_id)
3622
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003623 msg = 'SDN controller list:\n {}'.format(data)
3624 logger.debug(msg)
3625 return data
3626
3627def sdn_controller_delete(mydb, tenant_id, controller_id):
3628 select_ = ('uuid', 'config')
3629 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
3630 for datacenter in datacenters:
3631 if datacenter['config']:
3632 config = yaml.load(datacenter['config'])
3633 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
3634 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), HTTP_Conflict)
3635
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003636 data = ovim.delete_of_controller(controller_id)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003637 msg = 'SDN controller {} deleted'.format(data)
3638 logger.debug(msg)
3639 return msg
3640
3641def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
3642 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
3643 if len(controller) < 1:
3644 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), HTTP_Not_Found)
3645
3646 try:
3647 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
3648 except:
3649 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), HTTP_Bad_Request)
3650
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003651 sdn_controller = ovim.show_of_controller(sdn_controller_id)
3652 switch_dpid = sdn_controller["dpid"]
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003653
3654 maps = list()
3655 for compute_node in sdn_port_mapping:
3656 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
3657 element = dict()
3658 element["compute_node"] = compute_node["compute_node"]
3659 for port in compute_node["ports"]:
3660 element["pci"] = port.get("pci")
3661 element["switch_port"] = port.get("switch_port")
3662 element["switch_mac"] = port.get("switch_mac")
3663 if not element["pci"] or not (element["switch_port"] or element["switch_mac"]):
3664 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
3665 " or 'switch_mac'", HTTP_Bad_Request)
3666 maps.append(dict(element))
3667
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003668 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 +01003669
3670def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
Pablo Montes Moreno7e0e9c62017-03-27 12:42:32 +02003671 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003672
3673 result = {
3674 "sdn-controller": None,
3675 "datacenter-id": datacenter_id,
3676 "dpid": None,
3677 "ports_mapping": list()
3678 }
3679
3680 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
3681 if datacenter['config']:
3682 config = yaml.load(datacenter['config'])
3683 if 'sdn-controller' in config:
3684 controller_id = config['sdn-controller']
3685 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
3686 result["sdn-controller"] = controller_id
3687 result["dpid"] = sdn_controller["dpid"]
3688
Pablo Montes Moreno6aa0b2b2017-05-23 18:33:12 +02003689 if result["sdn-controller"] == None:
3690 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), HTTP_Bad_Request)
3691 if result["dpid"] == None:
3692 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
3693 HTTP_Internal_Server_Error)
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01003694
3695 if len(maps) == 0:
3696 return result
3697
3698 ports_correspondence_dict = dict()
3699 for link in maps:
3700 if result["sdn-controller"] != link["ofc_id"]:
3701 raise NfvoException("The sdn-controller specified for different port mappings differ", HTTP_Internal_Server_Error)
3702 if result["dpid"] != link["switch_dpid"]:
3703 raise NfvoException("The dpid specified for different port mappings differ", HTTP_Internal_Server_Error)
3704 element = dict()
3705 element["pci"] = link["pci"]
3706 if link["switch_port"]:
3707 element["switch_port"] = link["switch_port"]
3708 if link["switch_mac"]:
3709 element["switch_mac"] = link["switch_mac"]
3710
3711 if not link["compute_node"] in ports_correspondence_dict:
3712 content = dict()
3713 content["compute_node"] = link["compute_node"]
3714 content["ports"] = list()
3715 ports_correspondence_dict[link["compute_node"]] = content
3716
3717 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
3718
3719 for key in sorted(ports_correspondence_dict):
3720 result["ports_mapping"].append(ports_correspondence_dict[key])
3721
3722 return result
3723
3724def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
tierno639520f2017-04-05 19:55:36 +02003725 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})