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