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