19af225652aeb4571ab2d4b56f95f6fa192bd81f
[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_internal': vim.get('type')}
337 if vim["config"]:
338 extra.update(yaml.load(vim["config"]))
339 if vim.get('dt_config'):
340 extra.update(yaml.load(vim["dt_config"]))
341 if vim["type"] not in vimconn_imported:
342 module_info=None
343 try:
344 module = "vimconn_" + vim["type"]
345 pkg = __import__("osm_ro." + module)
346 vim_conn = getattr(pkg, module)
347 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
348 # vim_conn = imp.load_module(vim["type"], *module_info)
349 vimconn_imported[vim["type"]] = vim_conn
350 except (IOError, ImportError) as e:
351 # if module_info and module_info[0]:
352 # file.close(module_info[0])
353 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": get_str(vnf, "member-vnf-index", 255),
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 elif vld.get("vim-network-name"):
2307 db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
2308
2309 # table sce_interfaces (vld:vnfd-connection-point-ref)
2310 for iface in vld.get("vnfd-connection-point-ref").itervalues():
2311 vnf_index = str(iface['member-vnf-index-ref'])
2312 # check correct parameters
2313 if vnf_index not in vnf_index2vnf_uuid:
2314 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2315 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2316 "'nsd':'constituent-vnfd'".format(
2317 str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
2318 HTTP_Bad_Request)
2319
2320 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
2321 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2322 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2323 'external_name': get_str(iface, "vnfd-connection-point-ref",
2324 255)})
2325 if not existing_ifaces:
2326 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2327 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2328 "connection-point name at VNFD '{}'".format(
2329 str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
2330 str(iface.get("vnfd-id-ref"))[:255]),
2331 HTTP_Bad_Request)
2332 interface_uuid = existing_ifaces[0]["uuid"]
2333 if existing_ifaces[0]["iface_type"] == "data" and not db_sce_net["type"]:
2334 db_sce_net["type"] = "data"
2335 sce_interface_uuid = str(uuid4())
2336 uuid_list.append(sce_net_uuid)
2337 iface_ip_address = None
2338 if iface.get("ip-address"):
2339 iface_ip_address = str(iface.get("ip-address"))
2340 db_sce_interface = {
2341 "uuid": sce_interface_uuid,
2342 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2343 "sce_net_id": sce_net_uuid,
2344 "interface_id": interface_uuid,
2345 "ip_address": iface_ip_address,
2346 }
2347 db_sce_interfaces.append(db_sce_interface)
2348 if not db_sce_net["type"]:
2349 db_sce_net["type"] = "bridge"
2350
2351 # table sce_vnffgs (vnffgd)
2352 for vnffg in nsd.get("vnffgd").itervalues():
2353 sce_vnffg_uuid = str(uuid4())
2354 uuid_list.append(sce_vnffg_uuid)
2355 db_sce_vnffg = {
2356 "uuid": sce_vnffg_uuid,
2357 "name": get_str(vnffg, "name", 255),
2358 "scenario_id": scenario_uuid,
2359 "vendor": get_str(vnffg, "vendor", 255),
2360 "description": get_str(vld, "description", 255),
2361 }
2362 db_sce_vnffgs.append(db_sce_vnffg)
2363
2364 # deal with rsps
2365 db_sce_rsps = []
2366 for rsp in vnffg.get("rsp").itervalues():
2367 sce_rsp_uuid = str(uuid4())
2368 uuid_list.append(sce_rsp_uuid)
2369 db_sce_rsp = {
2370 "uuid": sce_rsp_uuid,
2371 "name": get_str(rsp, "name", 255),
2372 "sce_vnffg_id": sce_vnffg_uuid,
2373 "id": get_str(rsp, "id", 255), # only useful to link with classifiers; will be removed later in the code
2374 }
2375 db_sce_rsps.append(db_sce_rsp)
2376 db_sce_rsp_hops = []
2377 for iface in rsp.get("vnfd-connection-point-ref").itervalues():
2378 vnf_index = str(iface['member-vnf-index-ref'])
2379 if_order = int(iface['order'])
2380 # check correct parameters
2381 if vnf_index not in vnf_index2vnf_uuid:
2382 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2383 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2384 "'nsd':'constituent-vnfd'".format(
2385 str(nsd["id"]), str(rsp["id"]), str(iface["member-vnf-index-ref"])),
2386 HTTP_Bad_Request)
2387
2388 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2389 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2390 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2391 'external_name': get_str(iface, "vnfd-connection-point-ref",
2392 255)})
2393 if not existing_ifaces:
2394 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2395 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2396 "connection-point name at VNFD '{}'".format(
2397 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2398 str(iface.get("vnfd-id-ref"))[:255]),
2399 HTTP_Bad_Request)
2400 interface_uuid = existing_ifaces[0]["uuid"]
2401 sce_rsp_hop_uuid = str(uuid4())
2402 uuid_list.append(sce_rsp_hop_uuid)
2403 db_sce_rsp_hop = {
2404 "uuid": sce_rsp_hop_uuid,
2405 "if_order": if_order,
2406 "interface_id": interface_uuid,
2407 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2408 "sce_rsp_id": sce_rsp_uuid,
2409 }
2410 db_sce_rsp_hops.append(db_sce_rsp_hop)
2411
2412 # deal with classifiers
2413 db_sce_classifiers = []
2414 for classifier in vnffg.get("classifier").itervalues():
2415 sce_classifier_uuid = str(uuid4())
2416 uuid_list.append(sce_classifier_uuid)
2417
2418 # source VNF
2419 vnf_index = str(classifier['member-vnf-index-ref'])
2420 if vnf_index not in vnf_index2vnf_uuid:
2421 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2422 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2423 "'nsd':'constituent-vnfd'".format(
2424 str(nsd["id"]), str(classifier["id"]), str(classifier["member-vnf-index-ref"])),
2425 HTTP_Bad_Request)
2426 existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid',),
2427 FROM="interfaces as i join vms on i.vm_id=vms.uuid",
2428 WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
2429 'external_name': get_str(classifier, "vnfd-connection-point-ref",
2430 255)})
2431 if not existing_ifaces:
2432 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2433 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2434 "connection-point name at VNFD '{}'".format(
2435 str(nsd["id"]), str(rsp["id"]), str(iface["vnfd-connection-point-ref"]),
2436 str(iface.get("vnfd-id-ref"))[:255]),
2437 HTTP_Bad_Request)
2438 interface_uuid = existing_ifaces[0]["uuid"]
2439
2440 db_sce_classifier = {
2441 "uuid": sce_classifier_uuid,
2442 "name": get_str(classifier, "name", 255),
2443 "sce_vnffg_id": sce_vnffg_uuid,
2444 "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
2445 "interface_id": interface_uuid,
2446 }
2447 rsp_id = get_str(classifier, "rsp-id-ref", 255)
2448 rsp = next((item for item in db_sce_rsps if item["id"] == rsp_id), None)
2449 db_sce_classifier["sce_rsp_id"] = rsp["uuid"]
2450 db_sce_classifiers.append(db_sce_classifier)
2451
2452 db_sce_classifier_matches = []
2453 for match in classifier.get("match-attributes").itervalues():
2454 sce_classifier_match_uuid = str(uuid4())
2455 uuid_list.append(sce_classifier_match_uuid)
2456 db_sce_classifier_match = {
2457 "uuid": sce_classifier_match_uuid,
2458 "ip_proto": get_str(match, "ip-proto", 2),
2459 "source_ip": get_str(match, "source-ip-address", 16),
2460 "destination_ip": get_str(match, "destination-ip-address", 16),
2461 "source_port": get_str(match, "source-port", 5),
2462 "destination_port": get_str(match, "destination-port", 5),
2463 "sce_classifier_id": sce_classifier_uuid,
2464 }
2465 db_sce_classifier_matches.append(db_sce_classifier_match)
2466 # TODO: vnf/cp keys
2467
2468 # remove unneeded id's in sce_rsps
2469 for rsp in db_sce_rsps:
2470 rsp.pop('id')
2471
2472 db_tables = [
2473 {"scenarios": db_scenarios},
2474 {"sce_nets": db_sce_nets},
2475 {"ip_profiles": db_ip_profiles},
2476 {"sce_vnfs": db_sce_vnfs},
2477 {"sce_interfaces": db_sce_interfaces},
2478 {"sce_vnffgs": db_sce_vnffgs},
2479 {"sce_rsps": db_sce_rsps},
2480 {"sce_rsp_hops": db_sce_rsp_hops},
2481 {"sce_classifiers": db_sce_classifiers},
2482 {"sce_classifier_matches": db_sce_classifier_matches},
2483 ]
2484
2485 logger.debug("new_nsd_v3 done: %s",
2486 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
2487 mydb.new_rows(db_tables, uuid_list)
2488 return nsd_uuid_list
2489 except NfvoException:
2490 raise
2491 except Exception as e:
2492 logger.error("Exception {}".format(e))
2493 raise # NfvoException("Exception {}".format(e), HTTP_Bad_Request)
2494
2495
2496 def edit_scenario(mydb, tenant_id, scenario_id, data):
2497 data["uuid"] = scenario_id
2498 data["tenant_id"] = tenant_id
2499 c = mydb.edit_scenario( data )
2500 return c
2501
2502
2503 def start_scenario(mydb, tenant_id, scenario_id, instance_scenario_name, instance_scenario_description, datacenter=None,vim_tenant=None, startvms=True):
2504 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2505 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter, vim_tenant=vim_tenant)
2506 vims = {datacenter_id: myvim}
2507 myvim_tenant = myvim['tenant_id']
2508 datacenter_name = myvim['name']
2509
2510 rollbackList=[]
2511 try:
2512 #print "Checking that the scenario_id exists and getting the scenario dictionary"
2513 scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id)
2514 scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] }
2515 scenarioDict['datacenter_id'] = datacenter_id
2516 #print '================scenarioDict======================='
2517 #print json.dumps(scenarioDict, indent=4)
2518 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
2519
2520 logger.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict['name'],len(scenarioDict['vnfs']))
2521 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2522
2523 auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2524 auxNetDict['scenario'] = {}
2525
2526 logger.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2527 for sce_net in scenarioDict['nets']:
2528 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
2529
2530 myNetName = "%s.%s" % (instance_scenario_name, sce_net['name'])
2531 myNetName = myNetName[0:255] #limit length
2532 myNetType = sce_net['type']
2533 myNetDict = {}
2534 myNetDict["name"] = myNetName
2535 myNetDict["type"] = myNetType
2536 myNetDict["tenant_id"] = myvim_tenant
2537 myNetIPProfile = sce_net.get('ip_profile', None)
2538 #TODO:
2539 #We should use the dictionary as input parameter for new_network
2540 #print myNetDict
2541 if not sce_net["external"]:
2542 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
2543 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2544 sce_net['vim_id'] = network_id
2545 auxNetDict['scenario'][sce_net['uuid']] = network_id
2546 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
2547 sce_net["created"] = True
2548 else:
2549 if sce_net['vim_id'] == None:
2550 error_text = "Error, datacenter '%s' does not have external network '%s'." % (datacenter_name, sce_net['name'])
2551 _, message = rollback(mydb, vims, rollbackList)
2552 logger.error("nfvo.start_scenario: %s", error_text)
2553 raise NfvoException(error_text, HTTP_Bad_Request)
2554 logger.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict['name'],sce_net['vim_id'])
2555 auxNetDict['scenario'][sce_net['uuid']] = sce_net['vim_id']
2556
2557 logger.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2558 #For each vnf net, we create it and we add it to instanceNetlist.
2559
2560 for sce_vnf in scenarioDict['vnfs']:
2561 for net in sce_vnf['nets']:
2562 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
2563
2564 myNetName = "%s.%s" % (instance_scenario_name,net['name'])
2565 myNetName = myNetName[0:255] #limit length
2566 myNetType = net['type']
2567 myNetDict = {}
2568 myNetDict["name"] = myNetName
2569 myNetDict["type"] = myNetType
2570 myNetDict["tenant_id"] = myvim_tenant
2571 myNetIPProfile = net.get('ip_profile', None)
2572 #print myNetDict
2573 #TODO:
2574 #We should use the dictionary as input parameter for new_network
2575 network_id = myvim.new_network(myNetName, myNetType, myNetIPProfile)
2576 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2577 net['vim_id'] = network_id
2578 if sce_vnf['uuid'] not in auxNetDict:
2579 auxNetDict[sce_vnf['uuid']] = {}
2580 auxNetDict[sce_vnf['uuid']][net['uuid']] = network_id
2581 rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':network_id})
2582 net["created"] = True
2583
2584 #print "auxNetDict:"
2585 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
2586
2587 logger.debug("start_scenario 3. Creating new vm instances in the VIM")
2588 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2589 i = 0
2590 for sce_vnf in scenarioDict['vnfs']:
2591 vnf_availability_zones = []
2592 for vm in sce_vnf['vms']:
2593 vm_av = vm.get('availability_zone')
2594 if vm_av and vm_av not in vnf_availability_zones:
2595 vnf_availability_zones.append(vm_av)
2596
2597 # check if there is enough availability zones available at vim level.
2598 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
2599 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
2600 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
2601
2602 for vm in sce_vnf['vms']:
2603 i += 1
2604 myVMDict = {}
2605 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
2606 myVMDict['name'] = "{}.{}.{}".format(instance_scenario_name,sce_vnf['name'],chr(96+i))
2607 #myVMDict['description'] = vm['description']
2608 myVMDict['description'] = myVMDict['name'][0:99]
2609 if not startvms:
2610 myVMDict['start'] = "no"
2611 myVMDict['name'] = myVMDict['name'][0:255] #limit name length
2612 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
2613
2614 #create image at vim in case it not exist
2615 image_dict = mydb.get_table_by_uuid_name("images", vm['image_id'])
2616 image_id = create_or_use_image(mydb, vims, image_dict, [], True)
2617 vm['vim_image_id'] = image_id
2618
2619 #create flavor at vim in case it not exist
2620 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
2621 if flavor_dict['extended']!=None:
2622 flavor_dict['extended']= yaml.load(flavor_dict['extended'])
2623 flavor_id = create_or_use_flavor(mydb, vims, flavor_dict, [], True)
2624 vm['vim_flavor_id'] = flavor_id
2625
2626
2627 myVMDict['imageRef'] = vm['vim_image_id']
2628 myVMDict['flavorRef'] = vm['vim_flavor_id']
2629 myVMDict['networks'] = []
2630 for iface in vm['interfaces']:
2631 netDict = {}
2632 if iface['type']=="data":
2633 netDict['type'] = iface['model']
2634 elif "model" in iface and iface["model"]!=None:
2635 netDict['model']=iface['model']
2636 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2637 #discover type of interface looking at flavor
2638 for numa in flavor_dict.get('extended',{}).get('numas',[]):
2639 for flavor_iface in numa.get('interfaces',[]):
2640 if flavor_iface.get('name') == iface['internal_name']:
2641 if flavor_iface['dedicated'] == 'yes':
2642 netDict['type']="PF" #passthrough
2643 elif flavor_iface['dedicated'] == 'no':
2644 netDict['type']="VF" #siov
2645 elif flavor_iface['dedicated'] == 'yes:sriov':
2646 netDict['type']="VFnotShared" #sriov but only one sriov on the PF
2647 netDict["mac_address"] = flavor_iface.get("mac_address")
2648 break;
2649 netDict["use"]=iface['type']
2650 if netDict["use"]=="data" and not netDict.get("type"):
2651 #print "netDict", netDict
2652 #print "iface", iface
2653 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'])
2654 if flavor_dict.get('extended')==None:
2655 raise NfvoException(e_text + "After database migration some information is not available. \
2656 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
2657 else:
2658 raise NfvoException(e_text, HTTP_Internal_Server_Error)
2659 if netDict["use"]=="mgmt" or netDict["use"]=="bridge":
2660 netDict["type"]="virtual"
2661 if "vpci" in iface and iface["vpci"] is not None:
2662 netDict['vpci'] = iface['vpci']
2663 if "mac" in iface and iface["mac"] is not None:
2664 netDict['mac_address'] = iface['mac']
2665 if "port-security" in iface and iface["port-security"] is not None:
2666 netDict['port_security'] = iface['port-security']
2667 if "floating-ip" in iface and iface["floating-ip"] is not None:
2668 netDict['floating_ip'] = iface['floating-ip']
2669 netDict['name'] = iface['internal_name']
2670 if iface['net_id'] is None:
2671 for vnf_iface in sce_vnf["interfaces"]:
2672 #print iface
2673 #print vnf_iface
2674 if vnf_iface['interface_id']==iface['uuid']:
2675 netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ]
2676 break
2677 else:
2678 netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ]
2679 #skip bridge ifaces not connected to any net
2680 #if 'net_id' not in netDict or netDict['net_id']==None:
2681 # continue
2682 myVMDict['networks'].append(netDict)
2683 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2684 #print myVMDict['name']
2685 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2686 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2687 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2688
2689 if 'availability_zone' in myVMDict:
2690 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
2691 else:
2692 av_index = None
2693
2694 vm_id, _ = myvim.new_vminstance(myVMDict['name'], myVMDict['description'], myVMDict.get('start', None),
2695 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'],
2696 availability_zone_index=av_index,
2697 availability_zone_list=vnf_availability_zones)
2698 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2699 vm['vim_id'] = vm_id
2700 rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id})
2701 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2702 for net in myVMDict['networks']:
2703 if "vim_id" in net:
2704 for iface in vm['interfaces']:
2705 if net["name"]==iface["internal_name"]:
2706 iface["vim_id"]=net["vim_id"]
2707 break
2708
2709 logger.debug("start scenario Deployment done")
2710 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2711 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
2712 instance_id = mydb.new_instance_scenario_as_a_whole(tenant_id,instance_scenario_name, instance_scenario_description, scenarioDict)
2713 return mydb.get_instance_scenario(instance_id)
2714
2715 except (db_base_Exception, vimconn.vimconnException) as e:
2716 _, message = rollback(mydb, vims, rollbackList)
2717 if isinstance(e, db_base_Exception):
2718 error_text = "Exception at database"
2719 else:
2720 error_text = "Exception at VIM"
2721 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
2722 #logger.error("start_scenario %s", error_text)
2723 raise NfvoException(error_text, e.http_code)
2724
2725 def unify_cloud_config(cloud_config_preserve, cloud_config):
2726 """ join the cloud config information into cloud_config_preserve.
2727 In case of conflict cloud_config_preserve preserves
2728 None is allowed
2729 """
2730 if not cloud_config_preserve and not cloud_config:
2731 return None
2732
2733 new_cloud_config = {"key-pairs":[], "users":[]}
2734 # key-pairs
2735 if cloud_config_preserve:
2736 for key in cloud_config_preserve.get("key-pairs", () ):
2737 if key not in new_cloud_config["key-pairs"]:
2738 new_cloud_config["key-pairs"].append(key)
2739 if cloud_config:
2740 for key in cloud_config.get("key-pairs", () ):
2741 if key not in new_cloud_config["key-pairs"]:
2742 new_cloud_config["key-pairs"].append(key)
2743 if not new_cloud_config["key-pairs"]:
2744 del new_cloud_config["key-pairs"]
2745
2746 # users
2747 if cloud_config:
2748 new_cloud_config["users"] += cloud_config.get("users", () )
2749 if cloud_config_preserve:
2750 new_cloud_config["users"] += cloud_config_preserve.get("users", () )
2751 index_to_delete = []
2752 users = new_cloud_config.get("users", [])
2753 for index0 in range(0,len(users)):
2754 if index0 in index_to_delete:
2755 continue
2756 for index1 in range(index0+1,len(users)):
2757 if index1 in index_to_delete:
2758 continue
2759 if users[index0]["name"] == users[index1]["name"]:
2760 index_to_delete.append(index1)
2761 for key in users[index1].get("key-pairs",()):
2762 if "key-pairs" not in users[index0]:
2763 users[index0]["key-pairs"] = [key]
2764 elif key not in users[index0]["key-pairs"]:
2765 users[index0]["key-pairs"].append(key)
2766 index_to_delete.sort(reverse=True)
2767 for index in index_to_delete:
2768 del users[index]
2769 if not new_cloud_config["users"]:
2770 del new_cloud_config["users"]
2771
2772 #boot-data-drive
2773 if cloud_config and cloud_config.get("boot-data-drive") != None:
2774 new_cloud_config["boot-data-drive"] = cloud_config["boot-data-drive"]
2775 if cloud_config_preserve and cloud_config_preserve.get("boot-data-drive") != None:
2776 new_cloud_config["boot-data-drive"] = cloud_config_preserve["boot-data-drive"]
2777
2778 # user-data
2779 new_cloud_config["user-data"] = []
2780 if cloud_config and cloud_config.get("user-data"):
2781 if isinstance(cloud_config["user-data"], list):
2782 new_cloud_config["user-data"] += cloud_config["user-data"]
2783 else:
2784 new_cloud_config["user-data"].append(cloud_config["user-data"])
2785 if cloud_config_preserve and cloud_config_preserve.get("user-data"):
2786 if isinstance(cloud_config_preserve["user-data"], list):
2787 new_cloud_config["user-data"] += cloud_config_preserve["user-data"]
2788 else:
2789 new_cloud_config["user-data"].append(cloud_config_preserve["user-data"])
2790 if not new_cloud_config["user-data"]:
2791 del new_cloud_config["user-data"]
2792
2793 # config files
2794 new_cloud_config["config-files"] = []
2795 if cloud_config and cloud_config.get("config-files") != None:
2796 new_cloud_config["config-files"] += cloud_config["config-files"]
2797 if cloud_config_preserve:
2798 for file in cloud_config_preserve.get("config-files", ()):
2799 for index in range(0, len(new_cloud_config["config-files"])):
2800 if new_cloud_config["config-files"][index]["dest"] == file["dest"]:
2801 new_cloud_config["config-files"][index] = file
2802 break
2803 else:
2804 new_cloud_config["config-files"].append(file)
2805 if not new_cloud_config["config-files"]:
2806 del new_cloud_config["config-files"]
2807 return new_cloud_config
2808
2809
2810 def get_vim_thread(mydb, tenant_id, datacenter_id_name=None, datacenter_tenant_id=None):
2811 datacenter_id = None
2812 datacenter_name = None
2813 thread = None
2814 try:
2815 if datacenter_tenant_id:
2816 thread_id = datacenter_tenant_id
2817 thread = vim_threads["running"].get(datacenter_tenant_id)
2818 else:
2819 where_={"td.nfvo_tenant_id": tenant_id}
2820 if datacenter_id_name:
2821 if utils.check_valid_uuid(datacenter_id_name):
2822 datacenter_id = datacenter_id_name
2823 where_["dt.datacenter_id"] = datacenter_id
2824 else:
2825 datacenter_name = datacenter_id_name
2826 where_["d.name"] = datacenter_name
2827 if datacenter_tenant_id:
2828 where_["dt.uuid"] = datacenter_tenant_id
2829 datacenters = mydb.get_rows(
2830 SELECT=("dt.uuid as datacenter_tenant_id",),
2831 FROM="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2832 "join datacenters as d on d.uuid=dt.datacenter_id",
2833 WHERE=where_)
2834 if len(datacenters) > 1:
2835 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2836 elif datacenters:
2837 thread_id = datacenters[0]["datacenter_tenant_id"]
2838 thread = vim_threads["running"].get(thread_id)
2839 if not thread:
2840 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2841 return thread_id, thread
2842 except db_base_Exception as e:
2843 raise NfvoException("{} {}".format(type(e).__name__ , str(e)), e.http_code)
2844
2845
2846 def get_datacenter_uuid(mydb, tenant_id, datacenter_id_name):
2847 WHERE_dict={}
2848 if utils.check_valid_uuid(datacenter_id_name):
2849 WHERE_dict['d.uuid'] = datacenter_id_name
2850 else:
2851 WHERE_dict['d.name'] = datacenter_id_name
2852
2853 if tenant_id:
2854 WHERE_dict['nfvo_tenant_id'] = tenant_id
2855 from_= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
2856 " dt on td.datacenter_tenant_id=dt.uuid"
2857 else:
2858 from_ = 'datacenters as d'
2859 vimaccounts = mydb.get_rows(FROM=from_, SELECT=("d.uuid as uuid",), WHERE=WHERE_dict )
2860 if len(vimaccounts) == 0:
2861 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2862 elif len(vimaccounts)>1:
2863 #print "nfvo.datacenter_action() error. Several datacenters found"
2864 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2865 return vimaccounts[0]["uuid"]
2866
2867
2868 def get_datacenter_by_name_uuid(mydb, tenant_id, datacenter_id_name=None, **extra_filter):
2869 datacenter_id = None
2870 datacenter_name = None
2871 if datacenter_id_name:
2872 if utils.check_valid_uuid(datacenter_id_name):
2873 datacenter_id = datacenter_id_name
2874 else:
2875 datacenter_name = datacenter_id_name
2876 vims = get_vim(mydb, tenant_id, datacenter_id, datacenter_name, **extra_filter)
2877 if len(vims) == 0:
2878 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name)), HTTP_Not_Found)
2879 elif len(vims)>1:
2880 #print "nfvo.datacenter_action() error. Several datacenters found"
2881 raise NfvoException("More than one datacenters found, try to identify with uuid", HTTP_Conflict)
2882 return vims.keys()[0], vims.values()[0]
2883
2884
2885 def update(d, u):
2886 '''Takes dict d and updates it with the values in dict u.'''
2887 '''It merges all depth levels'''
2888 for k, v in u.iteritems():
2889 if isinstance(v, collections.Mapping):
2890 r = update(d.get(k, {}), v)
2891 d[k] = r
2892 else:
2893 d[k] = u[k]
2894 return d
2895
2896
2897 def create_instance(mydb, tenant_id, instance_dict):
2898 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2899 # logger.debug("Creating instance...")
2900 scenario = instance_dict["scenario"]
2901
2902 # find main datacenter
2903 myvims = {}
2904 myvim_threads_id = {}
2905 datacenter = instance_dict.get("datacenter")
2906 default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
2907 myvims[default_datacenter_id] = vim
2908 myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id)
2909 tenant = mydb.get_rows_by_id('nfvo_tenants', tenant_id)
2910 # myvim_tenant = myvim['tenant_id']
2911 rollbackList = []
2912
2913 # print "Checking that the scenario exists and getting the scenario dictionary"
2914 scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id],
2915 datacenter_id=default_datacenter_id)
2916
2917 # logger.debug(">>>>>> Dictionaries before merging")
2918 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
2919 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
2920
2921 db_instance_vnfs = []
2922 db_instance_vms = []
2923 db_instance_interfaces = []
2924 db_instance_sfis = []
2925 db_instance_sfs = []
2926 db_instance_classifications = []
2927 db_instance_sfps = []
2928 db_ip_profiles = []
2929 db_vim_actions = []
2930 uuid_list = []
2931 task_index = 0
2932 instance_name = instance_dict["name"]
2933 instance_uuid = str(uuid4())
2934 uuid_list.append(instance_uuid)
2935 db_instance_scenario = {
2936 "uuid": instance_uuid,
2937 "name": instance_name,
2938 "tenant_id": tenant_id,
2939 "scenario_id": scenarioDict['uuid'],
2940 "datacenter_id": default_datacenter_id,
2941 # filled bellow 'datacenter_tenant_id'
2942 "description": instance_dict.get("description"),
2943 }
2944 if scenarioDict.get("cloud-config"):
2945 db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"],
2946 default_flow_style=True, width=256)
2947 instance_action_id = get_task_id()
2948 db_instance_action = {
2949 "uuid": instance_action_id, # same uuid for the instance and the action on create
2950 "tenant_id": tenant_id,
2951 "instance_id": instance_uuid,
2952 "description": "CREATE",
2953 }
2954
2955 # Auxiliary dictionaries from x to y
2956 sce_net2instance = {}
2957 net2task_id = {'scenario': {}}
2958
2959 # logger.debug("Creating instance from scenario-dict:\n%s",
2960 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
2961 try:
2962 # 0 check correct parameters
2963 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
2964 found = False
2965 for scenario_net in scenarioDict['nets']:
2966 if net_name == scenario_net["name"]:
2967 found = True
2968 break
2969 if not found:
2970 raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name),
2971 HTTP_Bad_Request)
2972 if "sites" not in net_instance_desc:
2973 net_instance_desc["sites"] = [ {} ]
2974 site_without_datacenter_field = False
2975 for site in net_instance_desc["sites"]:
2976 if site.get("datacenter"):
2977 site["datacenter"] = get_datacenter_uuid(mydb, tenant_id, site["datacenter"])
2978 if site["datacenter"] not in myvims:
2979 # Add this datacenter to myvims
2980 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"])
2981 myvims[d] = v
2982 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"])
2983 site["datacenter"] = d # change name to id
2984 else:
2985 if site_without_datacenter_field:
2986 raise NfvoException("Found more than one entries without datacenter field at "
2987 "instance:networks:{}:sites".format(net_name), HTTP_Bad_Request)
2988 site_without_datacenter_field = True
2989 site["datacenter"] = default_datacenter_id # change name to id
2990
2991 for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems():
2992 found = False
2993 for scenario_vnf in scenarioDict['vnfs']:
2994 if vnf_name == scenario_vnf['name']:
2995 found = True
2996 break
2997 if not found:
2998 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request)
2999 if "datacenter" in vnf_instance_desc:
3000 # Add this datacenter to myvims
3001 vnf_instance_desc["datacenter"] = get_datacenter_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3002 if vnf_instance_desc["datacenter"] not in myvims:
3003 d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"])
3004 myvims[d] = v
3005 myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"])
3006 scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"]
3007
3008 # 0.1 parse cloud-config parameters
3009 cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config"))
3010
3011 # 0.2 merge instance information into scenario
3012 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3013 # However, this is not possible yet.
3014 for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems():
3015 for scenario_net in scenarioDict['nets']:
3016 if net_name == scenario_net["name"]:
3017 if 'ip-profile' in net_instance_desc:
3018 # translate from input format to database format
3019 ipprofile_in = net_instance_desc['ip-profile']
3020 ipprofile_db = {}
3021 ipprofile_db['subnet_address'] = ipprofile_in.get('subnet-address')
3022 ipprofile_db['ip_version'] = ipprofile_in.get('ip-version', 'IPv4')
3023 ipprofile_db['gateway_address'] = ipprofile_in.get('gateway-address')
3024 ipprofile_db['dns_address'] = ipprofile_in.get('dns-address')
3025 if isinstance(ipprofile_db['dns_address'], (list, tuple)):
3026 ipprofile_db['dns_address'] = ";".join(ipprofile_db['dns_address'])
3027 if 'dhcp' in ipprofile_in:
3028 ipprofile_db['dhcp_start_address'] = ipprofile_in['dhcp'].get('start-address')
3029 ipprofile_db['dhcp_enabled'] = ipprofile_in['dhcp'].get('enabled', True)
3030 ipprofile_db['dhcp_count'] = ipprofile_in['dhcp'].get('count' )
3031 if 'ip_profile' not in scenario_net:
3032 scenario_net['ip_profile'] = ipprofile_db
3033 else:
3034 update(scenario_net['ip_profile'], ipprofile_db)
3035 for interface in net_instance_desc.get('interfaces', ()):
3036 if 'ip_address' in interface:
3037 for vnf in scenarioDict['vnfs']:
3038 if interface['vnf'] == vnf['name']:
3039 for vnf_interface in vnf['interfaces']:
3040 if interface['vnf_interface'] == vnf_interface['external_name']:
3041 vnf_interface['ip_address'] = interface['ip_address']
3042
3043 # logger.debug(">>>>>>>> Merged dictionary")
3044 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3045 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
3046
3047 # 1. Creating new nets (sce_nets) in the VIM"
3048 number_mgmt_networks = 0
3049 db_instance_nets = []
3050 for sce_net in scenarioDict['nets']:
3051 descriptor_net = instance_dict.get("networks", {}).get(sce_net["name"], {})
3052 net_name = descriptor_net.get("vim-network-name")
3053 sce_net2instance[sce_net['uuid']] = {}
3054 net2task_id['scenario'][sce_net['uuid']] = {}
3055
3056 sites = descriptor_net.get("sites", [ {} ])
3057 for site in sites:
3058 if site.get("datacenter"):
3059 vim = myvims[ site["datacenter"] ]
3060 datacenter_id = site["datacenter"]
3061 myvim_thread_id = myvim_threads_id[ site["datacenter"] ]
3062 else:
3063 vim = myvims[ default_datacenter_id ]
3064 datacenter_id = default_datacenter_id
3065 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3066 net_type = sce_net['type']
3067 lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
3068
3069 if not net_name:
3070 if sce_net["external"]:
3071 net_name = sce_net["name"]
3072 else:
3073 net_name = "{}.{}".format(instance_name, sce_net["name"])
3074 net_name = net_name[:255] # limit length
3075
3076 if sce_net["external"]:
3077 number_mgmt_networks += 1
3078 if "netmap-use" in site or "netmap-create" in site:
3079 create_network = False
3080 lookfor_network = False
3081 if "netmap-use" in site:
3082 lookfor_network = True
3083 if utils.check_valid_uuid(site["netmap-use"]):
3084 lookfor_filter["id"] = site["netmap-use"]
3085 else:
3086 lookfor_filter["name"] = site["netmap-use"]
3087 if "netmap-create" in site:
3088 create_network = True
3089 net_vim_name = net_name
3090 if site["netmap-create"]:
3091 net_vim_name = site["netmap-create"]
3092 elif sce_net.get("vim_network_name"):
3093 create_network = False
3094 lookfor_network = True
3095 lookfor_filter["name"] = sce_net.get("vim_network_name")
3096 elif sce_net["external"]:
3097 if sce_net['vim_id'] != None:
3098 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
3099 create_network = False
3100 lookfor_network = True
3101 lookfor_filter["id"] = sce_net['vim_id']
3102 elif vim["config"].get("management_network_id") or vim["config"].get("management_network_name"):
3103 if number_mgmt_networks > 1:
3104 raise NfvoException("Found several VLD of type mgmt. "
3105 "You must concrete what vim-network must be use for each one",
3106 HTTP_Bad_Request)
3107 create_network = False
3108 lookfor_network = True
3109 if vim["config"].get("management_network_id"):
3110 lookfor_filter["id"] = vim["config"]["management_network_id"]
3111 else:
3112 lookfor_filter["name"] = vim["config"]["management_network_name"]
3113 else:
3114 # There is not a netmap, look at datacenter for a net with this name and create if not found
3115 create_network = True
3116 lookfor_network = True
3117 lookfor_filter["name"] = sce_net["name"]
3118 net_vim_name = sce_net["name"]
3119 else:
3120 net_vim_name = net_name
3121 create_network = True
3122 lookfor_network = False
3123
3124 task_extra = {}
3125 if create_network:
3126 task_action = "CREATE"
3127 task_extra["params"] = (net_vim_name, net_type, sce_net.get('ip_profile', None))
3128 if lookfor_network:
3129 task_extra["find"] = (lookfor_filter,)
3130 elif lookfor_network:
3131 task_action = "FIND"
3132 task_extra["params"] = (lookfor_filter,)
3133
3134 # fill database content
3135 net_uuid = str(uuid4())
3136 uuid_list.append(net_uuid)
3137 sce_net2instance[sce_net['uuid']][datacenter_id] = net_uuid
3138 db_net = {
3139 "uuid": net_uuid,
3140 'vim_net_id': None,
3141 "instance_scenario_id": instance_uuid,
3142 "sce_net_id": sce_net["uuid"],
3143 "created": create_network,
3144 'datacenter_id': datacenter_id,
3145 'datacenter_tenant_id': myvim_thread_id,
3146 'status': 'BUILD' if create_network else "ACTIVE"
3147 }
3148 db_instance_nets.append(db_net)
3149 db_vim_action = {
3150 "instance_action_id": instance_action_id,
3151 "status": "SCHEDULED",
3152 "task_index": task_index,
3153 "datacenter_vim_id": myvim_thread_id,
3154 "action": task_action,
3155 "item": "instance_nets",
3156 "item_id": net_uuid,
3157 "extra": yaml.safe_dump(task_extra, default_flow_style=True, width=256)
3158 }
3159 net2task_id['scenario'][sce_net['uuid']][datacenter_id] = task_index
3160 task_index += 1
3161 db_vim_actions.append(db_vim_action)
3162
3163 if 'ip_profile' in sce_net:
3164 db_ip_profile={
3165 'instance_net_id': net_uuid,
3166 'ip_version': sce_net['ip_profile']['ip_version'],
3167 'subnet_address': sce_net['ip_profile']['subnet_address'],
3168 'gateway_address': sce_net['ip_profile']['gateway_address'],
3169 'dns_address': sce_net['ip_profile']['dns_address'],
3170 'dhcp_enabled': sce_net['ip_profile']['dhcp_enabled'],
3171 'dhcp_start_address': sce_net['ip_profile']['dhcp_start_address'],
3172 'dhcp_count': sce_net['ip_profile']['dhcp_count'],
3173 }
3174 db_ip_profiles.append(db_ip_profile)
3175
3176 # Create VNFs
3177 vnf_params = {
3178 "default_datacenter_id": default_datacenter_id,
3179 "myvim_threads_id": myvim_threads_id,
3180 "instance_uuid": instance_uuid,
3181 "instance_name": instance_name,
3182 "instance_action_id": instance_action_id,
3183 "myvims": myvims,
3184 "cloud_config": cloud_config,
3185 "RO_pub_key": tenant[0].get('RO_pub_key'),
3186 }
3187 vnf_params_out = {
3188 "task_index": task_index,
3189 "uuid_list": uuid_list,
3190 "db_instance_nets": db_instance_nets,
3191 "db_vim_actions": db_vim_actions,
3192 "db_ip_profiles": db_ip_profiles,
3193 "db_instance_vnfs": db_instance_vnfs,
3194 "db_instance_vms": db_instance_vms,
3195 "db_instance_interfaces": db_instance_interfaces,
3196 "net2task_id": net2task_id,
3197 "sce_net2instance": sce_net2instance,
3198 }
3199 sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
3200 for sce_vnf in sce_vnf_list:
3201 instantiate_vnf(mydb, sce_vnf, vnf_params, vnf_params_out, rollbackList)
3202 task_index = vnf_params_out["task_index"]
3203 uuid_list = vnf_params_out["uuid_list"]
3204
3205 # Create VNFFGs
3206 # task_depends_on = []
3207 for vnffg in scenarioDict['vnffgs']:
3208 for rsp in vnffg['rsps']:
3209 sfs_created = []
3210 for cp in rsp['connection_points']:
3211 count = mydb.get_rows(
3212 SELECT=('vms.count'),
3213 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h on interfaces.uuid=h.interface_id",
3214 WHERE={'h.uuid': cp['uuid']})[0]['count']
3215 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == cp['sce_vnf_id']), None)
3216 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3217 dependencies = []
3218 for instance_vm in instance_vms:
3219 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3220 if action:
3221 dependencies.append(action['task_index'])
3222 # TODO: throw exception if count != len(instance_vms)
3223 # TODO: and action shouldn't ever be None
3224 sfis_created = []
3225 for i in range(count):
3226 # create sfis
3227 sfi_uuid = str(uuid4())
3228 uuid_list.append(sfi_uuid)
3229 db_sfi = {
3230 "uuid": sfi_uuid,
3231 "instance_scenario_id": instance_uuid,
3232 'sce_rsp_hop_id': cp['uuid'],
3233 'datacenter_id': datacenter_id,
3234 'datacenter_tenant_id': myvim_thread_id,
3235 "vim_sfi_id": None, # vim thread will populate
3236 }
3237 db_instance_sfis.append(db_sfi)
3238 db_vim_action = {
3239 "instance_action_id": instance_action_id,
3240 "task_index": task_index,
3241 "datacenter_vim_id": myvim_thread_id,
3242 "action": "CREATE",
3243 "status": "SCHEDULED",
3244 "item": "instance_sfis",
3245 "item_id": sfi_uuid,
3246 "extra": yaml.safe_dump({"params": "", "depends_on": [dependencies[i]]},
3247 default_flow_style=True, width=256)
3248 }
3249 sfis_created.append(task_index)
3250 task_index += 1
3251 db_vim_actions.append(db_vim_action)
3252 # create sfs
3253 sf_uuid = str(uuid4())
3254 uuid_list.append(sf_uuid)
3255 db_sf = {
3256 "uuid": sf_uuid,
3257 "instance_scenario_id": instance_uuid,
3258 'sce_rsp_hop_id': cp['uuid'],
3259 'datacenter_id': datacenter_id,
3260 'datacenter_tenant_id': myvim_thread_id,
3261 "vim_sf_id": None, # vim thread will populate
3262 }
3263 db_instance_sfs.append(db_sf)
3264 db_vim_action = {
3265 "instance_action_id": instance_action_id,
3266 "task_index": task_index,
3267 "datacenter_vim_id": myvim_thread_id,
3268 "action": "CREATE",
3269 "status": "SCHEDULED",
3270 "item": "instance_sfs",
3271 "item_id": sf_uuid,
3272 "extra": yaml.safe_dump({"params": "", "depends_on": sfis_created},
3273 default_flow_style=True, width=256)
3274 }
3275 sfs_created.append(task_index)
3276 task_index += 1
3277 db_vim_actions.append(db_vim_action)
3278 classifier = rsp['classifier']
3279
3280 # TODO the following ~13 lines can be reused for the sfi case
3281 count = mydb.get_rows(
3282 SELECT=('vms.count'),
3283 FROM="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3284 WHERE={'c.uuid': classifier['uuid']})[0]['count']
3285 instance_vnf = next((item for item in db_instance_vnfs if item['sce_vnf_id'] == classifier['sce_vnf_id']), None)
3286 instance_vms = [item for item in db_instance_vms if item['instance_vnf_id'] == instance_vnf['uuid']]
3287 dependencies = []
3288 for instance_vm in instance_vms:
3289 action = next((item for item in db_vim_actions if item['item_id'] == instance_vm['uuid']), None)
3290 if action:
3291 dependencies.append(action['task_index'])
3292 # TODO: throw exception if count != len(instance_vms)
3293 # TODO: and action shouldn't ever be None
3294 classifications_created = []
3295 for i in range(count):
3296 for match in classifier['matches']:
3297 # create classifications
3298 classification_uuid = str(uuid4())
3299 uuid_list.append(classification_uuid)
3300 db_classification = {
3301 "uuid": classification_uuid,
3302 "instance_scenario_id": instance_uuid,
3303 'sce_classifier_match_id': match['uuid'],
3304 'datacenter_id': datacenter_id,
3305 'datacenter_tenant_id': myvim_thread_id,
3306 "vim_classification_id": None, # vim thread will populate
3307 }
3308 db_instance_classifications.append(db_classification)
3309 classification_params = {
3310 "ip_proto": match["ip_proto"],
3311 "source_ip": match["source_ip"],
3312 "destination_ip": match["destination_ip"],
3313 "source_port": match["source_port"],
3314 "destination_port": match["destination_port"]
3315 }
3316 db_vim_action = {
3317 "instance_action_id": instance_action_id,
3318 "task_index": task_index,
3319 "datacenter_vim_id": myvim_thread_id,
3320 "action": "CREATE",
3321 "status": "SCHEDULED",
3322 "item": "instance_classifications",
3323 "item_id": classification_uuid,
3324 "extra": yaml.safe_dump({"params": classification_params, "depends_on": [dependencies[i]]},
3325 default_flow_style=True, width=256)
3326 }
3327 classifications_created.append(task_index)
3328 task_index += 1
3329 db_vim_actions.append(db_vim_action)
3330
3331 # create sfps
3332 sfp_uuid = str(uuid4())
3333 uuid_list.append(sfp_uuid)
3334 db_sfp = {
3335 "uuid": sfp_uuid,
3336 "instance_scenario_id": instance_uuid,
3337 'sce_rsp_id': rsp['uuid'],
3338 'datacenter_id': datacenter_id,
3339 'datacenter_tenant_id': myvim_thread_id,
3340 "vim_sfp_id": None, # vim thread will populate
3341 }
3342 db_instance_sfps.append(db_sfp)
3343 db_vim_action = {
3344 "instance_action_id": instance_action_id,
3345 "task_index": task_index,
3346 "datacenter_vim_id": myvim_thread_id,
3347 "action": "CREATE",
3348 "status": "SCHEDULED",
3349 "item": "instance_sfps",
3350 "item_id": sfp_uuid,
3351 "extra": yaml.safe_dump({"params": "", "depends_on": sfs_created + classifications_created},
3352 default_flow_style=True, width=256)
3353 }
3354 task_index += 1
3355 db_vim_actions.append(db_vim_action)
3356
3357 scenarioDict["datacenter2tenant"] = myvim_threads_id
3358
3359 db_instance_action["number_tasks"] = task_index
3360 db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id]
3361 db_instance_scenario['datacenter_id'] = default_datacenter_id
3362 db_tables=[
3363 {"instance_scenarios": db_instance_scenario},
3364 {"instance_vnfs": db_instance_vnfs},
3365 {"instance_nets": db_instance_nets},
3366 {"ip_profiles": db_ip_profiles},
3367 {"instance_vms": db_instance_vms},
3368 {"instance_interfaces": db_instance_interfaces},
3369 {"instance_actions": db_instance_action},
3370 {"instance_sfis": db_instance_sfis},
3371 {"instance_sfs": db_instance_sfs},
3372 {"instance_classifications": db_instance_classifications},
3373 {"instance_sfps": db_instance_sfps},
3374 {"vim_actions": db_vim_actions}
3375 ]
3376
3377 logger.debug("create_instance done DB tables: %s",
3378 yaml.safe_dump(db_tables, indent=4, default_flow_style=False) )
3379 mydb.new_rows(db_tables, uuid_list)
3380 for myvim_thread_id in myvim_threads_id.values():
3381 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
3382
3383 returned_instance = mydb.get_instance_scenario(instance_uuid)
3384 returned_instance["action_id"] = instance_action_id
3385 return returned_instance
3386 except (NfvoException, vimconn.vimconnException, db_base_Exception) as e:
3387 message = rollback(mydb, myvims, rollbackList)
3388 if isinstance(e, db_base_Exception):
3389 error_text = "database Exception"
3390 elif isinstance(e, vimconn.vimconnException):
3391 error_text = "VIM Exception"
3392 else:
3393 error_text = "Exception"
3394 error_text += " {} {}. {}".format(type(e).__name__, str(e), message)
3395 # logger.error("create_instance: %s", error_text)
3396 raise NfvoException(error_text, e.http_code)
3397
3398
3399 def instantiate_vnf(mydb, sce_vnf, params, params_out, rollbackList):
3400 default_datacenter_id = params["default_datacenter_id"]
3401 myvim_threads_id = params["myvim_threads_id"]
3402 instance_uuid = params["instance_uuid"]
3403 instance_name = params["instance_name"]
3404 instance_action_id = params["instance_action_id"]
3405 myvims = params["myvims"]
3406 cloud_config = params["cloud_config"]
3407 RO_pub_key = params["RO_pub_key"]
3408
3409 task_index = params_out["task_index"]
3410 uuid_list = params_out["uuid_list"]
3411 db_instance_nets = params_out["db_instance_nets"]
3412 db_vim_actions = params_out["db_vim_actions"]
3413 db_ip_profiles = params_out["db_ip_profiles"]
3414 db_instance_vnfs = params_out["db_instance_vnfs"]
3415 db_instance_vms = params_out["db_instance_vms"]
3416 db_instance_interfaces = params_out["db_instance_interfaces"]
3417 net2task_id = params_out["net2task_id"]
3418 sce_net2instance = params_out["sce_net2instance"]
3419
3420 vnf_net2instance = {}
3421
3422 # 2. Creating new nets (vnf internal nets) in the VIM"
3423 # For each vnf net, we create it and we add it to instanceNetlist.
3424 if sce_vnf.get("datacenter"):
3425 datacenter_id = sce_vnf["datacenter"]
3426 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3427 else:
3428 datacenter_id = default_datacenter_id
3429 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3430 for net in sce_vnf['nets']:
3431 # TODO revis
3432 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3433 # net_name = descriptor_net.get("name")
3434 net_name = None
3435 if not net_name:
3436 net_name = "{}.{}".format(instance_name, net["name"])
3437 net_name = net_name[:255] # limit length
3438 net_type = net['type']
3439
3440 if sce_vnf['uuid'] not in vnf_net2instance:
3441 vnf_net2instance[sce_vnf['uuid']] = {}
3442 if sce_vnf['uuid'] not in net2task_id:
3443 net2task_id[sce_vnf['uuid']] = {}
3444 net2task_id[sce_vnf['uuid']][net['uuid']] = task_index
3445
3446 # fill database content
3447 net_uuid = str(uuid4())
3448 uuid_list.append(net_uuid)
3449 vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid
3450 db_net = {
3451 "uuid": net_uuid,
3452 'vim_net_id': None,
3453 "instance_scenario_id": instance_uuid,
3454 "net_id": net["uuid"],
3455 "created": True,
3456 'datacenter_id': datacenter_id,
3457 'datacenter_tenant_id': myvim_thread_id,
3458 }
3459 db_instance_nets.append(db_net)
3460
3461 db_vim_action = {
3462 "instance_action_id": instance_action_id,
3463 "task_index": task_index,
3464 "datacenter_vim_id": myvim_thread_id,
3465 "status": "SCHEDULED",
3466 "action": "CREATE",
3467 "item": "instance_nets",
3468 "item_id": net_uuid,
3469 "extra": yaml.safe_dump({"params": (net_name, net_type, net.get('ip_profile', None))},
3470 default_flow_style=True, width=256)
3471 }
3472 task_index += 1
3473 db_vim_actions.append(db_vim_action)
3474
3475 if 'ip_profile' in net:
3476 db_ip_profile = {
3477 'instance_net_id': net_uuid,
3478 'ip_version': net['ip_profile']['ip_version'],
3479 'subnet_address': net['ip_profile']['subnet_address'],
3480 'gateway_address': net['ip_profile']['gateway_address'],
3481 'dns_address': net['ip_profile']['dns_address'],
3482 'dhcp_enabled': net['ip_profile']['dhcp_enabled'],
3483 'dhcp_start_address': net['ip_profile']['dhcp_start_address'],
3484 'dhcp_count': net['ip_profile']['dhcp_count'],
3485 }
3486 db_ip_profiles.append(db_ip_profile)
3487
3488 # print "vnf_net2instance:"
3489 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3490
3491 # 3. Creating new vm instances in the VIM
3492 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3493 ssh_access = None
3494 if sce_vnf.get('mgmt_access'):
3495 ssh_access = sce_vnf['mgmt_access'].get('config-access', {}).get('ssh-access')
3496 vnf_availability_zones = []
3497 for vm in sce_vnf['vms']:
3498 vm_av = vm.get('availability_zone')
3499 if vm_av and vm_av not in vnf_availability_zones:
3500 vnf_availability_zones.append(vm_av)
3501
3502 # check if there is enough availability zones available at vim level.
3503 if myvims[datacenter_id].availability_zone and vnf_availability_zones:
3504 if len(vnf_availability_zones) > len(myvims[datacenter_id].availability_zone):
3505 raise NfvoException('No enough availability zones at VIM for this deployment', HTTP_Bad_Request)
3506
3507 if sce_vnf.get("datacenter"):
3508 vim = myvims[sce_vnf["datacenter"]]
3509 myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]]
3510 datacenter_id = sce_vnf["datacenter"]
3511 else:
3512 vim = myvims[default_datacenter_id]
3513 myvim_thread_id = myvim_threads_id[default_datacenter_id]
3514 datacenter_id = default_datacenter_id
3515 sce_vnf["datacenter_id"] = datacenter_id
3516 i = 0
3517
3518 vnf_uuid = str(uuid4())
3519 uuid_list.append(vnf_uuid)
3520 db_instance_vnf = {
3521 'uuid': vnf_uuid,
3522 'instance_scenario_id': instance_uuid,
3523 'vnf_id': sce_vnf['vnf_id'],
3524 'sce_vnf_id': sce_vnf['uuid'],
3525 'datacenter_id': datacenter_id,
3526 'datacenter_tenant_id': myvim_thread_id,
3527 }
3528 db_instance_vnfs.append(db_instance_vnf)
3529
3530 for vm in sce_vnf['vms']:
3531 myVMDict = {}
3532 myVMDict['name'] = "{}.{}.{}".format(instance_name[:64], sce_vnf['name'][:64], vm["name"][:64])
3533 myVMDict['description'] = myVMDict['name'][0:99]
3534 # if not startvms:
3535 # myVMDict['start'] = "no"
3536 myVMDict['name'] = myVMDict['name'][0:255] # limit name length
3537 # create image at vim in case it not exist
3538 image_uuid = vm['image_id']
3539 if vm.get("image_list"):
3540 for alternative_image in vm["image_list"]:
3541 if alternative_image["vim_type"] == vim["config"]["_vim_type_internal"]:
3542 image_uuid = alternative_image['image_id']
3543 break
3544 image_dict = mydb.get_table_by_uuid_name("images", image_uuid)
3545 image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True)
3546 vm['vim_image_id'] = image_id
3547
3548 # create flavor at vim in case it not exist
3549 flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id'])
3550 if flavor_dict['extended'] != None:
3551 flavor_dict['extended'] = yaml.load(flavor_dict['extended'])
3552 flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True)
3553
3554 # Obtain information for additional disks
3555 extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',),
3556 WHERE={'vim_id': flavor_id})
3557 if not extended_flavor_dict:
3558 raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found)
3559
3560 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0])
3561 myVMDict['disks'] = None
3562 extended_info = extended_flavor_dict[0]['extended']
3563 if extended_info != None:
3564 extended_flavor_dict_yaml = yaml.load(extended_info)
3565 if 'disks' in extended_flavor_dict_yaml:
3566 myVMDict['disks'] = extended_flavor_dict_yaml['disks']
3567
3568 vm['vim_flavor_id'] = flavor_id
3569 myVMDict['imageRef'] = vm['vim_image_id']
3570 myVMDict['flavorRef'] = vm['vim_flavor_id']
3571 myVMDict['availability_zone'] = vm.get('availability_zone')
3572 myVMDict['networks'] = []
3573 task_depends_on = []
3574 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
3575 db_vm_ifaces = []
3576 for iface in vm['interfaces']:
3577 netDict = {}
3578 if iface['type'] == "data":
3579 netDict['type'] = iface['model']
3580 elif "model" in iface and iface["model"] != None:
3581 netDict['model'] = iface['model']
3582 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
3583 # is obtained from iterface table model
3584 # discover type of interface looking at flavor
3585 for numa in flavor_dict.get('extended', {}).get('numas', []):
3586 for flavor_iface in numa.get('interfaces', []):
3587 if flavor_iface.get('name') == iface['internal_name']:
3588 if flavor_iface['dedicated'] == 'yes':
3589 netDict['type'] = "PF" # passthrough
3590 elif flavor_iface['dedicated'] == 'no':
3591 netDict['type'] = "VF" # siov
3592 elif flavor_iface['dedicated'] == 'yes:sriov':
3593 netDict['type'] = "VFnotShared" # sriov but only one sriov on the PF
3594 netDict["mac_address"] = flavor_iface.get("mac_address")
3595 break
3596 netDict["use"] = iface['type']
3597 if netDict["use"] == "data" and not netDict.get("type"):
3598 # print "netDict", netDict
3599 # print "iface", iface
3600 e_text = "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
3601 sce_vnf['name'], vm['name'], iface['internal_name'])
3602 if flavor_dict.get('extended') == None:
3603 raise NfvoException(e_text + "After database migration some information is not available. \
3604 Try to delete and create the scenarios and VNFs again", HTTP_Conflict)
3605 else:
3606 raise NfvoException(e_text, HTTP_Internal_Server_Error)
3607 if netDict["use"] == "mgmt" or netDict["use"] == "bridge":
3608 netDict["type"] = "virtual"
3609 if iface.get("vpci"):
3610 netDict['vpci'] = iface['vpci']
3611 if iface.get("mac"):
3612 netDict['mac_address'] = iface['mac']
3613 if iface.get("ip_address"):
3614 netDict['ip_address'] = iface['ip_address']
3615 if iface.get("port-security") is not None:
3616 netDict['port_security'] = iface['port-security']
3617 if iface.get("floating-ip") is not None:
3618 netDict['floating_ip'] = iface['floating-ip']
3619 netDict['name'] = iface['internal_name']
3620 if iface['net_id'] is None:
3621 for vnf_iface in sce_vnf["interfaces"]:
3622 # print iface
3623 # print vnf_iface
3624 if vnf_iface['interface_id'] == iface['uuid']:
3625 netDict['net_id'] = "TASK-{}".format(
3626 net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3627 instance_net_id = sce_net2instance[vnf_iface['sce_net_id']][datacenter_id]
3628 task_depends_on.append(net2task_id['scenario'][vnf_iface['sce_net_id']][datacenter_id])
3629 break
3630 else:
3631 netDict['net_id'] = "TASK-{}".format(net2task_id[sce_vnf['uuid']][iface['net_id']])
3632 instance_net_id = vnf_net2instance[sce_vnf['uuid']][iface['net_id']]
3633 task_depends_on.append(net2task_id[sce_vnf['uuid']][iface['net_id']])
3634 # skip bridge ifaces not connected to any net
3635 if 'net_id' not in netDict or netDict['net_id'] == None:
3636 continue
3637 myVMDict['networks'].append(netDict)
3638 db_vm_iface = {
3639 # "uuid"
3640 # 'instance_vm_id': instance_vm_uuid,
3641 "instance_net_id": instance_net_id,
3642 'interface_id': iface['uuid'],
3643 # 'vim_interface_id': ,
3644 'type': 'external' if iface['external_name'] is not None else 'internal',
3645 'ip_address': iface.get('ip_address'),
3646 'mac_address': iface.get('mac'),
3647 'floating_ip': int(iface.get('floating-ip', False)),
3648 'port_security': int(iface.get('port-security', True))
3649 }
3650 db_vm_ifaces.append(db_vm_iface)
3651 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3652 # print myVMDict['name']
3653 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
3654 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
3655 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
3656
3657 # We add the RO key to cloud_config if vnf will need ssh access
3658 cloud_config_vm = cloud_config
3659 if ssh_access and ssh_access['required'] and ssh_access['default-user'] and tenant[0].get('RO_pub_key'):
3660 RO_key = {"key-pairs": [tenant[0]['RO_pub_key']]}
3661 cloud_config_vm = unify_cloud_config(cloud_config_vm, RO_key)
3662 if vm.get("boot_data"):
3663 cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
3664
3665 if myVMDict.get('availability_zone'):
3666 av_index = vnf_availability_zones.index(myVMDict['availability_zone'])
3667 else:
3668 av_index = None
3669 for vm_index in range(0, vm.get('count', 1)):
3670 vm_index_name = ""
3671 if vm.get('count', 1) > 1:
3672 vm_index_name += "." + chr(97 + vm_index)
3673 task_params = (myVMDict['name'] + vm_index_name, myVMDict['description'], myVMDict.get('start', None),
3674 myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm,
3675 myVMDict['disks'], av_index, vnf_availability_zones)
3676 # put interface uuid back to scenario[vnfs][vms[[interfaces]
3677 for net in myVMDict['networks']:
3678 if "vim_id" in net:
3679 for iface in vm['interfaces']:
3680 if net["name"] == iface["internal_name"]:
3681 iface["vim_id"] = net["vim_id"]
3682 break
3683 vm_uuid = str(uuid4())
3684 uuid_list.append(vm_uuid)
3685 db_vm = {
3686 "uuid": vm_uuid,
3687 'instance_vnf_id': vnf_uuid,
3688 # TODO delete "vim_vm_id": vm_id,
3689 "vm_id": vm["uuid"],
3690 # "status":
3691 }
3692 db_instance_vms.append(db_vm)
3693
3694 iface_index = 0
3695 for db_vm_iface in db_vm_ifaces:
3696 iface_uuid = str(uuid4())
3697 uuid_list.append(iface_uuid)
3698 db_vm_iface_instance = {
3699 "uuid": iface_uuid,
3700 "instance_vm_id": vm_uuid
3701 }
3702 db_vm_iface_instance.update(db_vm_iface)
3703 if db_vm_iface_instance.get("ip_address"): # increment ip_address
3704 ip = db_vm_iface_instance.get("ip_address")
3705 i = ip.rfind(".")
3706 if i > 0:
3707 try:
3708 i += 1
3709 ip = ip[i:] + str(int(ip[:i]) + 1)
3710 db_vm_iface_instance["ip_address"] = ip
3711 except:
3712 db_vm_iface_instance["ip_address"] = None
3713 db_instance_interfaces.append(db_vm_iface_instance)
3714 myVMDict['networks'][iface_index]["uuid"] = iface_uuid
3715 iface_index += 1
3716
3717 db_vim_action = {
3718 "instance_action_id": instance_action_id,
3719 "task_index": task_index,
3720 "datacenter_vim_id": myvim_thread_id,
3721 "action": "CREATE",
3722 "status": "SCHEDULED",
3723 "item": "instance_vms",
3724 "item_id": vm_uuid,
3725 "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on},
3726 default_flow_style=True, width=256)
3727 }
3728 task_index += 1
3729 db_vim_actions.append(db_vim_action)
3730 params_out["task_index"] = task_index
3731 params_out["uuid_list"] = uuid_list
3732
3733
3734 def delete_instance(mydb, tenant_id, instance_id):
3735 # print "Checking that the instance_id exists and getting the instance dictionary"
3736 instanceDict = mydb.get_instance_scenario(instance_id, tenant_id)
3737 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
3738 tenant_id = instanceDict["tenant_id"]
3739 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
3740 # 1. Delete from Database
3741 message = mydb.delete_instance_scenario(instance_id, tenant_id)
3742
3743 # 2. delete from VIM
3744 error_msg = ""
3745 myvims = {}
3746 myvim_threads = {}
3747 vimthread_affected = {}
3748 net2vm_dependencies = {}
3749
3750 task_index = 0
3751 instance_action_id = get_task_id()
3752 db_vim_actions = []
3753 db_instance_action = {
3754 "uuid": instance_action_id, # same uuid for the instance and the action on create
3755 "tenant_id": tenant_id,
3756 "instance_id": instance_id,
3757 "description": "DELETE",
3758 # "number_tasks": 0 # filled bellow
3759 }
3760
3761 # 2.1 deleting VMs
3762 # vm_fail_list=[]
3763 for sce_vnf in instanceDict['vnfs']:
3764 datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
3765 vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None
3766 if datacenter_key not in myvims:
3767 try:
3768 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
3769 except NfvoException as e:
3770 logger.error(str(e))
3771 myvim_thread = None
3772 myvim_threads[datacenter_key] = myvim_thread
3773 vims = get_vim(mydb, tenant_id, datacenter_id=sce_vnf["datacenter_id"],
3774 datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
3775 if len(vims) == 0:
3776 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"],
3777 sce_vnf["datacenter_tenant_id"]))
3778 myvims[datacenter_key] = None
3779 else:
3780 myvims[datacenter_key] = vims.values()[0]
3781 myvim = myvims[datacenter_key]
3782 myvim_thread = myvim_threads[datacenter_key]
3783 for vm in sce_vnf['vms']:
3784 if not myvim:
3785 error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"])
3786 continue
3787 db_vim_action = {
3788 "instance_action_id": instance_action_id,
3789 "task_index": task_index,
3790 "datacenter_vim_id": sce_vnf["datacenter_tenant_id"],
3791 "action": "DELETE",
3792 "status": "SCHEDULED",
3793 "item": "instance_vms",
3794 "item_id": vm["uuid"],
3795 "extra": yaml.safe_dump({"params": vm["interfaces"]},
3796 default_flow_style=True, width=256)
3797 }
3798 db_vim_actions.append(db_vim_action)
3799 for interface in vm["interfaces"]:
3800 if not interface.get("instance_net_id"):
3801 continue
3802 if interface["instance_net_id"] not in net2vm_dependencies:
3803 net2vm_dependencies[interface["instance_net_id"]] = []
3804 net2vm_dependencies[interface["instance_net_id"]].append(task_index)
3805 task_index += 1
3806
3807 # 2.2 deleting NETS
3808 # net_fail_list=[]
3809 for net in instanceDict['nets']:
3810 vimthread_affected[net["datacenter_tenant_id"]] = None
3811 datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
3812 if datacenter_key not in myvims:
3813 try:
3814 _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
3815 except NfvoException as e:
3816 logger.error(str(e))
3817 myvim_thread = None
3818 myvim_threads[datacenter_key] = myvim_thread
3819 vims = get_vim(mydb, tenant_id, datacenter_id=net["datacenter_id"],
3820 datacenter_tenant_id=net["datacenter_tenant_id"])
3821 if len(vims) == 0:
3822 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
3823 myvims[datacenter_key] = None
3824 else:
3825 myvims[datacenter_key] = vims.values()[0]
3826 myvim = myvims[datacenter_key]
3827 myvim_thread = myvim_threads[datacenter_key]
3828
3829 if not myvim:
3830 error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"])
3831 continue
3832 extra = {"params": (net['vim_net_id'], net['sdn_net_id'])}
3833 if net2vm_dependencies.get(net["uuid"]):
3834 extra["depends_on"] = net2vm_dependencies[net["uuid"]]
3835 db_vim_action = {
3836 "instance_action_id": instance_action_id,
3837 "task_index": task_index,
3838 "datacenter_vim_id": net["datacenter_tenant_id"],
3839 "action": "DELETE",
3840 "status": "SCHEDULED",
3841 "item": "instance_nets",
3842 "item_id": net["uuid"],
3843 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3844 }
3845 task_index += 1
3846 db_vim_actions.append(db_vim_action)
3847
3848 # 2.3 deleting VNFFGs
3849
3850 for sfp in instanceDict.get('sfps', ()):
3851 vimthread_affected[sfp["datacenter_tenant_id"]] = None
3852 datacenter_key = (sfp["datacenter_id"], sfp["datacenter_tenant_id"])
3853 if datacenter_key not in myvims:
3854 try:
3855 _,myvim_thread = get_vim_thread(mydb, tenant_id, sfp["datacenter_id"], sfp["datacenter_tenant_id"])
3856 except NfvoException as e:
3857 logger.error(str(e))
3858 myvim_thread = None
3859 myvim_threads[datacenter_key] = myvim_thread
3860 vims = get_vim(mydb, tenant_id, datacenter_id=sfp["datacenter_id"],
3861 datacenter_tenant_id=sfp["datacenter_tenant_id"])
3862 if len(vims) == 0:
3863 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp["datacenter_id"], sfp["datacenter_tenant_id"]))
3864 myvims[datacenter_key] = None
3865 else:
3866 myvims[datacenter_key] = vims.values()[0]
3867 myvim = myvims[datacenter_key]
3868 myvim_thread = myvim_threads[datacenter_key]
3869
3870 if not myvim:
3871 error_msg += "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp['vim_sfp_id'], sfp["datacenter_id"])
3872 continue
3873 extra = {"params": (sfp['vim_sfp_id'])}
3874 db_vim_action = {
3875 "instance_action_id": instance_action_id,
3876 "task_index": task_index,
3877 "datacenter_vim_id": sfp["datacenter_tenant_id"],
3878 "action": "DELETE",
3879 "status": "SCHEDULED",
3880 "item": "instance_sfps",
3881 "item_id": sfp["uuid"],
3882 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3883 }
3884 task_index += 1
3885 db_vim_actions.append(db_vim_action)
3886
3887 for sf in instanceDict.get('sfs', ()):
3888 vimthread_affected[sf["datacenter_tenant_id"]] = None
3889 datacenter_key = (sf["datacenter_id"], sf["datacenter_tenant_id"])
3890 if datacenter_key not in myvims:
3891 try:
3892 _,myvim_thread = get_vim_thread(mydb, tenant_id, sf["datacenter_id"], sf["datacenter_tenant_id"])
3893 except NfvoException as e:
3894 logger.error(str(e))
3895 myvim_thread = None
3896 myvim_threads[datacenter_key] = myvim_thread
3897 vims = get_vim(mydb, tenant_id, datacenter_id=sf["datacenter_id"],
3898 datacenter_tenant_id=sf["datacenter_tenant_id"])
3899 if len(vims) == 0:
3900 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf["datacenter_id"], sf["datacenter_tenant_id"]))
3901 myvims[datacenter_key] = None
3902 else:
3903 myvims[datacenter_key] = vims.values()[0]
3904 myvim = myvims[datacenter_key]
3905 myvim_thread = myvim_threads[datacenter_key]
3906
3907 if not myvim:
3908 error_msg += "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf['vim_sf_id'], sf["datacenter_id"])
3909 continue
3910 extra = {"params": (sf['vim_sf_id'])}
3911 db_vim_action = {
3912 "instance_action_id": instance_action_id,
3913 "task_index": task_index,
3914 "datacenter_vim_id": sf["datacenter_tenant_id"],
3915 "action": "DELETE",
3916 "status": "SCHEDULED",
3917 "item": "instance_sfs",
3918 "item_id": sf["uuid"],
3919 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3920 }
3921 task_index += 1
3922 db_vim_actions.append(db_vim_action)
3923
3924 for sfi in instanceDict.get('sfis', ()):
3925 vimthread_affected[sfi["datacenter_tenant_id"]] = None
3926 datacenter_key = (sfi["datacenter_id"], sfi["datacenter_tenant_id"])
3927 if datacenter_key not in myvims:
3928 try:
3929 _,myvim_thread = get_vim_thread(mydb, tenant_id, sfi["datacenter_id"], sfi["datacenter_tenant_id"])
3930 except NfvoException as e:
3931 logger.error(str(e))
3932 myvim_thread = None
3933 myvim_threads[datacenter_key] = myvim_thread
3934 vims = get_vim(mydb, tenant_id, datacenter_id=sfi["datacenter_id"],
3935 datacenter_tenant_id=sfi["datacenter_tenant_id"])
3936 if len(vims) == 0:
3937 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi["datacenter_id"], sfi["datacenter_tenant_id"]))
3938 myvims[datacenter_key] = None
3939 else:
3940 myvims[datacenter_key] = vims.values()[0]
3941 myvim = myvims[datacenter_key]
3942 myvim_thread = myvim_threads[datacenter_key]
3943
3944 if not myvim:
3945 error_msg += "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi['vim_sfi_id'], sfi["datacenter_id"])
3946 continue
3947 extra = {"params": (sfi['vim_sfi_id'])}
3948 db_vim_action = {
3949 "instance_action_id": instance_action_id,
3950 "task_index": task_index,
3951 "datacenter_vim_id": sfi["datacenter_tenant_id"],
3952 "action": "DELETE",
3953 "status": "SCHEDULED",
3954 "item": "instance_sfis",
3955 "item_id": sfi["uuid"],
3956 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3957 }
3958 task_index += 1
3959 db_vim_actions.append(db_vim_action)
3960
3961 for classification in instanceDict['classifications']:
3962 vimthread_affected[classification["datacenter_tenant_id"]] = None
3963 datacenter_key = (classification["datacenter_id"], classification["datacenter_tenant_id"])
3964 if datacenter_key not in myvims:
3965 try:
3966 _,myvim_thread = get_vim_thread(mydb, tenant_id, classification["datacenter_id"], classification["datacenter_tenant_id"])
3967 except NfvoException as e:
3968 logger.error(str(e))
3969 myvim_thread = None
3970 myvim_threads[datacenter_key] = myvim_thread
3971 vims = get_vim(mydb, tenant_id, datacenter_id=classification["datacenter_id"],
3972 datacenter_tenant_id=classification["datacenter_tenant_id"])
3973 if len(vims) == 0:
3974 logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification["datacenter_id"], classification["datacenter_tenant_id"]))
3975 myvims[datacenter_key] = None
3976 else:
3977 myvims[datacenter_key] = vims.values()[0]
3978 myvim = myvims[datacenter_key]
3979 myvim_thread = myvim_threads[datacenter_key]
3980
3981 if not myvim:
3982 error_msg += "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification['vim_classification_id'], classification["datacenter_id"])
3983 continue
3984 extra = {"params": (classification['vim_classification_id'])}
3985 db_vim_action = {
3986 "instance_action_id": instance_action_id,
3987 "task_index": task_index,
3988 "datacenter_vim_id": classification["datacenter_tenant_id"],
3989 "action": "DELETE",
3990 "status": "SCHEDULED",
3991 "item": "instance_classifications",
3992 "item_id": classification["uuid"],
3993 "extra": yaml.safe_dump(extra, default_flow_style=True, width=256)
3994 }
3995 task_index += 1
3996 db_vim_actions.append(db_vim_action)
3997
3998 db_instance_action["number_tasks"] = task_index
3999 db_tables = [
4000 {"instance_actions": db_instance_action},
4001 {"vim_actions": db_vim_actions}
4002 ]
4003
4004 logger.debug("delete_instance done DB tables: %s",
4005 yaml.safe_dump(db_tables, indent=4, default_flow_style=False))
4006 mydb.new_rows(db_tables, ())
4007 for myvim_thread_id in vimthread_affected.keys():
4008 vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions)
4009
4010 if len(error_msg) > 0:
4011 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4012 '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg)
4013 else:
4014 return "action_id={} instance {} deleted".format(instance_action_id, message)
4015
4016
4017 def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None):
4018 '''Refreshes a scenario instance. It modifies instanceDict'''
4019 '''Returns:
4020 - 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
4021 - error_msg
4022 '''
4023 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4024 # #print "nfvo.refresh_instance begins"
4025 # #print json.dumps(instanceDict, indent=4)
4026 #
4027 # #print "Getting the VIM URL and the VIM tenant_id"
4028 # myvims={}
4029 #
4030 # # 1. Getting VIM vm and net list
4031 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4032 # vms_notupdated=[]
4033 # vm_list = {}
4034 # for sce_vnf in instanceDict['vnfs']:
4035 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4036 # if datacenter_key not in vm_list:
4037 # vm_list[datacenter_key] = []
4038 # if datacenter_key not in myvims:
4039 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4040 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4041 # if len(vims) == 0:
4042 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4043 # myvims[datacenter_key] = None
4044 # else:
4045 # myvims[datacenter_key] = vims.values()[0]
4046 # for vm in sce_vnf['vms']:
4047 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4048 # vms_notupdated.append(vm["uuid"])
4049 #
4050 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4051 # nets_notupdated=[]
4052 # net_list = {}
4053 # for net in instanceDict['nets']:
4054 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4055 # if datacenter_key not in net_list:
4056 # net_list[datacenter_key] = []
4057 # if datacenter_key not in myvims:
4058 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4059 # datacenter_tenant_id=net["datacenter_tenant_id"])
4060 # if len(vims) == 0:
4061 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4062 # myvims[datacenter_key] = None
4063 # else:
4064 # myvims[datacenter_key] = vims.values()[0]
4065 #
4066 # net_list[datacenter_key].append(net['vim_net_id'])
4067 # nets_notupdated.append(net["uuid"])
4068 #
4069 # # 1. Getting the status of all VMs
4070 # vm_dict={}
4071 # for datacenter_key in myvims:
4072 # if not vm_list.get(datacenter_key):
4073 # continue
4074 # failed = True
4075 # failed_message=""
4076 # if not myvims[datacenter_key]:
4077 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4078 # else:
4079 # try:
4080 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4081 # failed = False
4082 # except vimconn.vimconnException as e:
4083 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4084 # failed_message = str(e)
4085 # if failed:
4086 # for vm in vm_list[datacenter_key]:
4087 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4088 #
4089 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4090 # for sce_vnf in instanceDict['vnfs']:
4091 # for vm in sce_vnf['vms']:
4092 # vm_id = vm['vim_vm_id']
4093 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4094 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4095 # has_mgmt_iface = False
4096 # for iface in vm["interfaces"]:
4097 # if iface["type"]=="mgmt":
4098 # has_mgmt_iface = True
4099 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4100 # vm_dict[vm_id]['status'] = "ACTIVE"
4101 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4102 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4103 # 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'):
4104 # vm['status'] = vm_dict[vm_id]['status']
4105 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4106 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4107 # # 2.1. Update in openmano DB the VMs whose status changed
4108 # try:
4109 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4110 # vms_notupdated.remove(vm["uuid"])
4111 # if updates>0:
4112 # vms_updated.append(vm["uuid"])
4113 # except db_base_Exception as e:
4114 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4115 # # 2.2. Update in openmano DB the interface VMs
4116 # for interface in interfaces:
4117 # #translate from vim_net_id to instance_net_id
4118 # network_id_list=[]
4119 # for net in instanceDict['nets']:
4120 # if net["vim_net_id"] == interface["vim_net_id"]:
4121 # network_id_list.append(net["uuid"])
4122 # if not network_id_list:
4123 # continue
4124 # del interface["vim_net_id"]
4125 # try:
4126 # for network_id in network_id_list:
4127 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4128 # except db_base_Exception as e:
4129 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4130 #
4131 # # 3. Getting the status of all nets
4132 # net_dict = {}
4133 # for datacenter_key in myvims:
4134 # if not net_list.get(datacenter_key):
4135 # continue
4136 # failed = True
4137 # failed_message = ""
4138 # if not myvims[datacenter_key]:
4139 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4140 # else:
4141 # try:
4142 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4143 # failed = False
4144 # except vimconn.vimconnException as e:
4145 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4146 # failed_message = str(e)
4147 # if failed:
4148 # for net in net_list[datacenter_key]:
4149 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4150 #
4151 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4152 # # TODO: update nets inside a vnf
4153 # for net in instanceDict['nets']:
4154 # net_id = net['vim_net_id']
4155 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4156 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4157 # 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'):
4158 # net['status'] = net_dict[net_id]['status']
4159 # net['error_msg'] = net_dict[net_id].get('error_msg')
4160 # net['vim_info'] = net_dict[net_id].get('vim_info')
4161 # # 5.1. Update in openmano DB the nets whose status changed
4162 # try:
4163 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4164 # nets_notupdated.remove(net["uuid"])
4165 # if updated>0:
4166 # nets_updated.append(net["uuid"])
4167 # except db_base_Exception as e:
4168 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4169 #
4170 # # Returns appropriate output
4171 # #print "nfvo.refresh_instance finishes"
4172 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4173 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
4174 instance_id = instanceDict['uuid']
4175 # if len(vms_notupdated)+len(nets_notupdated)>0:
4176 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4177 # return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
4178
4179 return 0, 'Scenario instance ' + instance_id + ' refreshed.'
4180
4181 def instance_action(mydb,nfvo_tenant,instance_id, action_dict):
4182 #print "Checking that the instance_id exists and getting the instance dictionary"
4183 instanceDict = mydb.get_instance_scenario(instance_id, nfvo_tenant)
4184 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4185
4186 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
4187 vims = get_vim(mydb, nfvo_tenant, instanceDict['datacenter_id'])
4188 if len(vims) == 0:
4189 raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found)
4190 myvim = vims.values()[0]
4191
4192 if action_dict.get("create-vdu"):
4193 for vdu in action_dict["create-vdu"]:
4194 vdu_id = vdu.get("vdu-id")
4195 vdu_count = vdu.get("count", 1)
4196 # get from database TODO
4197 # insert tasks TODO
4198 pass
4199
4200 input_vnfs = action_dict.pop("vnfs", [])
4201 input_vms = action_dict.pop("vms", [])
4202 action_over_all = True if len(input_vnfs)==0 and len (input_vms)==0 else False
4203 vm_result = {}
4204 vm_error = 0
4205 vm_ok = 0
4206 for sce_vnf in instanceDict['vnfs']:
4207 for vm in sce_vnf['vms']:
4208 if not action_over_all:
4209 if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \
4210 vm['uuid'] not in input_vms and vm['name'] not in input_vms:
4211 continue
4212 try:
4213 if "add_public_key" in action_dict:
4214 mgmt_access = {}
4215 if sce_vnf.get('mgmt_access'):
4216 mgmt_access = yaml.load(sce_vnf['mgmt_access'])
4217 ssh_access = mgmt_access['config-access']['ssh-access']
4218 tenant = mydb.get_rows_by_id('nfvo_tenants', nfvo_tenant)
4219 try:
4220 if ssh_access['required'] and ssh_access['default-user']:
4221 if 'ip_address' in vm:
4222 mgmt_ip = vm['ip_address'].split(';')
4223 password = mgmt_access['config-access'].get('password')
4224 priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
4225 myvim.inject_user_key(mgmt_ip[0], ssh_access['default-user'],
4226 action_dict['add_public_key'],
4227 password=password, ro_key=priv_RO_key)
4228 else:
4229 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4230 HTTP_Internal_Server_Error)
4231 except KeyError:
4232 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4233 HTTP_Internal_Server_Error)
4234 else:
4235 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
4236 HTTP_Internal_Server_Error)
4237 else:
4238 data = myvim.action_vminstance(vm['vim_vm_id'], action_dict)
4239 if "console" in action_dict:
4240 if not global_config["http_console_proxy"]:
4241 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4242 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4243 protocol=data["protocol"],
4244 ip = data["server"],
4245 port = data["port"],
4246 suffix = data["suffix"]),
4247 "name":vm['name']
4248 }
4249 vm_ok +=1
4250 elif data["server"]=="127.0.0.1" or data["server"]=="localhost":
4251 vm_result[ vm['uuid'] ] = {"vim_result": -HTTP_Unauthorized,
4252 "description": "this console is only reachable by local interface",
4253 "name":vm['name']
4254 }
4255 vm_error+=1
4256 else:
4257 #print "console data", data
4258 try:
4259 console_thread = create_or_use_console_proxy_thread(data["server"], data["port"])
4260 vm_result[ vm['uuid'] ] = {"vim_result": 200,
4261 "description": "{protocol}//{ip}:{port}/{suffix}".format(
4262 protocol=data["protocol"],
4263 ip = global_config["http_console_host"],
4264 port = console_thread.port,
4265 suffix = data["suffix"]),
4266 "name":vm['name']
4267 }
4268 vm_ok +=1
4269 except NfvoException as e:
4270 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4271 vm_error+=1
4272
4273 else:
4274 vm_result[ vm['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm['name']}
4275 vm_ok +=1
4276 except vimconn.vimconnException as e:
4277 vm_result[ vm['uuid'] ] = {"vim_result": e.http_code, "name":vm['name'], "description": str(e)}
4278 vm_error+=1
4279
4280 if vm_ok==0: #all goes wrong
4281 return vm_result
4282 else:
4283 return vm_result
4284
4285 def instance_action_get(mydb, nfvo_tenant, instance_id, action_id):
4286 filter = {}
4287 if nfvo_tenant and nfvo_tenant != "any":
4288 filter["tenant_id"] = nfvo_tenant
4289 if instance_id and instance_id != "any":
4290 filter["instance_id"] = instance_id
4291 if action_id:
4292 filter["uuid"] = action_id
4293 rows = mydb.get_rows(FROM="instance_actions", WHERE=filter)
4294 if action_id:
4295 if not rows:
4296 raise NfvoException("Not found any action with this criteria", HTTP_Not_Found)
4297 vim_actions = mydb.get_rows(FROM="vim_actions", WHERE={"instance_action_id": action_id})
4298 rows[0]["vim_actions"] = vim_actions
4299 return {"ations": rows}
4300
4301
4302 def create_or_use_console_proxy_thread(console_server, console_port):
4303 #look for a non-used port
4304 console_thread_key = console_server + ":" + str(console_port)
4305 if console_thread_key in global_config["console_thread"]:
4306 #global_config["console_thread"][console_thread_key].start_timeout()
4307 return global_config["console_thread"][console_thread_key]
4308
4309 for port in global_config["console_port_iterator"]():
4310 #print "create_or_use_console_proxy_thread() port:", port
4311 if port in global_config["console_ports"]:
4312 continue
4313 try:
4314 clithread = cli.ConsoleProxyThread(global_config['http_host'], port, console_server, console_port)
4315 clithread.start()
4316 global_config["console_thread"][console_thread_key] = clithread
4317 global_config["console_ports"][port] = console_thread_key
4318 return clithread
4319 except cli.ConsoleProxyExceptionPortUsed as e:
4320 #port used, try with onoher
4321 continue
4322 except cli.ConsoleProxyException as e:
4323 raise NfvoException(str(e), HTTP_Bad_Request)
4324 raise NfvoException("Not found any free 'http_console_ports'", HTTP_Conflict)
4325
4326
4327 def check_tenant(mydb, tenant_id):
4328 '''check that tenant exists at database'''
4329 tenant = mydb.get_rows(FROM='nfvo_tenants', SELECT=('uuid',), WHERE={'uuid': tenant_id})
4330 if not tenant:
4331 raise NfvoException("tenant '{}' not found".format(tenant_id), HTTP_Not_Found)
4332 return
4333
4334 def new_tenant(mydb, tenant_dict):
4335
4336 tenant_uuid = str(uuid4())
4337 tenant_dict['uuid'] = tenant_uuid
4338 try:
4339 pub_key, priv_key = create_RO_keypair(tenant_uuid)
4340 tenant_dict['RO_pub_key'] = pub_key
4341 tenant_dict['encrypted_RO_priv_key'] = priv_key
4342 mydb.new_row("nfvo_tenants", tenant_dict, confidential_data=True)
4343 except db_base_Exception as e:
4344 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict['name']) + str(e), e.http_code)
4345 return tenant_uuid
4346
4347 def delete_tenant(mydb, tenant):
4348 #get nfvo_tenant info
4349
4350 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant, 'tenant')
4351 mydb.delete_row_by_id("nfvo_tenants", tenant_dict['uuid'])
4352 return tenant_dict['uuid'] + " " + tenant_dict["name"]
4353
4354
4355 def new_datacenter(mydb, datacenter_descriptor):
4356 if "config" in datacenter_descriptor:
4357 datacenter_descriptor["config"]=yaml.safe_dump(datacenter_descriptor["config"],default_flow_style=True,width=256)
4358 #Check that datacenter-type is correct
4359 datacenter_type = datacenter_descriptor.get("type", "openvim");
4360 module_info = None
4361 try:
4362 module = "vimconn_" + datacenter_type
4363 pkg = __import__("osm_ro." + module)
4364 vim_conn = getattr(pkg, module)
4365 # module_info = imp.find_module(module, [__file__[:__file__.rfind("/")]])
4366 except (IOError, ImportError):
4367 # if module_info and module_info[0]:
4368 # file.close(module_info[0])
4369 raise NfvoException("Incorrect datacenter type '{}'. Plugin '{}.py' not installed".format(datacenter_type, module), HTTP_Bad_Request)
4370
4371 datacenter_id = mydb.new_row("datacenters", datacenter_descriptor, add_uuid=True, confidential_data=True)
4372 return datacenter_id
4373
4374
4375 def edit_datacenter(mydb, datacenter_id_name, datacenter_descriptor):
4376 # obtain data, check that only one exist
4377 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id_name)
4378
4379 # edit data
4380 datacenter_id = datacenter['uuid']
4381 where={'uuid': datacenter['uuid']}
4382 remove_port_mapping = False
4383 if "config" in datacenter_descriptor:
4384 if datacenter_descriptor['config'] != None:
4385 try:
4386 new_config_dict = datacenter_descriptor["config"]
4387 #delete null fields
4388 to_delete=[]
4389 for k in new_config_dict:
4390 if new_config_dict[k] == None:
4391 to_delete.append(k)
4392 if k == 'sdn-controller':
4393 remove_port_mapping = True
4394
4395 config_text = datacenter.get("config")
4396 if not config_text:
4397 config_text = '{}'
4398 config_dict = yaml.load(config_text)
4399 config_dict.update(new_config_dict)
4400 #delete null fields
4401 for k in to_delete:
4402 del config_dict[k]
4403 except Exception as e:
4404 raise NfvoException("Bad format at datacenter:config " + str(e), HTTP_Bad_Request)
4405 if config_dict:
4406 datacenter_descriptor["config"] = yaml.safe_dump(config_dict, default_flow_style=True, width=256)
4407 else:
4408 datacenter_descriptor["config"] = None
4409 if remove_port_mapping:
4410 try:
4411 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_id)
4412 except ovimException as e:
4413 logger.error("Error deleting datacenter-port-mapping " + str(e))
4414
4415 mydb.update_rows('datacenters', datacenter_descriptor, where)
4416 return datacenter_id
4417
4418
4419 def delete_datacenter(mydb, datacenter):
4420 #get nfvo_tenant info
4421 datacenter_dict = mydb.get_table_by_uuid_name('datacenters', datacenter, 'datacenter')
4422 mydb.delete_row_by_id("datacenters", datacenter_dict['uuid'])
4423 try:
4424 datacenter_sdn_port_mapping_delete(mydb, None, datacenter_dict['uuid'])
4425 except ovimException as e:
4426 logger.error("Error deleting datacenter-port-mapping " + str(e))
4427 return datacenter_dict['uuid'] + " " + datacenter_dict['name']
4428
4429
4430 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):
4431 # get datacenter info
4432 try:
4433 datacenter_id = get_datacenter_uuid(mydb, None, datacenter)
4434
4435 create_vim_tenant = True if not vim_tenant_id and not vim_tenant_name else False
4436
4437 # get nfvo_tenant info
4438 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant)
4439 if vim_tenant_name==None:
4440 vim_tenant_name=tenant_dict['name']
4441
4442 #check that this association does not exist before
4443 tenants_datacenter_dict={"nfvo_tenant_id":tenant_dict['uuid'], "datacenter_id":datacenter_id }
4444 tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4445 if len(tenants_datacenters)>0:
4446 raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Conflict)
4447
4448 vim_tenant_id_exist_atdb=False
4449 if not create_vim_tenant:
4450 where_={"datacenter_id": datacenter_id}
4451 if vim_tenant_id!=None:
4452 where_["vim_tenant_id"] = vim_tenant_id
4453 if vim_tenant_name!=None:
4454 where_["vim_tenant_name"] = vim_tenant_name
4455 #check if vim_tenant_id is already at database
4456 datacenter_tenants_dict = mydb.get_rows(FROM='datacenter_tenants', WHERE=where_)
4457 if len(datacenter_tenants_dict)>=1:
4458 datacenter_tenants_dict = datacenter_tenants_dict[0]
4459 vim_tenant_id_exist_atdb=True
4460 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
4461 else: #result=0
4462 datacenter_tenants_dict = {}
4463 #insert at table datacenter_tenants
4464 else: #if vim_tenant_id==None:
4465 #create tenant at VIM if not provided
4466 try:
4467 _, myvim = get_datacenter_by_name_uuid(mydb, None, datacenter, vim_user=vim_username,
4468 vim_passwd=vim_password)
4469 datacenter_name = myvim["name"]
4470 vim_tenant_id = myvim.new_tenant(vim_tenant_name, "created by openmano for datacenter "+datacenter_name)
4471 except vimconn.vimconnException as e:
4472 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id, str(e)), HTTP_Internal_Server_Error)
4473 datacenter_tenants_dict = {}
4474 datacenter_tenants_dict["created"]="true"
4475
4476 #fill datacenter_tenants table
4477 if not vim_tenant_id_exist_atdb:
4478 datacenter_tenants_dict["vim_tenant_id"] = vim_tenant_id
4479 datacenter_tenants_dict["vim_tenant_name"] = vim_tenant_name
4480 datacenter_tenants_dict["user"] = vim_username
4481 datacenter_tenants_dict["passwd"] = vim_password
4482 datacenter_tenants_dict["datacenter_id"] = datacenter_id
4483 if config:
4484 datacenter_tenants_dict["config"] = yaml.safe_dump(config, default_flow_style=True, width=256)
4485 id_ = mydb.new_row('datacenter_tenants', datacenter_tenants_dict, add_uuid=True, confidential_data=True)
4486 datacenter_tenants_dict["uuid"] = id_
4487
4488 #fill tenants_datacenters table
4489 datacenter_tenant_id = datacenter_tenants_dict["uuid"]
4490 tenants_datacenter_dict["datacenter_tenant_id"] = datacenter_tenant_id
4491 mydb.new_row('tenants_datacenters', tenants_datacenter_dict)
4492 # create thread
4493 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_dict['uuid'], datacenter_id) # reload data
4494 datacenter_name = myvim["name"]
4495 thread_name = get_non_used_vim_name(datacenter_name, datacenter_id, tenant_dict['name'], tenant_dict['uuid'])
4496 new_thread = vim_thread.vim_thread(myvim, task_lock, thread_name, datacenter_name, datacenter_tenant_id,
4497 db=db, db_lock=db_lock, ovim=ovim)
4498 new_thread.start()
4499 thread_id = datacenter_tenants_dict["uuid"]
4500 vim_threads["running"][thread_id] = new_thread
4501 return datacenter_id
4502 except vimconn.vimconnException as e:
4503 raise NfvoException(str(e), HTTP_Bad_Request)
4504
4505
4506 def edit_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=None, vim_tenant_name=None,
4507 vim_username=None, vim_password=None, config=None):
4508 #Obtain the data of this datacenter_tenant_id
4509 vim_data = mydb.get_rows(
4510 SELECT=("datacenter_tenants.vim_tenant_name", "datacenter_tenants.vim_tenant_id", "datacenter_tenants.user",
4511 "datacenter_tenants.passwd", "datacenter_tenants.config"),
4512 FROM="datacenter_tenants JOIN tenants_datacenters ON datacenter_tenants.uuid=tenants_datacenters.datacenter_tenant_id",
4513 WHERE={"tenants_datacenters.nfvo_tenant_id": nfvo_tenant,
4514 "tenants_datacenters.datacenter_id": datacenter_id})
4515
4516 logger.debug(str(vim_data))
4517 if len(vim_data) < 1:
4518 raise NfvoException("Datacenter {} is not attached for tenant {}".format(datacenter_id, nfvo_tenant), HTTP_Conflict)
4519
4520 v = vim_data[0]
4521 if v['config']:
4522 v['config'] = yaml.load(v['config'])
4523
4524 if vim_tenant_id:
4525 v['vim_tenant_id'] = vim_tenant_id
4526 if vim_tenant_name:
4527 v['vim_tenant_name'] = vim_tenant_name
4528 if vim_username:
4529 v['user'] = vim_username
4530 if vim_password:
4531 v['passwd'] = vim_password
4532 if config:
4533 if not v['config']:
4534 v['config'] = {}
4535 v['config'].update(config)
4536
4537 logger.debug(str(v))
4538 deassociate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'])
4539 associate_datacenter_to_tenant(mydb, nfvo_tenant, datacenter_id, vim_tenant_id=v['vim_tenant_id'], vim_tenant_name=v['vim_tenant_name'],
4540 vim_username=v['user'], vim_password=v['passwd'], config=v['config'])
4541
4542 return datacenter_id
4543
4544 def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id=None):
4545 #get nfvo_tenant info
4546 if not tenant_id or tenant_id=="any":
4547 tenant_uuid = None
4548 else:
4549 tenant_dict = mydb.get_table_by_uuid_name('nfvo_tenants', tenant_id)
4550 tenant_uuid = tenant_dict['uuid']
4551
4552 datacenter_id = get_datacenter_uuid(mydb, tenant_uuid, datacenter)
4553 #check that this association exist before
4554 tenants_datacenter_dict={"datacenter_id": datacenter_id }
4555 if tenant_uuid:
4556 tenants_datacenter_dict["nfvo_tenant_id"] = tenant_uuid
4557 tenant_datacenter_list = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4558 if len(tenant_datacenter_list)==0 and tenant_uuid:
4559 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id, tenant_dict['uuid']), HTTP_Not_Found)
4560
4561 #delete this association
4562 mydb.delete_row(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
4563
4564 #get vim_tenant info and deletes
4565 warning=''
4566 for tenant_datacenter_item in tenant_datacenter_list:
4567 vim_tenant_dict = mydb.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
4568 #try to delete vim:tenant
4569 try:
4570 mydb.delete_row_by_id('datacenter_tenants', tenant_datacenter_item['datacenter_tenant_id'])
4571 if vim_tenant_dict['created']=='true':
4572 #delete tenant at VIM if created by NFVO
4573 try:
4574 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4575 myvim.delete_tenant(vim_tenant_dict['vim_tenant_id'])
4576 except vimconn.vimconnException as e:
4577 warning = "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict['vim_tenant_id'], str(e))
4578 logger.warn(warning)
4579 except db_base_Exception as e:
4580 logger.error("Cannot delete datacenter_tenants " + str(e))
4581 pass # the error will be caused because dependencies, vim_tenant can not be deleted
4582 thread_id = tenant_datacenter_item["datacenter_tenant_id"]
4583 thread = vim_threads["running"][thread_id]
4584 thread.insert_task("exit")
4585 vim_threads["deleting"][thread_id] = thread
4586 return "datacenter {} detached. {}".format(datacenter_id, warning)
4587
4588
4589 def datacenter_action(mydb, tenant_id, datacenter, action_dict):
4590 #DEPRECATED
4591 #get datacenter info
4592 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4593
4594 if 'net-update' in action_dict:
4595 try:
4596 nets = myvim.get_network_list(filter_dict={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
4597 #print content
4598 except vimconn.vimconnException as e:
4599 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
4600 raise NfvoException(str(e), HTTP_Internal_Server_Error)
4601 #update nets Change from VIM format to NFVO format
4602 net_list=[]
4603 for net in nets:
4604 net_nfvo={'datacenter_id': datacenter_id}
4605 net_nfvo['name'] = net['name']
4606 #net_nfvo['description']= net['name']
4607 net_nfvo['vim_net_id'] = net['id']
4608 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
4609 net_nfvo['shared'] = net['shared']
4610 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
4611 net_list.append(net_nfvo)
4612 inserted, deleted = mydb.update_datacenter_nets(datacenter_id, net_list)
4613 logger.info("Inserted %d nets, deleted %d old nets", inserted, deleted)
4614 return inserted
4615 elif 'net-edit' in action_dict:
4616 net = action_dict['net-edit'].pop('net')
4617 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
4618 result = mydb.update_rows('datacenter_nets', action_dict['net-edit'],
4619 WHERE={'datacenter_id':datacenter_id, what: net})
4620 return result
4621 elif 'net-delete' in action_dict:
4622 net = action_dict['net-deelte'].get('net')
4623 what = 'vim_net_id' if utils.check_valid_uuid(net) else 'name'
4624 result = mydb.delete_row(FROM='datacenter_nets',
4625 WHERE={'datacenter_id':datacenter_id, what: net})
4626 return result
4627
4628 else:
4629 raise NfvoException("Unknown action " + str(action_dict), HTTP_Bad_Request)
4630
4631
4632 def datacenter_edit_netmap(mydb, tenant_id, datacenter, netmap, action_dict):
4633 #get datacenter info
4634 datacenter_id, _ = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4635
4636 what = 'uuid' if utils.check_valid_uuid(netmap) else 'name'
4637 result = mydb.update_rows('datacenter_nets', action_dict['netmap'],
4638 WHERE={'datacenter_id':datacenter_id, what: netmap})
4639 return result
4640
4641
4642 def datacenter_new_netmap(mydb, tenant_id, datacenter, action_dict=None):
4643 #get datacenter info
4644 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4645 filter_dict={}
4646 if action_dict:
4647 action_dict = action_dict["netmap"]
4648 if 'vim_id' in action_dict:
4649 filter_dict["id"] = action_dict['vim_id']
4650 if 'vim_name' in action_dict:
4651 filter_dict["name"] = action_dict['vim_name']
4652 else:
4653 filter_dict["shared"] = True
4654
4655 try:
4656 vim_nets = myvim.get_network_list(filter_dict=filter_dict)
4657 except vimconn.vimconnException as e:
4658 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
4659 raise NfvoException(str(e), HTTP_Internal_Server_Error)
4660 if len(vim_nets)>1 and action_dict:
4661 raise NfvoException("more than two networks found, specify with vim_id", HTTP_Conflict)
4662 elif len(vim_nets)==0: # and action_dict:
4663 raise NfvoException("Not found a network at VIM with " + str(filter_dict), HTTP_Not_Found)
4664 net_list=[]
4665 for net in vim_nets:
4666 net_nfvo={'datacenter_id': datacenter_id}
4667 if action_dict and "name" in action_dict:
4668 net_nfvo['name'] = action_dict['name']
4669 else:
4670 net_nfvo['name'] = net['name']
4671 #net_nfvo['description']= net['name']
4672 net_nfvo['vim_net_id'] = net['id']
4673 net_nfvo['type'] = net['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
4674 net_nfvo['shared'] = net['shared']
4675 net_nfvo['multipoint'] = False if net['type']=='ptp' else True
4676 try:
4677 net_id = mydb.new_row("datacenter_nets", net_nfvo, add_uuid=True)
4678 net_nfvo["status"] = "OK"
4679 net_nfvo["uuid"] = net_id
4680 except db_base_Exception as e:
4681 if action_dict:
4682 raise
4683 else:
4684 net_nfvo["status"] = "FAIL: " + str(e)
4685 net_list.append(net_nfvo)
4686 return net_list
4687
4688 def get_sdn_net_id(mydb, tenant_id, datacenter, network_id):
4689 # obtain all network data
4690 try:
4691 if utils.check_valid_uuid(network_id):
4692 filter_dict = {"id": network_id}
4693 else:
4694 filter_dict = {"name": network_id}
4695
4696 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4697 network = myvim.get_network_list(filter_dict=filter_dict)
4698 except vimconn.vimconnException as e:
4699 raise NfvoException("Not possible to get_sdn_net_id from VIM: {}".format(str(e)), e.http_code)
4700
4701 # ensure the network is defined
4702 if len(network) == 0:
4703 raise NfvoException("Network {} is not present in the system".format(network_id),
4704 HTTP_Bad_Request)
4705
4706 # ensure there is only one network with the provided name
4707 if len(network) > 1:
4708 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id), HTTP_Bad_Request)
4709
4710 # ensure it is a dataplane network
4711 if network[0]['type'] != 'data':
4712 return None
4713
4714 # ensure we use the id
4715 network_id = network[0]['id']
4716
4717 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
4718 # and with instance_scenario_id==NULL
4719 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
4720 search_dict = {'vim_net_id': network_id}
4721
4722 try:
4723 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
4724 result = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)
4725 except db_base_Exception as e:
4726 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
4727 network_id) + str(e), e.http_code)
4728
4729 sdn_net_counter = 0
4730 for net in result:
4731 if net['sdn_net_id'] != None:
4732 sdn_net_counter+=1
4733 sdn_net_id = net['sdn_net_id']
4734
4735 if sdn_net_counter == 0:
4736 return None
4737 elif sdn_net_counter == 1:
4738 return sdn_net_id
4739 else:
4740 raise NfvoException("More than one SDN network is associated to vim network {}".format(
4741 network_id), HTTP_Internal_Server_Error)
4742
4743 def get_sdn_controller_id(mydb, datacenter):
4744 # Obtain sdn controller id
4745 config = mydb.get_rows(SELECT=('config',), FROM='datacenters', WHERE={'uuid': datacenter})[0].get('config', '{}')
4746 if not config:
4747 return None
4748
4749 return yaml.load(config).get('sdn-controller')
4750
4751 def vim_net_sdn_attach(mydb, tenant_id, datacenter, network_id, descriptor):
4752 try:
4753 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4754 if not sdn_network_id:
4755 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id), HTTP_Internal_Server_Error)
4756
4757 #Obtain sdn controller id
4758 controller_id = get_sdn_controller_id(mydb, datacenter)
4759 if not controller_id:
4760 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter), HTTP_Internal_Server_Error)
4761
4762 #Obtain sdn controller info
4763 sdn_controller = ovim.show_of_controller(controller_id)
4764
4765 port_data = {
4766 'name': 'external_port',
4767 'net_id': sdn_network_id,
4768 'ofc_id': controller_id,
4769 'switch_dpid': sdn_controller['dpid'],
4770 'switch_port': descriptor['port']
4771 }
4772
4773 if 'vlan' in descriptor:
4774 port_data['vlan'] = descriptor['vlan']
4775 if 'mac' in descriptor:
4776 port_data['mac'] = descriptor['mac']
4777
4778 result = ovim.new_port(port_data)
4779 except ovimException as e:
4780 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
4781 sdn_network_id, network_id) + str(e), HTTP_Internal_Server_Error)
4782 except db_base_Exception as e:
4783 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
4784 network_id) + str(e), e.http_code)
4785
4786 return 'Port uuid: '+ result
4787
4788 def vim_net_sdn_detach(mydb, tenant_id, datacenter, network_id, port_id=None):
4789 if port_id:
4790 filter = {'uuid': port_id}
4791 else:
4792 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, network_id)
4793 if not sdn_network_id:
4794 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id),
4795 HTTP_Internal_Server_Error)
4796 #in case no port_id is specified only ports marked as 'external_port' will be detached
4797 filter = {'name': 'external_port', 'net_id': sdn_network_id}
4798
4799 try:
4800 port_list = ovim.get_ports(columns={'uuid'}, filter=filter)
4801 except ovimException as e:
4802 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4803 HTTP_Internal_Server_Error)
4804
4805 if len(port_list) == 0:
4806 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id),
4807 HTTP_Bad_Request)
4808
4809 port_uuid_list = []
4810 for port in port_list:
4811 try:
4812 port_uuid_list.append(port['uuid'])
4813 ovim.delete_port(port['uuid'])
4814 except ovimException as e:
4815 raise NfvoException("ovimException deleting port {} for net {}. ".format(port['uuid'], network_id) + str(e), HTTP_Internal_Server_Error)
4816
4817 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list))
4818
4819 def vim_action_get(mydb, tenant_id, datacenter, item, name):
4820 #get datacenter info
4821 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4822 filter_dict={}
4823 if name:
4824 if utils.check_valid_uuid(name):
4825 filter_dict["id"] = name
4826 else:
4827 filter_dict["name"] = name
4828 try:
4829 if item=="networks":
4830 #filter_dict['tenant_id'] = myvim['tenant_id']
4831 content = myvim.get_network_list(filter_dict=filter_dict)
4832
4833 if len(content) == 0:
4834 raise NfvoException("Network {} is not present in the system. ".format(name),
4835 HTTP_Bad_Request)
4836
4837 #Update the networks with the attached ports
4838 for net in content:
4839 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, net['id'])
4840 if sdn_network_id != None:
4841 try:
4842 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
4843 port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id})
4844 except ovimException as e:
4845 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id) + str(e), HTTP_Internal_Server_Error)
4846 #Remove field name and if port name is external_port save it as 'type'
4847 for port in port_list:
4848 if port['name'] == 'external_port':
4849 port['type'] = "External"
4850 del port['name']
4851 net['sdn_network_id'] = sdn_network_id
4852 net['sdn_attached_ports'] = port_list
4853
4854 elif item=="tenants":
4855 content = myvim.get_tenant_list(filter_dict=filter_dict)
4856 elif item == "images":
4857
4858 content = myvim.get_image_list(filter_dict=filter_dict)
4859 else:
4860 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
4861 logger.debug("vim_action response %s", content) #update nets Change from VIM format to NFVO format
4862 if name and len(content)==1:
4863 return {item[:-1]: content[0]}
4864 elif name and len(content)==0:
4865 raise NfvoException("No {} found with ".format(item[:-1]) + " and ".join(map(lambda x: str(x[0])+": "+str(x[1]), filter_dict.iteritems())),
4866 datacenter)
4867 else:
4868 return {item: content}
4869 except vimconn.vimconnException as e:
4870 print "vim_action Not possible to get_%s_list from VIM: %s " % (item, str(e))
4871 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item, str(e)), e.http_code)
4872
4873
4874 def vim_action_delete(mydb, tenant_id, datacenter, item, name):
4875 #get datacenter info
4876 if tenant_id == "any":
4877 tenant_id=None
4878
4879 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4880 #get uuid name
4881 content = vim_action_get(mydb, tenant_id, datacenter, item, name)
4882 logger.debug("vim_action_delete vim response: " + str(content))
4883 items = content.values()[0]
4884 if type(items)==list and len(items)==0:
4885 raise NfvoException("Not found " + item, HTTP_Not_Found)
4886 elif type(items)==list and len(items)>1:
4887 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item), HTTP_Not_Found)
4888 else: # it is a dict
4889 item_id = items["id"]
4890 item_name = str(items.get("name"))
4891
4892 try:
4893 if item=="networks":
4894 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
4895 sdn_network_id = get_sdn_net_id(mydb, tenant_id, datacenter, item_id)
4896 if sdn_network_id != None:
4897 #Delete any port attachment to this network
4898 try:
4899 port_list = ovim.get_ports(columns={'uuid'}, filter={'net_id': sdn_network_id})
4900 except ovimException as e:
4901 raise NfvoException(
4902 "ovimException obtaining external ports for net {}. ".format(network_id) + str(e),
4903 HTTP_Internal_Server_Error)
4904
4905 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
4906 for port in port_list:
4907 vim_net_sdn_detach(mydb, tenant_id, datacenter, item_id, port['uuid'])
4908
4909 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
4910 try:
4911 mydb.delete_row(FROM='instance_nets', WHERE={'instance_scenario_id': None, 'sdn_net_id': sdn_network_id, 'vim_net_id': item_id})
4912 except db_base_Exception as e:
4913 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: ".format(correspondence) +
4914 str(e), e.http_code)
4915
4916 #Delete the SDN network
4917 try:
4918 ovim.delete_network(sdn_network_id)
4919 except ovimException as e:
4920 logger.error("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e), exc_info=True)
4921 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id) + str(e),
4922 HTTP_Internal_Server_Error)
4923
4924 content = myvim.delete_network(item_id)
4925 elif item=="tenants":
4926 content = myvim.delete_tenant(item_id)
4927 elif item == "images":
4928 content = myvim.delete_image(item_id)
4929 else:
4930 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
4931 except vimconn.vimconnException as e:
4932 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
4933 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item, name, str(e)), e.http_code)
4934
4935 return "{} {} {} deleted".format(item[:-1], item_id,item_name)
4936
4937
4938 def vim_action_create(mydb, tenant_id, datacenter, item, descriptor):
4939 #get datacenter info
4940 logger.debug("vim_action_create descriptor %s", str(descriptor))
4941 if tenant_id == "any":
4942 tenant_id=None
4943 datacenter_id, myvim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter)
4944 try:
4945 if item=="networks":
4946 net = descriptor["network"]
4947 net_name = net.pop("name")
4948 net_type = net.pop("type", "bridge")
4949 net_public = net.pop("shared", False)
4950 net_ipprofile = net.pop("ip_profile", None)
4951 net_vlan = net.pop("vlan", None)
4952 content = myvim.new_network(net_name, net_type, net_ipprofile, shared=net_public, vlan=net_vlan) #, **net)
4953
4954 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
4955 if get_sdn_controller_id(mydb, datacenter) != None and (net_type == 'data' or net_type == 'ptp'):
4956 #obtain datacenter_tenant_id
4957 datacenter_tenant_id = mydb.get_rows(SELECT=('uuid',),
4958 FROM='datacenter_tenants',
4959 WHERE={'datacenter_id': datacenter})[0]['uuid']
4960 try:
4961 sdn_network = {}
4962 sdn_network['vlan'] = net_vlan
4963 sdn_network['type'] = net_type
4964 sdn_network['name'] = net_name
4965 sdn_network['region'] = datacenter_tenant_id
4966 ovim_content = ovim.new_network(sdn_network)
4967 except ovimException as e:
4968 logger.error("ovimException creating SDN network={} ".format(
4969 sdn_network) + str(e), exc_info=True)
4970 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network) + str(e),
4971 HTTP_Internal_Server_Error)
4972
4973 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
4974 # use instance_scenario_id=None to distinguish from real instaces of nets
4975 correspondence = {'instance_scenario_id': None,
4976 'sdn_net_id': ovim_content,
4977 'vim_net_id': content,
4978 'datacenter_tenant_id': datacenter_tenant_id
4979 }
4980 try:
4981 mydb.new_row('instance_nets', correspondence, add_uuid=True)
4982 except db_base_Exception as e:
4983 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
4984 correspondence, e), e.http_code)
4985 elif item=="tenants":
4986 tenant = descriptor["tenant"]
4987 content = myvim.new_tenant(tenant["name"], tenant.get("description"))
4988 else:
4989 raise NfvoException(item + "?", HTTP_Method_Not_Allowed)
4990 except vimconn.vimconnException as e:
4991 raise NfvoException("Not possible to create {} at VIM: {}".format(item, str(e)), e.http_code)
4992
4993 return vim_action_get(mydb, tenant_id, datacenter, item, content)
4994
4995 def sdn_controller_create(mydb, tenant_id, sdn_controller):
4996 data = ovim.new_of_controller(sdn_controller)
4997 logger.debug('New SDN controller created with uuid {}'.format(data))
4998 return data
4999
5000 def sdn_controller_update(mydb, tenant_id, controller_id, sdn_controller):
5001 data = ovim.edit_of_controller(controller_id, sdn_controller)
5002 msg = 'SDN controller {} updated'.format(data)
5003 logger.debug(msg)
5004 return msg
5005
5006 def sdn_controller_list(mydb, tenant_id, controller_id=None):
5007 if controller_id == None:
5008 data = ovim.get_of_controllers()
5009 else:
5010 data = ovim.show_of_controller(controller_id)
5011
5012 msg = 'SDN controller list:\n {}'.format(data)
5013 logger.debug(msg)
5014 return data
5015
5016 def sdn_controller_delete(mydb, tenant_id, controller_id):
5017 select_ = ('uuid', 'config')
5018 datacenters = mydb.get_rows(FROM='datacenters', SELECT=select_)
5019 for datacenter in datacenters:
5020 if datacenter['config']:
5021 config = yaml.load(datacenter['config'])
5022 if 'sdn-controller' in config and config['sdn-controller'] == controller_id:
5023 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id, datacenter['uuid']), HTTP_Conflict)
5024
5025 data = ovim.delete_of_controller(controller_id)
5026 msg = 'SDN controller {} deleted'.format(data)
5027 logger.debug(msg)
5028 return msg
5029
5030 def datacenter_sdn_port_mapping_set(mydb, tenant_id, datacenter_id, sdn_port_mapping):
5031 controller = mydb.get_rows(FROM="datacenters", SELECT=("config",), WHERE={"uuid":datacenter_id})
5032 if len(controller) < 1:
5033 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id), HTTP_Not_Found)
5034
5035 try:
5036 sdn_controller_id = yaml.load(controller[0]["config"])["sdn-controller"]
5037 except:
5038 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id), HTTP_Bad_Request)
5039
5040 sdn_controller = ovim.show_of_controller(sdn_controller_id)
5041 switch_dpid = sdn_controller["dpid"]
5042
5043 maps = list()
5044 for compute_node in sdn_port_mapping:
5045 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5046 element = dict()
5047 element["compute_node"] = compute_node["compute_node"]
5048 for port in compute_node["ports"]:
5049 element["pci"] = port.get("pci")
5050 element["switch_port"] = port.get("switch_port")
5051 element["switch_mac"] = port.get("switch_mac")
5052 if not element["pci"] or not (element["switch_port"] or element["switch_mac"]):
5053 raise NfvoException ("The mapping must contain the 'pci' and at least one of the elements 'switch_port'"
5054 " or 'switch_mac'", HTTP_Bad_Request)
5055 maps.append(dict(element))
5056
5057 return ovim.set_of_port_mapping(maps, ofc_id=sdn_controller_id, switch_dpid=switch_dpid, region=datacenter_id)
5058
5059 def datacenter_sdn_port_mapping_list(mydb, tenant_id, datacenter_id):
5060 maps = ovim.get_of_port_mappings(db_filter={"region": datacenter_id})
5061
5062 result = {
5063 "sdn-controller": None,
5064 "datacenter-id": datacenter_id,
5065 "dpid": None,
5066 "ports_mapping": list()
5067 }
5068
5069 datacenter = mydb.get_table_by_uuid_name('datacenters', datacenter_id)
5070 if datacenter['config']:
5071 config = yaml.load(datacenter['config'])
5072 if 'sdn-controller' in config:
5073 controller_id = config['sdn-controller']
5074 sdn_controller = sdn_controller_list(mydb, tenant_id, controller_id)
5075 result["sdn-controller"] = controller_id
5076 result["dpid"] = sdn_controller["dpid"]
5077
5078 if result["sdn-controller"] == None:
5079 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id), HTTP_Bad_Request)
5080 if result["dpid"] == None:
5081 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result["sdn-controller"]),
5082 HTTP_Internal_Server_Error)
5083
5084 if len(maps) == 0:
5085 return result
5086
5087 ports_correspondence_dict = dict()
5088 for link in maps:
5089 if result["sdn-controller"] != link["ofc_id"]:
5090 raise NfvoException("The sdn-controller specified for different port mappings differ", HTTP_Internal_Server_Error)
5091 if result["dpid"] != link["switch_dpid"]:
5092 raise NfvoException("The dpid specified for different port mappings differ", HTTP_Internal_Server_Error)
5093 element = dict()
5094 element["pci"] = link["pci"]
5095 if link["switch_port"]:
5096 element["switch_port"] = link["switch_port"]
5097 if link["switch_mac"]:
5098 element["switch_mac"] = link["switch_mac"]
5099
5100 if not link["compute_node"] in ports_correspondence_dict:
5101 content = dict()
5102 content["compute_node"] = link["compute_node"]
5103 content["ports"] = list()
5104 ports_correspondence_dict[link["compute_node"]] = content
5105
5106 ports_correspondence_dict[link["compute_node"]]["ports"].append(element)
5107
5108 for key in sorted(ports_correspondence_dict):
5109 result["ports_mapping"].append(ports_correspondence_dict[key])
5110
5111 return result
5112
5113 def datacenter_sdn_port_mapping_delete(mydb, tenant_id, datacenter_id):
5114 return ovim.clear_of_port_mapping(db_filter={"region":datacenter_id})
5115
5116 def create_RO_keypair(tenant_id):
5117 """
5118 Creates a public / private keys for a RO tenant and returns their values
5119 Params:
5120 tenant_id: ID of the tenant
5121 Return:
5122 public_key: Public key for the RO tenant
5123 private_key: Encrypted private key for RO tenant
5124 """
5125
5126 bits = 2048
5127 key = RSA.generate(bits)
5128 try:
5129 public_key = key.publickey().exportKey('OpenSSH')
5130 if isinstance(public_key, ValueError):
5131 raise NfvoException("Unable to create public key: {}".format(public_key), HTTP_Internal_Server_Error)
5132 private_key = key.exportKey(passphrase=tenant_id, pkcs=8)
5133 except (ValueError, NameError) as e:
5134 raise NfvoException("Unable to create private key: {}".format(e), HTTP_Internal_Server_Error)
5135 return public_key, private_key
5136
5137 def decrypt_key (key, tenant_id):
5138 """
5139 Decrypts an encrypted RSA key
5140 Params:
5141 key: Private key to be decrypted
5142 tenant_id: ID of the tenant
5143 Return:
5144 unencrypted_key: Unencrypted private key for RO tenant
5145 """
5146 try:
5147 key = RSA.importKey(key,tenant_id)
5148 unencrypted_key = key.exportKey('PEM')
5149 if isinstance(unencrypted_key, ValueError):
5150 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key), HTTP_Internal_Server_Error)
5151 except ValueError as e:
5152 raise NfvoException("Unable to decrypt the private key: {}".format(e), HTTP_Internal_Server_Error)
5153 return unencrypted_key