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