Prevent URL trailing char errors in VIM/WIM
[osm/RO.git] / RO / osm_ro / nfvo.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefonica Investigacion 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 '''
25 NFVO 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
30 # import imp
31 import json
32 import string
33 import yaml
34 from random import choice as random_choice
35 from osm_ro import utils
36 from osm_ro.utils import deprecated
37 from osm_ro.vim_thread import vim_thread
38 import osm_ro.console_proxy_thread as cli
39 from osm_ro import vimconn
40 import logging
41 import collections
42 import math
43 from uuid import uuid4
44 from osm_ro.db_base import db_base_Exception
45
46 from osm_ro import nfvo_db
47 from threading import Lock
48 import time as t
49 # TODO py3 BEGIN
50 from osm_ro.sdn import Sdn, SdnException as ovimException
51 # from lib_osm_openvim.ovim import ovimException
52 # from unittest.mock import MagicMock
53 # class ovimException(Exception):
54 # pass
55 # TODO py3 END
56
57 from Crypto.PublicKey import RSA
58
59 import osm_im.vnfd as vnfd_catalog
60 import osm_im.nsd as nsd_catalog
61 from pyangbind.lib.serialise import pybindJSONDecoder
62 from copy import deepcopy
63 from pkg_resources import iter_entry_points
64
65
66 # WIM
67 from .wim import sdnconn
68 from .wim.wimconn_dummy import DummyConnector
69 from .wim.failing_connector import FailingConnector
70 from .http_tools import errors as httperrors
71 from .wim.engine import WimEngine
72 from .wim.persistence import WimPersistence
73 from copy import deepcopy
74 from pprint import pformat
75 #
76
77 global global_config
78 # WIM
79 global wim_engine
80 wim_engine = None
81 global sdnconn_imported
82 #
83 global logger
84 global default_volume_size
85 default_volume_size = '5' #size in GB
86 global ovim
87 ovim = None
88 global_config = None
89
90 plugins = {} # dictionary with VIM type as key, loaded module as value
91 vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
92 vim_persistent_info = {}
93 # WIM
94 sdnconn_imported = {} # dictionary with WIM type as key, loaded module as value
95 wim_threads = {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
96 wim_persistent_info = {}
97 #
98
99 logger = logging.getLogger('openmano.nfvo')
100 task_lock = Lock()
101 last_task_id = 0.0
102 db = None
103 db_lock = Lock()
104
105 worker_id = None
106
107 class NfvoException(httperrors.HttpMappedError):
108 """Common Class for NFVO errors"""
109
110 def _load_plugin(name, type="vim"):
111 # type can be vim or sdn
112 global plugins
113 try:
114 for v in iter_entry_points('osm_ro{}.plugins'.format(type), name):
115 plugins[name] = v.load()
116 except Exception as e:
117 logger.critical("Cannot load osm_{}: {}".format(name, e))
118 if name:
119 plugins[name] = FailingConnector("Cannot load osm_{}: {}".format(name, e))
120 if name and name not in plugins:
121 error_text = "Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been" \
122 " registered".format(t=type, n=name)
123 logger.critical(error_text)
124 plugins[name] = FailingConnector(error_text)
125 # raise NfvoException("Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been registered".
126 # format(t=type, n=name), httperrors.Bad_Request)
127
128 def get_task_id():
129 global last_task_id
130 task_id = t.time()
131 if task_id <= last_task_id:
132 task_id = last_task_id + 0.000001
133 last_task_id = task_id
134 return "ACTION-{:.6f}".format(task_id)
135 # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6))
136
137
138 def new_task(name, params, depends=None):
139 """Deprected!!!"""
140 task_id = get_task_id()
141 task = {"status": "enqueued", "id": task_id, "name": name, "params": params}
142 if depends:
143 task["depends"] = depends
144 return task
145
146
147 def is_task_id(id):
148 return True if id[:5] == "TASK-" else False
149
150 def get_process_id():
151 """
152 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
153 will provide a random one
154 :return: Obtained ID
155 """
156 # Try getting docker id. If fails, get pid
157 try:
158 with open("/proc/self/cgroup", "r") as f:
159 text_id_ = f.readline()
160 _, _, text_id = text_id_.rpartition("/")
161 text_id = text_id.replace("\n", "")[:12]
162 if text_id:
163 return text_id
164 except Exception:
165 pass
166 # Return a random id
167 return "".join(random_choice("0123456789abcdef") for _ in range(12))
168
169 def get_non_used_vim_name(datacenter_name, datacenter_id):
170 return "{}:{}:{}".format(
171 worker_id[:12], datacenter_id.replace("-", "")[:32], datacenter_name[:16]
172 )
173
174 # -- Move
175 def get_non_used_wim_name(wim_name, wim_id, tenant_name, tenant_id):
176 name = wim_name[:16]
177 if name not in wim_threads["names"]:
178 wim_threads["names"].append(name)
179 return name
180 name = wim_name[:16] + "." + tenant_name[:16]
181 if name not in wim_threads["names"]:
182 wim_threads["names"].append(name)
183 return name
184 name = wim_id + "-" + tenant_id
185 wim_threads["names"].append(name)
186 return name
187
188
189 def start_service(mydb, persistence=None, wim=None):
190 global db, global_config, plugins, ovim, worker_id
191 db = nfvo_db.nfvo_db(lock=db_lock)
192 mydb.lock = db_lock
193 db.connect(global_config['db_host'], global_config['db_user'], global_config['db_passwd'], global_config['db_name'])
194
195 persistence = persistence or WimPersistence(db)
196
197 try:
198 worker_id = get_process_id()
199 if "rosdn_dummy" not in plugins:
200 plugins["rosdn_dummy"] = DummyConnector
201 # starts ovim library
202 ovim = Sdn(db, plugins)
203
204 global wim_engine
205 wim_engine = wim or WimEngine(persistence, plugins)
206 wim_engine.ovim = ovim
207
208 ovim.start_service()
209
210 #delete old unneeded vim_wim_actions
211 clean_db(mydb)
212
213 # starts vim_threads
214 from_= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
215 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
216 select_ = ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
217 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
218 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
219 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
220 vims = mydb.get_rows(FROM=from_, SELECT=select_)
221 for vim in vims:
222 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
223 'datacenter_id': vim.get('datacenter_id')}
224 if vim["config"]:
225 extra.update(yaml.load(vim["config"], Loader=yaml.Loader))
226 if vim.get('dt_config'):
227 extra.update(yaml.load(vim["dt_config"], Loader=yaml.Loader))
228 plugin_name = "rovim_" + vim["type"]
229 if plugin_name not in plugins:
230 _load_plugin(plugin_name, type="vim")
231
232 thread_id = vim['datacenter_tenant_id']
233 vim_persistent_info[thread_id] = {}
234 try:
235 #if not tenant:
236 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
237 myvim = plugins[plugin_name].vimconnector(
238 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
239 tenant_id=vim['vim_tenant_id'], tenant_name=vim['vim_tenant_name'],
240 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
241 user=vim['user'], passwd=vim['passwd'],
242 config=extra, persistent_info=vim_persistent_info[thread_id]
243 )
244 except vimconn.vimconnException as e:
245 myvim = e
246 logger.error("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
247 vim['datacenter_id'], e))
248 except Exception as e:
249 logger.critical("Cannot launch thread for VIM {} '{}': {}".format(vim['datacenter_name'],
250 vim['datacenter_id'], e))
251 # raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
252 # httperrors.Internal_Server_Error)
253 thread_name = get_non_used_vim_name(vim['datacenter_name'], vim['datacenter_id'])
254 new_thread = vim_thread(task_lock, plugins, thread_name, None,
255 vim['datacenter_tenant_id'], db=db)
256 new_thread.start()
257 vim_threads["running"][thread_id] = new_thread
258 wims = mydb.get_rows(FROM="wim_accounts join wims on wim_accounts.wim_id=wims.uuid",
259 WHERE={"sdn": "true"},
260 SELECT=("wim_accounts.uuid as uuid", "type", "wim_accounts.name as name"))
261 for wim in wims:
262 plugin_name = "rosdn_" + wim["type"]
263 if plugin_name not in plugins:
264 _load_plugin(plugin_name, type="sdn")
265
266 thread_id = wim['uuid']
267 thread_name = get_non_used_vim_name(wim['name'], wim['uuid'])
268 new_thread = vim_thread(task_lock, plugins, thread_name, wim['uuid'], None, db=db)
269 new_thread.start()
270 vim_threads["running"][thread_id] = new_thread
271 wim_engine.start_threads()
272 except db_base_Exception as e:
273 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
274 except ovimException as e:
275 message = str(e)
276 if message[:22] == "DATABASE wrong version":
277 message = "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
278 "at host {dbhost}".format(
279 msg=message[22:-3], dbname=global_config["db_ovim_name"],
280 dbuser=global_config["db_ovim_user"], dbpass=global_config["db_ovim_passwd"],
281 ver=message[-3:-1], dbhost=global_config["db_ovim_host"])
282 raise NfvoException(message, httperrors.Bad_Request)
283
284
285 def stop_service():
286 global ovim, global_config
287 if ovim:
288 ovim.stop_service()
289 for thread_id, thread in vim_threads["running"].items():
290 thread.insert_task("exit")
291 vim_threads["deleting"][thread_id] = thread
292 vim_threads["running"] = {}
293
294 if wim_engine:
295 wim_engine.stop_threads()
296
297 if global_config and global_config.get("console_thread"):
298 for thread in global_config["console_thread"]:
299 thread.terminate = True
300
301 def get_version():
302 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config["version"],
303 global_config["version_date"] ))
304
305 def clean_db(mydb):
306 """
307 Clean unused or old entries at database to avoid unlimited growing
308 :param mydb: database connector
309 :return: None
310 """
311 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
312 now = t.time()-3600*24*7
313 instance_action_id = None
314 nb_deleted = 0
315 while True:
316 actions_to_delete = mydb.get_rows(
317 SELECT=("item", "item_id", "instance_action_id"),
318 FROM="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
319 "left join instance_scenarios as i on ia.instance_id=i.uuid",
320 WHERE={"va.action": "DELETE", "va.modified_at<": now, "i.uuid": None,
321 "va.status": ("DONE", "SUPERSEDED")},
322 LIMIT=100
323 )
324 for to_delete in actions_to_delete:
325 mydb.delete_row(FROM="vim_wim_actions", WHERE=to_delete)
326 if instance_action_id != to_delete["instance_action_id"]:
327 instance_action_id = to_delete["instance_action_id"]
328 mydb.delete_row(FROM="instance_actions", WHERE={"uuid": instance_action_id})
329 nb_deleted += len(actions_to_delete)
330 if len(actions_to_delete) < 100:
331 break
332 # clean locks
333 mydb.update_rows("vim_wim_actions", UPDATE={"worker": None}, WHERE={"worker<>": None})
334
335 if nb_deleted:
336 logger.debug("Removed {} unused vim_wim_actions".format(nb_deleted))
337
338
339 def get_flavorlist(mydb, vnf_id, nfvo_tenant=None):
340 '''Obtain flavorList
341 return result, content:
342 <0, error_text upon error
343 nb_records, flavor_list on success
344 '''
345 WHERE_dict={}
346 WHERE_dict['vnf_id'] = vnf_id
347 if nfvo_tenant is not None:
348 WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
349
350 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
351 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
352 flavors = mydb.get_rows(FROM='vms join flavors on vms.flavor_id=flavors.uuid',SELECT=('flavor_id',),WHERE=WHERE_dict )
353 #print "get_flavor_list result:", result
354 #print "get_flavor_list content:", content
355 flavorList=[]
356 for flavor in flavors:
357 flavorList.append(flavor['flavor_id'])
358 return flavorList
359
360
361 def get_imagelist(mydb, vnf_id, nfvo_tenant=None):
362 """
363 Get used images of all vms belonging to this VNFD
364 :param mydb: database conector
365 :param vnf_id: vnfd uuid
366 :param nfvo_tenant: tenant, not used
367 :return: The list of image uuid used
368 """
369 image_list = []
370 vms = mydb.get_rows(SELECT=('image_id','image_list'), FROM='vms', WHERE={'vnf_id': vnf_id})
371 for vm in vms:
372 if vm["image_id"] and vm["image_id"] not in image_list:
373 image_list.append(vm["image_id"])
374 if vm["image_list"]:
375 vm_image_list = yaml.load(vm["image_list"], Loader=yaml.Loader)
376 for image_dict in vm_image_list:
377 if image_dict["image_id"] not in image_list:
378 image_list.append(image_dict["image_id"])
379 return image_list
380
381
382 def get_vim(mydb, nfvo_tenant=None, datacenter_id=None, datacenter_name=None, datacenter_tenant_id=None,
383 vim_tenant=None, vim_tenant_name=None, vim_user=None, vim_passwd=None, ignore_errors=False):
384 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
385 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
386 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
387 raise exception upon error
388 '''
389 global plugins
390 WHERE_dict={}
391 if nfvo_tenant is not None: WHERE_dict['nfvo_tenant_id'] = nfvo_tenant
392 if datacenter_id is not None: WHERE_dict['d.uuid'] = datacenter_id
393 if datacenter_tenant_id is not None: WHERE_dict['datacenter_tenant_id'] = datacenter_tenant_id
394 if datacenter_name is not None: WHERE_dict['d.name'] = datacenter_name
395 if vim_tenant is not None: WHERE_dict['dt.vim_tenant_id'] = vim_tenant
396 if vim_tenant_name is not None: WHERE_dict['vim_tenant_name'] = vim_tenant_name
397 if nfvo_tenant or vim_tenant or vim_tenant_name or datacenter_tenant_id:
398 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'
399 select_ = ('type','d.config as config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
400 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
401 'user','passwd', 'dt.config as dt_config')
402 else:
403 from_ = 'datacenters as d'
404 select_ = ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
405 try:
406 vims = mydb.get_rows(FROM=from_, SELECT=select_, WHERE=WHERE_dict )
407 vim_dict={}
408 for vim in vims:
409 extra={'datacenter_tenant_id': vim.get('datacenter_tenant_id'),
410 'datacenter_id': vim.get('datacenter_id'),
411 '_vim_type_internal': vim.get('type')}
412 if vim["config"]:
413 extra.update(yaml.load(vim["config"], Loader=yaml.Loader))
414 if vim.get('dt_config'):
415 extra.update(yaml.load(vim["dt_config"], Loader=yaml.Loader))
416 plugin_name = "rovim_" + vim["type"]
417 if plugin_name not in plugins:
418 try:
419 _load_plugin(plugin_name, type="vim")
420 except NfvoException as e:
421 if ignore_errors:
422 logger.error("{}".format(e))
423 continue
424 else:
425 raise
426 try:
427 if 'datacenter_tenant_id' in vim:
428 thread_id = vim["datacenter_tenant_id"]
429 if thread_id not in vim_persistent_info:
430 vim_persistent_info[thread_id] = {}
431 persistent_info = vim_persistent_info[thread_id]
432 else:
433 persistent_info = {}
434 #if not tenant:
435 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
436 vim_dict[vim['datacenter_id']] = plugins[plugin_name].vimconnector(
437 uuid=vim['datacenter_id'], name=vim['datacenter_name'],
438 tenant_id=vim.get('vim_tenant_id',vim_tenant),
439 tenant_name=vim.get('vim_tenant_name',vim_tenant_name),
440 url=vim['vim_url'], url_admin=vim['vim_url_admin'],
441 user=vim.get('user',vim_user), passwd=vim.get('passwd',vim_passwd),
442 config=extra, persistent_info=persistent_info
443 )
444 except Exception as e:
445 if ignore_errors:
446 logger.error("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)))
447 continue
448 http_code = httperrors.Internal_Server_Error
449 if isinstance(e, vimconn.vimconnException):
450 http_code = e.http_code
451 raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, str(e)), http_code)
452 return vim_dict
453 except db_base_Exception as e:
454 raise NfvoException(str(e) + " at nfvo.get_vim", e.http_code)
455
456
457 def rollback(mydb, vims, rollback_list):
458 undeleted_items=[]
459 #delete things by reverse order
460 for i in range(len(rollback_list)-1, -1, -1):
461 item = rollback_list[i]
462 if item["where"]=="vim":
463 if item["vim_id"] not in vims:
464 continue
465 if is_task_id(item["uuid"]):
466 continue
467 vim = vims[item["vim_id"]]
468 try:
469 if item["what"]=="image":
470 vim.delete_image(item["uuid"])
471 mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
472 elif item["what"]=="flavor":
473 vim.delete_flavor(item["uuid"])
474 mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]})
475 elif item["what"]=="network":
476 vim.delete_network(item["uuid"])
477 elif item["what"]=="vm":
478 vim.delete_vminstance(item["uuid"])
479 except vimconn.vimconnException as e:
480 logger.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item['what'], item["uuid"], str(e))
481 undeleted_items.append("{} {} from VIM {}".format(item['what'], item["uuid"], vim["name"]))
482 except db_base_Exception as e:
483 logger.error("Error in rollback. Not possible to delete %s '%s' from DB.datacenters Message: %s", item['what'], item["uuid"], str(e))
484
485 else: # where==mano
486 try:
487 if item["what"]=="image":
488 mydb.delete_row(FROM="images", WHERE={"uuid": item["uuid"]})
489 elif item["what"]=="flavor":
490 mydb.delete_row(FROM="flavors", WHERE={"uuid": item["uuid"]})
491 except db_base_Exception as e:
492 logger.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item['what'], item["uuid"], str(e))
493 undeleted_items.append("{} '{}'".format(item['what'], item["uuid"]))
494 if len(undeleted_items)==0:
495 return True," Rollback successful."
496 else:
497 return False," Rollback fails to delete: " + str(undeleted_items)
498
499
500 def check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1):
501 global global_config
502 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
503 vnfc_interfaces={}
504 for vnfc in vnf_descriptor["vnf"]["VNFC"]:
505 name_dict = {}
506 #dataplane interfaces
507 for numa in vnfc.get("numas",() ):
508 for interface in numa.get("interfaces",()):
509 if interface["name"] in name_dict:
510 raise NfvoException(
511 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
512 vnfc["name"], interface["name"]),
513 httperrors.Bad_Request)
514 name_dict[ interface["name"] ] = "underlay"
515 #bridge interfaces
516 for interface in vnfc.get("bridge-ifaces",() ):
517 if interface["name"] in name_dict:
518 raise NfvoException(
519 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
520 vnfc["name"], interface["name"]),
521 httperrors.Bad_Request)
522 name_dict[ interface["name"] ] = "overlay"
523 vnfc_interfaces[ vnfc["name"] ] = name_dict
524 # check bood-data info
525 # if "boot-data" in vnfc:
526 # # check that user-data is incompatible with users and config-files
527 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
528 # raise NfvoException(
529 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
530 # httperrors.Bad_Request)
531
532 #check if the info in external_connections matches with the one in the vnfcs
533 name_list=[]
534 for external_connection in vnf_descriptor["vnf"].get("external-connections",() ):
535 if external_connection["name"] in name_list:
536 raise NfvoException(
537 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
538 external_connection["name"]),
539 httperrors.Bad_Request)
540 name_list.append(external_connection["name"])
541 if external_connection["VNFC"] not in vnfc_interfaces:
542 raise NfvoException(
543 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
544 external_connection["name"], external_connection["VNFC"]),
545 httperrors.Bad_Request)
546
547 if external_connection["local_iface_name"] not in vnfc_interfaces[ external_connection["VNFC"] ]:
548 raise NfvoException(
549 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
550 external_connection["name"],
551 external_connection["local_iface_name"]),
552 httperrors.Bad_Request )
553
554 #check if the info in internal_connections matches with the one in the vnfcs
555 name_list=[]
556 for internal_connection in vnf_descriptor["vnf"].get("internal-connections",() ):
557 if internal_connection["name"] in name_list:
558 raise NfvoException(
559 "Error at vnf:internal-connections:name, value '{}' already used as an internal-connection".format(
560 internal_connection["name"]),
561 httperrors.Bad_Request)
562 name_list.append(internal_connection["name"])
563 #We should check that internal-connections of type "ptp" have only 2 elements
564
565 if len(internal_connection["elements"])>2 and (internal_connection.get("type") == "ptp" or internal_connection.get("type") == "e-line"):
566 raise NfvoException(
567 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
568 internal_connection["name"],
569 'ptp' if vnf_descriptor_version==1 else 'e-line',
570 'data' if vnf_descriptor_version==1 else "e-lan"),
571 httperrors.Bad_Request)
572 for port in internal_connection["elements"]:
573 vnf = port["VNFC"]
574 iface = port["local_iface_name"]
575 if vnf not in vnfc_interfaces:
576 raise NfvoException(
577 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
578 internal_connection["name"], vnf),
579 httperrors.Bad_Request)
580 if iface not in vnfc_interfaces[ vnf ]:
581 raise NfvoException(
582 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
583 internal_connection["name"], iface),
584 httperrors.Bad_Request)
585 return -httperrors.Bad_Request,
586 if vnf_descriptor_version==1 and "type" not in internal_connection:
587 if vnfc_interfaces[vnf][iface] == "overlay":
588 internal_connection["type"] = "bridge"
589 else:
590 internal_connection["type"] = "data"
591 if vnf_descriptor_version==2 and "implementation" not in internal_connection:
592 if vnfc_interfaces[vnf][iface] == "overlay":
593 internal_connection["implementation"] = "overlay"
594 else:
595 internal_connection["implementation"] = "underlay"
596 if (internal_connection.get("type") == "data" or internal_connection.get("type") == "ptp" or \
597 internal_connection.get("implementation") == "underlay") and vnfc_interfaces[vnf][iface] == "overlay":
598 raise NfvoException(
599 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
600 internal_connection["name"],
601 iface, 'bridge' if vnf_descriptor_version==1 else 'overlay',
602 'data' if vnf_descriptor_version==1 else 'underlay'),
603 httperrors.Bad_Request)
604 if (internal_connection.get("type") == "bridge" or internal_connection.get("implementation") == "overlay") and \
605 vnfc_interfaces[vnf][iface] == "underlay":
606 raise NfvoException(
607 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
608 internal_connection["name"], iface,
609 'data' if vnf_descriptor_version==1 else 'underlay',
610 'bridge' if vnf_descriptor_version==1 else 'overlay'),
611 httperrors.Bad_Request)
612
613
614 def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error=None):
615 #look if image exist
616 if only_create_at_vim:
617 image_mano_id = image_dict['uuid']
618 if return_on_error == None:
619 return_on_error = True
620 else:
621 if image_dict['location']:
622 images = mydb.get_rows(FROM="images", WHERE={'location':image_dict['location'], 'metadata':image_dict['metadata']})
623 else:
624 images = mydb.get_rows(FROM="images", WHERE={'universal_name':image_dict['universal_name'], 'checksum':image_dict['checksum']})
625 if len(images)>=1:
626 image_mano_id = images[0]['uuid']
627 else:
628 #create image in MANO DB
629 temp_image_dict={'name':image_dict['name'], 'description':image_dict.get('description',None),
630 'location':image_dict['location'], 'metadata':image_dict.get('metadata',None),
631 'universal_name':image_dict['universal_name'] , 'checksum':image_dict['checksum']
632 }
633 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
634 image_mano_id = mydb.new_row('images', temp_image_dict, add_uuid=True)
635 rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id})
636 #create image at every vim
637 for vim_id,vim in vims.items():
638 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
639 image_created="false"
640 #look at database
641 image_db = mydb.get_rows(FROM="datacenters_images",
642 WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id})
643 #look at VIM if this image exist
644 try:
645 if image_dict['location'] is not None:
646 image_vim_id = vim.get_image_id_from_path(image_dict['location'])
647 else:
648 filter_dict = {}
649 filter_dict['name'] = image_dict['universal_name']
650 if image_dict.get('checksum') != None:
651 filter_dict['checksum'] = image_dict['checksum']
652 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
653 vim_images = vim.get_image_list(filter_dict)
654 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
655 if len(vim_images) > 1:
656 raise vimconn.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict)), httperrors.Conflict)
657 elif len(vim_images) == 0:
658 raise vimconn.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict)))
659 else:
660 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
661 image_vim_id = vim_images[0]['id']
662
663 except vimconn.vimconnNotFoundException as e:
664 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
665 try:
666 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
667 if image_dict['location']:
668 image_vim_id = vim.new_image(image_dict)
669 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"image","uuid":image_vim_id})
670 image_created="true"
671 else:
672 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
673 raise vimconn.vimconnException(str(e))
674 except vimconn.vimconnException as e:
675 if return_on_error:
676 logger.error("Error creating image at VIM '%s': %s", vim["name"], str(e))
677 raise
678 image_vim_id = None
679 logger.warn("Error creating image at VIM '%s': %s", vim["name"], str(e))
680 continue
681 except vimconn.vimconnException as e:
682 if return_on_error:
683 logger.error("Error contacting VIM to know if the image exists at VIM: %s", str(e))
684 raise
685 logger.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e))
686 image_vim_id = None
687 continue
688 #if we reach here, the image has been created or existed
689 if len(image_db)==0:
690 #add new vim_id at datacenters_images
691 mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id,
692 'image_id':image_mano_id,
693 'vim_id': image_vim_id,
694 'created':image_created})
695 elif image_db[0]["vim_id"]!=image_vim_id:
696 #modify existing vim_id at datacenters_images
697 mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_vim_id':vim_id, 'image_id':image_mano_id})
698
699 return image_vim_id if only_create_at_vim else image_mano_id
700
701
702 def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_vim=False, return_on_error = None):
703 temp_flavor_dict= {'disk':flavor_dict.get('disk',0),
704 'ram':flavor_dict.get('ram'),
705 'vcpus':flavor_dict.get('vcpus'),
706 }
707 if 'extended' in flavor_dict and flavor_dict['extended']==None:
708 del flavor_dict['extended']
709 if 'extended' in flavor_dict:
710 temp_flavor_dict['extended']=yaml.safe_dump(flavor_dict['extended'],default_flow_style=True,width=256)
711
712 #look if flavor exist
713 if only_create_at_vim:
714 flavor_mano_id = flavor_dict['uuid']
715 if return_on_error == None:
716 return_on_error = True
717 else:
718 flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
719 if len(flavors)>=1:
720 flavor_mano_id = flavors[0]['uuid']
721 else:
722 #create flavor
723 #create one by one the images of aditional disks
724 dev_image_list=[] #list of images
725 if 'extended' in flavor_dict and flavor_dict['extended']!=None:
726 dev_nb=0
727 for device in flavor_dict['extended'].get('devices',[]):
728 if "image" not in device and "image name" not in device:
729 continue
730 image_dict={}
731 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
732 image_dict['universal_name']=device.get('image name')
733 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
734 image_dict['location']=device.get('image')
735 #image_dict['new_location']=vnfc.get('image location')
736 image_dict['checksum']=device.get('image checksum')
737 image_metadata_dict = device.get('image metadata', None)
738 image_metadata_str = None
739 if image_metadata_dict != None:
740 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
741 image_dict['metadata']=image_metadata_str
742 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
743 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
744 dev_image_list.append(image_id)
745 dev_nb += 1
746 temp_flavor_dict['name'] = flavor_dict['name']
747 temp_flavor_dict['description'] = flavor_dict.get('description',None)
748 content = mydb.new_row('flavors', temp_flavor_dict, add_uuid=True)
749 flavor_mano_id= content
750 rollback_list.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id})
751 #create flavor at every vim
752 if 'uuid' in flavor_dict:
753 del flavor_dict['uuid']
754 flavor_vim_id=None
755 for vim_id,vim in vims.items():
756 datacenter_vim_id = vim["config"]["datacenter_tenant_id"]
757 flavor_created="false"
758 #look at database
759 flavor_db = mydb.get_rows(FROM="datacenters_flavors",
760 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
761 #look at VIM if this flavor exist SKIPPED
762 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
763 #if res_vim < 0:
764 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
765 # continue
766 #elif res_vim==0:
767
768 # Create the flavor in VIM
769 # Translate images at devices from MANO id to VIM id
770 disk_list = []
771 if 'extended' in flavor_dict and flavor_dict['extended']!=None and "devices" in flavor_dict['extended']:
772 # make a copy of original devices
773 devices_original=[]
774
775 for device in flavor_dict["extended"].get("devices",[]):
776 dev={}
777 dev.update(device)
778 devices_original.append(dev)
779 if 'image' in device:
780 del device['image']
781 if 'image metadata' in device:
782 del device['image metadata']
783 if 'image checksum' in device:
784 del device['image checksum']
785 dev_nb = 0
786 for index in range(0,len(devices_original)) :
787 device=devices_original[index]
788 if "image" not in device and "image name" not in device:
789 # if 'size' in device:
790 disk_list.append({'size': device.get('size', default_volume_size), 'name': device.get('name')})
791 continue
792 image_dict={}
793 image_dict['name']=device.get('image name',flavor_dict['name']+str(dev_nb)+"-img")
794 image_dict['universal_name']=device.get('image name')
795 image_dict['description']=flavor_dict['name']+str(dev_nb)+"-img"
796 image_dict['location']=device.get('image')
797 # image_dict['new_location']=device.get('image location')
798 image_dict['checksum']=device.get('image checksum')
799 image_metadata_dict = device.get('image metadata', None)
800 image_metadata_str = None
801 if image_metadata_dict != None:
802 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
803 image_dict['metadata']=image_metadata_str
804 image_mano_id=create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=False, return_on_error=return_on_error )
805 image_dict["uuid"]=image_mano_id
806 image_vim_id=create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vim=True, return_on_error=return_on_error)
807
808 #save disk information (image must be based on and size
809 disk_list.append({'image_id': image_vim_id, 'size': device.get('size', default_volume_size)})
810
811 flavor_dict["extended"]["devices"][index]['imageRef']=image_vim_id
812 dev_nb += 1
813 if len(flavor_db)>0:
814 #check that this vim_id exist in VIM, if not create
815 flavor_vim_id=flavor_db[0]["vim_id"]
816 try:
817 vim.get_flavor(flavor_vim_id)
818 continue #flavor exist
819 except vimconn.vimconnException:
820 pass
821 #create flavor at vim
822 logger.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim["name"])
823 try:
824 flavor_vim_id = None
825 flavor_vim_id=vim.get_flavor_id_from_data(flavor_dict)
826 flavor_created="false"
827 except vimconn.vimconnException as e:
828 pass
829 try:
830 if not flavor_vim_id:
831 flavor_vim_id = vim.new_flavor(flavor_dict)
832 rollback_list.append({"where":"vim", "vim_id": vim_id, "what":"flavor","uuid":flavor_vim_id})
833 flavor_created="true"
834 except vimconn.vimconnException as e:
835 if return_on_error:
836 logger.error("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
837 raise
838 logger.warn("Error creating flavor at VIM %s: %s.", vim["name"], str(e))
839 flavor_vim_id = None
840 continue
841 #if reach here the flavor has been create or exist
842 if len(flavor_db)==0:
843 #add new vim_id at datacenters_flavors
844 extended_devices_yaml = None
845 if len(disk_list) > 0:
846 extended_devices = dict()
847 extended_devices['disks'] = disk_list
848 extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256)
849 mydb.new_row('datacenters_flavors',
850 {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id,
851 'created': flavor_created, 'extended': extended_devices_yaml})
852 elif flavor_db[0]["vim_id"]!=flavor_vim_id:
853 #modify existing vim_id at datacenters_flavors
854 mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id},
855 WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id})
856
857 return flavor_vim_id if only_create_at_vim else flavor_mano_id
858
859
860 def get_str(obj, field, length):
861 """
862 Obtain the str value,
863 :param obj:
864 :param length:
865 :return:
866 """
867 value = obj.get(field)
868 if value is not None:
869 value = str(value)[:length]
870 return value
871
872 def _lookfor_or_create_image(db_image, mydb, descriptor):
873 """
874 fill image content at db_image dictionary. Check if the image with this image and checksum exist
875 :param db_image: dictionary to insert data
876 :param mydb: database connector
877 :param descriptor: yang descriptor
878 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
879 """
880
881 db_image["name"] = get_str(descriptor, "image", 255)
882 db_image["checksum"] = get_str(descriptor, "image-checksum", 32)
883 if not db_image["checksum"]: # Ensure that if empty string, None is stored
884 db_image["checksum"] = None
885 if db_image["name"].startswith("/"):
886 db_image["location"] = db_image["name"]
887 existing_images = mydb.get_rows(FROM="images", WHERE={'location': db_image["location"]})
888 else:
889 db_image["universal_name"] = db_image["name"]
890 existing_images = mydb.get_rows(FROM="images", WHERE={'universal_name': db_image['universal_name'],
891 'checksum': db_image['checksum']})
892 if existing_images:
893 return existing_images[0]["uuid"]
894 else:
895 image_uuid = str(uuid4())
896 db_image["uuid"] = image_uuid
897 return None
898
899 def get_resource_allocation_params(quota_descriptor):
900 """
901 read the quota_descriptor from vnfd and fetch the resource allocation properties from the descriptor object
902 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
903 :return: quota params for limit, reserve, shares from the descriptor object
904 """
905 quota = {}
906 if quota_descriptor.get("limit"):
907 quota["limit"] = int(quota_descriptor["limit"])
908 if quota_descriptor.get("reserve"):
909 quota["reserve"] = int(quota_descriptor["reserve"])
910 if quota_descriptor.get("shares"):
911 quota["shares"] = int(quota_descriptor["shares"])
912 return quota
913
914 def new_vnfd_v3(mydb, tenant_id, vnf_descriptor):
915 """
916 Parses an OSM IM vnfd_catalog and insert at DB
917 :param mydb:
918 :param tenant_id:
919 :param vnf_descriptor:
920 :return: The list of cretated vnf ids
921 """
922 try:
923 myvnfd = vnfd_catalog.vnfd()
924 try:
925 pybindJSONDecoder.load_ietf_json(vnf_descriptor, None, None, obj=myvnfd, path_helper=True,
926 skip_unknown=True)
927 except Exception as e:
928 raise NfvoException("Error. Invalid VNF descriptor format " + str(e), httperrors.Bad_Request)
929 db_vnfs = []
930 db_nets = []
931 db_vms = []
932 db_vms_index = 0
933 db_interfaces = []
934 db_images = []
935 db_flavors = []
936 db_ip_profiles_index = 0
937 db_ip_profiles = []
938 uuid_list = []
939 vnfd_uuid_list = []
940 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd:vnfd-catalog")
941 if not vnfd_catalog_descriptor:
942 vnfd_catalog_descriptor = vnf_descriptor.get("vnfd-catalog")
943 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd")
944 if not vnfd_descriptor_list:
945 vnfd_descriptor_list = vnfd_catalog_descriptor.get("vnfd:vnfd")
946 for vnfd_yang in myvnfd.vnfd_catalog.vnfd.values():
947 vnfd = vnfd_yang.get()
948
949 # table vnf
950 vnf_uuid = str(uuid4())
951 uuid_list.append(vnf_uuid)
952 vnfd_uuid_list.append(vnf_uuid)
953 vnfd_id = get_str(vnfd, "id", 255)
954 db_vnf = {
955 "uuid": vnf_uuid,
956 "osm_id": vnfd_id,
957 "name": get_str(vnfd, "name", 255),
958 "description": get_str(vnfd, "description", 255),
959 "tenant_id": tenant_id,
960 "vendor": get_str(vnfd, "vendor", 255),
961 "short_name": get_str(vnfd, "short-name", 255),
962 "descriptor": str(vnf_descriptor)[:60000]
963 }
964
965 for vnfd_descriptor in vnfd_descriptor_list:
966 if vnfd_descriptor["id"] == str(vnfd["id"]):
967 break
968
969 # table ip_profiles (ip-profiles)
970 ip_profile_name2db_table_index = {}
971 for ip_profile in vnfd.get("ip-profiles").values():
972 db_ip_profile = {
973 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
974 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
975 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
976 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
977 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
978 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
979 }
980 dns_list = []
981 for dns in ip_profile["ip-profile-params"]["dns-server"].values():
982 dns_list.append(str(dns.get("address")))
983 db_ip_profile["dns_address"] = ";".join(dns_list)
984 if ip_profile["ip-profile-params"].get('security-group'):
985 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
986 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
987 db_ip_profiles_index += 1
988 db_ip_profiles.append(db_ip_profile)
989
990 # table nets (internal-vld)
991 net_id2uuid = {} # for mapping interface with network
992 net_id2index = {} # for mapping interface with network
993 for vld in vnfd.get("internal-vld").values():
994 net_uuid = str(uuid4())
995 uuid_list.append(net_uuid)
996 db_net = {
997 "name": get_str(vld, "name", 255),
998 "vnf_id": vnf_uuid,
999 "uuid": net_uuid,
1000 "description": get_str(vld, "description", 255),
1001 "osm_id": get_str(vld, "id", 255),
1002 "type": "bridge", # TODO adjust depending on connection point type
1003 }
1004 net_id2uuid[vld.get("id")] = net_uuid
1005 net_id2index[vld.get("id")] = len(db_nets)
1006 db_nets.append(db_net)
1007 # ip-profile, link db_ip_profile with db_sce_net
1008 if vld.get("ip-profile-ref"):
1009 ip_profile_name = vld.get("ip-profile-ref")
1010 if ip_profile_name not in ip_profile_name2db_table_index:
1011 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
1012 "'{}'. Reference to a non-existing 'ip_profiles'".format(
1013 str(vnfd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
1014 httperrors.Bad_Request)
1015 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["net_id"] = net_uuid
1016 else: #check no ip-address has been defined
1017 for icp in vld.get("internal-connection-point").values():
1018 if icp.get("ip-address"):
1019 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
1020 "contains an ip-address but no ip-profile has been defined at VLD".format(
1021 str(vnfd["id"]), str(vld["id"]), str(icp["id"])),
1022 httperrors.Bad_Request)
1023
1024 # connection points vaiable declaration
1025 cp_name2iface_uuid = {}
1026 cp_name2vdu_id = {}
1027 cp_name2vm_uuid = {}
1028 cp_name2db_interface = {}
1029 vdu_id2cp_name = {} # stored only when one external connection point is presented at this VDU
1030
1031 # table vms (vdus)
1032 vdu_id2uuid = {}
1033 vdu_id2db_table_index = {}
1034 mgmt_access = {}
1035 for vdu in vnfd.get("vdu").values():
1036
1037 for vdu_descriptor in vnfd_descriptor["vdu"]:
1038 if vdu_descriptor["id"] == str(vdu["id"]):
1039 break
1040 vm_uuid = str(uuid4())
1041 uuid_list.append(vm_uuid)
1042 vdu_id = get_str(vdu, "id", 255)
1043 db_vm = {
1044 "uuid": vm_uuid,
1045 "osm_id": vdu_id,
1046 "name": get_str(vdu, "name", 255),
1047 "description": get_str(vdu, "description", 255),
1048 "pdu_type": get_str(vdu, "pdu-type", 255),
1049 "vnf_id": vnf_uuid,
1050 }
1051 vdu_id2uuid[db_vm["osm_id"]] = vm_uuid
1052 vdu_id2db_table_index[db_vm["osm_id"]] = db_vms_index
1053 if vdu.get("count"):
1054 db_vm["count"] = int(vdu["count"])
1055
1056 # table image
1057 image_present = False
1058 if vdu.get("image"):
1059 image_present = True
1060 db_image = {}
1061 image_uuid = _lookfor_or_create_image(db_image, mydb, vdu)
1062 if not image_uuid:
1063 image_uuid = db_image["uuid"]
1064 db_images.append(db_image)
1065 db_vm["image_id"] = image_uuid
1066 if vdu.get("alternative-images"):
1067 vm_alternative_images = []
1068 for alt_image in vdu.get("alternative-images").values():
1069 db_image = {}
1070 image_uuid = _lookfor_or_create_image(db_image, mydb, alt_image)
1071 if not image_uuid:
1072 image_uuid = db_image["uuid"]
1073 db_images.append(db_image)
1074 vm_alternative_images.append({
1075 "image_id": image_uuid,
1076 "vim_type": str(alt_image["vim-type"]),
1077 # "universal_name": str(alt_image["image"]),
1078 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1079 })
1080
1081 db_vm["image_list"] = yaml.safe_dump(vm_alternative_images, default_flow_style=True, width=256)
1082
1083 # volumes
1084 devices = []
1085 if vdu.get("volumes"):
1086 for volume_key in vdu["volumes"]:
1087 volume = vdu["volumes"][volume_key]
1088 if not image_present:
1089 # Convert the first volume to vnfc.image
1090 image_present = True
1091 db_image = {}
1092 image_uuid = _lookfor_or_create_image(db_image, mydb, volume)
1093 if not image_uuid:
1094 image_uuid = db_image["uuid"]
1095 db_images.append(db_image)
1096 db_vm["image_id"] = image_uuid
1097 else:
1098 # Add Openmano devices
1099 device = {"name": str(volume.get("name"))}
1100 device["type"] = str(volume.get("device-type"))
1101 if volume.get("size"):
1102 device["size"] = int(volume["size"])
1103 if volume.get("image"):
1104 device["image name"] = str(volume["image"])
1105 if volume.get("image-checksum"):
1106 device["image checksum"] = str(volume["image-checksum"])
1107
1108 devices.append(device)
1109
1110 if not db_vm.get("image_id"):
1111 if not db_vm["pdu_type"]:
1112 raise NfvoException("Not defined image for VDU")
1113 # create a fake image
1114
1115 # cloud-init
1116 boot_data = {}
1117 if vdu.get("cloud-init"):
1118 boot_data["user-data"] = str(vdu["cloud-init"])
1119 elif vdu.get("cloud-init-file"):
1120 # TODO Where this file content is present???
1121 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1122 boot_data["user-data"] = str(vdu["cloud-init-file"])
1123
1124 if vdu.get("supplemental-boot-data"):
1125 if vdu["supplemental-boot-data"].get('boot-data-drive'):
1126 boot_data['boot-data-drive'] = True
1127 if vdu["supplemental-boot-data"].get('config-file'):
1128 om_cfgfile_list = list()
1129 for custom_config_file in vdu["supplemental-boot-data"]['config-file'].values():
1130 # TODO Where this file content is present???
1131 cfg_source = str(custom_config_file["source"])
1132 om_cfgfile_list.append({"dest": custom_config_file["dest"],
1133 "content": cfg_source})
1134 boot_data['config-files'] = om_cfgfile_list
1135 if boot_data:
1136 db_vm["boot_data"] = yaml.safe_dump(boot_data, default_flow_style=True, width=256)
1137
1138 db_vms.append(db_vm)
1139 db_vms_index += 1
1140
1141 # table interfaces (internal/external interfaces)
1142 flavor_epa_interfaces = []
1143 # for iface in chain(vdu.get("internal-interface").values(), vdu.get("external-interface").values()):
1144 for iface in vdu.get("interface").values():
1145 flavor_epa_interface = {}
1146 iface_uuid = str(uuid4())
1147 uuid_list.append(iface_uuid)
1148 db_interface = {
1149 "uuid": iface_uuid,
1150 "internal_name": get_str(iface, "name", 255),
1151 "vm_id": vm_uuid,
1152 }
1153 flavor_epa_interface["name"] = db_interface["internal_name"]
1154 if iface.get("virtual-interface").get("vpci"):
1155 db_interface["vpci"] = get_str(iface.get("virtual-interface"), "vpci", 12)
1156 flavor_epa_interface["vpci"] = db_interface["vpci"]
1157
1158 if iface.get("virtual-interface").get("bandwidth"):
1159 bps = int(iface.get("virtual-interface").get("bandwidth"))
1160 db_interface["bw"] = int(math.ceil(bps / 1000000.0))
1161 flavor_epa_interface["bandwidth"] = "{} Mbps".format(db_interface["bw"])
1162
1163 if iface.get("virtual-interface").get("type") == "OM-MGMT":
1164 db_interface["type"] = "mgmt"
1165 elif iface.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1166 db_interface["type"] = "bridge"
1167 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1168 elif iface.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1169 db_interface["type"] = "data"
1170 db_interface["model"] = get_str(iface.get("virtual-interface"), "type", 12)
1171 flavor_epa_interface["dedicated"] = "no" if iface["virtual-interface"]["type"] == "SR-IOV" \
1172 else "yes"
1173 flavor_epa_interfaces.append(flavor_epa_interface)
1174 else:
1175 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1176 "-interface':'type':'{}'. Interface type is not supported".format(
1177 vnfd_id, vdu_id, iface.get("virtual-interface").get("type")),
1178 httperrors.Bad_Request)
1179
1180 if iface.get("mgmt-interface"):
1181 db_interface["type"] = "mgmt"
1182
1183 if iface.get("external-connection-point-ref"):
1184 try:
1185 cp = vnfd.get("connection-point")[iface.get("external-connection-point-ref")]
1186 db_interface["external_name"] = get_str(cp, "name", 255)
1187 cp_name2iface_uuid[db_interface["external_name"]] = iface_uuid
1188 cp_name2vdu_id[db_interface["external_name"]] = vdu_id
1189 cp_name2vm_uuid[db_interface["external_name"]] = vm_uuid
1190 cp_name2db_interface[db_interface["external_name"]] = db_interface
1191 for cp_descriptor in vnfd_descriptor["connection-point"]:
1192 if cp_descriptor["name"] == db_interface["external_name"]:
1193 break
1194 else:
1195 raise KeyError()
1196
1197 if vdu_id in vdu_id2cp_name:
1198 vdu_id2cp_name[vdu_id] = None # more than two connection point for this VDU
1199 else:
1200 vdu_id2cp_name[vdu_id] = db_interface["external_name"]
1201
1202 # port security
1203 if str(cp_descriptor.get("port-security-enabled")).lower() == "false":
1204 db_interface["port_security"] = 0
1205 elif str(cp_descriptor.get("port-security-enabled")).lower() == "true":
1206 db_interface["port_security"] = 1
1207 except KeyError:
1208 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1209 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1210 " at connection-point".format(
1211 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1212 cp=iface.get("vnfd-connection-point-ref")),
1213 httperrors.Bad_Request)
1214 elif iface.get("internal-connection-point-ref"):
1215 try:
1216 for icp_descriptor in vdu_descriptor["internal-connection-point"]:
1217 if icp_descriptor["id"] == str(iface.get("internal-connection-point-ref")):
1218 break
1219 else:
1220 raise KeyError("does not exist at vdu:internal-connection-point")
1221 icp = None
1222 icp_vld = None
1223 for vld in vnfd.get("internal-vld").values():
1224 for cp in vld.get("internal-connection-point").values():
1225 if cp.get("id-ref") == iface.get("internal-connection-point-ref"):
1226 if icp:
1227 raise KeyError("is referenced by more than one 'internal-vld'")
1228 icp = cp
1229 icp_vld = vld
1230 if not icp:
1231 raise KeyError("is not referenced by any 'internal-vld'")
1232
1233 # set network type as data
1234 if iface.get("virtual-interface") and iface["virtual-interface"].get("type") in \
1235 ("SR-IOV", "PCI-PASSTHROUGH"):
1236 db_nets[net_id2index[icp_vld.get("id")]]["type"] = "data"
1237 db_interface["net_id"] = net_id2uuid[icp_vld.get("id")]
1238 if str(icp_descriptor.get("port-security-enabled")).lower() == "false":
1239 db_interface["port_security"] = 0
1240 elif str(icp_descriptor.get("port-security-enabled")).lower() == "true":
1241 db_interface["port_security"] = 1
1242 if icp.get("ip-address"):
1243 if not icp_vld.get("ip-profile-ref"):
1244 raise NfvoException
1245 db_interface["ip_address"] = str(icp.get("ip-address"))
1246 except KeyError as e:
1247 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1248 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1249 " {msg}".format(
1250 vnf=vnfd_id, vdu=vdu_id, iface=iface["name"],
1251 cp=iface.get("internal-connection-point-ref"), msg=str(e)),
1252 httperrors.Bad_Request)
1253 if iface.get("position"):
1254 db_interface["created_at"] = int(iface.get("position")) * 50
1255 if iface.get("mac-address"):
1256 db_interface["mac"] = str(iface.get("mac-address"))
1257 db_interfaces.append(db_interface)
1258
1259 # table flavors
1260 db_flavor = {
1261 "name": get_str(vdu, "name", 250) + "-flv",
1262 "vcpus": int(vdu["vm-flavor"].get("vcpu-count", 1)),
1263 "ram": int(vdu["vm-flavor"].get("memory-mb", 1)),
1264 "disk": int(vdu["vm-flavor"].get("storage-gb", 0)),
1265 }
1266 # TODO revise the case of several numa-node-policy node
1267 extended = {}
1268 numa = {}
1269 if devices:
1270 extended["devices"] = devices
1271 if flavor_epa_interfaces:
1272 numa["interfaces"] = flavor_epa_interfaces
1273 if vdu.get("guest-epa"): # TODO or dedicated_int:
1274 epa_vcpu_set = False
1275 if vdu["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1276 numa_node_policy = vdu["guest-epa"].get("numa-node-policy")
1277 if numa_node_policy.get("node"):
1278 numa_node = next(iter(numa_node_policy["node"].values()))
1279 if numa_node.get("num-cores"):
1280 numa["cores"] = numa_node["num-cores"]
1281 epa_vcpu_set = True
1282 if numa_node.get("paired-threads"):
1283 if numa_node["paired-threads"].get("num-paired-threads"):
1284 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
1285 epa_vcpu_set = True
1286 if len(numa_node["paired-threads"].get("paired-thread-ids")):
1287 numa["paired-threads-id"] = []
1288 for pair in numa_node["paired-threads"]["paired-thread-ids"].values():
1289 numa["paired-threads-id"].append(
1290 (str(pair["thread-a"]), str(pair["thread-b"]))
1291 )
1292 if numa_node.get("num-threads"):
1293 numa["threads"] = int(numa_node["num-threads"])
1294 epa_vcpu_set = True
1295 if numa_node.get("memory-mb"):
1296 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
1297 if vdu["guest-epa"].get("mempage-size"):
1298 if vdu["guest-epa"]["mempage-size"] != "SMALL":
1299 numa["memory"] = max(int(db_flavor["ram"] / 1024), 1)
1300 if vdu["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
1301 if vdu["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1302 if vdu["guest-epa"].get("cpu-thread-pinning-policy") and \
1303 vdu["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1304 numa["cores"] = max(db_flavor["vcpus"], 1)
1305 else:
1306 numa["threads"] = max(db_flavor["vcpus"], 1)
1307 epa_vcpu_set = True
1308 if vdu["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
1309 cpuquota = get_resource_allocation_params(vdu["guest-epa"].get("cpu-quota"))
1310 if cpuquota:
1311 extended["cpu-quota"] = cpuquota
1312 if vdu["guest-epa"].get("mem-quota"):
1313 vduquota = get_resource_allocation_params(vdu["guest-epa"].get("mem-quota"))
1314 if vduquota:
1315 extended["mem-quota"] = vduquota
1316 if vdu["guest-epa"].get("disk-io-quota"):
1317 diskioquota = get_resource_allocation_params(vdu["guest-epa"].get("disk-io-quota"))
1318 if diskioquota:
1319 extended["disk-io-quota"] = diskioquota
1320 if vdu["guest-epa"].get("vif-quota"):
1321 vifquota = get_resource_allocation_params(vdu["guest-epa"].get("vif-quota"))
1322 if vifquota:
1323 extended["vif-quota"] = vifquota
1324 if numa:
1325 extended["numas"] = [numa]
1326 if extended:
1327 extended_text = yaml.safe_dump(extended, default_flow_style=True, width=256)
1328 db_flavor["extended"] = extended_text
1329 # look if flavor exist
1330 temp_flavor_dict = {'disk': db_flavor.get('disk', 0),
1331 'ram': db_flavor.get('ram'),
1332 'vcpus': db_flavor.get('vcpus'),
1333 'extended': db_flavor.get('extended')
1334 }
1335 existing_flavors = mydb.get_rows(FROM="flavors", WHERE=temp_flavor_dict)
1336 if existing_flavors:
1337 flavor_uuid = existing_flavors[0]["uuid"]
1338 else:
1339 flavor_uuid = str(uuid4())
1340 uuid_list.append(flavor_uuid)
1341 db_flavor["uuid"] = flavor_uuid
1342 db_flavors.append(db_flavor)
1343 db_vm["flavor_id"] = flavor_uuid
1344
1345 # VNF affinity and antiaffinity
1346 for pg in vnfd.get("placement-groups").values():
1347 pg_name = get_str(pg, "name", 255)
1348 for vdu in pg.get("member-vdus").values():
1349 vdu_id = get_str(vdu, "member-vdu-ref", 255)
1350 if vdu_id not in vdu_id2db_table_index:
1351 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1352 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
1353 vnf=vnfd_id, pg=pg_name, vdu=vdu_id),
1354 httperrors.Bad_Request)
1355 db_vms[vdu_id2db_table_index[vdu_id]]["availability_zone"] = pg_name
1356 # TODO consider the case of isolation and not colocation
1357 # if pg.get("strategy") == "ISOLATION":
1358
1359 # VNF mgmt configuration
1360 if vnfd["mgmt-interface"].get("vdu-id"):
1361 mgmt_vdu_id = get_str(vnfd["mgmt-interface"], "vdu-id", 255)
1362 if mgmt_vdu_id not in vdu_id2uuid:
1363 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1364 "'{vdu}'. Reference to a non-existing vdu".format(
1365 vnf=vnfd_id, vdu=mgmt_vdu_id),
1366 httperrors.Bad_Request)
1367 mgmt_access["vm_id"] = vdu_id2uuid[mgmt_vdu_id]
1368 mgmt_access["vdu-id"] = mgmt_vdu_id
1369 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1370 if vdu_id2cp_name.get(mgmt_vdu_id):
1371 if cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]:
1372 cp_name2db_interface[vdu_id2cp_name[mgmt_vdu_id]]["type"] = "mgmt"
1373
1374 if vnfd["mgmt-interface"].get("ip-address"):
1375 mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
1376 if vnfd["mgmt-interface"].get("cp") and vnfd.get("vdu"):
1377 if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
1378 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
1379 "Reference to a non-existing connection-point".format(
1380 vnf=vnfd_id, cp=vnfd["mgmt-interface"]["cp"]),
1381 httperrors.Bad_Request)
1382 mgmt_access["vm_id"] = cp_name2vm_uuid[vnfd["mgmt-interface"]["cp"]]
1383 mgmt_access["interface_id"] = cp_name2iface_uuid[vnfd["mgmt-interface"]["cp"]]
1384 mgmt_access["vdu-id"] = cp_name2vdu_id[vnfd["mgmt-interface"]["cp"]]
1385 # mark this interface as of type mgmt
1386 if cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]:
1387 cp_name2db_interface[vnfd["mgmt-interface"]["cp"]]["type"] = "mgmt"
1388
1389 default_user = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1390 "default-user", 64)
1391 if default_user:
1392 mgmt_access["default_user"] = default_user
1393
1394 required = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1395 "required", 6)
1396 if required:
1397 mgmt_access["required"] = required
1398
1399 password_ = get_str(vnfd.get("vnf-configuration", {}).get("config-access", {}),
1400 "password", 64)
1401 if password_:
1402 mgmt_access["password"] = password_
1403
1404 if mgmt_access:
1405 db_vnf["mgmt_access"] = yaml.safe_dump(mgmt_access, default_flow_style=True, width=256)
1406
1407 db_vnfs.append(db_vnf)
1408 db_tables=[
1409 {"vnfs": db_vnfs},
1410 {"nets": db_nets},
1411 {"images": db_images},
1412 {"flavors": db_flavors},
1413 {"ip_profiles": db_ip_profiles},
1414 {"vms": db_vms},
1415 {"interfaces": db_interfaces},
1416 ]
1417
1418 logger.debug("create_vnf Deployment done vnfDict: %s",
1419 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
1420 mydb.new_rows(db_tables, uuid_list)
1421 return vnfd_uuid_list
1422 except NfvoException:
1423 raise
1424 except Exception as e:
1425 logger.error("Exception {}".format(e))
1426 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
1427
1428
1429 @deprecated("Use new_vnfd_v3")
1430 def new_vnf(mydb, tenant_id, vnf_descriptor):
1431 global global_config
1432
1433 # Step 1. Check the VNF descriptor
1434 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=1)
1435 # Step 2. Check tenant exist
1436 vims = {}
1437 if tenant_id != "any":
1438 check_tenant(mydb, tenant_id)
1439 if "tenant_id" in vnf_descriptor["vnf"]:
1440 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1441 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1442 httperrors.Unauthorized)
1443 else:
1444 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1445 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1446 if global_config["auto_push_VNF_to_VIMs"]:
1447 vims = get_vim(mydb, tenant_id, ignore_errors=True)
1448
1449 # Step 4. Review the descriptor and add missing fields
1450 #print vnf_descriptor
1451 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1452 vnf_name = vnf_descriptor['vnf']['name']
1453 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1454 if "physical" in vnf_descriptor['vnf']:
1455 del vnf_descriptor['vnf']['physical']
1456 #print vnf_descriptor
1457
1458 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1459 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1460 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
1461
1462 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1463 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1464 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1465 try:
1466 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1467 for vnfc in vnf_descriptor['vnf']['VNFC']:
1468 VNFCitem={}
1469 VNFCitem["name"] = vnfc['name']
1470 VNFCitem["availability_zone"] = vnfc.get('availability_zone')
1471 VNFCitem["description"] = vnfc.get("description", 'VM {} of the VNF {}'.format(vnfc['name'],vnf_name))
1472
1473 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
1474
1475 myflavorDict = {}
1476 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
1477 myflavorDict["description"] = VNFCitem["description"]
1478 myflavorDict["ram"] = vnfc.get("ram", 0)
1479 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
1480 myflavorDict["disk"] = vnfc.get("disk", 0)
1481 myflavorDict["extended"] = {}
1482
1483 devices = vnfc.get("devices")
1484 if devices != None:
1485 myflavorDict["extended"]["devices"] = devices
1486
1487 # TODO:
1488 # 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
1489 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1490
1491 # Previous code has been commented
1492 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1493 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1494 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1495 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1496 #else:
1497 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1498 # if result2:
1499 # print "Error creating flavor: unknown processor model. Rollback successful."
1500 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1501 # else:
1502 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1503 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1504
1505 if 'numas' in vnfc and len(vnfc['numas'])>0:
1506 myflavorDict['extended']['numas'] = vnfc['numas']
1507
1508 #print myflavorDict
1509
1510 # Step 6.2 New flavors are created in the VIM
1511 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1512
1513 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1514 VNFCitem["flavor_id"] = flavor_id
1515 VNFCDict[vnfc['name']] = VNFCitem
1516
1517 logger.debug("Creating new images in the VIM for each VNFC")
1518 # Step 6.3 New images are created in the VIM
1519 #For each VNFC, we must create the appropriate image.
1520 #This "for" loop might be integrated with the previous one
1521 #In case this integration is made, the VNFCDict might become a VNFClist.
1522 for vnfc in vnf_descriptor['vnf']['VNFC']:
1523 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
1524 image_dict={}
1525 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1526 image_dict['universal_name']=vnfc.get('image name')
1527 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1528 image_dict['location']=vnfc.get('VNFC image')
1529 #image_dict['new_location']=vnfc.get('image location')
1530 image_dict['checksum']=vnfc.get('image checksum')
1531 image_metadata_dict = vnfc.get('image metadata', None)
1532 image_metadata_str = None
1533 if image_metadata_dict is not None:
1534 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1535 image_dict['metadata']=image_metadata_str
1536 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1537 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1538 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1539 VNFCDict[vnfc['name']]["image_id"] = image_id
1540 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
1541 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
1542 if vnfc.get("boot-data"):
1543 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
1544
1545
1546 # Step 7. Storing the VNF descriptor in the repository
1547 if "descriptor" not in vnf_descriptor["vnf"]:
1548 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
1549
1550 # Step 8. Adding the VNF to the NFVO DB
1551 vnf_id = mydb.new_vnf_as_a_whole(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1552 return vnf_id
1553 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1554 _, message = rollback(mydb, vims, rollback_list)
1555 if isinstance(e, db_base_Exception):
1556 error_text = "Exception at database"
1557 elif isinstance(e, KeyError):
1558 error_text = "KeyError exception "
1559 e.http_code = httperrors.Internal_Server_Error
1560 else:
1561 error_text = "Exception at VIM"
1562 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1563 #logger.error("start_scenario %s", error_text)
1564 raise NfvoException(error_text, e.http_code)
1565
1566
1567 @deprecated("Use new_vnfd_v3")
1568 def new_vnf_v02(mydb, tenant_id, vnf_descriptor):
1569 global global_config
1570
1571 # Step 1. Check the VNF descriptor
1572 check_vnf_descriptor(vnf_descriptor, vnf_descriptor_version=2)
1573 # Step 2. Check tenant exist
1574 vims = {}
1575 if tenant_id != "any":
1576 check_tenant(mydb, tenant_id)
1577 if "tenant_id" in vnf_descriptor["vnf"]:
1578 if vnf_descriptor["vnf"]["tenant_id"] != tenant_id:
1579 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor["vnf"]["tenant_id"], tenant_id),
1580 httperrors.Unauthorized)
1581 else:
1582 vnf_descriptor['vnf']['tenant_id'] = tenant_id
1583 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1584 if global_config["auto_push_VNF_to_VIMs"]:
1585 vims = get_vim(mydb, tenant_id, ignore_errors=True)
1586
1587 # Step 4. Review the descriptor and add missing fields
1588 #print vnf_descriptor
1589 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1590 vnf_name = vnf_descriptor['vnf']['name']
1591 vnf_descriptor['vnf']['description'] = vnf_descriptor['vnf'].get("description", vnf_name)
1592 if "physical" in vnf_descriptor['vnf']:
1593 del vnf_descriptor['vnf']['physical']
1594 #print vnf_descriptor
1595
1596 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1597 logger.debug('BEGIN creation of VNF "%s"' % vnf_name)
1598 logger.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name,len(vnf_descriptor['vnf']['VNFC'])))
1599
1600 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1601 VNFCDict = {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1602 rollback_list = [] # It will contain the new images created in mano. It is used for rollback
1603 try:
1604 logger.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1605 for vnfc in vnf_descriptor['vnf']['VNFC']:
1606 VNFCitem={}
1607 VNFCitem["name"] = vnfc['name']
1608 VNFCitem["description"] = vnfc.get("description", 'VM {} of the VNF {}'.format(vnfc['name'],vnf_name))
1609
1610 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
1611
1612 myflavorDict = {}
1613 myflavorDict["name"] = vnfc['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
1614 myflavorDict["description"] = VNFCitem["description"]
1615 myflavorDict["ram"] = vnfc.get("ram", 0)
1616 myflavorDict["vcpus"] = vnfc.get("vcpus", 0)
1617 myflavorDict["disk"] = vnfc.get("disk", 0)
1618 myflavorDict["extended"] = {}
1619
1620 devices = vnfc.get("devices")
1621 if devices != None:
1622 myflavorDict["extended"]["devices"] = devices
1623
1624 # TODO:
1625 # 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
1626 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1627
1628 # Previous code has been commented
1629 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1630 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1631 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1632 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1633 #else:
1634 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1635 # if result2:
1636 # print "Error creating flavor: unknown processor model. Rollback successful."
1637 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1638 # else:
1639 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1640 myflavorDict['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1641
1642 if 'numas' in vnfc and len(vnfc['numas'])>0:
1643 myflavorDict['extended']['numas'] = vnfc['numas']
1644
1645 #print myflavorDict
1646
1647 # Step 6.2 New flavors are created in the VIM
1648 flavor_id = create_or_use_flavor(mydb, vims, myflavorDict, rollback_list)
1649
1650 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1651 VNFCitem["flavor_id"] = flavor_id
1652 VNFCDict[vnfc['name']] = VNFCitem
1653
1654 logger.debug("Creating new images in the VIM for each VNFC")
1655 # Step 6.3 New images are created in the VIM
1656 #For each VNFC, we must create the appropriate image.
1657 #This "for" loop might be integrated with the previous one
1658 #In case this integration is made, the VNFCDict might become a VNFClist.
1659 for vnfc in vnf_descriptor['vnf']['VNFC']:
1660 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
1661 image_dict={}
1662 image_dict['name']=vnfc.get('image name',vnf_name+"-"+vnfc['name']+"-img")
1663 image_dict['universal_name']=vnfc.get('image name')
1664 image_dict['description']=vnfc.get('image name', VNFCDict[vnfc['name']]['description'])
1665 image_dict['location']=vnfc.get('VNFC image')
1666 #image_dict['new_location']=vnfc.get('image location')
1667 image_dict['checksum']=vnfc.get('image checksum')
1668 image_metadata_dict = vnfc.get('image metadata', None)
1669 image_metadata_str = None
1670 if image_metadata_dict is not None:
1671 image_metadata_str = yaml.safe_dump(image_metadata_dict,default_flow_style=True,width=256)
1672 image_dict['metadata']=image_metadata_str
1673 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1674 image_id = create_or_use_image(mydb, vims, image_dict, rollback_list)
1675 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1676 VNFCDict[vnfc['name']]["image_id"] = image_id
1677 VNFCDict[vnfc['name']]["image_path"] = vnfc.get('VNFC image')
1678 VNFCDict[vnfc['name']]["count"] = vnfc.get('count', 1)
1679 if vnfc.get("boot-data"):
1680 VNFCDict[vnfc['name']]["boot_data"] = yaml.safe_dump(vnfc["boot-data"], default_flow_style=True, width=256)
1681
1682 # Step 7. Storing the VNF descriptor in the repository
1683 if "descriptor" not in vnf_descriptor["vnf"]:
1684 vnf_descriptor["vnf"]["descriptor"] = yaml.safe_dump(vnf_descriptor, indent=4, explicit_start=True, default_flow_style=False)
1685
1686 # Step 8. Adding the VNF to the NFVO DB
1687 vnf_id = mydb.new_vnf_as_a_whole2(tenant_id,vnf_name,vnf_descriptor,VNFCDict)
1688 return vnf_id
1689 except (db_base_Exception, vimconn.vimconnException, KeyError) as e:
1690 _, message = rollback(mydb, vims, rollback_list)
1691 if isinstance(e, db_base_Exception):
1692 error_text = "Exception at database"
1693 elif isinstance(e, KeyError):
1694 error_text = "KeyError exception "
1695 e.http_code = httperrors.Internal_Server_Error
1696 else:
1697 error_text = "Exception at VIM"
1698 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
1699 #logger.error("start_scenario %s", error_text)
1700 raise NfvoException(error_text, e.http_code)
1701
1702
1703 def get_vnf_id(mydb, tenant_id, vnf_id):
1704 #check valid tenant_id
1705 check_tenant(mydb, tenant_id)
1706 #obtain data
1707 where_or = {}
1708 if tenant_id != "any":
1709 where_or["tenant_id"] = tenant_id
1710 where_or["public"] = True
1711 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1712
1713 vnf_id = vnf["uuid"]
1714 filter_keys = ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
1715 filtered_content = dict( (k,v) for k,v in vnf.items() if k in filter_keys )
1716 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1717 data={'vnf' : filtered_content}
1718 #GET VM
1719 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id',
1720 SELECT=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1721 'boot_data'),
1722 WHERE={'vnfs.uuid': vnf_id} )
1723 if len(content) != 0:
1724 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
1725 # change boot_data into boot-data
1726 for vm in content:
1727 if vm.get("boot_data"):
1728 vm["boot-data"] = yaml.safe_load(vm["boot_data"])
1729 del vm["boot_data"]
1730
1731 data['vnf']['VNFC'] = content
1732 #TODO: GET all the information from a VNFC and include it in the output.
1733
1734 #GET NET
1735 content = mydb.get_rows(FROM='vnfs join nets on vnfs.uuid=nets.vnf_id',
1736 SELECT=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1737 WHERE={'vnfs.uuid': vnf_id} )
1738 data['vnf']['nets'] = content
1739
1740 #GET ip-profile for each net
1741 for net in data['vnf']['nets']:
1742 ipprofiles = mydb.get_rows(FROM='ip_profiles',
1743 SELECT=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1744 WHERE={'net_id': net["uuid"]} )
1745 if len(ipprofiles)==1:
1746 net["ip_profile"] = ipprofiles[0]
1747 elif len(ipprofiles)>1:
1748 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net['uuid']), httperrors.Bad_Request)
1749
1750
1751 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
1752
1753 #GET External Interfaces
1754 content = mydb.get_rows(FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces on vms.uuid=interfaces.vm_id',\
1755 SELECT=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1756 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
1757 WHERE={'vnfs.uuid': vnf_id, 'interfaces.external_name<>': None} )
1758 #print content
1759 data['vnf']['external-connections'] = content
1760
1761 return data
1762
1763
1764 def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None):
1765 # Check tenant exist
1766 if tenant_id != "any":
1767 check_tenant(mydb, tenant_id)
1768 # Get the URL of the VIM from the nfvo_tenant and the datacenter
1769 vims = get_vim(mydb, tenant_id, ignore_errors=True)
1770 else:
1771 vims={}
1772
1773 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1774 where_or = {}
1775 if tenant_id != "any":
1776 where_or["tenant_id"] = tenant_id
1777 where_or["public"] = True
1778 vnf = mydb.get_table_by_uuid_name('vnfs', vnf_id, "VNF", WHERE_OR=where_or, WHERE_AND_OR="AND")
1779 vnf_id = vnf["uuid"]
1780
1781 # "Getting the list of flavors and tenants of the VNF"
1782 flavorList = get_flavorlist(mydb, vnf_id)
1783 if len(flavorList)==0:
1784 logger.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id)
1785
1786 imageList = get_imagelist(mydb, vnf_id)
1787 if len(imageList)==0:
1788 logger.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id)
1789
1790 deleted = mydb.delete_row_by_id('vnfs', vnf_id)
1791 if deleted == 0:
1792 raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
1793
1794 undeletedItems = []
1795 for flavor in flavorList:
1796 #check if flavor is used by other vnf
1797 try:
1798 c = mydb.get_rows(FROM='vms', WHERE={'flavor_id':flavor} )
1799 if len(c) > 0:
1800 logger.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor)
1801 continue
1802 #flavor not used, must be deleted
1803 #delelte at VIM
1804 c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id': flavor})
1805 for flavor_vim in c:
1806 if not flavor_vim['created']: # skip this flavor because not created by openmano
1807 continue
1808 # look for vim
1809 myvim = None
1810 for vim in vims.values():
1811 if vim["config"]["datacenter_tenant_id"] == flavor_vim["datacenter_vim_id"]:
1812 myvim = vim
1813 break
1814 if not myvim:
1815 continue
1816 try:
1817 myvim.delete_flavor(flavor_vim["vim_id"])
1818 except vimconn.vimconnNotFoundException:
1819 logger.warn("VIM flavor %s not exist at datacenter %s", flavor_vim["vim_id"],
1820 flavor_vim["datacenter_vim_id"] )
1821 except vimconn.vimconnException as e:
1822 logger.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1823 flavor_vim["vim_id"], flavor_vim["datacenter_vim_id"], type(e).__name__, str(e))
1824 undeletedItems.append("flavor {} from VIM {}".format(flavor_vim["vim_id"],
1825 flavor_vim["datacenter_vim_id"]))
1826 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1827 mydb.delete_row_by_id('flavors', flavor)
1828 except db_base_Exception as e:
1829 logger.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor, str(e))
1830 undeletedItems.append("flavor {}".format(flavor))
1831
1832
1833 for image in imageList:
1834 try:
1835 #check if image is used by other vnf
1836 c = mydb.get_rows(FROM='vms', WHERE=[{'image_id': image}, {'image_list LIKE ': '%' + image + '%'}])
1837 if len(c) > 0:
1838 logger.debug("Image '%s' not deleted because it is being used by another VNF", image)
1839 continue
1840 #image not used, must be deleted
1841 #delelte at VIM
1842 c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image})
1843 for image_vim in c:
1844 if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id
1845 continue
1846 if image_vim['created']=='false': #skip this image because not created by openmano
1847 continue
1848 myvim=vims[ image_vim["datacenter_id"] ]
1849 try:
1850 myvim.delete_image(image_vim["vim_id"])
1851 except vimconn.vimconnNotFoundException as e:
1852 logger.warn("VIM image %s not exist at datacenter %s", image_vim["vim_id"], image_vim["datacenter_id"] )
1853 except vimconn.vimconnException as e:
1854 logger.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1855 image_vim["vim_id"], image_vim["datacenter_id"], type(e).__name__, str(e))
1856 undeletedItems.append("image {} from VIM {}".format(image_vim["vim_id"], image_vim["datacenter_id"] ))
1857 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1858 mydb.delete_row_by_id('images', image)
1859 except db_base_Exception as e:
1860 logger.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image, str(e))
1861 undeletedItems.append("image {}".format(image))
1862
1863 return vnf_id + " " + vnf["name"]
1864 #if undeletedItems:
1865 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
1866
1867
1868 @deprecated("Not used")
1869 def get_hosts_info(mydb, nfvo_tenant_id, datacenter_name=None):
1870 result, vims = get_vim(mydb, nfvo_tenant_id, None, datacenter_name)
1871 if result < 0:
1872 return result, vims
1873 elif result == 0:
1874 return -httperrors.Not_Found, "datacenter '{}' not found".format(datacenter_name)
1875 myvim = next(iter(vims.values()))
1876 result,servers = myvim.get_hosts_info()
1877 if result < 0:
1878 return result, servers
1879 topology = {'name':myvim['name'] , 'servers': servers}
1880 return result, topology
1881
1882
1883 def get_hosts(mydb, nfvo_tenant_id):
1884 vims = get_vim(mydb, nfvo_tenant_id)
1885 if len(vims) == 0:
1886 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id)), httperrors.Not_Found)
1887 elif len(vims)>1:
1888 #print "nfvo.datacenter_action() error. Several datacenters found"
1889 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
1890 myvim = next(iter(vims.values()))
1891 try:
1892 hosts = myvim.get_hosts()
1893 logger.debug('VIM hosts response: '+ yaml.safe_dump(hosts, indent=4, default_flow_style=False))
1894
1895 datacenter = {'Datacenters': [ {'name':myvim['name'],'servers':[]} ] }
1896 for host in hosts:
1897 server={'name':host['name'], 'vms':[]}
1898 for vm in host['instances']:
1899 #get internal name and model
1900 try:
1901 c = mydb.get_rows(SELECT=('name',), FROM='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1902 WHERE={'vim_vm_id':vm['id']} )
1903 if len(c) == 0:
1904 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm['id']))
1905 continue
1906 server['vms'].append( {'name':vm['name'] , 'model':c[0]['name']} )
1907
1908 except db_base_Exception as e:
1909 logger.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm['id'], str(e)))
1910 datacenter['Datacenters'][0]['servers'].append(server)
1911 #return -400, "en construccion"
1912
1913 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1914 return datacenter
1915 except vimconn.vimconnException as e:
1916 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e)), e.http_code)
1917
1918
1919 @deprecated("Use new_nsd_v3")
1920 def new_scenario(mydb, tenant_id, topo):
1921
1922 # result, vims = get_vim(mydb, tenant_id)
1923 # if result < 0:
1924 # return result, vims
1925 #1: parse input
1926 if tenant_id != "any":
1927 check_tenant(mydb, tenant_id)
1928 if "tenant_id" in topo:
1929 if topo["tenant_id"] != tenant_id:
1930 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo["tenant_id"], tenant_id),
1931 httperrors.Unauthorized)
1932 else:
1933 tenant_id=None
1934
1935 #1.1: get VNFs and external_networks (other_nets).
1936 vnfs={}
1937 other_nets={} #external_networks, bridge_networks and data_networkds
1938 nodes = topo['topology']['nodes']
1939 for k in nodes.keys():
1940 if nodes[k]['type'] == 'VNF':
1941 vnfs[k] = nodes[k]
1942 vnfs[k]['ifaces'] = {}
1943 elif nodes[k]['type'] == 'other_network' or nodes[k]['type'] == 'external_network':
1944 other_nets[k] = nodes[k]
1945 other_nets[k]['external']=True
1946 elif nodes[k]['type'] == 'network':
1947 other_nets[k] = nodes[k]
1948 other_nets[k]['external']=False
1949
1950
1951 #1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1952 for name,vnf in vnfs.items():
1953 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
1954 error_text = ""
1955 error_pos = "'topology':'nodes':'" + name + "'"
1956 if 'vnf_id' in vnf:
1957 error_text += " 'vnf_id' " + vnf['vnf_id']
1958 where['uuid'] = vnf['vnf_id']
1959 if 'VNF model' in vnf:
1960 error_text += " 'VNF model' " + vnf['VNF model']
1961 where['name'] = vnf['VNF model']
1962 if len(where) == 1:
1963 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos, httperrors.Bad_Request)
1964
1965 vnf_db = mydb.get_rows(SELECT=('uuid','name','description'),
1966 FROM='vnfs',
1967 WHERE=where)
1968 if len(vnf_db)==0:
1969 raise NfvoException("unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
1970 elif len(vnf_db)>1:
1971 raise NfvoException("more than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
1972 vnf['uuid']=vnf_db[0]['uuid']
1973 vnf['description']=vnf_db[0]['description']
1974 #get external interfaces
1975 ext_ifaces = mydb.get_rows(SELECT=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1976 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1977 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
1978 for ext_iface in ext_ifaces:
1979 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type':ext_iface['type']}
1980
1981 #1.4 get list of connections
1982 conections = topo['topology']['connections']
1983 conections_list = []
1984 conections_list_name = []
1985 for k in conections.keys():
1986 if type(conections[k]['nodes'])==dict: #dict with node:iface pairs
1987 ifaces_list = conections[k]['nodes'].items()
1988 elif type(conections[k]['nodes'])==list: #list with dictionary
1989 ifaces_list=[]
1990 conection_pair_list = map(lambda x: x.items(), conections[k]['nodes'] )
1991 for k2 in conection_pair_list:
1992 ifaces_list += k2
1993
1994 con_type = conections[k].get("type", "link")
1995 if con_type != "link":
1996 if k in other_nets:
1997 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k)), httperrors.Bad_Request)
1998 other_nets[k] = {'external': False}
1999 if conections[k].get("graph"):
2000 other_nets[k]["graph"] = conections[k]["graph"]
2001 ifaces_list.append( (k, None) )
2002
2003
2004 if con_type == "external_network":
2005 other_nets[k]['external'] = True
2006 if conections[k].get("model"):
2007 other_nets[k]["model"] = conections[k]["model"]
2008 else:
2009 other_nets[k]["model"] = k
2010 if con_type == "dataplane_net" or con_type == "bridge_net":
2011 other_nets[k]["model"] = con_type
2012
2013 conections_list_name.append(k)
2014 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)
2015 #print set(ifaces_list)
2016 #check valid VNF and iface names
2017 for iface in ifaces_list:
2018 if iface[0] not in vnfs and iface[0] not in other_nets :
2019 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
2020 str(k), iface[0]), httperrors.Not_Found)
2021 if iface[0] in vnfs and iface[1] not in vnfs[ iface[0] ]['ifaces']:
2022 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
2023 str(k), iface[0], iface[1]), httperrors.Not_Found)
2024
2025 #1.5 unify connections from the pair list to a consolidated list
2026 index=0
2027 while index < len(conections_list):
2028 index2 = index+1
2029 while index2 < len(conections_list):
2030 if len(conections_list[index] & conections_list[index2])>0: #common interface, join nets
2031 conections_list[index] |= conections_list[index2]
2032 del conections_list[index2]
2033 del conections_list_name[index2]
2034 else:
2035 index2 += 1
2036 conections_list[index] = list(conections_list[index]) # from set to list again
2037 index += 1
2038 #for k in conections_list:
2039 # print k
2040
2041
2042
2043 #1.6 Delete non external nets
2044 # for k in other_nets.keys():
2045 # if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
2046 # for con in conections_list:
2047 # delete_indexes=[]
2048 # for index in range(0,len(con)):
2049 # if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
2050 # for index in delete_indexes:
2051 # del con[index]
2052 # del other_nets[k]
2053 #1.7: Check external_ports are present at database table datacenter_nets
2054 for k,net in other_nets.items():
2055 error_pos = "'topology':'nodes':'" + k + "'"
2056 if net['external']==False:
2057 if 'name' not in net:
2058 net['name']=k
2059 if 'model' not in net:
2060 raise NfvoException("needed a 'model' at " + error_pos, httperrors.Bad_Request)
2061 if net['model']=='bridge_net':
2062 net['type']='bridge';
2063 elif net['model']=='dataplane_net':
2064 net['type']='data';
2065 else:
2066 raise NfvoException("unknown 'model' '"+ net['model'] +"' at " + error_pos, httperrors.Not_Found)
2067 else: #external
2068 #IF we do not want to check that external network exist at datacenter
2069 pass
2070 #ELSE
2071 # error_text = ""
2072 # WHERE_={}
2073 # if 'net_id' in net:
2074 # error_text += " 'net_id' " + net['net_id']
2075 # WHERE_['uuid'] = net['net_id']
2076 # if 'model' in net:
2077 # error_text += " 'model' " + net['model']
2078 # WHERE_['name'] = net['model']
2079 # if len(WHERE_) == 0:
2080 # return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
2081 # r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2082 # FROM='datacenter_nets', WHERE=WHERE_ )
2083 # if r<0:
2084 # print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2085 # elif r==0:
2086 # print "nfvo.new_scenario Error" +error_text+ " is not present at database"
2087 # return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
2088 # elif r>1:
2089 # print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
2090 # return -httperrors.Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
2091 # other_nets[k].update(net_db[0])
2092 #ENDIF
2093 net_list={}
2094 net_nb=0 #Number of nets
2095 for con in conections_list:
2096 #check if this is connected to a external net
2097 other_net_index=-1
2098 #print
2099 #print "con", con
2100 for index in range(0,len(con)):
2101 #check if this is connected to a external net
2102 for net_key in other_nets.keys():
2103 if con[index][0]==net_key:
2104 if other_net_index>=0:
2105 error_text = "There is some interface connected both to net '{}' and net '{}'".format(
2106 con[other_net_index][0], net_key)
2107 #print "nfvo.new_scenario " + error_text
2108 raise NfvoException(error_text, httperrors.Bad_Request)
2109 else:
2110 other_net_index = index
2111 net_target = net_key
2112 break
2113 #print "other_net_index", other_net_index
2114 try:
2115 if other_net_index>=0:
2116 del con[other_net_index]
2117 #IF we do not want to check that external network exist at datacenter
2118 if other_nets[net_target]['external'] :
2119 if "name" not in other_nets[net_target]:
2120 other_nets[net_target]['name'] = other_nets[net_target]['model']
2121 if other_nets[net_target]["type"] == "external_network":
2122 if vnfs[ con[0][0] ]['ifaces'][ con[0][1] ]["type"] == "data":
2123 other_nets[net_target]["type"] = "data"
2124 else:
2125 other_nets[net_target]["type"] = "bridge"
2126 #ELSE
2127 # if other_nets[net_target]['external'] :
2128 # 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
2129 # if type_=='data' and other_nets[net_target]['type']=="ptp":
2130 # error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2131 # print "nfvo.new_scenario " + error_text
2132 # return -httperrors.Bad_Request, error_text
2133 #ENDIF
2134 for iface in con:
2135 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2136 else:
2137 #create a net
2138 net_type_bridge=False
2139 net_type_data=False
2140 net_target = "__-__net"+str(net_nb)
2141 net_list[net_target] = {'name': conections_list_name[net_nb], #"net-"+str(net_nb),
2142 'description':"net-{} in scenario {}".format(net_nb,topo['name']),
2143 'external':False}
2144 for iface in con:
2145 vnfs[ iface[0] ]['ifaces'][ iface[1] ]['net_key'] = net_target
2146 iface_type = vnfs[ iface[0] ]['ifaces'][ iface[1] ]['type']
2147 if iface_type=='mgmt' or iface_type=='bridge':
2148 net_type_bridge = True
2149 else:
2150 net_type_data = True
2151 if net_type_bridge and net_type_data:
2152 error_text = "Error connection interfaces of bridge type with data type. Firs node {}, iface {}".format(iface[0], iface[1])
2153 #print "nfvo.new_scenario " + error_text
2154 raise NfvoException(error_text, httperrors.Bad_Request)
2155 elif net_type_bridge:
2156 type_='bridge'
2157 else:
2158 type_='data' if len(con)>2 else 'ptp'
2159 net_list[net_target]['type'] = type_
2160 net_nb+=1
2161 except Exception:
2162 error_text = "Error connection node {} : {} does not match any VNF or interface".format(iface[0], iface[1])
2163 #print "nfvo.new_scenario " + error_text
2164 #raise e
2165 raise NfvoException(error_text, httperrors.Bad_Request)
2166
2167 #1.8: Connect to management net all not already connected interfaces of type 'mgmt'
2168 #1.8.1 obtain management net
2169 mgmt_net = mydb.get_rows(SELECT=('uuid','name','description','type','shared'),
2170 FROM='datacenter_nets', WHERE={'name':'mgmt'} )
2171 #1.8.2 check all interfaces from all vnfs
2172 if len(mgmt_net)>0:
2173 add_mgmt_net = False
2174 for vnf in vnfs.values():
2175 for iface in vnf['ifaces'].values():
2176 if iface['type']=='mgmt' and 'net_key' not in iface:
2177 #iface not connected
2178 iface['net_key'] = 'mgmt'
2179 add_mgmt_net = True
2180 if add_mgmt_net and 'mgmt' not in net_list:
2181 net_list['mgmt']=mgmt_net[0]
2182 net_list['mgmt']['external']=True
2183 net_list['mgmt']['graph']={'visible':False}
2184
2185 net_list.update(other_nets)
2186 #print
2187 #print 'net_list', net_list
2188 #print
2189 #print 'vnfs', vnfs
2190 #print
2191
2192 #2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
2193 c = mydb.new_scenario( { 'vnfs':vnfs, 'nets':net_list,
2194 'tenant_id':tenant_id, 'name':topo['name'],
2195 'description':topo.get('description',topo['name']),
2196 'public': topo.get('public', False)
2197 })
2198
2199 return c
2200
2201
2202 @deprecated("Use new_nsd_v3")
2203 def new_scenario_v02(mydb, tenant_id, scenario_dict, version):
2204 """ This creates a new scenario for version 0.2 and 0.3"""
2205 scenario = scenario_dict["scenario"]
2206 if tenant_id != "any":
2207 check_tenant(mydb, tenant_id)
2208 if "tenant_id" in scenario:
2209 if scenario["tenant_id"] != tenant_id:
2210 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
2211 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
2212 scenario["tenant_id"], tenant_id), httperrors.Unauthorized)
2213 else:
2214 tenant_id=None
2215
2216 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
2217 for name,vnf in scenario["vnfs"].items():
2218 where = {"OR": {"tenant_id": tenant_id, 'public': "true"}}
2219 error_text = ""
2220 error_pos = "'scenario':'vnfs':'" + name + "'"
2221 if 'vnf_id' in vnf:
2222 error_text += " 'vnf_id' " + vnf['vnf_id']
2223 where['uuid'] = vnf['vnf_id']
2224 if 'vnf_name' in vnf:
2225 error_text += " 'vnf_name' " + vnf['vnf_name']
2226 where['name'] = vnf['vnf_name']
2227 if len(where) == 1:
2228 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos, httperrors.Bad_Request)
2229 vnf_db = mydb.get_rows(SELECT=('uuid', 'name', 'description'),
2230 FROM='vnfs',
2231 WHERE=where)
2232 if len(vnf_db) == 0:
2233 raise NfvoException("Unknown" + error_text + " at " + error_pos, httperrors.Not_Found)
2234 elif len(vnf_db) > 1:
2235 raise NfvoException("More than one" + error_text + " at " + error_pos + " Concrete with 'vnf_id'", httperrors.Conflict)
2236 vnf['uuid'] = vnf_db[0]['uuid']
2237 vnf['description'] = vnf_db[0]['description']
2238 vnf['ifaces'] = {}
2239 # get external interfaces
2240 ext_ifaces = mydb.get_rows(SELECT=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2241 FROM='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
2242 WHERE={'vnfs.uuid':vnf['uuid'], 'external_name<>': None} )
2243 for ext_iface in ext_ifaces:
2244 vnf['ifaces'][ ext_iface['name'] ] = {'uuid':ext_iface['iface_uuid'], 'type': ext_iface['type']}
2245 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
2246
2247 # 2: Insert net_key and ip_address at every vnf interface
2248 for net_name, net in scenario["networks"].items():
2249 net_type_bridge = False
2250 net_type_data = False
2251 for iface_dict in net["interfaces"]:
2252 if version == "0.2":
2253 temp_dict = iface_dict
2254 ip_address = None
2255 elif version == "0.3":
2256 temp_dict = {iface_dict["vnf"] : iface_dict["vnf_interface"]}
2257 ip_address = iface_dict.get('ip_address', None)
2258 for vnf, iface in temp_dict.items():
2259 if vnf not in scenario["vnfs"]:
2260 error_text = "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2261 net_name, vnf)
2262 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2263 raise NfvoException(error_text, httperrors.Not_Found)
2264 if iface not in scenario["vnfs"][vnf]['ifaces']:
2265 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2266 .format(net_name, iface)
2267 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2268 raise NfvoException(error_text, httperrors.Bad_Request)
2269 if "net_key" in scenario["vnfs"][vnf]['ifaces'][iface]:
2270 error_text = "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2271 "'{}'".format(net_name, iface,scenario["vnfs"][vnf]['ifaces'][iface]['net_key'])
2272 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2273 raise NfvoException(error_text, httperrors.Bad_Request)
2274 scenario["vnfs"][vnf]['ifaces'][ iface ]['net_key'] = net_name
2275 scenario["vnfs"][vnf]['ifaces'][iface]['ip_address'] = ip_address
2276 iface_type = scenario["vnfs"][vnf]['ifaces'][iface]['type']
2277 if iface_type == 'mgmt' or iface_type == 'bridge':
2278 net_type_bridge = True
2279 else:
2280 net_type_data = True
2281
2282 if net_type_bridge and net_type_data:
2283 error_text = "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2284 .format(net_name)
2285 # logger.debug("nfvo.new_scenario " + error_text)
2286 raise NfvoException(error_text, httperrors.Bad_Request)
2287 elif net_type_bridge:
2288 type_ = 'bridge'
2289 else:
2290 type_ = 'data' if len(net["interfaces"]) > 2 else 'ptp'
2291
2292 if net.get("implementation"): # for v0.3
2293 if type_ == "bridge" and net["implementation"] == "underlay":
2294 error_text = "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2295 "'network':'{}'".format(net_name)
2296 # logger.debug(error_text)
2297 raise NfvoException(error_text, httperrors.Bad_Request)
2298 elif type_ != "bridge" and net["implementation"] == "overlay":
2299 error_text = "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2300 "'network':'{}'".format(net_name)
2301 # logger.debug(error_text)
2302 raise NfvoException(error_text, httperrors.Bad_Request)
2303 net.pop("implementation")
2304 if "type" in net and version == "0.3": # for v0.3
2305 if type_ == "data" and net["type"] == "e-line":
2306 error_text = "Error connecting more than 2 interfaces of data type to a network declared as type "\
2307 "'e-line' at 'network':'{}'".format(net_name)
2308 # logger.debug(error_text)
2309 raise NfvoException(error_text, httperrors.Bad_Request)
2310 elif type_ == "ptp" and net["type"] == "e-lan":
2311 type_ = "data"
2312
2313 net['type'] = type_
2314 net['name'] = net_name
2315 net['external'] = net.get('external', False)
2316
2317 # 3: insert at database
2318 scenario["nets"] = scenario["networks"]
2319 scenario['tenant_id'] = tenant_id
2320 scenario_id = mydb.new_scenario(scenario)
2321 return scenario_id
2322
2323
2324 def new_nsd_v3(mydb, tenant_id, nsd_descriptor):
2325 """
2326 Parses an OSM IM nsd_catalog and insert at DB
2327 :param mydb:
2328 :param tenant_id:
2329 :param nsd_descriptor:
2330 :return: The list of created NSD ids
2331 """
2332 try:
2333 mynsd = nsd_catalog.nsd()
2334 try:
2335 pybindJSONDecoder.load_ietf_json(nsd_descriptor, None, None, obj=mynsd, skip_unknown=True)
2336 except Exception as e:
2337 raise NfvoException("Error. Invalid NS descriptor format: " + str(e), httperrors.Bad_Request)
2338 db_scenarios = []
2339 db_sce_nets = []
2340 db_sce_vnfs = []
2341 db_sce_interfaces = []
2342 db_sce_vnffgs = []
2343 db_sce_rsps = []
2344 db_sce_rsp_hops = []
2345 db_sce_classifiers = []
2346 db_sce_classifier_matches = []
2347 db_ip_profiles = []
2348 db_ip_profiles_index = 0
2349 uuid_list = []
2350 nsd_uuid_list = []
2351 for nsd_yang in mynsd.nsd_catalog.nsd.values():
2352 nsd = nsd_yang.get()
2353
2354 # table scenarios
2355 scenario_uuid = str(uuid4())
2356 uuid_list.append(scenario_uuid)
2357 nsd_uuid_list.append(scenario_uuid)
2358 db_scenario = {
2359 "uuid": scenario_uuid,
2360 "osm_id": get_str(nsd, "id", 255),
2361 "name": get_str(nsd, "name", 255),
2362 "description": get_str(nsd, "description", 255),
2363 "tenant_id": tenant_id,
2364 "vendor": get_str(nsd, "vendor", 255),
2365 "short_name": get_str(nsd, "short-name", 255),
2366 "descriptor": str(nsd_descriptor)[:60000],
2367 }
2368 db_scenarios.append(db_scenario)
2369
2370 # table sce_vnfs (constituent-vnfd)
2371 vnf_index2scevnf_uuid = {}
2372 vnf_index2vnf_uuid = {}
2373 for vnf in nsd.get("constituent-vnfd").values():
2374 existing_vnf = mydb.get_rows(FROM="vnfs", WHERE={'osm_id': str(vnf["vnfd-id-ref"])[:255],
2375 'tenant_id': tenant_id})
2376 if not existing_vnf:
2377 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2378 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2379 str(nsd["id"]), str(vnf["vnfd-id-ref"])[:255]),
2380 httperrors.Bad_Request)
2381 sce_vnf_uuid = str(uuid4())
2382 uuid_list.append(sce_vnf_uuid)
2383 db_sce_vnf = {
2384 "uuid": sce_vnf_uuid,
2385 "scenario_id": scenario_uuid,
2386 # "name": get_str(vnf, "member-vnf-index", 255),
2387 "name": existing_vnf[0]["name"][:200] + "." + get_str(vnf, "member-vnf-index", 50),
2388 "vnf_id": existing_vnf[0]["uuid"],
2389 "member_vnf_index": str(vnf["member-vnf-index"]),
2390 # TODO 'start-by-default': True
2391 }
2392 vnf_index2scevnf_uuid[str(vnf['member-vnf-index'])] = sce_vnf_uuid
2393 vnf_index2vnf_uuid[str(vnf['member-vnf-index'])] = existing_vnf[0]["uuid"]
2394 db_sce_vnfs.append(db_sce_vnf)
2395
2396 # table ip_profiles (ip-profiles)
2397 ip_profile_name2db_table_index = {}
2398 for ip_profile in nsd.get("ip-profiles").values():
2399 db_ip_profile = {
2400 "ip_version": str(ip_profile["ip-profile-params"].get("ip-version", "ipv4")),
2401 "subnet_address": str(ip_profile["ip-profile-params"].get("subnet-address")),
2402 "gateway_address": str(ip_profile["ip-profile-params"].get("gateway-address")),
2403 "dhcp_enabled": str(ip_profile["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2404 "dhcp_start_address": str(ip_profile["ip-profile-params"]["dhcp-params"].get("start-address")),
2405 "dhcp_count": str(ip_profile["ip-profile-params"]["dhcp-params"].get("count")),
2406 }
2407 dns_list = []
2408 for dns in ip_profile["ip-profile-params"]["dns-server"].values():
2409 dns_list.append(str(dns.get("address")))
2410 db_ip_profile["dns_address"] = ";".join(dns_list)
2411 if ip_profile["ip-profile-params"].get('security-group'):
2412 db_ip_profile["security_group"] = ip_profile["ip-profile-params"]['security-group']
2413 ip_profile_name2db_table_index[str(ip_profile["name"])] = db_ip_profiles_index
2414 db_ip_profiles_index += 1
2415 db_ip_profiles.append(db_ip_profile)
2416
2417 # table sce_nets (internal-vld)
2418 for vld in nsd.get("vld").values():
2419 sce_net_uuid = str(uuid4())
2420 uuid_list.append(sce_net_uuid)
2421 db_sce_net = {
2422 "uuid": sce_net_uuid,
2423 "name": get_str(vld, "name", 255),
2424 "scenario_id": scenario_uuid,
2425 # "type": #TODO
2426 "multipoint": not vld.get("type") == "ELINE",
2427 "osm_id": get_str(vld, "id", 255),
2428 # "external": #TODO
2429 "description": get_str(vld, "description", 255),
2430 }
2431 # guess type of network
2432 if vld.get("mgmt-network"):
2433 db_sce_net["type"] = "bridge"
2434 db_sce_net["external"] = True
2435 elif vld.get("provider-network").get("overlay-type") == "VLAN":
2436 db_sce_net["type"] = "data"
2437 else:
2438 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2439 db_sce_net["type"] = None
2440 db_sce_nets.append(db_sce_net)
2441
2442 # ip-profile, link db_ip_profile with db_sce_net
2443 if vld.get("ip-profile-ref"):
2444 ip_profile_name = vld.get("ip-profile-ref")
2445 if ip_profile_name not in ip_profile_name2db_table_index:
2446 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2447 " Reference to a non-existing 'ip_profiles'".format(
2448 str(nsd["id"]), str(vld["id"]), str(vld["ip-profile-ref"])),
2449 httperrors.Bad_Request)
2450 db_ip_profiles[ip_profile_name2db_table_index[ip_profile_name]]["sce_net_id"] = sce_net_uuid
2451 elif vld.get("vim-network-name"):
2452 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
2453
2454 # table sce_interfaces (vld:vnfd-connection-point-ref)
2455 for iface in vld.get("vnfd-connection-point-ref").values():
2456 # Check if there are VDUs in the descriptor
2457 vnf_index = str(iface['member-vnf-index-ref'])
2458 existing_vdus = mydb.get_rows(SELECT=('vms.uuid'), FROM="vms", WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index]})
2459 if existing_vdus:
2460 # check correct parameters
2461 if vnf_index not in vnf_index2vnf_uuid:
2462 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2463 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2464 "'nsd':'constituent-vnfd'".format(
2465 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
2466 httperrors.Bad_Request)
2467
2468 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
2469 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2470 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2471 'external_name': get_str(iface, "vnfd-connection-point-ref",
2472 255)})
2473 if not existing_ifaces:
2474 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2475 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2476 "connection-point name at VNFD '{}'".format(
2477 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2478 str(iface.get("vnfd-id-ref"))[:255]),
2479 httperrors.Bad_Request)
2480 interface_uuid = existing_ifaces[0]["uuid"]
2481 if existing_ifaces[0]["iface_type"] == "data":
2482 db_sce_net["type"] = "data"
2483 sce_interface_uuid = str(uuid4())
2484 uuid_list.append(sce_net_uuid)
2485 iface_ip_address = None
2486 if iface.get("ip-address"):
2487 iface_ip_address = str(iface.get("ip-address"))
2488 db_sce_interface = {
2489 "uuid": sce_interface_uuid,
2490 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2491 "sce_net_id": sce_net_uuid,
2492 "interface_id": interface_uuid,
2493 "ip_address": iface_ip_address,
2494 }
2495 db_sce_interfaces.append(db_sce_interface)
2496 if not db_sce_net["type"]:
2497 db_sce_net["type"] = "bridge"
2498
2499 # table sce_vnffgs (vnffgd)
2500 for vnffg in nsd.get("vnffgd").values():
2501 sce_vnffg_uuid = str(uuid4())
2502 uuid_list.append(sce_vnffg_uuid)
2503 db_sce_vnffg = {
2504 "uuid": sce_vnffg_uuid,
2505 "name": get_str(vnffg, "name", 255),
2506 "scenario_id": scenario_uuid,
2507 "vendor": get_str(vnffg, "vendor", 255),
2508 "description": get_str(vld, "description", 255),
2509 }
2510 db_sce_vnffgs.append(db_sce_vnffg)
2511
2512 # deal with rsps
2513 for rsp in vnffg.get("rsp").values():
2514 sce_rsp_uuid = str(uuid4())
2515 uuid_list.append(sce_rsp_uuid)
2516 db_sce_rsp = {
2517 "uuid": sce_rsp_uuid,
2518 "name": get_str(rsp, "name", 255),
2519 "sce_vnffg_id": sce_vnffg_uuid,
2520 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2521 }
2522 db_sce_rsps.append(db_sce_rsp)
2523 for iface in rsp.get("vnfd-connection-point-ref").values():
2524 vnf_index = str(iface['member-vnf-index-ref'])
2525 if_order = int(iface['order'])
2526 # check correct parameters
2527 if vnf_index not in vnf_index2vnf_uuid:
2528 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2529 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2530 "'nsd':'constituent-vnfd'".format(
2531 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
2532 httperrors.Bad_Request)
2533
2534 ingress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2535 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2536 WHERE={
2537 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2538 'external_name': get_str(iface, "vnfd-ingress-connection-point-ref",
2539 255)})
2540 if not ingress_existing_ifaces:
2541 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2542 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
2543 "connection-point name at VNFD '{}'".format(
2544 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-ingress-connection-point-ref"]),
2545 str(iface.get("vnfd-id-ref"))[:255]), httperrors.Bad_Request)
2546
2547 egress_existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2548 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2549 WHERE={
2550 'vnf_id': vnf_index2vnf_uuid[vnf_index],
2551 'external_name': get_str(iface, "vnfd-egress-connection-point-ref",
2552 255)})
2553 if not egress_existing_ifaces:
2554 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2555 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2556 "connection-point name at VNFD '{}'".format(
2557 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-egress-connection-point-ref"]),
2558 str(iface.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request)
2559
2560 ingress_interface_uuid = ingress_existing_ifaces[0]["uuid"]
2561 egress_interface_uuid = egress_existing_ifaces[0]["uuid"]
2562 sce_rsp_hop_uuid = str(uuid4())
2563 uuid_list.append(sce_rsp_hop_uuid)
2564 db_sce_rsp_hop = {
2565 "uuid": sce_rsp_hop_uuid,
2566 "if_order": if_order,
2567 "ingress_interface_id": ingress_interface_uuid,
2568 "egress_interface_id": egress_interface_uuid,
2569 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2570 "sce_rsp_id": sce_rsp_uuid,
2571 }
2572 db_sce_rsp_hops.append(db_sce_rsp_hop)
2573
2574 # deal with classifiers
2575 for classifier in vnffg.get("classifier").values():
2576 sce_classifier_uuid = str(uuid4())
2577 uuid_list.append(sce_classifier_uuid)
2578
2579 # source VNF
2580 vnf_index = str(classifier['member-vnf-index-ref'])
2581 if vnf_index not in vnf_index2vnf_uuid:
2582 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2583 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2584 "'nsd':'constituent-vnfd'".format(
2585 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
2586 httperrors.Bad_Request)
2587 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2588 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2589 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2590 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2591 255)})
2592 if not existing_ifaces:
2593 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2594 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2595 "connection-point name at VNFD '{}'".format(
2596 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2597 str(iface.get("vnfd-id-ref"))[:255]),
2598 httperrors.Bad_Request)
2599 interface_uuid = existing_ifaces[0]["uuid"]
2600
2601 db_sce_classifier = {
2602 "uuid": sce_classifier_uuid,
2603 "name": get_str(classifier, "name", 255),
2604 "sce_vnffg_id": sce_vnffg_uuid,
2605 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2606 "interface_id": interface_uuid,
2607 }
2608 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2609 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2610 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2611 db_sce_classifiers.append(db_sce_classifier)
2612
2613 for match in classifier.get("match-attributes").values():
2614 sce_classifier_match_uuid = str(uuid4())
2615 uuid_list.append(sce_classifier_match_uuid)
2616 db_sce_classifier_match = {
2617 "uuid": sce_classifier_match_uuid,
2618 "ip_proto": get_str(match, "ip-proto", 2),
2619 "source_ip": get_str(match, "source-ip-address", 16),
2620 "destination_ip": get_str(match, "destination-ip-address", 16),
2621 "source_port": get_str(match, "source-port", 5),
2622 "destination_port": get_str(match, "destination-port", 5),
2623 "sce_classifier_id": sce_classifier_uuid,
2624 }
2625 db_sce_classifier_matches.append(db_sce_classifier_match)
2626 # TODO: vnf/cp keys
2627
2628 # remove unneeded id's in sce_rsps
2629 for rsp in db_sce_rsps:
2630 rsp.pop('id')
2631
2632 db_tables = [
2633 {"scenarios": db_scenarios},
2634 {"sce_nets": db_sce_nets},
2635 {"ip_profiles": db_ip_profiles},
2636 {"sce_vnfs": db_sce_vnfs},
2637 {"sce_interfaces": db_sce_interfaces},
2638 {"sce_vnffgs": db_sce_vnffgs},
2639 {"sce_rsps": db_sce_rsps},
2640 {"sce_rsp_hops": db_sce_rsp_hops},
2641 {"sce_classifiers": db_sce_classifiers},
2642 {"sce_classifier_matches": db_sce_classifier_matches},
2643 ]
2644
2645 logger.debug("new_nsd_v3 done: %s",
2646 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2647 mydb.new_rows(db_tables, uuid_list)
2648 return nsd_uuid_list
2649 except NfvoException:
2650 raise
2651 except Exception as e:
2652 logger.error("Exception {}".format(e))
2653 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
2654
2655
2656 def edit_scenario(mydb, tenant_id, scenario_id, data):
2657 data["uuid"] = scenario_id
2658 data["tenant_id"] = tenant_id
2659 c = mydb.edit_scenario( data )
2660 return c
2661
2662
2663 @deprecated("Use create_instance")
2664 def start_scenario(mydb, tenant_id, scenario_id, instance_scenario_name, instance_scenario_description, datacenter=None,vim_tenant=None, startvms=True):
2665 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2666 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2667 vims = {datacenter_id: myvim}
2668 myvim_tenant = myvim['tenant_id']
2669 datacenter_name = myvim['name']
2670
2671 rollbackList=[]
2672 try:
2673 #print "Checking that the scenario_id exists and getting the scenario dictionary"
2674 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
2675 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
2676 scenarioDict['datacenter_id'] = datacenter_id
2677 #print '================scenarioDict======================='
2678 #print json.dumps(scenarioDict, indent=4)
2679 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
2680
2681 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2682 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2683
2684 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2685 auxNetDict['scenario'] = {}
2686
2687 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2688 for sce_net in scenarioDict['nets']:
2689 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
2690
2691 myNetName = "{}.{}".format(instance_scenario_name, sce_net['name'])
2692 myNetName = myNetName[0:255] #limit length
2693 myNetType = sce_net['type']
2694 myNetDict = {}
2695 myNetDict["name"] = myNetName
2696 myNetDict["type"] = myNetType
2697 myNetDict["tenant_id"] = myvim_tenant
2698 myNetIPProfile = sce_net.get('ip_profile', None)
2699 myProviderNetwork = sce_net.get('provider_network', None)
2700 #TODO:
2701 #We should use the dictionary as input parameter for new_network
2702 #print myNetDict
2703 if not sce_net["external"]:
2704 network_id, _ = myvim.new_network(myNetName, myNetType, myNetIPProfile, provider_network_profile=myProviderNetwork)
2705 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2706 sce_net['vim_id'] = network_id
2707 auxNetDict['scenario'][sce_net['uuid']] = network_id
2708 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
2709 sce_net["created"] = True
2710 else:
2711 if sce_net['vim_id'] == None:
2712 error_text = "Error, datacenter '{}' does not have external network '{}'.".format(
2713 datacenter_name, sce_net['name'])
2714 _, message = rollback(mydb, vims, rollbackList)
2715 logger.error("nfvo.start_scenario: %s", error_text)
2716 raise NfvoException(error_text, httperrors.Bad_Request)
2717 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2718 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
2719
2720 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2721 #For each vnf net, we create it and we add it to instanceNetlist.
2722
2723 for sce_vnf in scenarioDict['vnfs']:
2724 for net in sce_vnf['nets']:
2725 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
2726
2727 myNetName = "{}.{}".format(instance_scenario_name,net['name'])
2728 myNetName = myNetName[0:255] #limit length
2729 myNetType = net['type']
2730 myNetDict = {}
2731 myNetDict["name"] = myNetName
2732 myNetDict["type"] = myNetType
2733 myNetDict["tenant_id"] = myvim_tenant
2734 myNetIPProfile = net.get('ip_profile', None)
2735 myProviderNetwork = sce_net.get('provider_network', None)
2736 #print myNetDict
2737 #TODO:
2738 #We should use the dictionary as input parameter for new_network
2739 network_id, _ = myvim.new_network(myNetName, myNetType, myNetIPProfile, provider_network_profile=myProviderNetwork)
2740 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2741 net['vim_id'] = network_id
2742 if sce_vnf['uuid'] not in auxNetDict:
2743 auxNetDict[sce_vnf['uuid']] = {}
2744 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2745 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
2746 net["created"] = True
2747
2748 #print "auxNetDict:"
2749 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
2750
2751 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2752 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2753 i = 0
2754 for sce_vnf in scenarioDict['vnfs']:
2755 vnf_availability_zones = []
2756 for vm in sce_vnf['vms']:
2757 vm_av = vm.get('availability_zone')
2758 if vm_av and vm_av not in vnf_availability_zones:
2759 vnf_availability_zones.append(vm_av)
2760
2761 # check if there is enough availability zones available at vim level.
2762 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2763 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
2764 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
2765
2766 for vm in sce_vnf['vms']:
2767 i += 1
2768 myVMDict = {}
2769 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
2770 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
2771 #myVMDict['description'] = vm['description']
2772 myVMDict['description'] = myVMDict['name'][0:99]
2773 if not startvms:
2774 myVMDict['start'] = "no"
2775 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2776 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
2777
2778 #create image at vim in case it not exist
2779 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
2780 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
2781 vm['vim_image_id'] = image_id
2782
2783 #create flavor at vim in case it not exist
2784 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
2785 if flavor_dict['extended']!=None:
2786 flavor_dict['extended']= yaml.load(flavor_dict['extended'], Loader=yaml.Loader)
2787 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
2788 vm['vim_flavor_id'] = flavor_id
2789
2790
2791 myVMDict['imageRef'] = vm['vim_image_id']
2792 myVMDict['flavorRef'] = vm['vim_flavor_id']
2793 myVMDict['networks'] = []
2794 for iface in vm['interfaces']:
2795 netDict = {}
2796 if iface['type']=="data":
2797 netDict['type'] = iface['model']
2798 elif "model" in iface and iface["model"]!=None:
2799 netDict['model']=iface['model']
2800 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2801 #discover type of interface looking at flavor
2802 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2803 for flavor_iface in numa.get('interfaces',[]):
2804 if flavor_iface.get('name') == iface['internal_name']:
2805 if flavor_iface['dedicated'] == 'yes':
2806 netDict['type']="PF" #passthrough
2807 elif flavor_iface['dedicated'] == 'no':
2808 netDict['type']="VF" #siov
2809 elif flavor_iface['dedicated'] == 'yes:sriov':
2810 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2811 netDict["mac_address"] = flavor_iface.get("mac_address")
2812 break;
2813 netDict["use"]=iface['type']
2814 if netDict["use"]=="data" and not netDict.get("type"):
2815 #print "netDict", netDict
2816 #print "iface", iface
2817 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".format(
2818 sce_vnf['name'], vm['name'], iface['internal_name'])
2819 if flavor_dict.get('extended')==None:
2820 raise NfvoException(e_text + "After database migration some information is not available. \
2821 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
2822 else:
2823 raise NfvoException(e_text, httperrors.Internal_Server_Error)
2824 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2825 netDict["type"]="virtual"
2826 if "vpci" in iface and iface["vpci"] is not None:
2827 netDict['vpci'] = iface['vpci']
2828 if "mac" in iface and iface["mac"] is not None:
2829 netDict['mac_address'] = iface['mac']
2830 if "port-security" in iface and iface["port-security"] is not None:
2831 netDict['port_security'] = iface['port-security']
2832 if "floating-ip" in iface and iface["floating-ip"] is not None:
2833 netDict['floating_ip'] = iface['floating-ip']
2834 netDict['name'] = iface['internal_name']
2835 if iface['net_id'] is None:
2836 for vnf_iface in sce_vnf["interfaces"]:
2837 #print iface
2838 #print vnf_iface
2839 if vnf_iface['interface_id']==iface['uuid']:
2840 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2841 break
2842 else:
2843 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2844 #skip bridge ifaces not connected to any net
2845 #if 'net_id' not in netDict or netDict['net_id']==None:
2846 # continue
2847 myVMDict['networks'].append(netDict)
2848 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2849 #print myVMDict['name']
2850 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2851 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2852 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2853
2854 if 'availability_zone' in myVMDict:
2855 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
2856 else:
2857 av_index = None
2858
2859 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
2860 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
2861 availability_zone_index=av_index,
2862 availability_zone_list=vnf_availability_zones)
2863 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2864 vm['vim_id'] = vm_id
2865 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2866 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2867 for net in myVMDict['networks']:
2868 if "vim_id" in net:
2869 for iface in vm['interfaces']:
2870 if net["name"]==iface["internal_name"]:
2871 iface["vim_id"]=net["vim_id"]
2872 break
2873
2874 logger.debug("start scenario Deployment done")
2875 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2876 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
2877 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2878 return mydb.get_instance_scenario(instance_id)
2879
2880 except (db_base_Exception, vimconn.vimconnException) as e:
2881 _, message = rollback(mydb, vims, rollbackList)
2882 if isinstance(e, db_base_Exception):
2883 error_text = "Exception at database"
2884 else:
2885 error_text = "Exception at VIM"
2886 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2887 #logger.error("start_scenario %s", error_text)
2888 raise NfvoException(error_text, e.http_code)
2889
2890 def unify_cloud_config(cloud_config_preserve, cloud_config):
2891 """ join the cloud config information into cloud_config_preserve.
2892 In case of conflict cloud_config_preserve preserves
2893 None is allowed
2894 """
2895 if not cloud_config_preserve and not cloud_config:
2896 return None
2897
2898 new_cloud_config = {"key-pairs":[], "users":[]}
2899 # key-pairs
2900 if cloud_config_preserve:
2901 for key in cloud_config_preserve.get("key-pairs", () ):
2902 if key not in new_cloud_config["key-pairs"]:
2903 new_cloud_config["key-pairs"].append(key)
2904 if cloud_config:
2905 for key in cloud_config.get("key-pairs", () ):
2906 if key not in new_cloud_config["key-pairs"]:
2907 new_cloud_config["key-pairs"].append(key)
2908 if not new_cloud_config["key-pairs"]:
2909 del new_cloud_config["key-pairs"]
2910
2911 # users
2912 if cloud_config:
2913 new_cloud_config["users"] += cloud_config.get("users", () )
2914 if cloud_config_preserve:
2915 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
2916 index_to_delete = []
2917 users = new_cloud_config.get("users", [])
2918 for index0 in range(0,len(users)):
2919 if index0 in index_to_delete:
2920 continue
2921 for index1 in range(index0+1,len(users)):
2922 if index1 in index_to_delete:
2923 continue
2924 if users[index0]["name"] == users[index1]["name"]:
2925 index_to_delete.append(index1)
2926 for key in users[index1].get("key-pairs",()):
2927 if "key-pairs" not in users[index0]:
2928 users[index0]["key-pairs"] = [key]
2929 elif key not in users[index0]["key-pairs"]:
2930 users[index0]["key-pairs"].append(key)
2931 index_to_delete.sort(reverse=True)
2932 for index in index_to_delete:
2933 del users[index]
2934 if not new_cloud_config["users"]:
2935 del new_cloud_config["users"]
2936
2937 #boot-data-drive
2938 if cloud_config and cloud_config.get("boot-data-drive") != None:
2939 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2940 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2941 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2942
2943 # user-data
2944 new_cloud_config["user-data"] = []
2945 if cloud_config and cloud_config.get("user-data"):
2946 if isinstance(cloud_config["user-data"], list):
2947 new_cloud_config["user-data"] += cloud_config["user-data"]
2948 else:
2949 new_cloud_config["user-data"].append(cloud_config["user-data"])
2950 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2951 if isinstance(cloud_config_preserve["user-data"], list):
2952 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2953 else:
2954 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2955 if not new_cloud_config["user-data"]:
2956 del new_cloud_config["user-data"]
2957
2958 # config files
2959 new_cloud_config["config-files"] = []
2960 if cloud_config and cloud_config.get("config-files") != None:
2961 new_cloud_config["config-files"] += cloud_config["config-files"]
2962 if cloud_config_preserve:
2963 for file in cloud_config_preserve.get("config-files", ()):
2964 for index in range(0, len(new_cloud_config["config-files"])):
2965 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2966 new_cloud_config["config-files"][index] = file
2967 break
2968 else:
2969 new_cloud_config["config-files"].append(file)
2970 if not new_cloud_config["config-files"]:
2971 del new_cloud_config["config-files"]
2972 return new_cloud_config
2973
2974
2975 def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
2976 datacenter_id = None
2977 datacenter_name = None
2978 thread = None
2979 try:
2980 if datacenter_tenant_id:
2981 thread_id = datacenter_tenant_id
2982 thread = vim_threads["running"].get(datacenter_tenant_id)
2983 if not thread:
2984 where_={"td.nfvo_tenant_id": tenant_id}
2985 if datacenter_id_name:
2986 if utils.check_valid_uuid(datacenter_id_name):
2987 datacenter_id = datacenter_id_name
2988 where_["dt.datacenter_id"] = datacenter_id
2989 else:
2990 datacenter_name = datacenter_id_name
2991 where_["d.name"] = datacenter_name
2992 if datacenter_tenant_id:
2993 where_["dt.uuid"] = datacenter_tenant_id
2994 datacenters = mydb.get_rows(
2995 SELECT=("dt.uuid as datacenter_tenant_id, d.name as datacenter_name",),
2996 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2997 "join datacenters as d on d.uuid=dt.datacenter_id",
2998 WHERE=where_)
2999 if len(datacenters) > 1:
3000 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
3001 elif datacenters:
3002 thread_id = datacenters[0]["datacenter_tenant_id"]
3003 datacenter_name = datacenters[0]["datacenter_name"]
3004 thread = vim_threads["running"].get(thread_id)
3005 if not thread:
3006 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id)
3007 thread = vim_thread(task_lock, plugins, thread_name, None,
3008 thread_id, db=mydb)
3009 thread.start()
3010 vim_threads["running"][thread_id] = thread
3011 if not thread:
3012 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
3013 return thread_id, thread
3014 except db_base_Exception as e:
3015 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
3016
3017
3018 def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
3019 WHERE_dict={}
3020 if utils.check_valid_uuid(datacenter_id_name):
3021 WHERE_dict['d.uuid'] = datacenter_id_name
3022 else:
3023 WHERE_dict['d.name'] = datacenter_id_name
3024
3025 if tenant_id:
3026 WHERE_dict['nfvo_tenant_id'] = tenant_id
3027 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
3028 " dt on td.datacenter_tenant_id=dt.uuid"
3029 else:
3030 from_ = 'datacenters as d'
3031 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid, d.name as name",), WHERE=WHERE_dict )
3032 if len(vimaccounts) == 0:
3033 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
3034 elif len(vimaccounts)>1:
3035 #print "nfvo.datacenter_action() error. Several datacenters found"
3036 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
3037 return vimaccounts[0]["uuid"], vimaccounts[0]["name"]
3038
3039
3040 def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
3041 datacenter_id = None
3042 datacenter_name = None
3043 if datacenter_id_name:
3044 if utils.check_valid_uuid(datacenter_id_name):
3045 datacenter_id = datacenter_id_name
3046 else:
3047 datacenter_name = datacenter_id_name
3048 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
3049 if len(vims) == 0:
3050 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), httperrors.Not_Found)
3051 elif len(vims)>1:
3052 #print "nfvo.datacenter_action() error. Several datacenters found"
3053 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors.Conflict)
3054 for vim_id, vim_content in vims.items():
3055 return vim_id, vim_content
3056
3057
3058 def update(d, u):
3059 """Takes dict d and updates it with the values in dict u.
3060 It merges all depth levels"""
3061 for k, v in u.items():
3062 if isinstance(v, collections.Mapping):
3063 r = update(d.get(k, {}), v)
3064 d[k] = r
3065 else:
3066 d[k] = u[k]
3067 return d
3068
3069
3070 def _get_wim(db, wim_account_id):
3071 # get wim from wim_account
3072 wim_accounts = db.get_rows(FROM='wim_accounts', WHERE={"uuid": wim_account_id})
3073 if not wim_accounts:
3074 raise NfvoException("Not found sdn id={}".format(wim_account_id), http_code=httperrors.Not_Found)
3075 return wim_accounts[0]["wim_id"]
3076
3077
3078 def create_instance(mydb, tenant_id, instance_dict):
3079 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
3080 # logger.debug("Creating instance...")
3081
3082 scenario = instance_dict["scenario"]
3083
3084 # find main datacenter
3085 myvims = {}
3086 myvim_threads_id = {}
3087 datacenter = instance_dict.get("datacenter")
3088 default_wim_account = instance_dict.get("wim_account")
3089 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
3090 myvims[default_datacenter_id] = vim
3091 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
3092 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
3093 # myvim_tenant = myvim['tenant_id']
3094 rollbackList = []
3095
3096 # print "Checking that the scenario exists and getting the scenario dictionary"
3097 if isinstance(scenario, str):
3098 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
3099 datacenter_id=default_datacenter_id)
3100 else:
3101 scenarioDict = scenario
3102 scenarioDict["uuid"] = None
3103
3104 # logger.debug(">>>>>> Dictionaries before merging")
3105 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
3106 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
3107
3108 db_instance_vnfs = []
3109 db_instance_vms = []
3110 db_instance_interfaces = []
3111 db_instance_sfis = []
3112 db_instance_sfs = []
3113 db_instance_classifications = []
3114 db_instance_sfps = []
3115 db_ip_profiles = []
3116 db_vim_actions = []
3117 uuid_list = []
3118 task_index = 0
3119 instance_name = instance_dict["name"]
3120 instance_uuid = str(uuid4())
3121 uuid_list.append(instance_uuid)
3122 db_instance_scenario = {
3123 "uuid": instance_uuid,
3124 "name": instance_name,
3125 "tenant_id": tenant_id,
3126 "scenario_id": scenarioDict['uuid'],
3127 "datacenter_id": default_datacenter_id,
3128 # filled bellow 'datacenter_tenant_id'
3129 "description": instance_dict.get("description"),
3130 }
3131 if scenarioDict.get("cloud-config"):
3132 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
3133 default_flow_style=True, width=256)
3134 instance_action_id = get_task_id()
3135 db_instance_action = {
3136 "uuid": instance_action_id, # same uuid for the instance and the action on create
3137 "tenant_id": tenant_id,
3138 "instance_id": instance_uuid,
3139 "description": "CREATE",
3140 }
3141
3142 # Auxiliary dictionaries from x to y
3143 sce_net2wim_instance = {}
3144 sce_net2instance = {}
3145 net2task_id = {'scenario': {}}
3146 # Mapping between local networks and WIMs
3147 wim_usage = {}
3148
3149 def ip_profile_IM2RO(ip_profile_im):
3150 # translate from input format to database format
3151 ip_profile_ro = {}
3152 if 'subnet-address' in ip_profile_im:
3153 ip_profile_ro['subnet_address'] = ip_profile_im['subnet-address']
3154 if 'ip-version' in ip_profile_im:
3155 ip_profile_ro['ip_version'] = ip_profile_im['ip-version']
3156 if 'gateway-address' in ip_profile_im:
3157 ip_profile_ro['gateway_address'] = ip_profile_im['gateway-address']
3158 if 'dns-address' in ip_profile_im:
3159 ip_profile_ro['dns_address'] = ip_profile_im['dns-address']
3160 if isinstance(ip_profile_ro['dns_address'], (list, tuple)):
3161 ip_profile_ro['dns_address'] = ";".join(ip_profile_ro['dns_address'])
3162 if 'dhcp' in ip_profile_im:
3163 ip_profile_ro['dhcp_start_address'] = ip_profile_im['dhcp'].get('start-address')
3164 ip_profile_ro['dhcp_enabled'] = ip_profile_im['dhcp'].get('enabled', True)
3165 ip_profile_ro['dhcp_count'] = ip_profile_im['dhcp'].get('count')
3166 return ip_profile_ro
3167
3168 # logger.debug("Creating instance from scenario-dict:\n%s",
3169 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
3170 try:
3171 # 0 check correct parameters
3172 for net_name, net_instance_desc in instance_dict.get("networks", {}).items():
3173 for scenario_net in scenarioDict['nets']:
3174 if net_name == scenario_net.get("name") or net_name == scenario_net.get("osm_id") or net_name == scenario_net.get("uuid"):
3175 break
3176 else:
3177 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name),
3178 httperrors.Bad_Request)
3179 if "sites" not in net_instance_desc:
3180 net_instance_desc["sites"] = [ {} ]
3181 site_without_datacenter_field = False
3182 for site in net_instance_desc["sites"]:
3183 if site.get("datacenter"):
3184 site["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
3185 if site["datacenter"] not in myvims:
3186 # Add this datacenter to myvims
3187 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
3188 myvims[d] = v
3189 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
3190 site["datacenter"] = d # change name to id
3191 else:
3192 if site_without_datacenter_field:
3193 raise NfvoException("Found more than one entries without datacenter field at "
3194 "instance:networks:{}:sites".format(net_name), httperrors.Bad_Request)
3195 site_without_datacenter_field = True
3196 site["datacenter"] = default_datacenter_id # change name to id
3197
3198 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).items():
3199 for scenario_vnf in scenarioDict['vnfs']:
3200 if vnf_name == scenario_vnf['member_vnf_index'] or vnf_name == scenario_vnf['uuid'] or vnf_name == scenario_vnf['name']:
3201 break
3202 else:
3203 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name), httperrors.Bad_Request)
3204 if "datacenter" in vnf_instance_desc:
3205 # Add this datacenter to myvims
3206 vnf_instance_desc["datacenter"], _ = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3207 if vnf_instance_desc["datacenter"] not in myvims:
3208 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3209 myvims[d] = v
3210 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
3211 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
3212
3213 for net_id, net_instance_desc in vnf_instance_desc.get("networks", {}).items():
3214 for scenario_net in scenario_vnf['nets']:
3215 if net_id == scenario_net['osm_id'] or net_id == scenario_net['uuid'] or net_id == scenario_net["name"]:
3216 break
3217 else:
3218 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id), httperrors.Bad_Request)
3219 if net_instance_desc.get("vim-network-name"):
3220 scenario_net["vim-network-name"] = net_instance_desc["vim-network-name"]
3221 if net_instance_desc.get("vim-network-id"):
3222 scenario_net["vim-network-id"] = net_instance_desc["vim-network-id"]
3223 if net_instance_desc.get("name"):
3224 scenario_net["name"] = net_instance_desc["name"]
3225 if 'ip-profile' in net_instance_desc:
3226 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3227 if 'ip_profile' not in scenario_net:
3228 scenario_net['ip_profile'] = ipprofile_db
3229 else:
3230 update(scenario_net['ip_profile'], ipprofile_db)
3231
3232 if 'provider-network' in net_instance_desc:
3233 provider_network_db = net_instance_desc['provider-network']
3234 if 'provider-network' not in scenario_net:
3235 scenario_net['provider-network'] = provider_network_db
3236 else:
3237 update(scenario_net['provider-network'], provider_network_db)
3238
3239 for vdu_id, vdu_instance_desc in vnf_instance_desc.get("vdus", {}).items():
3240 for scenario_vm in scenario_vnf['vms']:
3241 if vdu_id == scenario_vm['osm_id'] or vdu_id == scenario_vm["name"]:
3242 break
3243 else:
3244 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
3245 scenario_vm["instance_parameters"] = vdu_instance_desc
3246 for iface_id, iface_instance_desc in vdu_instance_desc.get("interfaces", {}).items():
3247 for scenario_interface in scenario_vm['interfaces']:
3248 if iface_id == scenario_interface['internal_name'] or iface_id == scenario_interface["external_name"]:
3249 scenario_interface.update(iface_instance_desc)
3250 break
3251 else:
3252 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id), httperrors.Bad_Request)
3253
3254 # 0.1 parse cloud-config parameters
3255 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
3256
3257 # 0.2 merge instance information into scenario
3258 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3259 # However, this is not possible yet.
3260 for net_name, net_instance_desc in instance_dict.get("networks", {}).items():
3261 for scenario_net in scenarioDict['nets']:
3262 if net_name == scenario_net.get("name") or net_name == scenario_net.get("osm_id") or net_name == scenario_net.get("uuid"):
3263 if "wim_account" in net_instance_desc and net_instance_desc["wim_account"] is not None:
3264 scenario_net["wim_account"] = net_instance_desc["wim_account"]
3265 if 'ip-profile' in net_instance_desc:
3266 ipprofile_db = ip_profile_IM2RO(net_instance_desc['ip-profile'])
3267 if 'ip_profile' not in scenario_net:
3268 scenario_net['ip_profile'] = ipprofile_db
3269 else:
3270 update(scenario_net['ip_profile'], ipprofile_db)
3271 if 'provider-network' in net_instance_desc:
3272 provider_network_db = net_instance_desc['provider-network']
3273
3274 if 'provider-network' not in scenario_net:
3275 scenario_net['provider_network'] = provider_network_db
3276 else:
3277 update(scenario_net['provider-network'], provider_network_db)
3278
3279 for interface in net_instance_desc.get('interfaces', ()):
3280 if 'ip_address' in interface:
3281 for vnf in scenarioDict['vnfs']:
3282 if interface['vnf'] == vnf['name']:
3283 for vnf_interface in vnf['interfaces']:
3284 if interface['vnf_interface'] == vnf_interface['external_name']:
3285 vnf_interface['ip_address'] = interface['ip_address']
3286
3287 # logger.debug(">>>>>>>> Merged dictionary")
3288 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3289 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
3290
3291
3292 # 1. Creating new nets (sce_nets) in the VIM"
3293 number_mgmt_networks = 0
3294 db_instance_nets = []
3295 db_instance_wim_nets = []
3296 for sce_net in scenarioDict['nets']:
3297
3298 sce_net_uuid = sce_net.get('uuid', sce_net["name"])
3299 # get involved datacenters where this network need to be created
3300 involved_datacenters = []
3301 for sce_vnf in scenarioDict.get("vnfs", ()):
3302 vnf_datacenter = sce_vnf.get("datacenter", default_datacenter_id)
3303 if vnf_datacenter in involved_datacenters:
3304 continue
3305 if sce_vnf.get("interfaces"):
3306 for sce_vnf_ifaces in sce_vnf["interfaces"]:
3307 if sce_vnf_ifaces.get("sce_net_id") == sce_net["uuid"]:
3308 involved_datacenters.append(vnf_datacenter)
3309 break
3310 if not involved_datacenters:
3311 involved_datacenters.append(default_datacenter_id)
3312 target_wim_account = sce_net.get("wim_account", default_wim_account)
3313
3314 # --> WIM
3315 # TODO: use this information during network creation
3316 wim_account_id = wim_account_name = None
3317 if len(involved_datacenters) > 1 and 'uuid' in sce_net:
3318 if target_wim_account is None or target_wim_account is True: # automatic selection of WIM
3319 # OBS: sce_net without uuid are used internally to VNFs
3320 # and the assumption is that VNFs will not be split among
3321 # different datacenters
3322 wim_account = wim_engine.find_suitable_wim_account(
3323 involved_datacenters, tenant_id)
3324 wim_account_id = wim_account['uuid']
3325 wim_account_name = wim_account['name']
3326 wim_usage[sce_net['uuid']] = wim_account_id
3327 elif isinstance(target_wim_account, str): # manual selection of WIM
3328 wim_account.persist.get_wim_account_by(target_wim_account, tenant_id)
3329 wim_account_id = wim_account['uuid']
3330 wim_account_name = wim_account['name']
3331 wim_usage[sce_net['uuid']] = wim_account_id
3332 else: # not WIM usage
3333 wim_usage[sce_net['uuid']] = False
3334 # <-- WIM
3335
3336 descriptor_net = {}
3337 if instance_dict.get("networks"):
3338 if sce_net.get("uuid") in instance_dict["networks"]:
3339 descriptor_net = instance_dict["networks"][sce_net["uuid"]]
3340 descriptor_net_name = sce_net["uuid"]
3341 elif sce_net.get("osm_id") in instance_dict["networks"]:
3342 descriptor_net = instance_dict["networks"][sce_net["osm_id"]]
3343 descriptor_net_name = sce_net["osm_id"]
3344 elif sce_net["name"] in instance_dict["networks"]:
3345 descriptor_net = instance_dict["networks"][sce_net["name"]]
3346 descriptor_net_name = sce_net["name"]
3347 net_name = descriptor_net.get("vim-network-name")
3348 # add datacenters from instantiation parameters
3349 if descriptor_net.get("sites"):
3350 for site in descriptor_net["sites"]:
3351 if site.get("datacenter") and site["datacenter"] not in involved_datacenters:
3352 involved_datacenters.append(site["datacenter"])
3353 sce_net2instance[sce_net_uuid] = {}
3354 sce_net2wim_instance[sce_net_uuid] = {}
3355 net2task_id['scenario'][sce_net_uuid] = {}
3356
3357 use_network = None
3358 related_network = None
3359 if descriptor_net.get("use-network"):
3360 target_instance_nets = mydb.get_rows(
3361 SELECT="related",
3362 FROM="instance_nets",
3363 WHERE={"instance_scenario_id": descriptor_net["use-network"]["instance_scenario_id"],
3364 "osm_id": descriptor_net["use-network"]["osm_id"]},
3365 )
3366 if not target_instance_nets:
3367 raise NfvoException(
3368 "Cannot find the target network at instance:networks[{}]:use-network".format(descriptor_net_name),
3369 httperrors.Bad_Request)
3370 else:
3371 use_network = target_instance_nets[0]["related"]
3372
3373 if sce_net["external"]:
3374 number_mgmt_networks += 1
3375
3376 for datacenter_id in involved_datacenters:
3377 netmap_use = None
3378 netmap_create = None
3379 if descriptor_net.get("sites"):
3380 for site in descriptor_net["sites"]:
3381 if site.get("datacenter") == datacenter_id:
3382 netmap_use = site.get("netmap-use")
3383 netmap_create = site.get("netmap-create")
3384 break
3385
3386 vim = myvims[datacenter_id]
3387 myvim_thread_id = myvim_threads_id[datacenter_id]
3388
3389 net_type = sce_net['type']
3390 net_vim_name = None
3391 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
3392
3393 if not net_name:
3394 if sce_net["external"]:
3395 net_name = sce_net["name"]
3396 else:
3397 net_name = "{}-{}".format(instance_name, sce_net["name"])
3398 net_name = net_name[:255] # limit length
3399
3400 if netmap_use or netmap_create:
3401 create_network = False
3402 lookfor_network = False
3403 if netmap_use:
3404 lookfor_network = True
3405 if utils.check_valid_uuid(netmap_use):
3406 lookfor_filter["id"] = netmap_use
3407 else:
3408 lookfor_filter["name"] = netmap_use
3409 if netmap_create:
3410 create_network = True
3411 net_vim_name = net_name
3412 if isinstance(netmap_create, str):
3413 net_vim_name = netmap_create
3414 elif sce_net.get("vim_network_name"):
3415 create_network = False
3416 lookfor_network = True
3417 lookfor_filter["name"] = sce_net.get("vim_network_name")
3418 elif sce_net["external"]:
3419 if sce_net.get('vim_id'):
3420 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
3421 create_network = False
3422 lookfor_network = True
3423 lookfor_filter["id"] = sce_net['vim_id']
3424 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3425 if number_mgmt_networks > 1:
3426 raise NfvoException("Found several VLD of type mgmt. "
3427 "You must concrete what vim-network must be use for each one",
3428 httperrors.Bad_Request)
3429 create_network = False
3430 lookfor_network = True
3431 if vim["config"].get("management_network_id"):
3432 lookfor_filter["id"] = vim["config"]["management_network_id"]
3433 else:
3434 lookfor_filter["name"] = vim["config"]["management_network_name"]
3435 else:
3436 # There is not a netmap, look at datacenter for a net with this name and create if not found
3437 create_network = True
3438 lookfor_network = True
3439 lookfor_filter["name"] = sce_net["name"]
3440 net_vim_name = sce_net["name"]
3441 else:
3442 net_vim_name = net_name
3443 create_network = True
3444 lookfor_network = False
3445
3446 task_extra = {}
3447 if create_network:
3448 task_action = "CREATE"
3449 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None), False,
3450 sce_net.get('provider_network', None), wim_account_name)
3451
3452 if lookfor_network:
3453 task_extra["find"] = (lookfor_filter,)
3454 elif lookfor_network:
3455 task_action = "FIND"
3456 task_extra["params"] = (lookfor_filter,)
3457
3458 # fill database content
3459 net_uuid = str(uuid4())
3460 uuid_list.append(net_uuid)
3461 sce_net2instance[sce_net_uuid][datacenter_id] = net_uuid
3462 if not related_network: # all db_instance_nets will have same related
3463 related_network = use_network or net_uuid
3464 sdn_net_id = None
3465 sdn_controller = vim.config.get('sdn-controller')
3466 sce_net2wim_instance[sce_net_uuid][datacenter_id] = None
3467 if sdn_controller and net_type in ("data", "ptp"):
3468 wim_id = _get_wim(mydb, sdn_controller)
3469 sdn_net_id = str(uuid4())
3470 sce_net2wim_instance[sce_net_uuid][datacenter_id] = sdn_net_id
3471 task_extra["sdn_net_id"] = sdn_net_id
3472 db_instance_wim_nets.append({
3473 "uuid": sdn_net_id,
3474 "instance_scenario_id": instance_uuid,
3475 "sce_net_id": sce_net.get("uuid"),
3476 "wim_id": wim_id,
3477 "wim_account_id": sdn_controller,
3478 'status': 'BUILD', # if create_network else "ACTIVE"
3479 "related": related_network,
3480 'multipoint': True if net_type=="data" else False,
3481 "created": create_network, # TODO py3
3482 "sdn": True,
3483 })
3484 task_wim_extra = {"params": [net_type, wim_account_name]}
3485 db_vim_action = {
3486 "instance_action_id": instance_action_id,
3487 "status": "SCHEDULED",
3488 "task_index": task_index,
3489 # "datacenter_vim_id": myvim_thread_id,
3490 "wim_account_id": sdn_controller,
3491 "action": task_action,
3492 "item": "instance_wim_nets",
3493 "item_id": sdn_net_id,
3494 "related": related_network,
3495 "extra": yaml.safe_dump(task_wim_extra, default_flow_style=True, width=256)
3496 }
3497 task_index += 1
3498 db_vim_actions.append(db_vim_action)
3499 db_net = {
3500 "uuid": net_uuid,
3501 "osm_id": sce_net.get("osm_id") or sce_net["name"],
3502 "related": related_network,
3503 'vim_net_id': None,
3504 "vim_name": net_vim_name,
3505 "instance_scenario_id": instance_uuid,
3506 "sce_net_id": sce_net.get("uuid"),
3507 "created": create_network,
3508 'datacenter_id': datacenter_id,
3509 'datacenter_tenant_id': myvim_thread_id,
3510 'status': 'BUILD', # if create_network else "ACTIVE"
3511 'sdn_net_id': sdn_net_id,
3512 }
3513 db_instance_nets.append(db_net)
3514 db_vim_action = {
3515 "instance_action_id": instance_action_id,
3516 "status": "SCHEDULED",
3517 "task_index": task_index,
3518 "datacenter_vim_id": myvim_thread_id,
3519 "action": task_action,
3520 "item": "instance_nets",
3521 "item_id": net_uuid,
3522 "related": related_network,
3523 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
3524 }
3525 net2task_id['scenario'][sce_net_uuid][datacenter_id] = task_index
3526 task_index += 1
3527 db_vim_actions.append(db_vim_action)
3528
3529 if 'ip_profile' in sce_net:
3530 db_ip_profile={
3531 'instance_net_id': net_uuid,
3532 'ip_version': sce_net['ip_profile']['ip_version'],
3533 'subnet_address': sce_net['ip_profile']['subnet_address'],
3534 'gateway_address': sce_net['ip_profile']['gateway_address'],
3535 'dns_address': sce_net['ip_profile']['dns_address'],
3536 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3537 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3538 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3539 }
3540 db_ip_profiles.append(db_ip_profile)
3541
3542 # Create VNFs
3543 vnf_params = {
3544 "default_datacenter_id": default_datacenter_id,
3545 "myvim_threads_id": myvim_threads_id,
3546 "instance_uuid": instance_uuid,
3547 "instance_name": instance_name,
3548 "instance_action_id": instance_action_id,
3549 "myvims": myvims,
3550 "cloud_config": cloud_config,
3551 "RO_pub_key": tenant[0].get('RO_pub_key'),
3552 "instance_parameters": instance_dict,
3553 }
3554 vnf_params_out = {
3555 "task_index": task_index,
3556 "uuid_list": uuid_list,
3557 "db_instance_nets": db_instance_nets,
3558 "db_instance_wim_nets": db_instance_wim_nets,
3559 "db_vim_actions": db_vim_actions,
3560 "db_ip_profiles": db_ip_profiles,
3561 "db_instance_vnfs": db_instance_vnfs,
3562 "db_instance_vms": db_instance_vms,
3563 "db_instance_interfaces": db_instance_interfaces,
3564 "net2task_id": net2task_id,
3565 "sce_net2instance": sce_net2instance,
3566 "sce_net2wim_instance": sce_net2wim_instance,
3567 }
3568 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
3569 for sce_vnf in scenarioDict.get('vnfs', ()): # sce_vnf_list:
3570 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3571 task_index = vnf_params_out["task_index"]
3572 uuid_list = vnf_params_out["uuid_list"]
3573
3574 # Create VNFFGs
3575 # task_depends_on = []
3576 for vnffg in scenarioDict.get('vnffgs', ()):
3577 for rsp in vnffg['rsps']:
3578 sfs_created = []
3579 for cp in rsp['connection_points']:
3580 count = mydb.get_rows(
3581 SELECT='vms.count',
3582 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h "
3583 "on interfaces.uuid=h.ingress_interface_id",
3584 WHERE={'h.uuid': cp['uuid']})[0]['count']
3585 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3586 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3587 dependencies = []
3588 for instance_vm in instance_vms:
3589 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3590 if action:
3591 dependencies.append(action['task_index'])
3592 # TODO: throw exception if count != len(instance_vms)
3593 # TODO: and action shouldn't ever be None
3594 sfis_created = []
3595 for i in range(count):
3596 # create sfis
3597 sfi_uuid = str(uuid4())
3598 extra_params = {
3599 "ingress_interface_id": cp["ingress_interface_id"],
3600 "egress_interface_id": cp["egress_interface_id"]
3601 }
3602 uuid_list.append(sfi_uuid)
3603 db_sfi = {
3604 "uuid": sfi_uuid,
3605 "related": sfi_uuid,
3606 "instance_scenario_id": instance_uuid,
3607 'sce_rsp_hop_id': cp['uuid'],
3608 'datacenter_id': datacenter_id,
3609 'datacenter_tenant_id': myvim_thread_id,
3610 "vim_sfi_id": None, # vim thread will populate
3611 }
3612 db_instance_sfis.append(db_sfi)
3613 db_vim_action = {
3614 "instance_action_id": instance_action_id,
3615 "task_index": task_index,
3616 "datacenter_vim_id": myvim_thread_id,
3617 "action": "CREATE",
3618 "status": "SCHEDULED",
3619 "item": "instance_sfis",
3620 "item_id": sfi_uuid,
3621 "related": sfi_uuid,
3622 "extra": yaml.safe_dump({"params": extra_params, "depends_on": [dependencies[i]]},
3623 default_flow_style=True, width=256)
3624 }
3625 sfis_created.append(task_index)
3626 task_index += 1
3627 db_vim_actions.append(db_vim_action)
3628 # create sfs
3629 sf_uuid = str(uuid4())
3630 uuid_list.append(sf_uuid)
3631 db_sf = {
3632 "uuid": sf_uuid,
3633 "related": sf_uuid,
3634 "instance_scenario_id": instance_uuid,
3635 'sce_rsp_hop_id': cp['uuid'],
3636 'datacenter_id': datacenter_id,
3637 'datacenter_tenant_id': myvim_thread_id,
3638 "vim_sf_id": None, # vim thread will populate
3639 }
3640 db_instance_sfs.append(db_sf)
3641 db_vim_action = {
3642 "instance_action_id": instance_action_id,
3643 "task_index": task_index,
3644 "datacenter_vim_id": myvim_thread_id,
3645 "action": "CREATE",
3646 "status": "SCHEDULED",
3647 "item": "instance_sfs",
3648 "item_id": sf_uuid,
3649 "related": sf_uuid,
3650 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3651 default_flow_style=True, width=256)
3652 }
3653 sfs_created.append(task_index)
3654 task_index += 1
3655 db_vim_actions.append(db_vim_action)
3656 classifier = rsp['classifier']
3657
3658 # TODO the following ~13 lines can be reused for the sfi case
3659 count = mydb.get_rows(
3660 SELECT=('vms.count'),
3661 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3662 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3663 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3664 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3665 dependencies = []
3666 for instance_vm in instance_vms:
3667 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3668 if action:
3669 dependencies.append(action['task_index'])
3670 # TODO: throw exception if count != len(instance_vms)
3671 # TODO: and action shouldn't ever be None
3672 classifications_created = []
3673 for i in range(count):
3674 for match in classifier['matches']:
3675 # create classifications
3676 classification_uuid = str(uuid4())
3677 uuid_list.append(classification_uuid)
3678 db_classification = {
3679 "uuid": classification_uuid,
3680 "related": classification_uuid,
3681 "instance_scenario_id": instance_uuid,
3682 'sce_classifier_match_id': match['uuid'],
3683 'datacenter_id': datacenter_id,
3684 'datacenter_tenant_id': myvim_thread_id,
3685 "vim_classification_id": None, # vim thread will populate
3686 }
3687 db_instance_classifications.append(db_classification)
3688 classification_params = {
3689 "ip_proto": match["ip_proto"],
3690 "source_ip": match["source_ip"],
3691 "destination_ip": match["destination_ip"],
3692 "source_port": match["source_port"],
3693 "destination_port": match["destination_port"],
3694 "logical_source_port": classifier["interface_id"]
3695 }
3696 db_vim_action = {
3697 "instance_action_id": instance_action_id,
3698 "task_index": task_index,
3699 "datacenter_vim_id": myvim_thread_id,
3700 "action": "CREATE",
3701 "status": "SCHEDULED",
3702 "item": "instance_classifications",
3703 "item_id": classification_uuid,
3704 "related": classification_uuid,
3705 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3706 default_flow_style=True, width=256)
3707 }
3708 classifications_created.append(task_index)
3709 task_index += 1
3710 db_vim_actions.append(db_vim_action)
3711
3712 # create sfps
3713 sfp_uuid = str(uuid4())
3714 uuid_list.append(sfp_uuid)
3715 db_sfp = {
3716 "uuid": sfp_uuid,
3717 "related": sfp_uuid,
3718 "instance_scenario_id": instance_uuid,
3719 'sce_rsp_id': rsp['uuid'],
3720 'datacenter_id': datacenter_id,
3721 'datacenter_tenant_id': myvim_thread_id,
3722 "vim_sfp_id": None, # vim thread will populate
3723 }
3724 db_instance_sfps.append(db_sfp)
3725 db_vim_action = {
3726 "instance_action_id": instance_action_id,
3727 "task_index": task_index,
3728 "datacenter_vim_id": myvim_thread_id,
3729 "action": "CREATE",
3730 "status": "SCHEDULED",
3731 "item": "instance_sfps",
3732 "item_id": sfp_uuid,
3733 "related": sfp_uuid,
3734 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3735 default_flow_style=True, width=256)
3736 }
3737 task_index += 1
3738 db_vim_actions.append(db_vim_action)
3739 db_instance_action["number_tasks"] = task_index
3740
3741 # --> WIM
3742 logger.debug('wim_usage:\n%s\n\n', pformat(wim_usage))
3743 wan_links = wim_engine.derive_wan_links(wim_usage, db_instance_nets, tenant_id)
3744 wim_actions = wim_engine.create_actions(wan_links)
3745 wim_actions, db_instance_action = (
3746 wim_engine.incorporate_actions(wim_actions, db_instance_action))
3747 # <-- WIM
3748
3749 scenarioDict["datacenter2tenant"] = myvim_threads_id
3750
3751 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3752 db_instance_scenario['datacenter_id'] = default_datacenter_id
3753 db_tables=[
3754 {"instance_scenarios": db_instance_scenario},
3755 {"instance_vnfs": db_instance_vnfs},
3756 {"instance_nets": db_instance_nets},
3757 {"ip_profiles": db_ip_profiles},
3758 {"instance_vms": db_instance_vms},
3759 {"instance_interfaces": db_instance_interfaces},
3760 {"instance_actions": db_instance_action},
3761 {"instance_sfis": db_instance_sfis},
3762 {"instance_sfs": db_instance_sfs},
3763 {"instance_classifications": db_instance_classifications},
3764 {"instance_sfps": db_instance_sfps},
3765 {"instance_wim_nets": db_instance_wim_nets + wan_links},
3766 {"vim_wim_actions": db_vim_actions + wim_actions}
3767 ]
3768
3769 logger.debug("create_instance done DB tables: %s",
3770 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3771 mydb.new_rows(db_tables, uuid_list)
3772 for myvim_thread_id in myvim_threads_id.values():
3773 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
3774
3775 wim_engine.dispatch(wim_actions)
3776
3777 returned_instance = mydb.get_instance_scenario(instance_uuid)
3778 returned_instance["action_id"] = instance_action_id
3779 return returned_instance
3780 except (NfvoException, vimconn.vimconnException, sdnconn.SdnConnectorError, db_base_Exception) as e:
3781 message = rollback(mydb, myvims, rollbackList)
3782 if isinstance(e, db_base_Exception):
3783 error_text = "database Exception"
3784 elif isinstance(e, vimconn.vimconnException):
3785 error_text = "VIM Exception"
3786 elif isinstance(e, sdnconn.SdnConnectorError):
3787 error_text = "WIM Exception"
3788 else:
3789 error_text = "Exception"
3790 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
3791 # logger.error("create_instance: %s", error_text)
3792 logger.exception(e)
3793 raise NfvoException(error_text, e.http_code)
3794
3795
3796 def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3797 default_datacenter_id = params["default_datacenter_id"]
3798 myvim_threads_id = params["myvim_threads_id"]
3799 instance_uuid = params["instance_uuid"]
3800 instance_name = params["instance_name"]
3801 instance_action_id = params["instance_action_id"]
3802 myvims = params["myvims"]
3803 cloud_config = params["cloud_config"]
3804 RO_pub_key = params["RO_pub_key"]
3805
3806 task_index = params_out["task_index"]
3807 uuid_list = params_out["uuid_list"]
3808 db_instance_nets = params_out["db_instance_nets"]
3809 db_instance_wim_nets = params_out["db_instance_wim_nets"]
3810 db_vim_actions = params_out["db_vim_actions"]
3811 db_ip_profiles = params_out["db_ip_profiles"]
3812 db_instance_vnfs = params_out["db_instance_vnfs"]
3813 db_instance_vms = params_out["db_instance_vms"]
3814 db_instance_interfaces = params_out["db_instance_interfaces"]
3815 net2task_id = params_out["net2task_id"]
3816 sce_net2instance = params_out["sce_net2instance"]
3817 sce_net2wim_instance = params_out["sce_net2wim_instance"]
3818
3819 vnf_net2instance = {}
3820 vnf_net2wim_instance = {}
3821
3822 # 2. Creating new nets (vnf internal nets) in the VIM"
3823 # For each vnf net, we create it and we add it to instanceNetlist.
3824 if sce_vnf.get("datacenter"):
3825 vim = myvims[sce_vnf["datacenter"]]
3826 datacenter_id = sce_vnf["datacenter"]
3827 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3828 else:
3829 vim = myvims[default_datacenter_id]
3830 datacenter_id = default_datacenter_id
3831 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3832 for net in sce_vnf['nets']:
3833 # TODO revis
3834 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3835 # net_name = descriptor_net.get("name")
3836 net_name = None
3837 if not net_name:
3838 net_name = "{}-{}".format(instance_name, net["name"])
3839 net_name = net_name[:255] # limit length
3840 net_type = net['type']
3841
3842 if sce_vnf['uuid'] not in vnf_net2instance:
3843 vnf_net2instance[sce_vnf['uuid']] = {}
3844 if sce_vnf['uuid'] not in net2task_id:
3845 net2task_id[sce_vnf['uuid']] = {}
3846
3847 # fill database content
3848 net_uuid = str(uuid4())
3849 uuid_list.append(net_uuid)
3850 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3851
3852 sdn_controller = vim.config.get('sdn-controller')
3853 sdn_net_id = None
3854 if sdn_controller and net_type in ("data", "ptp"):
3855 wim_id = _get_wim(mydb, sdn_controller)
3856 sdn_net_id = str(uuid4())
3857 db_instance_wim_nets.append({
3858 "uuid": sdn_net_id,
3859 "instance_scenario_id": instance_uuid,
3860 "wim_id": wim_id,
3861 "wim_account_id": sdn_controller,
3862 'status': 'BUILD', # if create_network else "ACTIVE"
3863 "related": net_uuid,
3864 'multipoint': True if net_type == "data" else False,
3865 "created": True, # TODO py3
3866 "sdn": True,
3867 })
3868 vnf_net2wim_instance[net_uuid] = sdn_net_id
3869
3870 db_net = {
3871 "uuid": net_uuid,
3872 "related": net_uuid,
3873 'vim_net_id': None,
3874 "vim_name": net_name,
3875 "instance_scenario_id": instance_uuid,
3876 "net_id": net["uuid"],
3877 "created": True,
3878 'datacenter_id': datacenter_id,
3879 'datacenter_tenant_id': myvim_thread_id,
3880 'sdn_net_id': sdn_net_id,
3881 }
3882 db_instance_nets.append(db_net)
3883
3884 lookfor_filter = {}
3885 if net.get("vim-network-name"):
3886 lookfor_filter["name"] = net["vim-network-name"]
3887 if net.get("vim-network-id"):
3888 lookfor_filter["id"] = net["vim-network-id"]
3889 if lookfor_filter:
3890 task_action = "FIND"
3891 task_extra = {"params": (lookfor_filter,)}
3892 else:
3893 task_action = "CREATE"
3894 task_extra = {"params": (net_name, net_type, net.get('ip_profile', None))}
3895 if sdn_net_id:
3896 task_extra["sdn_net_id"] = sdn_net_id
3897
3898 if sdn_net_id:
3899 task_wim_extra = {"params": [net_type, None]}
3900 db_vim_action = {
3901 "instance_action_id": instance_action_id,
3902 "status": "SCHEDULED",
3903 "task_index": task_index,
3904 # "datacenter_vim_id": myvim_thread_id,
3905 "wim_account_id": sdn_controller,
3906 "action": task_action,
3907 "item": "instance_wim_nets",
3908 "item_id": sdn_net_id,
3909 "related": net_uuid,
3910 "extra": yaml.safe_dump(task_wim_extra, default_flow_style=True, width=256)
3911 }
3912 task_index += 1
3913 db_vim_actions.append(db_vim_action)
3914 db_vim_action = {
3915 "instance_action_id": instance_action_id,
3916 "task_index": task_index,
3917 "datacenter_vim_id": myvim_thread_id,
3918 "status": "SCHEDULED",
3919 "action": task_action,
3920 "item": "instance_nets",
3921 "item_id": net_uuid,
3922 "related": net_uuid,
3923 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
3924 }
3925 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3926 task_index += 1
3927 db_vim_actions.append(db_vim_action)
3928
3929 if 'ip_profile' in net:
3930 db_ip_profile = {
3931 'instance_net_id': net_uuid,
3932 'ip_version': net['ip_profile']['ip_version'],
3933 'subnet_address': net['ip_profile']['subnet_address'],
3934 'gateway_address': net['ip_profile']['gateway_address'],
3935 'dns_address': net['ip_profile']['dns_address'],
3936 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3937 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3938 'dhcp_count': net['ip_profile']['dhcp_count'],
3939 }
3940 db_ip_profiles.append(db_ip_profile)
3941
3942 # print "vnf_net2instance:"
3943 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3944
3945 # 3. Creating new vm instances in the VIM
3946 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3947 ssh_access = None
3948 if sce_vnf.get('mgmt_access'):
3949 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3950 vnf_availability_zones = []
3951 for vm in sce_vnf.get('vms'):
3952 vm_av = vm.get('availability_zone')
3953 if vm_av and vm_av not in vnf_availability_zones:
3954 vnf_availability_zones.append(vm_av)
3955
3956 # check if there is enough availability zones available at vim level.
3957 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3958 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
3959 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors.Bad_Request)
3960
3961 if sce_vnf.get("datacenter"):
3962 vim = myvims[sce_vnf["datacenter"]]
3963 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3964 datacenter_id = sce_vnf["datacenter"]
3965 else:
3966 vim = myvims[default_datacenter_id]
3967 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3968 datacenter_id = default_datacenter_id
3969 sce_vnf["datacenter_id"] = datacenter_id
3970 i = 0
3971
3972 vnf_uuid = str(uuid4())
3973 uuid_list.append(vnf_uuid)
3974 db_instance_vnf = {
3975 'uuid': vnf_uuid,
3976 'instance_scenario_id': instance_uuid,
3977 'vnf_id': sce_vnf['vnf_id'],
3978 'sce_vnf_id': sce_vnf['uuid'],
3979 'datacenter_id': datacenter_id,
3980 'datacenter_tenant_id': myvim_thread_id,
3981 }
3982 db_instance_vnfs.append(db_instance_vnf)
3983
3984 for vm in sce_vnf['vms']:
3985 # skip PDUs
3986 if vm.get("pdu_type"):
3987 continue
3988
3989 myVMDict = {}
3990 sce_vnf_name = sce_vnf['member_vnf_index'] if sce_vnf['member_vnf_index'] else sce_vnf['name']
3991 myVMDict['name'] = "{}-{}-{}".format(instance_name[:64], sce_vnf_name[:64], vm["name"][:64])
3992 myVMDict['description'] = myVMDict['name'][0:99]
3993 # if not startvms:
3994 # myVMDict['start'] = "no"
3995 if vm.get("instance_parameters") and vm["instance_parameters"].get("name"):
3996 myVMDict['name'] = vm["instance_parameters"].get("name")
3997 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3998 # create image at vim in case it not exist
3999 image_uuid = vm['image_id']
4000 if vm.get("image_list"):
4001 for alternative_image in vm["image_list"]:
4002 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
4003 image_uuid = alternative_image['image_id']
4004 break
4005 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
4006 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
4007 vm['vim_image_id'] = image_id
4008
4009 # create flavor at vim in case it not exist
4010 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
4011 if flavor_dict['extended'] != None:
4012 flavor_dict['extended'] = yaml.load(flavor_dict['extended'], Loader=yaml.Loader)
4013 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
4014
4015 # Obtain information for additional disks
4016 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
4017 WHERE={'vim_id': flavor_id})
4018 if not extended_flavor_dict:
4019 raise NfvoException("flavor '{}' not found".format(flavor_id), httperrors.Not_Found)
4020
4021 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0], Loader=yaml.Loader)
4022 myVMDict['disks'] = None
4023 extended_info = extended_flavor_dict[0]['extended']
4024 if extended_info != None:
4025 extended_flavor_dict_yaml = yaml.load(extended_info, Loader=yaml.Loader)
4026 if 'disks' in extended_flavor_dict_yaml:
4027 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
4028 if vm.get("instance_parameters") and vm["instance_parameters"].get("devices"):
4029 for disk in myVMDict['disks']:
4030 if disk.get("name") in vm["instance_parameters"]["devices"]:
4031 disk.update(vm["instance_parameters"]["devices"][disk.get("name")])
4032
4033 vm['vim_flavor_id'] = flavor_id
4034 myVMDict['imageRef'] = vm['vim_image_id']
4035 myVMDict['flavorRef'] = vm['vim_flavor_id']
4036 myVMDict['availability_zone'] = vm.get('availability_zone')
4037 myVMDict['networks'] = []
4038 task_depends_on = []
4039 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
4040 is_management_vm = False
4041 db_vm_ifaces = []
4042 for iface in vm['interfaces']:
4043 netDict = {}
4044 if iface['type'] == "data":
4045 netDict['type'] = iface['model']
4046 elif "model" in iface and iface["model"] != None:
4047 netDict['model'] = iface['model']
4048 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
4049 # is obtained from iterface table model
4050 # discover type of interface looking at flavor
4051 for numa in flavor_dict.get('extended', {}).get('numas', []):
4052 for flavor_iface in numa.get('interfaces', []):
4053 if flavor_iface.get('name') == iface['internal_name']:
4054 if flavor_iface['dedicated'] == 'yes':
4055 netDict['type'] = "PF" # passthrough
4056 elif flavor_iface['dedicated'] == 'no':
4057 netDict['type'] = "VF" # siov
4058 elif flavor_iface['dedicated'] == 'yes:sriov':
4059 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
4060 netDict["mac_address"] = flavor_iface.get("mac_address")
4061 break
4062 netDict["use"] = iface['type']
4063 if netDict["use"] == "data" and not netDict.get("type"):
4064 # print "netDict", netDict
4065 # print "iface", iface
4066 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
4067 sce_vnf['name'], vm['name'], iface['internal_name'])
4068 if flavor_dict.get('extended') == None:
4069 raise NfvoException(e_text + "After database migration some information is not available. \
4070 Try to delete and create the scenarios and VNFs again", httperrors.Conflict)
4071 else:
4072 raise NfvoException(e_text, httperrors.Internal_Server_Error)
4073 if netDict["use"] == "mgmt":
4074 is_management_vm = True
4075 netDict["type"] = "virtual"
4076 if netDict["use"] == "bridge":
4077 netDict["type"] = "virtual"
4078 if iface.get("vpci"):
4079 netDict['vpci'] = iface['vpci']
4080 if iface.get("mac"):
4081 netDict['mac_address'] = iface['mac']
4082 if iface.get("mac_address"):
4083 netDict['mac_address'] = iface['mac_address']
4084 if iface.get("ip_address"):
4085 netDict['ip_address'] = iface['ip_address']
4086 if iface.get("port-security") is not None:
4087 netDict['port_security'] = iface['port-security']
4088 if iface.get("floating-ip") is not None:
4089 netDict['floating_ip'] = iface['floating-ip']
4090 netDict['name'] = iface['internal_name']
4091 if iface['net_id'] is None:
4092 for vnf_iface in sce_vnf["interfaces"]:
4093 # print iface
4094 # print vnf_iface
4095 if vnf_iface['interface_id'] == iface['uuid']:
4096 netDict['net_id'] = "TASK-{}".format(
4097 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
4098 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
4099 instance_wim_net_id = sce_net2wim_instance[vnf_iface['sce_net_id']][datacenter_id]
4100 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
4101 break
4102 else:
4103 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
4104 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
4105 instance_wim_net_id = vnf_net2wim_instance.get(instance_net_id)
4106 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
4107 # skip bridge ifaces not connected to any net
4108 if 'net_id' not in netDict or netDict['net_id'] == None:
4109 continue
4110 myVMDict['networks'].append(netDict)
4111 db_vm_iface = {
4112 # "uuid"
4113 # 'instance_vm_id': instance_vm_uuid,
4114 "instance_net_id": instance_net_id,
4115 "instance_wim_net_id": instance_wim_net_id,
4116 'interface_id': iface['uuid'],
4117 # 'vim_interface_id': ,
4118 'type': 'external' if iface['external_name'] is not None else 'internal',
4119 'model': iface['model'],
4120 'ip_address': iface.get('ip_address'),
4121 'mac_address': iface.get('mac'),
4122 'floating_ip': int(iface.get('floating-ip', False)),
4123 'port_security': int(iface.get('port-security', True))
4124 }
4125 db_vm_ifaces.append(db_vm_iface)
4126 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
4127 # print myVMDict['name']
4128 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
4129 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
4130 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
4131
4132 # We add the RO key to cloud_config if vnf will need ssh access
4133 cloud_config_vm = cloud_config
4134 if is_management_vm and params["instance_parameters"].get("mgmt_keys"):
4135 cloud_config_vm = unify_cloud_config({"key-pairs": params["instance_parameters"]["mgmt_keys"]},
4136 cloud_config_vm)
4137
4138 if vm.get("instance_parameters") and "mgmt_keys" in vm["instance_parameters"]:
4139 if vm["instance_parameters"]["mgmt_keys"]:
4140 cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
4141 cloud_config_vm)
4142 if RO_pub_key:
4143 cloud_config_vm = unify_cloud_config(cloud_config_vm, {"key-pairs": [RO_pub_key]})
4144 if vm.get("boot_data"):
4145 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
4146
4147 if myVMDict.get('availability_zone'):
4148 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
4149 else:
4150 av_index = None
4151 for vm_index in range(0, vm.get('count', 1)):
4152 vm_name = myVMDict['name'] + "-" + str(vm_index+1)
4153 task_params = (vm_name, myVMDict['description'], myVMDict.get('start', None),
4154 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
4155 myVMDict['disks'], av_index, vnf_availability_zones)
4156 # put interface uuid back to scenario[vnfs][vms[[interfaces]
4157 for net in myVMDict['networks']:
4158 if "vim_id" in net:
4159 for iface in vm['interfaces']:
4160 if net["name"] == iface["internal_name"]:
4161 iface["vim_id"] = net["vim_id"]
4162 break
4163 vm_uuid = str(uuid4())
4164 uuid_list.append(vm_uuid)
4165 db_vm = {
4166 "uuid": vm_uuid,
4167 "related": vm_uuid,
4168 'instance_vnf_id': vnf_uuid,
4169 # TODO delete "vim_vm_id": vm_id,
4170 "vm_id": vm["uuid"],
4171 "vim_name": vm_name,
4172 # "status":
4173 }
4174 db_instance_vms.append(db_vm)
4175
4176 iface_index = 0
4177 for db_vm_iface in db_vm_ifaces:
4178 iface_uuid = str(uuid4())
4179 uuid_list.append(iface_uuid)
4180 db_vm_iface_instance = {
4181 "uuid": iface_uuid,
4182 "instance_vm_id": vm_uuid
4183 }
4184 db_vm_iface_instance.update(db_vm_iface)
4185 if db_vm_iface_instance.get("ip_address"): # increment ip_address
4186 ip = db_vm_iface_instance.get("ip_address")
4187 i = ip.rfind(".")
4188 if i > 0:
4189 try:
4190 i += 1
4191 ip = ip[i:] + str(int(ip[:i]) + 1)
4192 db_vm_iface_instance["ip_address"] = ip
4193 except:
4194 db_vm_iface_instance["ip_address"] = None
4195 db_instance_interfaces.append(db_vm_iface_instance)
4196 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
4197 iface_index += 1
4198
4199 db_vim_action = {
4200 "instance_action_id": instance_action_id,
4201 "task_index": task_index,
4202 "datacenter_vim_id": myvim_thread_id,
4203 "action": "CREATE",
4204 "status": "SCHEDULED",
4205 "item": "instance_vms",
4206 "item_id": vm_uuid,
4207 "related": vm_uuid,
4208 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
4209 default_flow_style=True, width=256)
4210 }
4211 task_index += 1
4212 db_vim_actions.append(db_vim_action)
4213 params_out["task_index"] = task_index
4214 params_out["uuid_list"] = uuid_list
4215
4216
4217 def delete_instance(mydb, tenant_id, instance_id):
4218 # print "Checking that the instance_id exists and getting the instance dictionary"
4219 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
4220 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4221 tenant_id = instanceDict["tenant_id"]
4222
4223 # --> WIM
4224 # We need to retrieve the WIM Actions now, before the instance_scenario is
4225 # deleted. The reason for that is that: ON CASCADE rules will delete the
4226 # instance_wim_nets record in the database
4227 wim_actions = wim_engine.delete_actions(instance_scenario_id=instance_id)
4228 # <-- WIM
4229
4230 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
4231 # 1. Delete from Database
4232 message = mydb.delete_instance_scenario(instance_id, tenant_id)
4233
4234 # 2. delete from VIM
4235 error_msg = ""
4236 myvims = {}
4237 myvim_threads = {}
4238 vimthread_affected = {}
4239 net2vm_dependencies = {}
4240
4241 task_index = 0
4242 instance_action_id = get_task_id()
4243 db_vim_actions = []
4244 db_instance_action = {
4245 "uuid": instance_action_id, # same uuid for the instance and the action on create
4246 "tenant_id": tenant_id,
4247 "instance_id": instance_id,
4248 "description": "DELETE",
4249 # "number_tasks": 0 # filled bellow
4250 }
4251
4252 # 2.1 deleting VNFFGs
4253 for sfp in instanceDict.get('sfps', ()):
4254 vimthread_affected[sfp["datacenter_tenant_id"]] = None
4255 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
4256 if datacenter_key not in myvims:
4257 try:
4258 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
4259 except NfvoException as e:
4260 logger.error(str(e))
4261 myvim_thread = None
4262 myvim_threads[datacenter_key] = myvim_thread
4263 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
4264 datacenter_tenant_id=sfp["datacenter_tenant_id"])
4265 if len(vims) == 0:
4266 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
4267 myvims[datacenter_key] = None
4268 else:
4269 myvims[datacenter_key] = next(iter(vims.values()))
4270 myvim = myvims[datacenter_key]
4271 myvim_thread = myvim_threads[datacenter_key]
4272
4273 if not myvim:
4274 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
4275 continue
4276 extra = {"params": (sfp['vim_sfp_id'])}
4277 db_vim_action = {
4278 "instance_action_id": instance_action_id,
4279 "task_index": task_index,
4280 "datacenter_vim_id": sfp["datacenter_tenant_id"],
4281 "action": "DELETE",
4282 "status": "SCHEDULED",
4283 "item": "instance_sfps",
4284 "item_id": sfp["uuid"],
4285 "related": sfp["related"],
4286 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4287 }
4288 task_index += 1
4289 db_vim_actions.append(db_vim_action)
4290
4291 for classification in instanceDict['classifications']:
4292 vimthread_affected[classification["datacenter_tenant_id"]] = None
4293 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
4294 if datacenter_key not in myvims:
4295 try:
4296 _, myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
4297 except NfvoException as e:
4298 logger.error(str(e))
4299 myvim_thread = None
4300 myvim_threads[datacenter_key] = myvim_thread
4301 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
4302 datacenter_tenant_id=classification["datacenter_tenant_id"])
4303 if len(vims) == 0:
4304 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"],
4305 classification["datacenter_tenant_id"]))
4306 myvims[datacenter_key] = None
4307 else:
4308 myvims[datacenter_key] = next(iter(vims.values()))
4309 myvim = myvims[datacenter_key]
4310 myvim_thread = myvim_threads[datacenter_key]
4311
4312 if not myvim:
4313 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'],
4314 classification["datacenter_id"])
4315 continue
4316 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4317 extra = {"params": (classification['vim_classification_id']), "depends_on": depends_on}
4318 db_vim_action = {
4319 "instance_action_id": instance_action_id,
4320 "task_index": task_index,
4321 "datacenter_vim_id": classification["datacenter_tenant_id"],
4322 "action": "DELETE",
4323 "status": "SCHEDULED",
4324 "item": "instance_classifications",
4325 "item_id": classification["uuid"],
4326 "related": classification["related"],
4327 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4328 }
4329 task_index += 1
4330 db_vim_actions.append(db_vim_action)
4331
4332 for sf in instanceDict.get('sfs', ()):
4333 vimthread_affected[sf["datacenter_tenant_id"]] = None
4334 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
4335 if datacenter_key not in myvims:
4336 try:
4337 _, myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
4338 except NfvoException as e:
4339 logger.error(str(e))
4340 myvim_thread = None
4341 myvim_threads[datacenter_key] = myvim_thread
4342 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
4343 datacenter_tenant_id=sf["datacenter_tenant_id"])
4344 if len(vims) == 0:
4345 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
4346 myvims[datacenter_key] = None
4347 else:
4348 myvims[datacenter_key] = next(iter(vims.values()))
4349 myvim = myvims[datacenter_key]
4350 myvim_thread = myvim_threads[datacenter_key]
4351
4352 if not myvim:
4353 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
4354 continue
4355 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfps"]
4356 extra = {"params": (sf['vim_sf_id']), "depends_on": depends_on}
4357 db_vim_action = {
4358 "instance_action_id": instance_action_id,
4359 "task_index": task_index,
4360 "datacenter_vim_id": sf["datacenter_tenant_id"],
4361 "action": "DELETE",
4362 "status": "SCHEDULED",
4363 "item": "instance_sfs",
4364 "item_id": sf["uuid"],
4365 "related": sf["related"],
4366 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4367 }
4368 task_index += 1
4369 db_vim_actions.append(db_vim_action)
4370
4371 for sfi in instanceDict.get('sfis', ()):
4372 vimthread_affected[sfi["datacenter_tenant_id"]] = None
4373 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4374 if datacenter_key not in myvims:
4375 try:
4376 _, myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
4377 except NfvoException as e:
4378 logger.error(str(e))
4379 myvim_thread = None
4380 myvim_threads[datacenter_key] = myvim_thread
4381 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
4382 datacenter_tenant_id=sfi["datacenter_tenant_id"])
4383 if len(vims) == 0:
4384 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
4385 myvims[datacenter_key] = None
4386 else:
4387 myvims[datacenter_key] = next(iter(vims.values()))
4388 myvim = myvims[datacenter_key]
4389 myvim_thread = myvim_threads[datacenter_key]
4390
4391 if not myvim:
4392 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
4393 continue
4394 depends_on = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfs"]
4395 extra = {"params": (sfi['vim_sfi_id']), "depends_on": depends_on}
4396 db_vim_action = {
4397 "instance_action_id": instance_action_id,
4398 "task_index": task_index,
4399 "datacenter_vim_id": sfi["datacenter_tenant_id"],
4400 "action": "DELETE",
4401 "status": "SCHEDULED",
4402 "item": "instance_sfis",
4403 "item_id": sfi["uuid"],
4404 "related": sfi["related"],
4405 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4406 }
4407 task_index += 1
4408 db_vim_actions.append(db_vim_action)
4409
4410 # 2.2 deleting VMs
4411 # vm_fail_list=[]
4412 for sce_vnf in instanceDict.get('vnfs', ()):
4413 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4414 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
4415 if datacenter_key not in myvims:
4416 try:
4417 _, myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4418 except NfvoException as e:
4419 logger.error(str(e))
4420 myvim_thread = None
4421 myvim_threads[datacenter_key] = myvim_thread
4422 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
4423 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4424 if len(vims) == 0:
4425 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
4426 sce_vnf["datacenter_tenant_id"]))
4427 myvims[datacenter_key] = None
4428 else:
4429 myvims[datacenter_key] = next(iter(vims.values()))
4430 myvim = myvims[datacenter_key]
4431 myvim_thread = myvim_threads[datacenter_key]
4432
4433 for vm in sce_vnf['vms']:
4434 if not myvim:
4435 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
4436 continue
4437 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4438 db_vim_action = {
4439 "instance_action_id": instance_action_id,
4440 "task_index": task_index,
4441 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
4442 "action": "DELETE",
4443 "status": "SCHEDULED",
4444 "item": "instance_vms",
4445 "item_id": vm["uuid"],
4446 "related": vm["related"],
4447 "extra": yaml.safe_dump({"params": vm["interfaces"], "depends_on": sfi_dependencies},
4448 default_flow_style=True, width=256)
4449 }
4450 db_vim_actions.append(db_vim_action)
4451 for interface in vm["interfaces"]:
4452 if not interface.get("instance_net_id"):
4453 continue
4454 if interface["instance_net_id"] not in net2vm_dependencies:
4455 net2vm_dependencies[interface["instance_net_id"]] = []
4456 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
4457 task_index += 1
4458
4459 # 2.3 deleting NETS
4460 # net_fail_list=[]
4461 for net in instanceDict['nets']:
4462 vimthread_affected[net["datacenter_tenant_id"]] = None
4463 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4464 if datacenter_key not in myvims:
4465 try:
4466 _,myvim_thread = get_vim_thread(mydb, tenant_id, net["datacenter_id"], net["datacenter_tenant_id"])
4467 except NfvoException as e:
4468 logger.error(str(e))
4469 myvim_thread = None
4470 myvim_threads[datacenter_key] = myvim_thread
4471 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
4472 datacenter_tenant_id=net["datacenter_tenant_id"])
4473 if len(vims) == 0:
4474 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4475 myvims[datacenter_key] = None
4476 else:
4477 myvims[datacenter_key] = next(iter(vims.values()))
4478 myvim = myvims[datacenter_key]
4479 myvim_thread = myvim_threads[datacenter_key]
4480
4481 if not myvim:
4482 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
4483 continue
4484 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
4485 if net2vm_dependencies.get(net["uuid"]):
4486 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
4487 sfi_dependencies = [action["task_index"] for action in db_vim_actions if action["item"] == "instance_sfis"]
4488 if len(sfi_dependencies) > 0:
4489 if "depends_on" in extra:
4490 extra["depends_on"] += sfi_dependencies
4491 else:
4492 extra["depends_on"] = sfi_dependencies
4493 db_vim_action = {
4494 "instance_action_id": instance_action_id,
4495 "task_index": task_index,
4496 "datacenter_vim_id": net["datacenter_tenant_id"],
4497 "action": "DELETE",
4498 "status": "SCHEDULED",
4499 "item": "instance_nets",
4500 "item_id": net["uuid"],
4501 "related": net["related"],
4502 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4503 }
4504 task_index += 1
4505 db_vim_actions.append(db_vim_action)
4506 for sdn_net in instanceDict['sdn_nets']:
4507 if not sdn_net["sdn"]:
4508 continue
4509 extra = {}
4510 db_vim_action = {
4511 "instance_action_id": instance_action_id,
4512 "task_index": task_index,
4513 "wim_account_id": sdn_net["wim_account_id"],
4514 "action": "DELETE",
4515 "status": "SCHEDULED",
4516 "item": "instance_wim_nets",
4517 "item_id": sdn_net["uuid"],
4518 "related": sdn_net["related"],
4519 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
4520 }
4521 task_index += 1
4522 db_vim_actions.append(db_vim_action)
4523
4524 db_instance_action["number_tasks"] = task_index
4525
4526 # --> WIM
4527 wim_actions, db_instance_action = (
4528 wim_engine.incorporate_actions(wim_actions, db_instance_action))
4529 # <-- WIM
4530
4531 db_tables = [
4532 {"instance_actions": db_instance_action},
4533 {"vim_wim_actions": db_vim_actions + wim_actions}
4534 ]
4535
4536 logger.debug("delete_instance done DB tables: %s",
4537 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4538 mydb.new_rows(db_tables, ())
4539 for myvim_thread_id in vimthread_affected.keys():
4540 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4541
4542 wim_engine.dispatch(wim_actions)
4543
4544 if len(error_msg) > 0:
4545 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4546 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
4547 else:
4548 return "action_id={} instance {} deleted".format(instance_action_id, message)
4549
4550 def get_instance_id(mydb, tenant_id, instance_id):
4551 global ovim
4552 #check valid tenant_id
4553 check_tenant(mydb, tenant_id)
4554 #obtain data
4555
4556 instance_dict = mydb.get_instance_scenario(instance_id, tenant_id, verbose=True)
4557 # TODO py3
4558 # for net in instance_dict["nets"]:
4559 # if net.get("sdn_net_id"):
4560 # net_sdn = ovim.show_network(net["sdn_net_id"])
4561 # net["sdn_info"] = {
4562 # "admin_state_up": net_sdn.get("admin_state_up"),
4563 # "flows": net_sdn.get("flows"),
4564 # "last_error": net_sdn.get("last_error"),
4565 # "ports": net_sdn.get("ports"),
4566 # "type": net_sdn.get("type"),
4567 # "status": net_sdn.get("status"),
4568 # "vlan": net_sdn.get("vlan"),
4569 # }
4570 return instance_dict
4571
4572 @deprecated("Instance is automatically refreshed by vim_threads")
4573 def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4574 '''Refreshes a scenario instance. It modifies instanceDict'''
4575 '''Returns:
4576 - 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
4577 - error_msg
4578 '''
4579 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4580 # #print "nfvo.refresh_instance begins"
4581 # #print json.dumps(instanceDict, indent=4)
4582 #
4583 # #print "Getting the VIM URL and the VIM tenant_id"
4584 # myvims={}
4585 #
4586 # # 1. Getting VIM vm and net list
4587 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4588 # vms_notupdated=[]
4589 # vm_list = {}
4590 # for sce_vnf in instanceDict['vnfs']:
4591 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4592 # if datacenter_key not in vm_list:
4593 # vm_list[datacenter_key] = []
4594 # if datacenter_key not in myvims:
4595 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4596 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4597 # if len(vims) == 0:
4598 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4599 # myvims[datacenter_key] = None
4600 # else:
4601 # myvims[datacenter_key] = next(iter(vims.values()))
4602 # for vm in sce_vnf['vms']:
4603 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4604 # vms_notupdated.append(vm["uuid"])
4605 #
4606 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4607 # nets_notupdated=[]
4608 # net_list = {}
4609 # for net in instanceDict['nets']:
4610 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4611 # if datacenter_key not in net_list:
4612 # net_list[datacenter_key] = []
4613 # if datacenter_key not in myvims:
4614 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4615 # datacenter_tenant_id=net["datacenter_tenant_id"])
4616 # if len(vims) == 0:
4617 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4618 # myvims[datacenter_key] = None
4619 # else:
4620 # myvims[datacenter_key] = next(iter(vims.values()))
4621 #
4622 # net_list[datacenter_key].append(net['vim_net_id'])
4623 # nets_notupdated.append(net["uuid"])
4624 #
4625 # # 1. Getting the status of all VMs
4626 # vm_dict={}
4627 # for datacenter_key in myvims:
4628 # if not vm_list.get(datacenter_key):
4629 # continue
4630 # failed = True
4631 # failed_message=""
4632 # if not myvims[datacenter_key]:
4633 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4634 # else:
4635 # try:
4636 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4637 # failed = False
4638 # except vimconn.vimconnException as e:
4639 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4640 # failed_message = str(e)
4641 # if failed:
4642 # for vm in vm_list[datacenter_key]:
4643 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4644 #
4645 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4646 # for sce_vnf in instanceDict['vnfs']:
4647 # for vm in sce_vnf['vms']:
4648 # vm_id = vm['vim_vm_id']
4649 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4650 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4651 # has_mgmt_iface = False
4652 # for iface in vm["interfaces"]:
4653 # if iface["type"]=="mgmt":
4654 # has_mgmt_iface = True
4655 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4656 # vm_dict[vm_id]['status'] = "ACTIVE"
4657 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4658 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4659 # 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'):
4660 # vm['status'] = vm_dict[vm_id]['status']
4661 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4662 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4663 # # 2.1. Update in openmano DB the VMs whose status changed
4664 # try:
4665 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4666 # vms_notupdated.remove(vm["uuid"])
4667 # if updates>0:
4668 # vms_updated.append(vm["uuid"])
4669 # except db_base_Exception as e:
4670 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4671 # # 2.2. Update in openmano DB the interface VMs
4672 # for interface in interfaces:
4673 # #translate from vim_net_id to instance_net_id
4674 # network_id_list=[]
4675 # for net in instanceDict['nets']:
4676 # if net["vim_net_id"] == interface["vim_net_id"]:
4677 # network_id_list.append(net["uuid"])
4678 # if not network_id_list:
4679 # continue
4680 # del interface["vim_net_id"]
4681 # try:
4682 # for network_id in network_id_list:
4683 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4684 # except db_base_Exception as e:
4685 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4686 #
4687 # # 3. Getting the status of all nets
4688 # net_dict = {}
4689 # for datacenter_key in myvims:
4690 # if not net_list.get(datacenter_key):
4691 # continue
4692 # failed = True
4693 # failed_message = ""
4694 # if not myvims[datacenter_key]:
4695 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4696 # else:
4697 # try:
4698 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4699 # failed = False
4700 # except vimconn.vimconnException as e:
4701 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4702 # failed_message = str(e)
4703 # if failed:
4704 # for net in net_list[datacenter_key]:
4705 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4706 #
4707 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4708 # # TODO: update nets inside a vnf
4709 # for net in instanceDict['nets']:
4710 # net_id = net['vim_net_id']
4711 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4712 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4713 # 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'):
4714 # net['status'] = net_dict[net_id]['status']
4715 # net['error_msg'] = net_dict[net_id].get('error_msg')
4716 # net['vim_info'] = net_dict[net_id].get('vim_info')
4717 # # 5.1. Update in openmano DB the nets whose status changed
4718 # try:
4719 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4720 # nets_notupdated.remove(net["uuid"])
4721 # if updated>0:
4722 # nets_updated.append(net["uuid"])
4723 # except db_base_Exception as e:
4724 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4725 #
4726 # # Returns appropriate output
4727 # #print "nfvo.refresh_instance finishes"
4728 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4729 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
4730 instance_id = instanceDict['uuid']
4731 # if len(vms_notupdated)+len(nets_notupdated)>0:
4732 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4733 # return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
4734
4735 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
4736
4737 def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
4738 #print "Checking that the instance_id exists and getting the instance dictionary"
4739 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
4740 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4741
4742 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
4743 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4744 if len(vims) == 0:
4745 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), httperrors.Not_Found)
4746 myvim = next(iter(vims.values()))
4747 vm_result = {}
4748 vm_error = 0
4749 vm_ok = 0
4750
4751 myvim_threads_id = {}
4752 if action_dict.get("vdu-scaling"):
4753 db_instance_vms = []
4754 db_vim_actions = []
4755 db_instance_interfaces = []
4756 instance_action_id = get_task_id()
4757 db_instance_action = {
4758 "uuid": instance_action_id, # same uuid for the instance and the action on create
4759 "tenant_id": nfvo_tenant,
4760 "instance_id": instance_id,
4761 "description": "SCALE",
4762 }
4763 vm_result["instance_action_id"] = instance_action_id
4764 vm_result["created"] = []
4765 vm_result["deleted"] = []
4766 task_index = 0
4767 for vdu in action_dict["vdu-scaling"]:
4768 vdu_id = vdu.get("vdu-id")
4769 osm_vdu_id = vdu.get("osm_vdu_id")
4770 member_vnf_index = vdu.get("member-vnf-index")
4771 vdu_count = vdu.get("count", 1)
4772 if vdu_id:
4773 target_vms = mydb.get_rows(
4774 FROM="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4775 WHERE={"vms.uuid": vdu_id},
4776 ORDER_BY="vms.created_at"
4777 )
4778 if not target_vms:
4779 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id), httperrors.Not_Found)
4780 else:
4781 if not osm_vdu_id and not member_vnf_index:
4782 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
4783 target_vms = mydb.get_rows(
4784 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4785 FROM="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4786 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4787 " join vms on ivms.vm_id=vms.uuid",
4788 WHERE={"vms.osm_id": osm_vdu_id, "svnfs.member_vnf_index": member_vnf_index,
4789 "ivnfs.instance_scenario_id": instance_id},
4790 ORDER_BY="ivms.created_at"
4791 )
4792 if not target_vms:
4793 raise NfvoException("Cannot find the vdu with osm_vdu_id {} and member-vnf-index {}".format(osm_vdu_id, member_vnf_index), httperrors.Not_Found)
4794 vdu_id = target_vms[-1]["uuid"]
4795 target_vm = target_vms[-1]
4796 datacenter = target_vm["datacenter_id"]
4797 myvim_threads_id[datacenter], _ = get_vim_thread(mydb, nfvo_tenant, datacenter)
4798
4799 if vdu["type"] == "delete":
4800 for index in range(0, vdu_count):
4801 target_vm = target_vms[-1-index]
4802 vdu_id = target_vm["uuid"]
4803 # look for nm
4804 vm_interfaces = None
4805 for sce_vnf in instanceDict['vnfs']:
4806 for vm in sce_vnf['vms']:
4807 if vm["uuid"] == vdu_id:
4808 # TODO revise this should not be vm["uuid"] instance_vms["vm_id"]
4809 vm_interfaces = vm["interfaces"]
4810 break
4811
4812 db_vim_action = {
4813 "instance_action_id": instance_action_id,
4814 "task_index": task_index,
4815 "datacenter_vim_id": target_vm["datacenter_tenant_id"],
4816 "action": "DELETE",
4817 "status": "SCHEDULED",
4818 "item": "instance_vms",
4819 "item_id": vdu_id,
4820 "related": target_vm["related"],
4821 "extra": yaml.safe_dump({"params": vm_interfaces},
4822 default_flow_style=True, width=256)
4823 }
4824 task_index += 1
4825 db_vim_actions.append(db_vim_action)
4826 vm_result["deleted"].append(vdu_id)
4827 # delete from database
4828 db_instance_vms.append({"TO-DELETE": vdu_id})
4829
4830 else: # vdu["type"] == "create":
4831 iface2iface = {}
4832 where = {"item": "instance_vms", "item_id": target_vm["uuid"], "action": "CREATE"}
4833
4834 vim_action_to_clone = mydb.get_rows(FROM="vim_wim_actions", WHERE=where)
4835 if not vim_action_to_clone:
4836 raise NfvoException("Cannot find the vim_action at database with {}".format(where), httperrors.Internal_Server_Error)
4837 vim_action_to_clone = vim_action_to_clone[0]
4838 extra = yaml.safe_load(vim_action_to_clone["extra"])
4839
4840 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4841 # TODO do the same for flavor and image when available
4842 task_depends_on = []
4843 task_params = extra["params"]
4844 task_params_networks = deepcopy(task_params[5])
4845 for iface in task_params[5]:
4846 if iface["net_id"].startswith("TASK-"):
4847 if "." not in iface["net_id"]:
4848 task_depends_on.append("{}.{}".format(vim_action_to_clone["instance_action_id"],
4849 iface["net_id"][5:]))
4850 iface["net_id"] = "TASK-{}.{}".format(vim_action_to_clone["instance_action_id"],
4851 iface["net_id"][5:])
4852 else:
4853 task_depends_on.append(iface["net_id"][5:])
4854 if "mac_address" in iface:
4855 del iface["mac_address"]
4856
4857 vm_ifaces_to_clone = mydb.get_rows(FROM="instance_interfaces", WHERE={"instance_vm_id": target_vm["uuid"]})
4858 for index in range(0, vdu_count):
4859 vm_uuid = str(uuid4())
4860 vm_name = target_vm.get('vim_name')
4861 try:
4862 suffix = vm_name.rfind("-")
4863 vm_name = vm_name[:suffix+1] + str(index + 1 + int(vm_name[suffix+1:]))
4864 except Exception:
4865 pass
4866 db_instance_vm = {
4867 "uuid": vm_uuid,
4868 'related': vm_uuid,
4869 'instance_vnf_id': target_vm['instance_vnf_id'],
4870 'vm_id': target_vm['vm_id'],
4871 'vim_name': vm_name,
4872 }
4873 db_instance_vms.append(db_instance_vm)
4874
4875 for vm_iface in vm_ifaces_to_clone:
4876 iface_uuid = str(uuid4())
4877 iface2iface[vm_iface["uuid"]] = iface_uuid
4878 db_vm_iface = {
4879 "uuid": iface_uuid,
4880 'instance_vm_id': vm_uuid,
4881 "instance_net_id": vm_iface["instance_net_id"],
4882 "instance_wim_net_id": vm_iface["instance_wim_net_id"],
4883 'interface_id': vm_iface['interface_id'],
4884 'type': vm_iface['type'],
4885 'model': vm_iface['model'],
4886 'floating_ip': vm_iface['floating_ip'],
4887 'port_security': vm_iface['port_security']
4888 }
4889 db_instance_interfaces.append(db_vm_iface)
4890 task_params_copy = deepcopy(task_params)
4891 for iface in task_params_copy[5]:
4892 iface["uuid"] = iface2iface[iface["uuid"]]
4893 # increment ip_address
4894 if "ip_address" in iface:
4895 ip = iface.get("ip_address")
4896 i = ip.rfind(".")
4897 if i > 0:
4898 try:
4899 i += 1
4900 ip = ip[i:] + str(int(ip[:i]) + 1)
4901 iface["ip_address"] = ip
4902 except:
4903 iface["ip_address"] = None
4904 if vm_name:
4905 task_params_copy[0] = vm_name
4906 db_vim_action = {
4907 "instance_action_id": instance_action_id,
4908 "task_index": task_index,
4909 "datacenter_vim_id": vim_action_to_clone["datacenter_vim_id"],
4910 "action": "CREATE",
4911 "status": "SCHEDULED",
4912 "item": "instance_vms",
4913 "item_id": vm_uuid,
4914 "related": vm_uuid,
4915 # ALF
4916 # ALF
4917 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4918 # ALF
4919 # ALF
4920 "extra": yaml.safe_dump({"params": task_params_copy, "depends_on": task_depends_on}, default_flow_style=True, width=256)
4921 }
4922 task_index += 1
4923 db_vim_actions.append(db_vim_action)
4924 vm_result["created"].append(vm_uuid)
4925
4926 db_instance_action["number_tasks"] = task_index
4927 db_tables = [
4928 {"instance_vms": db_instance_vms},
4929 {"instance_interfaces": db_instance_interfaces},
4930 {"instance_actions": db_instance_action},
4931 # TODO revise sfps
4932 # {"instance_sfis": db_instance_sfis},
4933 # {"instance_sfs": db_instance_sfs},
4934 # {"instance_classifications": db_instance_classifications},
4935 # {"instance_sfps": db_instance_sfps},
4936 {"vim_wim_actions": db_vim_actions}
4937 ]
4938 logger.debug("create_vdu done DB tables: %s",
4939 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4940 mydb.new_rows(db_tables, [])
4941 for myvim_thread in myvim_threads_id.values():
4942 vim_threads["running"][myvim_thread].insert_task(db_vim_actions)
4943
4944 return vm_result
4945
4946 input_vnfs = action_dict.pop("vnfs", [])
4947 input_vms = action_dict.pop("vms", [])
4948 action_over_all = True if not input_vnfs and not input_vms else False
4949 for sce_vnf in instanceDict['vnfs']:
4950 for vm in sce_vnf['vms']:
4951 if not action_over_all and sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4952 sce_vnf['member_vnf_index'] not in input_vnfs and \
4953 vm['uuid'] not in input_vms and vm['name'] not in input_vms and \
4954 sce_vnf['member_vnf_index'] + "-" + vm['vdu_osm_id'] not in input_vms: # TODO conside vm_count_index
4955 continue
4956 try:
4957 if "add_public_key" in action_dict:
4958 if sce_vnf.get('mgmt_access'):
4959 mgmt_access = yaml.load(sce_vnf['mgmt_access'], Loader=yaml.Loader)
4960 if not input_vms and mgmt_access.get("vdu-id") != vm['vdu_osm_id']:
4961 continue
4962 default_user = mgmt_access.get("default-user")
4963 password = mgmt_access.get("password")
4964 if mgmt_access.get(vm['vdu_osm_id']):
4965 default_user = mgmt_access[vm['vdu_osm_id']].get("default-user", default_user)
4966 password = mgmt_access[vm['vdu_osm_id']].get("password", password)
4967
4968 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
4969 try:
4970 if 'ip_address' in vm:
4971 mgmt_ip = vm['ip_address'].split(';')
4972 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4973 data = myvim.inject_user_key(mgmt_ip[0], action_dict.get('user', default_user),
4974 action_dict['add_public_key'],
4975 password=password, ro_key=priv_RO_key)
4976 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4977 "description": "Public key injected",
4978 "name":vm['name']
4979 }
4980 except KeyError:
4981 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4982 httperrors.Internal_Server_Error)
4983 else:
4984 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4985 httperrors.Internal_Server_Error)
4986 else:
4987 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4988 if "console" in action_dict:
4989 if not global_config["http_console_proxy"]:
4990 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4991 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4992 protocol=data["protocol"],
4993 ip = data["server"],
4994 port = data["port"],
4995 suffix = data["suffix"]),
4996 "name":vm['name']
4997 }
4998 vm_ok +=1
4999 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
5000 vm_result[ vm['uuid'] ] = {"vim_result": -httperrors.Unauthorized,
5001 "description": "this console is only reachable by local interface",
5002 "name":vm['name']
5003 }
5004 vm_error+=1
5005 else:
5006 #print "console data", data
5007 try:
5008 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
5009 vm_result[ vm['uuid'] ] = {"vim_result": 200,
5010 "description": "{protocol}//{ip}:{port}/{suffix}".format(
5011 protocol=data["protocol"],
5012 ip = global_config["http_console_host"],
5013 port = console_thread.port,
5014 suffix = data["suffix"]),
5015 "name":vm['name']
5016 }
5017 vm_ok +=1
5018 except NfvoException as e:
5019 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
5020 vm_error+=1
5021
5022 else:
5023 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
5024 vm_ok +=1
5025 except vimconn.vimconnException as e:
5026 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
5027 vm_error+=1
5028
5029 if vm_ok==0: #all goes wrong
5030 return vm_result
5031 else:
5032 return vm_result
5033
5034 def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
5035 filter = {}
5036 if nfvo_tenant and nfvo_tenant != "any":
5037 filter["tenant_id"] = nfvo_tenant
5038 if instance_id and instance_id != "any":
5039 filter["instance_id"] = instance_id
5040 if action_id:
5041 filter["uuid"] = action_id
5042 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
5043 if action_id:
5044 if not rows:
5045 raise NfvoException("Not found any action with this criteria", httperrors.Not_Found)
5046 vim_wim_actions = mydb.get_rows(FROM="vim_wim_actions", WHERE={"instance_action_id": action_id})
5047 rows[0]["vim_wim_actions"] = vim_wim_actions
5048 # for backward compatibility set vim_actions = vim_wim_actions
5049 rows[0]["vim_actions"] = vim_wim_actions
5050 return {"actions": rows}
5051
5052
5053 def create_or_use_console_proxy_thread(console_server, console_port):
5054 #look for a non-used port
5055 console_thread_key = console_server + ":" + str(console_port)
5056 if console_thread_key in global_config["console_thread"]:
5057 #global_config["console_thread"][console_thread_key].start_timeout()
5058 return global_config["console_thread"][console_thread_key]
5059
5060 for port in global_config["console_port_iterator"]():
5061 #print "create_or_use_console_proxy_thread() port:", port
5062 if port in global_config["console_ports"]:
5063 continue
5064 try:
5065 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
5066 clithread.start()
5067 global_config["console_thread"][console_thread_key] = clithread
5068 global_config["console_ports"][port] = console_thread_key
5069 return clithread
5070 except cli.ConsoleProxyExceptionPortUsed as e:
5071 #port used, try with onoher
5072 continue
5073 except cli.ConsoleProxyException as e:
5074 raise NfvoException(str(e), httperrors.Bad_Request)
5075 raise NfvoException("Not found any free 'http_console_ports'", httperrors.Conflict)
5076
5077
5078 def check_tenant(mydb, tenant_id):
5079 '''check that tenant exists at database'''
5080 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
5081 if not tenant:
5082 raise NfvoException("tenant '{}' not found".format(tenant_id), httperrors.Not_Found)
5083 return
5084
5085 def new_tenant(mydb, tenant_dict):
5086
5087 tenant_uuid = str(uuid4())
5088 tenant_dict['uuid'] = tenant_uuid
5089 try:
5090 pub_key, priv_key = create_RO_keypair(tenant_uuid)
5091 tenant_dict['RO_pub_key'] = pub_key
5092 tenant_dict['encrypted_RO_priv_key'] = priv_key
5093 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
5094 except db_base_Exception as e:
5095 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
5096 return tenant_uuid
5097
5098 def delete_tenant(mydb, tenant):
5099 #get nfvo_tenant info
5100
5101 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
5102 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
5103 return tenant_dict['uuid'] + " " + tenant_dict["name"]
5104
5105
5106 def new_datacenter(mydb, datacenter_descriptor):
5107 sdn_port_mapping = None
5108 if "config" in datacenter_descriptor:
5109 sdn_port_mapping = datacenter_descriptor["config"].pop("sdn-port-mapping", None)
5110 datacenter_descriptor["config"] = yaml.safe_dump(datacenter_descriptor["config"], default_flow_style=True,
5111 width=256)
5112 # Check that datacenter-type is correct
5113 datacenter_type = datacenter_descriptor.get("type", "openvim");
5114 # module_info = None
5115
5116 for url_field in ('vim_url', 'vim_url_admin'):
5117 # It is common that users copy and paste the URL from the VIM website
5118 # (example OpenStack), therefore a common mistake is to include blank
5119 # characters at the end of the URL. Let's remove it and just in case,
5120 # lets remove trailing slash as well.
5121 url = datacenter_descriptor.get(url_field)
5122 if url:
5123 datacenter_descriptor[url_field] = url.strip(string.whitespace + '/')
5124
5125 # load plugin
5126 plugin_name = "rovim_" + datacenter_type
5127 if plugin_name not in plugins:
5128 _load_plugin(plugin_name, type="vim")
5129
5130 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
5131 if sdn_port_mapping:
5132 try:
5133 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, sdn_port_mapping)
5134 except Exception as e:
5135 mydb.delete_row_by_id("datacenters", datacenter_id) # Rollback
5136 raise e
5137 return datacenter_id
5138
5139
5140 def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
5141 # obtain data, check that only one exist
5142 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
5143
5144 # edit data
5145 datacenter_id = datacenter['uuid']
5146 where = {'uuid': datacenter['uuid']}
5147 remove_port_mapping = False
5148 new_sdn_port_mapping = None
5149 if "config" in datacenter_descriptor:
5150 if datacenter_descriptor['config'] != None:
5151 try:
5152 new_config_dict = datacenter_descriptor["config"]
5153 if "sdn-port-mapping" in new_config_dict:
5154 remove_port_mapping = True
5155 new_sdn_port_mapping = new_config_dict.pop("sdn-port-mapping")
5156 # delete null fields
5157 to_delete = []
5158 for k in new_config_dict:
5159 if new_config_dict[k] is None:
5160 to_delete.append(k)
5161 if k == 'sdn-controller':
5162 remove_port_mapping = True
5163
5164 config_text = datacenter.get("config")
5165 if not config_text:
5166 config_text = '{}'
5167 config_dict = yaml.load(config_text, Loader=yaml.Loader)
5168 config_dict.update(new_config_dict)
5169 # delete null fields
5170 for k in to_delete:
5171 del config_dict[k]
5172 except Exception as e:
5173 raise NfvoException("Bad format at datacenter:config " + str(e), httperrors.Bad_Request)
5174 if config_dict:
5175 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
5176 else:
5177 datacenter_descriptor["config"] = None
5178 if remove_port_mapping:
5179 try:
5180 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
5181 except ovimException as e:
5182 raise NfvoException("Error deleting datacenter-port-mapping " + str(e), httperrors.Conflict)
5183
5184 mydb.update_rows('datacenters', datacenter_descriptor, where)
5185 if new_sdn_port_mapping:
5186 try:
5187 datacenter_sdn_port_mapping_set(mydb, None, datacenter_id, new_sdn_port_mapping)
5188 except ovimException as e:
5189 # Rollback
5190 mydb.update_rows('datacenters', datacenter, where)
5191 raise NfvoException("Error adding datacenter-port-mapping " + str(e), httperrors.Conflict)
5192 return datacenter_id
5193
5194
5195 def delete_datacenter(mydb, datacenter):
5196 #get nfvo_tenant info
5197 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
5198 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
5199 try:
5200 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
5201 except ovimException as e:
5202 raise NfvoException("Error deleting datacenter-port-mapping " + str(e))
5203 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
5204
5205
5206 def create_vim_account(mydb, nfvo_tenant, datacenter_id, name=None, vim_id=None, vim_tenant=None, vim_tenant_name=None,
5207 vim_username=None, vim_password=None, config=None):
5208 # get datacenter info
5209 try:
5210 if not datacenter_id:
5211 if not vim_id:
5212 raise NfvoException("You must provide 'vim_id", http_code=httperrors.Bad_Request)
5213 datacenter_id = vim_id
5214 datacenter_id, datacenter_name = get_datacenter_uuid(mydb, None, datacenter_id)
5215
5216 create_vim_tenant = True if not vim_tenant and not vim_tenant_name else False
5217
5218 # get nfvo_tenant info
5219 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
5220 if vim_tenant_name==None:
5221 vim_tenant_name=tenant_dict['name']
5222
5223 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
5224 # #check that this association does not exist before
5225 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5226 # if len(tenants_datacenters)>0:
5227 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
5228
5229 vim_tenant_id_exist_atdb=False
5230 if not create_vim_tenant:
5231 where_={"datacenter_id": datacenter_id}
5232 if vim_tenant!=None:
5233 where_["vim_tenant_id"] = vim_tenant
5234 if vim_tenant_name!=None:
5235 where_["vim_tenant_name"] = vim_tenant_name
5236 #check if vim_tenant_id is already at database
5237 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
5238 if len(datacenter_tenants_dict)>=1:
5239 datacenter_tenants_dict = datacenter_tenants_dict[0]
5240 vim_tenant_id_exist_atdb=True
5241 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
5242 else: #result=0
5243 datacenter_tenants_dict = {}
5244 #insert at table datacenter_tenants
5245 else: #if vim_tenant==None:
5246 #create tenant at VIM if not provided
5247 try:
5248 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
5249 vim_passwd=vim_password)
5250 datacenter_name = myvim["name"]
5251 vim_tenant = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
5252 except vimconn.vimconnException as e:
5253 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id, str(e)), httperrors.Internal_Server_Error)
5254 datacenter_tenants_dict = {}
5255 datacenter_tenants_dict["created"]="true"
5256
5257 #fill datacenter_tenants table
5258 if not vim_tenant_id_exist_atdb:
5259 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant
5260 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
5261 datacenter_tenants_dict["user"] = vim_username
5262 datacenter_tenants_dict["passwd"] = vim_password
5263 datacenter_tenants_dict["datacenter_id"] = datacenter_id
5264 if name:
5265 datacenter_tenants_dict["name"] = name
5266 else:
5267 datacenter_tenants_dict["name"] = datacenter_name
5268 if config:
5269 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
5270 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
5271 datacenter_tenants_dict["uuid"] = id_
5272
5273 #fill tenants_datacenters table
5274 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
5275 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
5276 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
5277
5278 # create thread
5279 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id)
5280 new_thread = vim_thread(task_lock, plugins, thread_name, None, datacenter_tenant_id, db=db)
5281 new_thread.start()
5282 thread_id = datacenter_tenants_dict["uuid"]
5283 vim_threads["running"][thread_id] = new_thread
5284 return thread_id
5285 except vimconn.vimconnException as e:
5286 raise NfvoException(str(e), httperrors.Bad_Request)
5287
5288
5289 def edit_vim_account(mydb, nfvo_tenant, datacenter_tenant_id, datacenter_id=None, name=None, vim_tenant=None,
5290 vim_tenant_name=None, vim_username=None, vim_password=None, config=None):
5291
5292 # get vim_account; check is valid for this tenant
5293 from_ = "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
5294 where_ = {"td.nfvo_tenant_id": nfvo_tenant}
5295 if datacenter_tenant_id:
5296 where_["dt.uuid"] = datacenter_tenant_id
5297 if datacenter_id:
5298 where_["dt.datacenter_id"] = datacenter_id
5299 vim_accounts = mydb.get_rows(SELECT="dt.uuid as uuid, config", FROM=from_, WHERE=where_)
5300 if not vim_accounts:
5301 raise NfvoException("vim_account not found for this tenant", http_code=httperrors.Not_Found)
5302 elif len(vim_accounts) > 1:
5303 raise NfvoException("found more than one vim_account for this tenant", http_code=httperrors.Conflict)
5304 datacenter_tenant_id = vim_accounts[0]["uuid"]
5305 original_config = vim_accounts[0]["config"]
5306
5307 update_ = {}
5308 if config:
5309 original_config_dict = yaml.load(original_config, Loader=yaml.Loader)
5310 original_config_dict.update(config)
5311 update["config"] = yaml.safe_dump(original_config_dict, default_flow_style=True, width=256)
5312 if name:
5313 update_['name'] = name
5314 if vim_tenant:
5315 update_['vim_tenant_id'] = vim_tenant
5316 if vim_tenant_name:
5317 update_['vim_tenant_name'] = vim_tenant_name
5318 if vim_username:
5319 update_['user'] = vim_username
5320 if vim_password:
5321 update_['passwd'] = vim_password
5322 if update_:
5323 mydb.update_rows("datacenter_tenants", UPDATE=update_, WHERE={"uuid": datacenter_tenant_id})
5324
5325 vim_threads["running"][datacenter_tenant_id].insert_task("reload")
5326 return datacenter_tenant_id
5327
5328 def delete_vim_account(mydb, tenant_id, vim_account_id, datacenter=None):
5329 #get nfvo_tenant info
5330 if not tenant_id or tenant_id=="any":
5331 tenant_uuid = None
5332 else:
5333 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
5334 tenant_uuid = tenant_dict['uuid']
5335
5336 #check that this association exist before
5337 tenants_datacenter_dict = {}
5338 if datacenter:
5339 datacenter_id, _ = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
5340 tenants_datacenter_dict["datacenter_id"] = datacenter_id
5341 elif vim_account_id:
5342 tenants_datacenter_dict["datacenter_tenant_id"] = vim_account_id
5343 if tenant_uuid:
5344 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
5345 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5346 if len(tenant_datacenter_list)==0 and tenant_uuid:
5347 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Not_Found)
5348
5349 #delete this association
5350 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5351
5352 #get vim_tenant info and deletes
5353 warning=''
5354 for tenant_datacenter_item in tenant_datacenter_list:
5355 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5356 #try to delete vim:tenant
5357 try:
5358 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
5359 if vim_tenant_dict['created']=='true':
5360 #delete tenant at VIM if created by NFVO
5361 try:
5362 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5363 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
5364 except vimconn.vimconnException as e:
5365 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
5366 logger.warn(warning)
5367 except db_base_Exception as e:
5368 logger.error("Cannot delete datacenter_tenants " + str(e))
5369 pass # the error will be caused because dependencies, vim_tenant can not be deleted
5370 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
5371 thread = vim_threads["running"].get(thread_id)
5372 if thread:
5373 thread.insert_task("exit")
5374 vim_threads["deleting"][thread_id] = thread
5375 return "datacenter {} detached. {}".format(datacenter_id, warning)
5376
5377
5378 def datacenter_action(mydb, tenant_id, datacenter, action_dict):
5379 #DEPRECATED
5380 #get datacenter info
5381 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5382
5383 if 'check-connectivity' in action_dict:
5384 try:
5385 myvim.check_vim_connectivity()
5386 except vimconn.vimconnException as e:
5387 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
5388 raise NfvoException(str(e), e.http_code)
5389 elif 'net-update' in action_dict:
5390 try:
5391 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
5392 #print content
5393 except vimconn.vimconnException as e:
5394 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
5395 raise NfvoException(str(e), httperrors.Internal_Server_Error)
5396 #update nets Change from VIM format to NFVO format
5397 net_list=[]
5398 for net in nets:
5399 net_nfvo={'datacenter_id': datacenter_id}
5400 net_nfvo['name'] = net['name']
5401 #net_nfvo['description']= net['name']
5402 net_nfvo['vim_net_id'] = net['id']
5403 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5404 net_nfvo['shared'] = net['shared']
5405 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5406 net_list.append(net_nfvo)
5407 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
5408 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
5409 return inserted
5410 elif 'net-edit' in action_dict:
5411 net = action_dict['net-edit'].pop('net')
5412 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
5413 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
5414 WHERE={'datacenter_id':datacenter_id, what: net})
5415 return result
5416 elif 'net-delete' in action_dict:
5417 net = action_dict['net-deelte'].get('net')
5418 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
5419 result = mydb.delete_row(FROM='datacenter_nets',
5420 WHERE={'datacenter_id':datacenter_id, what: net})
5421 return result
5422
5423 else:
5424 raise NfvoException("Unknown action " + str(action_dict), httperrors.Bad_Request)
5425
5426
5427 def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
5428 #get datacenter info
5429 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5430
5431 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
5432 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
5433 WHERE={'datacenter_id':datacenter_id, what: netmap})
5434 return result
5435
5436
5437 def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
5438 #get datacenter info
5439 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5440 filter_dict={}
5441 if action_dict:
5442 action_dict = action_dict["netmap"]
5443 if 'vim_id' in action_dict:
5444 filter_dict["id"] = action_dict['vim_id']
5445 if 'vim_name' in action_dict:
5446 filter_dict["name"] = action_dict['vim_name']
5447 else:
5448 filter_dict["shared"] = True
5449
5450 try:
5451 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
5452 except vimconn.vimconnException as e:
5453 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
5454 raise NfvoException(str(e), httperrors.Internal_Server_Error)
5455 if len(vim_nets)>1 and action_dict:
5456 raise NfvoException("more than two networks found, specify with vim_id", httperrors.Conflict)
5457 elif len(vim_nets)==0: # and action_dict:
5458 raise NfvoException("Not found a network at VIM with " + str(filter_dict), httperrors.Not_Found)
5459 net_list=[]
5460 for net in vim_nets:
5461 net_nfvo={'datacenter_id': datacenter_id}
5462 if action_dict and "name" in action_dict:
5463 net_nfvo['name'] = action_dict['name']
5464 else:
5465 net_nfvo['name'] = net['name']
5466 #net_nfvo['description']= net['name']
5467 net_nfvo['vim_net_id'] = net['id']
5468 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5469 net_nfvo['shared'] = net['shared']
5470 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
5471 try:
5472 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
5473 net_nfvo["status"] = "OK"
5474 net_nfvo["uuid"] = net_id
5475 except db_base_Exception as e:
5476 if action_dict:
5477 raise
5478 else:
5479 net_nfvo["status"] = "FAIL: " + str(e)
5480 net_list.append(net_nfvo)
5481 return net_list
5482
5483 def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
5484 # obtain all network data
5485 try:
5486 if utils.check_valid_uuid(network_id):
5487 filter_dict = {"id": network_id}
5488 else:
5489 filter_dict = {"name": network_id}
5490
5491 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5492 network = myvim.get_network_list(filter_dict=filter_dict)
5493 except vimconn.vimconnException as e:
5494 raise NfvoException("Not possible to get_sdn_net_id from VIM: {}".format(str(e)), e.http_code)
5495
5496 # ensure the network is defined
5497 if len(network) == 0:
5498 raise NfvoException("Network {} is not present in the system".format(network_id),
5499 httperrors.Bad_Request)
5500
5501 # ensure there is only one network with the provided name
5502 if len(network) > 1:
5503 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), httperrors.Bad_Request)
5504
5505 # ensure it is a dataplane network
5506 if network[0]['type'] != 'data':
5507 return None
5508
5509 # ensure we use the id
5510 network_id = network[0]['id']
5511
5512 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5513 # and with instance_scenario_id==NULL
5514 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5515 search_dict = {'vim_net_id': network_id}
5516
5517 try:
5518 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5519 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
5520 except db_base_Exception as e:
5521 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
5522 network_id) + str(e), e.http_code)
5523
5524 sdn_net_counter = 0
5525 for net in result:
5526 if net['sdn_net_id'] != None:
5527 sdn_net_counter+=1
5528 sdn_net_id = net['sdn_net_id']
5529
5530 if sdn_net_counter == 0:
5531 return None
5532 elif sdn_net_counter == 1:
5533 return sdn_net_id
5534 else:
5535 raise NfvoException("More than one SDN network is associated to vim network {}".format(
5536 network_id), httperrors.Internal_Server_Error)
5537
5538 def get_sdn_controller_id(mydb, datacenter):
5539 # Obtain sdn controller id
5540 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
5541 if not config:
5542 return None
5543
5544 return yaml.load(config, Loader=yaml.Loader).get('sdn-controller')
5545
5546 def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
5547 try:
5548 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5549 if not sdn_network_id:
5550 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), httperrors.Internal_Server_Error)
5551
5552 #Obtain sdn controller id
5553 controller_id = get_sdn_controller_id(mydb, datacenter)
5554 if not controller_id:
5555 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), httperrors.Internal_Server_Error)
5556
5557 #Obtain sdn controller info
5558 sdn_controller = ovim.show_of_controller(controller_id)
5559
5560 port_data = {
5561 'name': 'external_port',
5562 'net_id': sdn_network_id,
5563 'ofc_id': controller_id,
5564 'switch_dpid': sdn_controller['dpid'],
5565 'switch_port': descriptor['port']
5566 }
5567
5568 if 'vlan' in descriptor:
5569 port_data['vlan'] = descriptor['vlan']
5570 if 'mac' in descriptor:
5571 port_data['mac'] = descriptor['mac']
5572
5573 result = ovim.new_port(port_data)
5574 except ovimException as e:
5575 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
5576 sdn_network_id, network_id) + str(e), httperrors.Internal_Server_Error)
5577 except db_base_Exception as e:
5578 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
5579 network_id) + str(e), e.http_code)
5580
5581 return 'Port uuid: '+ result
5582
5583 def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
5584 if port_id:
5585 filter = {'uuid': port_id}
5586 else:
5587 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
5588 if not sdn_network_id:
5589 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
5590 httperrors.Internal_Server_Error)
5591 #in case no port_id is specified only ports marked as 'external_port' will be detached
5592 filter = {'name': 'external_port', 'net_id': sdn_network_id}
5593
5594 try:
5595 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
5596 except ovimException as e:
5597 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
5598 httperrors.Internal_Server_Error)
5599
5600 if len(port_list) == 0:
5601 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
5602 httperrors.Bad_Request)
5603
5604 port_uuid_list = []
5605 for port in port_list:
5606 try:
5607 port_uuid_list.append(port['uuid'])
5608 ovim.delete_port(port['uuid'])
5609 except ovimException as e:
5610 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), httperrors.Internal_Server_Error)
5611
5612 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
5613
5614 def vim_action_get(mydb, tenant_id, datacenter, item, name):
5615 #get datacenter info
5616 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5617 filter_dict={}
5618 if name:
5619 if utils.check_valid_uuid(name):
5620 filter_dict["id"] = name
5621 else:
5622 filter_dict["name"] = name
5623 try:
5624 if item=="networks":
5625 #filter_dict['tenant_id'] = myvim['tenant_id']
5626 content = myvim.get_network_list(filter_dict=filter_dict)
5627
5628 if len(content) == 0:
5629 raise NfvoException("Network {} is not present in the system. ".format(name),
5630 httperrors.Bad_Request)
5631
5632 #Update the networks with the attached ports
5633 for net in content:
5634 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
5635 if sdn_network_id != None:
5636 try:
5637 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5638 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
5639 except ovimException as e:
5640 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), httperrors.Internal_Server_Error)
5641 #Remove field name and if port name is external_port save it as 'type'
5642 for port in port_list:
5643 if port['name'] == 'external_port':
5644 port['type'] = "External"
5645 del port['name']
5646 net['sdn_network_id'] = sdn_network_id
5647 net['sdn_attached_ports'] = port_list
5648
5649 elif item=="tenants":
5650 content = myvim.get_tenant_list(filter_dict=filter_dict)
5651 elif item == "images":
5652
5653 content = myvim.get_image_list(filter_dict=filter_dict)
5654 else:
5655 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
5656 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
5657 if name and len(content)==1:
5658 return {item[:-1]: content[0]}
5659 elif name and len(content)==0:
5660 raise NfvoException("No {} found with ".format(item[:-1]) + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), filter_dict.items())),
5661 datacenter)
5662 else:
5663 return {item: content}
5664 except vimconn.vimconnException as e:
5665 print("vim_action Not possible to get_{}_list from VIM: {} ".format(item, str(e)))
5666 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
5667
5668
5669 def vim_action_delete(mydb, tenant_id, datacenter, item, name):
5670 #get datacenter info
5671 if tenant_id == "any":
5672 tenant_id=None
5673
5674 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5675 #get uuid name
5676 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
5677 logger.debug("vim_action_delete vim response: " + str(content))
5678 items = next(iter(content.values()))
5679 if type(items)==list and len(items)==0:
5680 raise NfvoException("Not found " + item, httperrors.Not_Found)
5681 elif type(items)==list and len(items)>1:
5682 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), httperrors.Not_Found)
5683 else: # it is a dict
5684 item_id = items["id"]
5685 item_name = str(items.get("name"))
5686
5687 try:
5688 if item=="networks":
5689 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5690 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
5691 if sdn_network_id != None:
5692 #Delete any port attachment to this network
5693 try:
5694 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
5695 except ovimException as e:
5696 raise NfvoException(
5697 "ovimException obtaining external ports for net {}. ".format(sdn_network_id) + str(e),
5698 httperrors.Internal_Server_Error)
5699
5700 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5701 for port in port_list:
5702 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
5703
5704 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5705 try:
5706 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None,
5707 'sdn_net_id': sdn_network_id,
5708 'vim_net_id': item_id})
5709 except db_base_Exception as e:
5710 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: {}".format(
5711 item_id, e), e.http_code)
5712
5713 #Delete the SDN network
5714 try:
5715 ovim.delete_network(sdn_network_id)
5716 except ovimException as e:
5717 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
5718 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
5719 httperrors.Internal_Server_Error)
5720
5721 content = myvim.delete_network(item_id)
5722 elif item=="tenants":
5723 content = myvim.delete_tenant(item_id)
5724 elif item == "images":
5725 content = myvim.delete_image(item_id)
5726 else:
5727 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
5728 except vimconn.vimconnException as e:
5729 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5730 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
5731
5732 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
5733
5734
5735 def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
5736 #get datacenter info
5737 logger.debug("vim_action_create descriptor %s", str(descriptor))
5738 if tenant_id == "any":
5739 tenant_id=None
5740 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
5741 try:
5742 if item=="networks":
5743 net = descriptor["network"]
5744 net_name = net.pop("name")
5745 net_type = net.pop("type", "bridge")
5746 net_public = net.pop("shared", False)
5747 net_ipprofile = net.pop("ip_profile", None)
5748 net_vlan = net.pop("vlan", None)
5749 net_provider_network_profile = None
5750 if net_vlan:
5751 net_provider_network_profile = {"segmentation-id": net_vlan}
5752 content, _ = myvim.new_network(net_name, net_type, net_ipprofile, shared=net_public, provider_network_profile=net_provider_network_profile) #, **net)
5753
5754 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5755 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
5756 #obtain datacenter_tenant_id
5757 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
5758 FROM='datacenter_tenants',
5759 WHERE={'datacenter_id': datacenter})[0]['uuid']
5760 try:
5761 sdn_network = {}
5762 sdn_network['vlan'] = net_vlan
5763 sdn_network['type'] = net_type
5764 sdn_network['name'] = net_name
5765 sdn_network['region'] = datacenter_tenant_id
5766 ovim_content = ovim.new_network(sdn_network)
5767 except ovimException as e:
5768 logger.error("ovimException creating SDN network={} ".format(
5769 sdn_network) + str(e), exc_info=True)
5770 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
5771 httperrors.Internal_Server_Error)
5772
5773 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5774 # use instance_scenario_id=None to distinguish from real instaces of nets
5775 correspondence = {'instance_scenario_id': None,
5776 'sdn_net_id': ovim_content,
5777 'vim_net_id': content,
5778 'datacenter_tenant_id': datacenter_tenant_id
5779 }
5780 try:
5781 mydb.new_row('instance_nets', correspondence, add_uuid=True)
5782 except db_base_Exception as e:
5783 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
5784 correspondence, e), e.http_code)
5785 elif item=="tenants":
5786 tenant = descriptor["tenant"]
5787 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
5788 else:
5789 raise NfvoException(item + "?", httperrors.Method_Not_Allowed)
5790 except vimconn.vimconnException as e:
5791 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
5792
5793 return vim_action_get(mydb, tenant_id, datacenter, item, content)
5794
5795 def sdn_controller_create(mydb, tenant_id, sdn_controller):
5796 try:
5797 wim_id = ovim.new_of_controller(sdn_controller)
5798
5799 # Load plugin if not previously loaded
5800 controller_type = sdn_controller.get("type")
5801 plugin_name = "rosdn_" + controller_type
5802 if plugin_name not in plugins:
5803 _load_plugin(plugin_name, type="sdn")
5804
5805 thread_name = get_non_used_vim_name(sdn_controller['name'], wim_id)
5806 new_thread = vim_thread(task_lock, plugins, thread_name, wim_id, None, db=db)
5807 new_thread.start()
5808 thread_id = wim_id
5809 vim_threads["running"][thread_id] = new_thread
5810 logger.debug('New SDN controller created with uuid {}'.format(wim_id))
5811 return wim_id
5812 except ovimException as e:
5813 raise NfvoException(e) from e
5814
5815 def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
5816 data = ovim.edit_of_controller(controller_id, sdn_controller)
5817 msg = 'SDN controller {} updated'.format(data)
5818 vim_threads["running"][controller_id].insert_task("reload")
5819 logger.debug(msg)
5820 return msg
5821
5822 def sdn_controller_list(mydb, tenant_id, controller_id=None):
5823 if controller_id == None:
5824 data = ovim.get_of_controllers()
5825 else:
5826 data = ovim.show_of_controller(controller_id)
5827
5828 msg = 'SDN controller list:\n {}'.format(data)
5829 logger.debug(msg)
5830 return data
5831
5832 def sdn_controller_delete(mydb, tenant_id, controller_id):
5833 select_ = ('uuid', 'config')
5834 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5835 for datacenter in datacenters:
5836 if datacenter['config']:
5837 config = yaml.load(datacenter['config'], Loader=yaml.Loader)
5838 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
5839 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), httperrors.Conflict)
5840
5841 data = ovim.delete_of_controller(controller_id)
5842 msg = 'SDN controller {} deleted'.format(data)
5843 logger.debug(msg)
5844 return msg
5845
5846 def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5847 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5848 if len(controller) < 1:
5849 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), httperrors.Not_Found)
5850
5851 try:
5852 sdn_controller_id = yaml.load(controller[0]["config"], Loader=yaml.Loader)["sdn-controller"]
5853 except:
5854 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), httperrors.Bad_Request)
5855
5856 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5857 switch_dpid = sdn_controller["dpid"]
5858
5859 maps = list()
5860 for compute_node in sdn_port_mapping:
5861 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5862 element = dict()
5863 element["compute_node"] = compute_node["compute_node"]
5864 if compute_node["ports"]:
5865 for port in compute_node["ports"]:
5866 pci = port.get("pci")
5867 element["switch_port"] = port.get("switch_port")
5868 element["switch_mac"] = port.get("switch_mac")
5869 element["switch_dpid"] = port.get("switch_dpid")
5870 element["switch_id"] = port.get("switch_id")
5871 if not element["switch_port"] and not element["switch_mac"]:
5872 raise NfvoException ("The mapping must contain 'switch_port' or 'switch_mac'", httperrors.Bad_Request)
5873 for pci_expanded in utils.expand_brackets(pci):
5874 element["pci"] = pci_expanded
5875 maps.append(dict(element))
5876
5877 out = ovim.set_of_port_mapping(maps, sdn_id=sdn_controller_id, switch_dpid=switch_dpid, vim_id=datacenter_id)
5878 vim_threads["running"][sdn_controller_id].insert_task("reload")
5879 return out
5880
5881 def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
5882 maps = ovim.get_of_port_mappings(db_filter={"datacenter_id": datacenter_id})
5883
5884 result = {
5885 "sdn-controller": None,
5886 "datacenter-id": datacenter_id,
5887 "dpid": None,
5888 "ports_mapping": list()
5889 }
5890
5891 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5892 if datacenter['config']:
5893 config = yaml.load(datacenter['config'], Loader=yaml.Loader)
5894 if 'sdn-controller' in config:
5895 controller_id = config['sdn-controller']
5896 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5897 result["sdn-controller"] = controller_id
5898 result["dpid"] = sdn_controller["dpid"]
5899
5900 if result["sdn-controller"] == None:
5901 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), httperrors.Bad_Request)
5902 if result["dpid"] == None:
5903 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
5904 httperrors.Internal_Server_Error)
5905
5906 if len(maps) == 0:
5907 return result
5908
5909 ports_correspondence_dict = dict()
5910 for link in maps:
5911 if result["sdn-controller"] != link["wim_id"]:
5912 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors.Internal_Server_Error)
5913 if result["dpid"] != link["switch_dpid"]:
5914 raise NfvoException("The dpid specified for different port mappings differ", httperrors.Internal_Server_Error)
5915 link_config = link["service_mapping_info"]
5916 element = dict()
5917 element["pci"] = link.get("device_interface_id")
5918 if link["switch_port"]:
5919 element["switch_port"] = link["switch_port"]
5920 if link_config["switch_mac"]:
5921 element["switch_mac"] = link_config.get("switch_mac")
5922
5923 if not link.get("interface_id") in ports_correspondence_dict:
5924 content = dict()
5925 content["compute_node"] = link.get("interface_id")
5926 content["ports"] = list()
5927 ports_correspondence_dict[link.get("interface_id")] = content
5928
5929 ports_correspondence_dict[link["interface_id"]]["ports"].append(element)
5930
5931 for key in sorted(ports_correspondence_dict):
5932 result["ports_mapping"].append(ports_correspondence_dict[key])
5933
5934 return result
5935
5936 def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
5937 return ovim.clear_of_port_mapping(db_filter={"datacenter_id":datacenter_id})
5938
5939 def create_RO_keypair(tenant_id):
5940 """
5941 Creates a public / private keys for a RO tenant and returns their values
5942 Params:
5943 tenant_id: ID of the tenant
5944 Return:
5945 public_key: Public key for the RO tenant
5946 private_key: Encrypted private key for RO tenant
5947 """
5948
5949 bits = 2048
5950 key = RSA.generate(bits)
5951 try:
5952 public_key = key.publickey().exportKey('OpenSSH')
5953 if isinstance(public_key, ValueError):
5954 raise NfvoException("Unable to create public key: {}".format(public_key), httperrors.Internal_Server_Error)
5955 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5956 except (ValueError, NameError) as e:
5957 raise NfvoException("Unable to create private key: {}".format(e), httperrors.Internal_Server_Error)
5958 if isinstance(public_key, bytes):
5959 public_key = public_key.decode(encoding='UTF-8')
5960 if isinstance(private_key, bytes):
5961 private_key = private_key.decode(encoding='UTF-8')
5962 return public_key, private_key
5963
5964 def decrypt_key (key, tenant_id):
5965 """
5966 Decrypts an encrypted RSA key
5967 Params:
5968 key: Private key to be decrypted
5969 tenant_id: ID of the tenant
5970 Return:
5971 unencrypted_key: Unencrypted private key for RO tenant
5972 """
5973 try:
5974 key = RSA.importKey(key,tenant_id)
5975 unencrypted_key = key.exportKey('PEM')
5976 if isinstance(unencrypted_key, ValueError):
5977 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), httperrors.Internal_Server_Error)
5978 if isinstance(unencrypted_key, bytes):
5979 unencrypted_key = unencrypted_key.decode(encoding='UTF-8')
5980 except ValueError as e:
5981 raise NfvoException("Unable to decrypt the private key: {}".format(e), httperrors.Internal_Server_Error)
5982 return unencrypted_key