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