1 # -*- coding: utf-8 -*-
4 # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
5 # This file is part of openmano
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
12 # http://www.apache.org/licenses/LICENSE-2.0
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
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
25 NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
27 __author__
="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28 __date__
="$16-sep-2014 22:05:01$"
34 from random
import choice
as random_choice
35 from osm_ro
import utils
36 from osm_ro
.utils
import deprecated
37 from osm_ro
.vim_thread
import vim_thread
38 import osm_ro
.console_proxy_thread
as cli
39 from osm_ro_plugin
.vim_dummy
import VimDummyConnector
40 from osm_ro_plugin
.sdn_dummy
import SdnDummyConnector
41 from osm_ro_plugin
.sdn_failing
import SdnFailingConnector
42 from osm_ro_plugin
import vimconn
, sdnconn
46 from uuid
import uuid4
47 from osm_ro
.db_base
import db_base_Exception
49 from osm_ro
import nfvo_db
50 from threading
import Lock
52 from osm_ro
.sdn
import Sdn
, SdnException
as ovimException
54 from Crypto
.PublicKey
import RSA
56 import osm_im
.vnfd
as vnfd_catalog
57 import osm_im
.nsd
as nsd_catalog
58 from pyangbind
.lib
.serialise
import pybindJSONDecoder
59 from copy
import deepcopy
60 from pkg_resources
import iter_entry_points
64 from .http_tools
import errors
as httperrors
65 from .wim
.engine
import WimEngine
66 from .wim
.persistence
import WimPersistence
67 from copy
import deepcopy
68 from pprint
import pformat
75 global sdnconn_imported
78 global default_volume_size
79 default_volume_size
= '5' #size in GB
84 plugins
= {} # dictionary with VIM type as key, loaded module as value
85 vim_threads
= {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
86 vim_persistent_info
= {}
88 sdnconn_imported
= {} # dictionary with WIM type as key, loaded module as value
89 wim_threads
= {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
90 wim_persistent_info
= {}
93 logger
= logging
.getLogger('openmano.nfvo')
101 class NfvoException(httperrors
.HttpMappedError
):
102 """Common Class for NFVO errors"""
104 def _load_plugin(name
, type="vim"):
105 # type can be vim or sdn
108 for v
in iter_entry_points('osm_ro{}.plugins'.format(type), name
):
109 plugins
[name
] = v
.load()
110 except Exception as e
:
111 logger
.critical("Cannot load osm_{}: {}".format(name
, e
))
113 plugins
[name
] = SdnFailingConnector("Cannot load osm_{}: {}".format(name
, e
))
114 if name
and name
not in plugins
:
115 error_text
= "Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been" \
116 " registered".format(t
=type, n
=name
)
117 logger
.critical(error_text
)
118 plugins
[name
] = SdnFailingConnector(error_text
)
119 # raise NfvoException("Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been registered".
120 # format(t=type, n=name), httperrors.Bad_Request)
125 if task_id
<= last_task_id
:
126 task_id
= last_task_id
+ 0.000001
127 last_task_id
= task_id
128 return "ACTION-{:.6f}".format(task_id
)
129 # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6))
132 def new_task(name
, params
, depends
=None):
134 task_id
= get_task_id()
135 task
= {"status": "enqueued", "id": task_id
, "name": name
, "params": params
}
137 task
["depends"] = depends
142 return True if id[:5] == "TASK-" else False
144 def get_process_id():
146 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
147 will provide a random one
150 # Try getting docker id. If fails, get pid
152 with
open("/proc/self/cgroup", "r") as f
:
153 for text_id_
in f
.readlines():
154 if "docker/" not in text_id_
:
156 _
, _
, text_id
= text_id_
.rpartition("/")
157 text_id
= text_id
.replace("\n", "")[:12]
163 return "".join(random_choice("0123456789abcdef") for _
in range(12))
165 def get_non_used_vim_name(datacenter_name
, datacenter_id
):
166 return "{}:{}:{}".format(
167 worker_id
[:12], datacenter_id
.replace("-", "")[:32], datacenter_name
[:16]
171 def get_non_used_wim_name(wim_name
, wim_id
, tenant_name
, tenant_id
):
173 if name
not in wim_threads
["names"]:
174 wim_threads
["names"].append(name
)
176 name
= wim_name
[:16] + "." + tenant_name
[:16]
177 if name
not in wim_threads
["names"]:
178 wim_threads
["names"].append(name
)
180 name
= wim_id
+ "-" + tenant_id
181 wim_threads
["names"].append(name
)
185 def start_service(mydb
, persistence
=None, wim
=None):
186 global db
, global_config
, plugins
, ovim
, worker_id
187 db
= nfvo_db
.nfvo_db(lock
=db_lock
)
189 db
.connect(global_config
['db_host'], global_config
['db_user'], global_config
['db_passwd'], global_config
['db_name'])
191 persistence
= persistence
or WimPersistence(db
)
194 worker_id
= get_process_id()
195 if "rosdn_dummy" not in plugins
:
196 plugins
["rosdn_dummy"] = SdnDummyConnector
197 if "rovim_dummy" not in plugins
:
198 plugins
["rovim_dummy"] = VimDummyConnector
199 # starts ovim library
200 ovim
= Sdn(db
, plugins
)
203 wim_engine
= wim
or WimEngine(persistence
, plugins
)
204 wim_engine
.ovim
= ovim
208 #delete old unneeded vim_wim_actions
212 from_
= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
213 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
214 select_
= ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
215 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
216 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
217 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
218 vims
= mydb
.get_rows(FROM
=from_
, SELECT
=select_
)
220 extra
={'datacenter_tenant_id': vim
.get('datacenter_tenant_id'),
221 'datacenter_id': vim
.get('datacenter_id')}
223 extra
.update(yaml
.load(vim
["config"], Loader
=yaml
.Loader
))
224 if vim
.get('dt_config'):
225 extra
.update(yaml
.load(vim
["dt_config"], Loader
=yaml
.Loader
))
226 plugin_name
= "rovim_" + vim
["type"]
227 if plugin_name
not in plugins
:
228 _load_plugin(plugin_name
, type="vim")
230 thread_id
= vim
['datacenter_tenant_id']
231 vim_persistent_info
[thread_id
] = {}
234 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
235 myvim
= plugins
[plugin_name
](
236 uuid
=vim
['datacenter_id'], name
=vim
['datacenter_name'],
237 tenant_id
=vim
['vim_tenant_id'], tenant_name
=vim
['vim_tenant_name'],
238 url
=vim
['vim_url'], url_admin
=vim
['vim_url_admin'],
239 user
=vim
['user'], passwd
=vim
['passwd'],
240 config
=extra
, persistent_info
=vim_persistent_info
[thread_id
]
242 except vimconn
.VimConnException
as e
:
244 logger
.error("Cannot launch thread for VIM {} '{}': {}".format(vim
['datacenter_name'],
245 vim
['datacenter_id'], e
))
246 except Exception as e
:
247 logger
.critical("Cannot launch thread for VIM {} '{}': {}".format(vim
['datacenter_name'],
248 vim
['datacenter_id'], e
))
249 # raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
250 # httperrors.Internal_Server_Error)
251 thread_name
= get_non_used_vim_name(vim
['datacenter_name'], vim
['datacenter_id'])
252 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, None,
253 vim
['datacenter_tenant_id'], db
=db
)
255 vim_threads
["running"][thread_id
] = new_thread
256 wims
= mydb
.get_rows(FROM
="wim_accounts join wims on wim_accounts.wim_id=wims.uuid",
257 WHERE
={"sdn": "true"},
258 SELECT
=("wim_accounts.uuid as uuid", "type", "wim_accounts.name as name"))
260 plugin_name
= "rosdn_" + wim
["type"]
261 if plugin_name
not in plugins
:
262 _load_plugin(plugin_name
, type="sdn")
264 thread_id
= wim
['uuid']
265 thread_name
= get_non_used_vim_name(wim
['name'], wim
['uuid'])
266 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, wim
['uuid'], None, db
=db
)
268 vim_threads
["running"][thread_id
] = new_thread
269 wim_engine
.start_threads()
270 except db_base_Exception
as e
:
271 raise NfvoException(str(e
) + " at nfvo.get_vim", e
.http_code
)
272 except ovimException
as e
:
274 if message
[:22] == "DATABASE wrong version":
275 message
= "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
276 "at host {dbhost}".format(
277 msg
=message
[22:-3], dbname
=global_config
["db_ovim_name"],
278 dbuser
=global_config
["db_ovim_user"], dbpass
=global_config
["db_ovim_passwd"],
279 ver
=message
[-3:-1], dbhost
=global_config
["db_ovim_host"])
280 raise NfvoException(message
, httperrors
.Bad_Request
)
284 global ovim
, global_config
287 for thread_id
, thread
in vim_threads
["running"].items():
288 thread
.insert_task("exit")
289 vim_threads
["deleting"][thread_id
] = thread
290 vim_threads
["running"] = {}
293 wim_engine
.stop_threads()
295 if global_config
and global_config
.get("console_thread"):
296 for thread
in global_config
["console_thread"]:
297 thread
.terminate
= True
300 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config
["version"],
301 global_config
["version_date"] ))
305 Clean unused or old entries at database to avoid unlimited growing
306 :param mydb: database connector
309 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
310 now
= t
.time()-3600*24*7
311 instance_action_id
= None
314 actions_to_delete
= mydb
.get_rows(
315 SELECT
=("item", "item_id", "instance_action_id"),
316 FROM
="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
317 "left join instance_scenarios as i on ia.instance_id=i.uuid",
318 WHERE
={"va.action": "DELETE", "va.modified_at<": now
, "i.uuid": None,
319 "va.status": ("DONE", "SUPERSEDED")},
322 for to_delete
in actions_to_delete
:
323 mydb
.delete_row(FROM
="vim_wim_actions", WHERE
=to_delete
)
324 if instance_action_id
!= to_delete
["instance_action_id"]:
325 instance_action_id
= to_delete
["instance_action_id"]
326 mydb
.delete_row(FROM
="instance_actions", WHERE
={"uuid": instance_action_id
})
327 nb_deleted
+= len(actions_to_delete
)
328 if len(actions_to_delete
) < 100:
331 mydb
.update_rows("vim_wim_actions", UPDATE
={"worker": None}, WHERE
={"worker<>": None})
334 logger
.debug("Removed {} unused vim_wim_actions".format(nb_deleted
))
337 def get_flavorlist(mydb
, vnf_id
, nfvo_tenant
=None):
339 return result, content:
340 <0, error_text upon error
341 nb_records, flavor_list on success
344 WHERE_dict
['vnf_id'] = vnf_id
345 if nfvo_tenant
is not None:
346 WHERE_dict
['nfvo_tenant_id'] = nfvo_tenant
348 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
349 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
350 flavors
= mydb
.get_rows(FROM
='vms join flavors on vms.flavor_id=flavors.uuid',SELECT
=('flavor_id',),WHERE
=WHERE_dict
)
351 #print "get_flavor_list result:", result
352 #print "get_flavor_list content:", content
354 for flavor
in flavors
:
355 flavorList
.append(flavor
['flavor_id'])
359 def get_imagelist(mydb
, vnf_id
, nfvo_tenant
=None):
361 Get used images of all vms belonging to this VNFD
362 :param mydb: database conector
363 :param vnf_id: vnfd uuid
364 :param nfvo_tenant: tenant, not used
365 :return: The list of image uuid used
368 vms
= mydb
.get_rows(SELECT
=('image_id','image_list'), FROM
='vms', WHERE
={'vnf_id': vnf_id
})
370 if vm
["image_id"] and vm
["image_id"] not in image_list
:
371 image_list
.append(vm
["image_id"])
373 vm_image_list
= yaml
.load(vm
["image_list"], Loader
=yaml
.Loader
)
374 for image_dict
in vm_image_list
:
375 if image_dict
["image_id"] not in image_list
:
376 image_list
.append(image_dict
["image_id"])
380 def get_vim(mydb
, nfvo_tenant
=None, datacenter_id
=None, datacenter_name
=None, datacenter_tenant_id
=None,
381 vim_tenant
=None, vim_tenant_name
=None, vim_user
=None, vim_passwd
=None, ignore_errors
=False):
382 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
383 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
384 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
385 raise exception upon error
389 if nfvo_tenant
is not None: WHERE_dict
['nfvo_tenant_id'] = nfvo_tenant
390 if datacenter_id
is not None: WHERE_dict
['d.uuid'] = datacenter_id
391 if datacenter_tenant_id
is not None: WHERE_dict
['datacenter_tenant_id'] = datacenter_tenant_id
392 if datacenter_name
is not None: WHERE_dict
['d.name'] = datacenter_name
393 if vim_tenant
is not None: WHERE_dict
['dt.vim_tenant_id'] = vim_tenant
394 if vim_tenant_name
is not None: WHERE_dict
['vim_tenant_name'] = vim_tenant_name
395 if nfvo_tenant
or vim_tenant
or vim_tenant_name
or datacenter_tenant_id
:
396 from_
= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
397 select_
= ('type','d.config as config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
398 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
399 'user','passwd', 'dt.config as dt_config')
401 from_
= 'datacenters as d'
402 select_
= ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
404 vims
= mydb
.get_rows(FROM
=from_
, SELECT
=select_
, WHERE
=WHERE_dict
)
407 extra
={'datacenter_tenant_id': vim
.get('datacenter_tenant_id'),
408 'datacenter_id': vim
.get('datacenter_id'),
409 '_vim_type_internal': vim
.get('type')}
411 extra
.update(yaml
.load(vim
["config"], Loader
=yaml
.Loader
))
412 if vim
.get('dt_config'):
413 extra
.update(yaml
.load(vim
["dt_config"], Loader
=yaml
.Loader
))
414 plugin_name
= "rovim_" + vim
["type"]
415 if plugin_name
not in plugins
:
417 _load_plugin(plugin_name
, type="vim")
418 except NfvoException
as e
:
420 logger
.error("{}".format(e
))
425 if 'datacenter_tenant_id' in vim
:
426 thread_id
= vim
["datacenter_tenant_id"]
427 if thread_id
not in vim_persistent_info
:
428 vim_persistent_info
[thread_id
] = {}
429 persistent_info
= vim_persistent_info
[thread_id
]
433 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
434 vim_dict
[vim
['datacenter_id']] = plugins
[plugin_name
](
435 uuid
=vim
['datacenter_id'], name
=vim
['datacenter_name'],
436 tenant_id
=vim
.get('vim_tenant_id',vim_tenant
),
437 tenant_name
=vim
.get('vim_tenant_name',vim_tenant_name
),
438 url
=vim
['vim_url'], url_admin
=vim
['vim_url_admin'],
439 user
=vim
.get('user',vim_user
), passwd
=vim
.get('passwd',vim_passwd
),
440 config
=extra
, persistent_info
=persistent_info
442 except Exception as e
:
444 logger
.error("Error at VIM {}; {}: {}".format(vim
["type"], type(e
).__name
__, str(e
)))
446 http_code
= httperrors
.Internal_Server_Error
447 if isinstance(e
, vimconn
.VimConnException
):
448 http_code
= e
.http_code
449 raise NfvoException("Error at VIM {}; {}: {}".format(vim
["type"], type(e
).__name
__, str(e
)), http_code
)
451 except db_base_Exception
as e
:
452 raise NfvoException(str(e
) + " at nfvo.get_vim", e
.http_code
)
455 def rollback(mydb
, vims
, rollback_list
):
457 #delete things by reverse order
458 for i
in range(len(rollback_list
)-1, -1, -1):
459 item
= rollback_list
[i
]
460 if item
["where"]=="vim":
461 if item
["vim_id"] not in vims
:
463 if is_task_id(item
["uuid"]):
465 vim
= vims
[item
["vim_id"]]
467 if item
["what"]=="image":
468 vim
.delete_image(item
["uuid"])
469 mydb
.delete_row(FROM
="datacenters_images", WHERE
={"datacenter_vim_id": vim
["id"], "vim_id":item
["uuid"]})
470 elif item
["what"]=="flavor":
471 vim
.delete_flavor(item
["uuid"])
472 mydb
.delete_row(FROM
="datacenters_flavors", WHERE
={"datacenter_vim_id": vim
["id"], "vim_id":item
["uuid"]})
473 elif item
["what"]=="network":
474 vim
.delete_network(item
["uuid"])
475 elif item
["what"]=="vm":
476 vim
.delete_vminstance(item
["uuid"])
477 except vimconn
.VimConnException
as e
:
478 logger
.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item
['what'], item
["uuid"], str(e
))
479 undeleted_items
.append("{} {} from VIM {}".format(item
['what'], item
["uuid"], vim
["name"]))
480 except db_base_Exception
as e
:
481 logger
.error("Error in rollback. Not possible to delete %s '%s' from DB.datacenters Message: %s", item
['what'], item
["uuid"], str(e
))
485 if item
["what"]=="image":
486 mydb
.delete_row(FROM
="images", WHERE
={"uuid": item
["uuid"]})
487 elif item
["what"]=="flavor":
488 mydb
.delete_row(FROM
="flavors", WHERE
={"uuid": item
["uuid"]})
489 except db_base_Exception
as e
:
490 logger
.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item
['what'], item
["uuid"], str(e
))
491 undeleted_items
.append("{} '{}'".format(item
['what'], item
["uuid"]))
492 if len(undeleted_items
)==0:
493 return True, "Rollback successful."
495 return False, "Rollback fails to delete: " + str(undeleted_items
)
498 def check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=1):
500 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
502 for vnfc
in vnf_descriptor
["vnf"]["VNFC"]:
504 #dataplane interfaces
505 for numa
in vnfc
.get("numas",() ):
506 for interface
in numa
.get("interfaces",()):
507 if interface
["name"] in name_dict
:
509 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
510 vnfc
["name"], interface
["name"]),
511 httperrors
.Bad_Request
)
512 name_dict
[ interface
["name"] ] = "underlay"
514 for interface
in vnfc
.get("bridge-ifaces",() ):
515 if interface
["name"] in name_dict
:
517 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
518 vnfc
["name"], interface
["name"]),
519 httperrors
.Bad_Request
)
520 name_dict
[ interface
["name"] ] = "overlay"
521 vnfc_interfaces
[ vnfc
["name"] ] = name_dict
522 # check bood-data info
523 # if "boot-data" in vnfc:
524 # # check that user-data is incompatible with users and config-files
525 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
526 # raise NfvoException(
527 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
528 # httperrors.Bad_Request)
530 #check if the info in external_connections matches with the one in the vnfcs
532 for external_connection
in vnf_descriptor
["vnf"].get("external-connections",() ):
533 if external_connection
["name"] in name_list
:
535 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
536 external_connection
["name"]),
537 httperrors
.Bad_Request
)
538 name_list
.append(external_connection
["name"])
539 if external_connection
["VNFC"] not in vnfc_interfaces
:
541 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
542 external_connection
["name"], external_connection
["VNFC"]),
543 httperrors
.Bad_Request
)
545 if external_connection
["local_iface_name"] not in vnfc_interfaces
[ external_connection
["VNFC"] ]:
547 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
548 external_connection
["name"],
549 external_connection
["local_iface_name"]),
550 httperrors
.Bad_Request
)
552 #check if the info in internal_connections matches with the one in the vnfcs
554 for internal_connection
in vnf_descriptor
["vnf"].get("internal-connections",() ):
555 if internal_connection
["name"] in name_list
:
557 "Error at vnf:internal-connections:name, value '{}' already used as an internal-connection".format(
558 internal_connection
["name"]),
559 httperrors
.Bad_Request
)
560 name_list
.append(internal_connection
["name"])
561 #We should check that internal-connections of type "ptp" have only 2 elements
563 if len(internal_connection
["elements"])>2 and (internal_connection
.get("type") == "ptp" or internal_connection
.get("type") == "e-line"):
565 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
566 internal_connection
["name"],
567 'ptp' if vnf_descriptor_version
==1 else 'e-line',
568 'data' if vnf_descriptor_version
==1 else "e-lan"),
569 httperrors
.Bad_Request
)
570 for port
in internal_connection
["elements"]:
572 iface
= port
["local_iface_name"]
573 if vnf
not in vnfc_interfaces
:
575 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
576 internal_connection
["name"], vnf
),
577 httperrors
.Bad_Request
)
578 if iface
not in vnfc_interfaces
[ vnf
]:
580 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
581 internal_connection
["name"], iface
),
582 httperrors
.Bad_Request
)
583 return -httperrors
.Bad_Request
,
584 if vnf_descriptor_version
==1 and "type" not in internal_connection
:
585 if vnfc_interfaces
[vnf
][iface
] == "overlay":
586 internal_connection
["type"] = "bridge"
588 internal_connection
["type"] = "data"
589 if vnf_descriptor_version
==2 and "implementation" not in internal_connection
:
590 if vnfc_interfaces
[vnf
][iface
] == "overlay":
591 internal_connection
["implementation"] = "overlay"
593 internal_connection
["implementation"] = "underlay"
594 if (internal_connection
.get("type") == "data" or internal_connection
.get("type") == "ptp" or \
595 internal_connection
.get("implementation") == "underlay") and vnfc_interfaces
[vnf
][iface
] == "overlay":
597 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
598 internal_connection
["name"],
599 iface
, 'bridge' if vnf_descriptor_version
==1 else 'overlay',
600 'data' if vnf_descriptor_version
==1 else 'underlay'),
601 httperrors
.Bad_Request
)
602 if (internal_connection
.get("type") == "bridge" or internal_connection
.get("implementation") == "overlay") and \
603 vnfc_interfaces
[vnf
][iface
] == "underlay":
605 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
606 internal_connection
["name"], iface
,
607 'data' if vnf_descriptor_version
==1 else 'underlay',
608 'bridge' if vnf_descriptor_version
==1 else 'overlay'),
609 httperrors
.Bad_Request
)
612 def create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
=None):
614 if only_create_at_vim
:
615 image_mano_id
= image_dict
['uuid']
616 if return_on_error
== None:
617 return_on_error
= True
619 if image_dict
['location']:
620 images
= mydb
.get_rows(FROM
="images", WHERE
={'location':image_dict
['location'], 'metadata':image_dict
['metadata']})
622 images
= mydb
.get_rows(FROM
="images", WHERE
={'universal_name':image_dict
['universal_name'], 'checksum':image_dict
['checksum']})
624 image_mano_id
= images
[0]['uuid']
626 #create image in MANO DB
627 temp_image_dict
={'name':image_dict
['name'], 'description':image_dict
.get('description',None),
628 'location':image_dict
['location'], 'metadata':image_dict
.get('metadata',None),
629 'universal_name':image_dict
['universal_name'] , 'checksum':image_dict
['checksum']
631 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
632 image_mano_id
= mydb
.new_row('images', temp_image_dict
, add_uuid
=True)
633 rollback_list
.append({"where":"mano", "what":"image","uuid":image_mano_id
})
634 #create image at every vim
635 for vim_id
,vim
in vims
.items():
636 datacenter_vim_id
= vim
["config"]["datacenter_tenant_id"]
637 image_created
="false"
639 image_db
= mydb
.get_rows(FROM
="datacenters_images",
640 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'image_id': image_mano_id
})
641 #look at VIM if this image exist
643 if image_dict
['location'] is not None:
644 image_vim_id
= vim
.get_image_id_from_path(image_dict
['location'])
647 filter_dict
['name'] = image_dict
['universal_name']
648 if image_dict
.get('checksum') != None:
649 filter_dict
['checksum'] = image_dict
['checksum']
650 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
651 vim_images
= vim
.get_image_list(filter_dict
)
652 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
653 if len(vim_images
) > 1:
654 raise vimconn
.VimConnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict
)), httperrors
.Conflict
)
655 elif len(vim_images
) == 0:
656 raise vimconn
.VimConnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict
)))
658 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
659 image_vim_id
= vim_images
[0]['id']
661 except vimconn
.VimConnNotFoundException
as e
:
662 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
664 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
665 if image_dict
['location']:
666 image_vim_id
= vim
.new_image(image_dict
)
667 rollback_list
.append({"where":"vim", "vim_id": vim_id
, "what":"image","uuid":image_vim_id
})
670 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
671 raise vimconn
.VimConnException(str(e
))
672 except vimconn
.VimConnException
as e
:
674 logger
.error("Error creating image at VIM '%s': %s", vim
["name"], str(e
))
677 logger
.warn("Error creating image at VIM '%s': %s", vim
["name"], str(e
))
679 except vimconn
.VimConnException
as e
:
681 logger
.error("Error contacting VIM to know if the image exists at VIM: %s", str(e
))
683 logger
.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e
))
686 #if we reach here, the image has been created or existed
688 #add new vim_id at datacenters_images
689 mydb
.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id
,
690 'image_id':image_mano_id
,
691 'vim_id': image_vim_id
,
692 'created':image_created
})
693 elif image_db
[0]["vim_id"]!=image_vim_id
:
694 #modify existing vim_id at datacenters_images
695 mydb
.update_rows('datacenters_images', UPDATE
={'vim_id':image_vim_id
}, WHERE
={'datacenter_vim_id':vim_id
, 'image_id':image_mano_id
})
697 return image_vim_id
if only_create_at_vim
else image_mano_id
700 def create_or_use_flavor(mydb
, vims
, flavor_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
= None):
701 temp_flavor_dict
= {'disk':flavor_dict
.get('disk',0),
702 'ram':flavor_dict
.get('ram'),
703 'vcpus':flavor_dict
.get('vcpus'),
705 if 'extended' in flavor_dict
and flavor_dict
['extended']==None:
706 del flavor_dict
['extended']
707 if 'extended' in flavor_dict
:
708 temp_flavor_dict
['extended']=yaml
.safe_dump(flavor_dict
['extended'],default_flow_style
=True,width
=256)
710 #look if flavor exist
711 if only_create_at_vim
:
712 flavor_mano_id
= flavor_dict
['uuid']
713 if return_on_error
== None:
714 return_on_error
= True
716 flavors
= mydb
.get_rows(FROM
="flavors", WHERE
=temp_flavor_dict
)
718 flavor_mano_id
= flavors
[0]['uuid']
721 #create one by one the images of aditional disks
722 dev_image_list
=[] #list of images
723 if 'extended' in flavor_dict
and flavor_dict
['extended']!=None:
725 for device
in flavor_dict
['extended'].get('devices',[]):
726 if "image" not in device
and "image name" not in device
:
729 image_dict
['name']=device
.get('image name',flavor_dict
['name']+str(dev_nb
)+"-img")
730 image_dict
['universal_name']=device
.get('image name')
731 image_dict
['description']=flavor_dict
['name']+str(dev_nb
)+"-img"
732 image_dict
['location']=device
.get('image')
733 #image_dict['new_location']=vnfc.get('image location')
734 image_dict
['checksum']=device
.get('image checksum')
735 image_metadata_dict
= device
.get('image metadata', None)
736 image_metadata_str
= None
737 if image_metadata_dict
!= None:
738 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
739 image_dict
['metadata']=image_metadata_str
740 image_id
= create_or_use_image(mydb
, vims
, image_dict
, rollback_list
)
741 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
742 dev_image_list
.append(image_id
)
744 temp_flavor_dict
['name'] = flavor_dict
['name']
745 temp_flavor_dict
['description'] = flavor_dict
.get('description',None)
746 content
= mydb
.new_row('flavors', temp_flavor_dict
, add_uuid
=True)
747 flavor_mano_id
= content
748 rollback_list
.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id
})
749 #create flavor at every vim
750 if 'uuid' in flavor_dict
:
751 del flavor_dict
['uuid']
753 for vim_id
,vim
in vims
.items():
754 datacenter_vim_id
= vim
["config"]["datacenter_tenant_id"]
755 flavor_created
="false"
757 flavor_db
= mydb
.get_rows(FROM
="datacenters_flavors",
758 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
})
759 #look at VIM if this flavor exist SKIPPED
760 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
762 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
766 # Create the flavor in VIM
767 # Translate images at devices from MANO id to VIM id
769 if 'extended' in flavor_dict
and flavor_dict
['extended']!=None and "devices" in flavor_dict
['extended']:
770 # make a copy of original devices
773 for device
in flavor_dict
["extended"].get("devices",[]):
776 devices_original
.append(dev
)
777 if 'image' in device
:
779 if 'image metadata' in device
:
780 del device
['image metadata']
781 if 'image checksum' in device
:
782 del device
['image checksum']
784 for index
in range(0,len(devices_original
)) :
785 device
=devices_original
[index
]
786 if "image" not in device
and "image name" not in device
:
787 # if 'size' in device:
788 disk_list
.append({'size': device
.get('size', default_volume_size
), 'name': device
.get('name')})
791 image_dict
['name']=device
.get('image name',flavor_dict
['name']+str(dev_nb
)+"-img")
792 image_dict
['universal_name']=device
.get('image name')
793 image_dict
['description']=flavor_dict
['name']+str(dev_nb
)+"-img"
794 image_dict
['location']=device
.get('image')
795 # image_dict['new_location']=device.get('image location')
796 image_dict
['checksum']=device
.get('image checksum')
797 image_metadata_dict
= device
.get('image metadata', None)
798 image_metadata_str
= None
799 if image_metadata_dict
!= None:
800 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
801 image_dict
['metadata']=image_metadata_str
802 image_mano_id
=create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
=return_on_error
)
803 image_dict
["uuid"]=image_mano_id
804 image_vim_id
=create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=True, return_on_error
=return_on_error
)
806 #save disk information (image must be based on and size
807 disk_list
.append({'image_id': image_vim_id
, 'size': device
.get('size', default_volume_size
)})
809 flavor_dict
["extended"]["devices"][index
]['imageRef']=image_vim_id
812 #check that this vim_id exist in VIM, if not create
813 flavor_vim_id
=flavor_db
[0]["vim_id"]
815 vim
.get_flavor(flavor_vim_id
)
816 continue #flavor exist
817 except vimconn
.VimConnException
:
819 #create flavor at vim
820 logger
.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim
["name"])
823 flavor_vim_id
=vim
.get_flavor_id_from_data(flavor_dict
)
824 flavor_created
="false"
825 except vimconn
.VimConnException
as e
:
828 if not flavor_vim_id
:
829 flavor_vim_id
= vim
.new_flavor(flavor_dict
)
830 rollback_list
.append({"where":"vim", "vim_id": vim_id
, "what":"flavor","uuid":flavor_vim_id
})
831 flavor_created
="true"
832 except vimconn
.VimConnException
as e
:
834 logger
.error("Error creating flavor at VIM %s: %s.", vim
["name"], str(e
))
836 logger
.warn("Error creating flavor at VIM %s: %s.", vim
["name"], str(e
))
839 #if reach here the flavor has been create or exist
840 if len(flavor_db
)==0:
841 #add new vim_id at datacenters_flavors
842 extended_devices_yaml
= None
843 if len(disk_list
) > 0:
844 extended_devices
= dict()
845 extended_devices
['disks'] = disk_list
846 extended_devices_yaml
= yaml
.safe_dump(extended_devices
,default_flow_style
=True,width
=256)
847 mydb
.new_row('datacenters_flavors',
848 {'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
, 'vim_id': flavor_vim_id
,
849 'created': flavor_created
, 'extended': extended_devices_yaml
})
850 elif flavor_db
[0]["vim_id"]!=flavor_vim_id
:
851 #modify existing vim_id at datacenters_flavors
852 mydb
.update_rows('datacenters_flavors', UPDATE
={'vim_id':flavor_vim_id
},
853 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
})
855 return flavor_vim_id
if only_create_at_vim
else flavor_mano_id
858 def get_str(obj
, field
, length
):
860 Obtain the str value,
865 value
= obj
.get(field
)
866 if value
is not None:
867 value
= str(value
)[:length
]
870 def _lookfor_or_create_image(db_image
, mydb
, descriptor
):
872 fill image content at db_image dictionary. Check if the image with this image and checksum exist
873 :param db_image: dictionary to insert data
874 :param mydb: database connector
875 :param descriptor: yang descriptor
876 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
879 db_image
["name"] = get_str(descriptor
, "image", 255)
880 db_image
["checksum"] = get_str(descriptor
, "image-checksum", 32)
881 if not db_image
["checksum"]: # Ensure that if empty string, None is stored
882 db_image
["checksum"] = None
883 if db_image
["name"].startswith("/"):
884 db_image
["location"] = db_image
["name"]
885 existing_images
= mydb
.get_rows(FROM
="images", WHERE
={'location': db_image
["location"]})
887 db_image
["universal_name"] = db_image
["name"]
888 existing_images
= mydb
.get_rows(FROM
="images", WHERE
={'universal_name': db_image
['universal_name'],
889 'checksum': db_image
['checksum']})
891 return existing_images
[0]["uuid"]
893 image_uuid
= str(uuid4())
894 db_image
["uuid"] = image_uuid
897 def get_resource_allocation_params(quota_descriptor
):
899 read the quota_descriptor from vnfd and fetch the resource allocation properties from the descriptor object
900 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
901 :return: quota params for limit, reserve, shares from the descriptor object
904 if quota_descriptor
.get("limit"):
905 quota
["limit"] = int(quota_descriptor
["limit"])
906 if quota_descriptor
.get("reserve"):
907 quota
["reserve"] = int(quota_descriptor
["reserve"])
908 if quota_descriptor
.get("shares"):
909 quota
["shares"] = int(quota_descriptor
["shares"])
912 def new_vnfd_v3(mydb
, tenant_id
, vnf_descriptor
):
914 Parses an OSM IM vnfd_catalog and insert at DB
917 :param vnf_descriptor:
918 :return: The list of cretated vnf ids
921 myvnfd
= vnfd_catalog
.vnfd()
923 pybindJSONDecoder
.load_ietf_json(vnf_descriptor
, None, None, obj
=myvnfd
, path_helper
=True,
925 except Exception as e
:
926 raise NfvoException("Error. Invalid VNF descriptor format " + str(e
), httperrors
.Bad_Request
)
934 db_ip_profiles_index
= 0
938 vnfd_catalog_descriptor
= vnf_descriptor
.get("vnfd:vnfd-catalog")
939 if not vnfd_catalog_descriptor
:
940 vnfd_catalog_descriptor
= vnf_descriptor
.get("vnfd-catalog")
941 vnfd_descriptor_list
= vnfd_catalog_descriptor
.get("vnfd")
942 if not vnfd_descriptor_list
:
943 vnfd_descriptor_list
= vnfd_catalog_descriptor
.get("vnfd:vnfd")
944 for vnfd_yang
in myvnfd
.vnfd_catalog
.vnfd
.values():
945 vnfd
= vnfd_yang
.get()
948 vnf_uuid
= str(uuid4())
949 uuid_list
.append(vnf_uuid
)
950 vnfd_uuid_list
.append(vnf_uuid
)
951 vnfd_id
= get_str(vnfd
, "id", 255)
955 "name": get_str(vnfd
, "name", 255),
956 "description": get_str(vnfd
, "description", 255),
957 "tenant_id": tenant_id
,
958 "vendor": get_str(vnfd
, "vendor", 255),
959 "short_name": get_str(vnfd
, "short-name", 255),
960 "descriptor": str(vnf_descriptor
)[:60000]
963 for vnfd_descriptor
in vnfd_descriptor_list
:
964 if vnfd_descriptor
["id"] == str(vnfd
["id"]):
967 # table ip_profiles (ip-profiles)
968 ip_profile_name2db_table_index
= {}
969 for ip_profile
in vnfd
.get("ip-profiles").values():
971 "ip_version": str(ip_profile
["ip-profile-params"].get("ip-version", "ipv4")),
972 "subnet_address": str(ip_profile
["ip-profile-params"].get("subnet-address")),
973 "gateway_address": str(ip_profile
["ip-profile-params"].get("gateway-address")),
974 "dhcp_enabled": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("enabled", True)),
975 "dhcp_start_address": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("start-address")),
976 "dhcp_count": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("count")),
979 for dns
in ip_profile
["ip-profile-params"]["dns-server"].values():
980 dns_list
.append(str(dns
.get("address")))
981 db_ip_profile
["dns_address"] = ";".join(dns_list
)
982 if ip_profile
["ip-profile-params"].get('security-group'):
983 db_ip_profile
["security_group"] = ip_profile
["ip-profile-params"]['security-group']
984 ip_profile_name2db_table_index
[str(ip_profile
["name"])] = db_ip_profiles_index
985 db_ip_profiles_index
+= 1
986 db_ip_profiles
.append(db_ip_profile
)
988 # table nets (internal-vld)
989 net_id2uuid
= {} # for mapping interface with network
990 net_id2index
= {} # for mapping interface with network
991 for vld
in vnfd
.get("internal-vld").values():
992 net_uuid
= str(uuid4())
993 uuid_list
.append(net_uuid
)
995 "name": get_str(vld
, "name", 255),
998 "description": get_str(vld
, "description", 255),
999 "osm_id": get_str(vld
, "id", 255),
1000 "type": "bridge", # TODO adjust depending on connection point type
1002 net_id2uuid
[vld
.get("id")] = net_uuid
1003 net_id2index
[vld
.get("id")] = len(db_nets
)
1004 db_nets
.append(db_net
)
1005 # ip-profile, link db_ip_profile with db_sce_net
1006 if vld
.get("ip-profile-ref"):
1007 ip_profile_name
= vld
.get("ip-profile-ref")
1008 if ip_profile_name
not in ip_profile_name2db_table_index
:
1009 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
1010 "'{}'. Reference to a non-existing 'ip_profiles'".format(
1011 str(vnfd
["id"]), str(vld
["id"]), str(vld
["ip-profile-ref"])),
1012 httperrors
.Bad_Request
)
1013 db_ip_profiles
[ip_profile_name2db_table_index
[ip_profile_name
]]["net_id"] = net_uuid
1014 else: #check no ip-address has been defined
1015 for icp
in vld
.get("internal-connection-point").values():
1016 if icp
.get("ip-address"):
1017 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
1018 "contains an ip-address but no ip-profile has been defined at VLD".format(
1019 str(vnfd
["id"]), str(vld
["id"]), str(icp
["id"])),
1020 httperrors
.Bad_Request
)
1022 # connection points vaiable declaration
1023 cp_name2iface_uuid
= {}
1025 cp_name2vm_uuid
= {}
1026 cp_name2db_interface
= {}
1027 vdu_id2cp_name
= {} # stored only when one external connection point is presented at this VDU
1031 vdu_id2db_table_index
= {}
1033 for vdu
in vnfd
.get("vdu").values():
1035 for vdu_descriptor
in vnfd_descriptor
["vdu"]:
1036 if vdu_descriptor
["id"] == str(vdu
["id"]):
1038 vm_uuid
= str(uuid4())
1039 uuid_list
.append(vm_uuid
)
1040 vdu_id
= get_str(vdu
, "id", 255)
1044 "name": get_str(vdu
, "name", 255),
1045 "description": get_str(vdu
, "description", 255),
1046 "pdu_type": get_str(vdu
, "pdu-type", 255),
1049 vdu_id2uuid
[db_vm
["osm_id"]] = vm_uuid
1050 vdu_id2db_table_index
[db_vm
["osm_id"]] = db_vms_index
1051 if vdu
.get("count"):
1052 db_vm
["count"] = int(vdu
["count"])
1055 image_present
= False
1056 if vdu
.get("image"):
1057 image_present
= True
1059 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, vdu
)
1061 image_uuid
= db_image
["uuid"]
1062 db_images
.append(db_image
)
1063 db_vm
["image_id"] = image_uuid
1064 if vdu
.get("alternative-images"):
1065 vm_alternative_images
= []
1066 for alt_image
in vdu
.get("alternative-images").values():
1068 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, alt_image
)
1070 image_uuid
= db_image
["uuid"]
1071 db_images
.append(db_image
)
1072 vm_alternative_images
.append({
1073 "image_id": image_uuid
,
1074 "vim_type": str(alt_image
["vim-type"]),
1075 # "universal_name": str(alt_image["image"]),
1076 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1079 db_vm
["image_list"] = yaml
.safe_dump(vm_alternative_images
, default_flow_style
=True, width
=256)
1083 if vdu
.get("volumes"):
1084 for volume_key
in vdu
["volumes"]:
1085 volume
= vdu
["volumes"][volume_key
]
1086 if not image_present
:
1087 # Convert the first volume to vnfc.image
1088 image_present
= True
1090 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, volume
)
1092 image_uuid
= db_image
["uuid"]
1093 db_images
.append(db_image
)
1094 db_vm
["image_id"] = image_uuid
1096 # Add Openmano devices
1097 device
= {"name": str(volume
.get("name"))}
1098 device
["type"] = str(volume
.get("device-type"))
1099 if volume
.get("size"):
1100 device
["size"] = int(volume
["size"])
1101 if volume
.get("image"):
1102 device
["image name"] = str(volume
["image"])
1103 if volume
.get("image-checksum"):
1104 device
["image checksum"] = str(volume
["image-checksum"])
1106 devices
.append(device
)
1108 if not db_vm
.get("image_id"):
1109 if not db_vm
["pdu_type"]:
1110 raise NfvoException("Not defined image for VDU")
1111 # create a fake image
1115 if vdu
.get("cloud-init"):
1116 boot_data
["user-data"] = str(vdu
["cloud-init"])
1117 elif vdu
.get("cloud-init-file"):
1118 # TODO Where this file content is present???
1119 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1120 boot_data
["user-data"] = str(vdu
["cloud-init-file"])
1122 if vdu
.get("supplemental-boot-data"):
1123 if vdu
["supplemental-boot-data"].get('boot-data-drive'):
1124 boot_data
['boot-data-drive'] = True
1125 if vdu
["supplemental-boot-data"].get('config-file'):
1126 om_cfgfile_list
= list()
1127 for custom_config_file
in vdu
["supplemental-boot-data"]['config-file'].values():
1128 # TODO Where this file content is present???
1129 cfg_source
= str(custom_config_file
["source"])
1130 om_cfgfile_list
.append({"dest": custom_config_file
["dest"],
1131 "content": cfg_source
})
1132 boot_data
['config-files'] = om_cfgfile_list
1134 db_vm
["boot_data"] = yaml
.safe_dump(boot_data
, default_flow_style
=True, width
=256)
1136 db_vms
.append(db_vm
)
1139 # table interfaces (internal/external interfaces)
1140 flavor_epa_interfaces
= []
1141 # for iface in chain(vdu.get("internal-interface").values(), vdu.get("external-interface").values()):
1142 for iface
in vdu
.get("interface").values():
1143 flavor_epa_interface
= {}
1144 iface_uuid
= str(uuid4())
1145 uuid_list
.append(iface_uuid
)
1148 "internal_name": get_str(iface
, "name", 255),
1151 flavor_epa_interface
["name"] = db_interface
["internal_name"]
1152 if iface
.get("virtual-interface").get("vpci"):
1153 db_interface
["vpci"] = get_str(iface
.get("virtual-interface"), "vpci", 12)
1154 flavor_epa_interface
["vpci"] = db_interface
["vpci"]
1156 if iface
.get("virtual-interface").get("bandwidth"):
1157 bps
= int(iface
.get("virtual-interface").get("bandwidth"))
1158 db_interface
["bw"] = int(math
.ceil(bps
/ 1000000.0))
1159 flavor_epa_interface
["bandwidth"] = "{} Mbps".format(db_interface
["bw"])
1161 if iface
.get("virtual-interface").get("type") == "OM-MGMT":
1162 db_interface
["type"] = "mgmt"
1163 elif iface
.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1164 db_interface
["type"] = "bridge"
1165 db_interface
["model"] = get_str(iface
.get("virtual-interface"), "type", 12)
1166 elif iface
.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1167 db_interface
["type"] = "data"
1168 db_interface
["model"] = get_str(iface
.get("virtual-interface"), "type", 12)
1169 flavor_epa_interface
["dedicated"] = "no" if iface
["virtual-interface"]["type"] == "SR-IOV" \
1171 flavor_epa_interfaces
.append(flavor_epa_interface
)
1173 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1174 "-interface':'type':'{}'. Interface type is not supported".format(
1175 vnfd_id
, vdu_id
, iface
.get("virtual-interface").get("type")),
1176 httperrors
.Bad_Request
)
1178 if iface
.get("mgmt-interface"):
1179 db_interface
["type"] = "mgmt"
1181 if iface
.get("external-connection-point-ref"):
1183 cp
= vnfd
.get("connection-point")[iface
.get("external-connection-point-ref")]
1184 db_interface
["external_name"] = get_str(cp
, "name", 255)
1185 cp_name2iface_uuid
[db_interface
["external_name"]] = iface_uuid
1186 cp_name2vdu_id
[db_interface
["external_name"]] = vdu_id
1187 cp_name2vm_uuid
[db_interface
["external_name"]] = vm_uuid
1188 cp_name2db_interface
[db_interface
["external_name"]] = db_interface
1189 for cp_descriptor
in vnfd_descriptor
["connection-point"]:
1190 if cp_descriptor
["name"] == db_interface
["external_name"]:
1195 if vdu_id
in vdu_id2cp_name
:
1196 vdu_id2cp_name
[vdu_id
] = None # more than two connection point for this VDU
1198 vdu_id2cp_name
[vdu_id
] = db_interface
["external_name"]
1201 if str(cp_descriptor
.get("port-security-enabled")).lower() == "false":
1202 db_interface
["port_security"] = 0
1203 elif str(cp_descriptor
.get("port-security-enabled")).lower() == "true":
1204 db_interface
["port_security"] = 1
1206 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1207 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1208 " at connection-point".format(
1209 vnf
=vnfd_id
, vdu
=vdu_id
, iface
=iface
["name"],
1210 cp
=iface
.get("vnfd-connection-point-ref")),
1211 httperrors
.Bad_Request
)
1212 elif iface
.get("internal-connection-point-ref"):
1214 for icp_descriptor
in vdu_descriptor
["internal-connection-point"]:
1215 if icp_descriptor
["id"] == str(iface
.get("internal-connection-point-ref")):
1218 raise KeyError("does not exist at vdu:internal-connection-point")
1221 for vld
in vnfd
.get("internal-vld").values():
1222 for cp
in vld
.get("internal-connection-point").values():
1223 if cp
.get("id-ref") == iface
.get("internal-connection-point-ref"):
1225 raise KeyError("is referenced by more than one 'internal-vld'")
1229 raise KeyError("is not referenced by any 'internal-vld'")
1231 # set network type as data
1232 if iface
.get("virtual-interface") and iface
["virtual-interface"].get("type") in \
1233 ("SR-IOV", "PCI-PASSTHROUGH"):
1234 db_nets
[net_id2index
[icp_vld
.get("id")]]["type"] = "data"
1235 db_interface
["net_id"] = net_id2uuid
[icp_vld
.get("id")]
1236 if str(icp_descriptor
.get("port-security-enabled")).lower() == "false":
1237 db_interface
["port_security"] = 0
1238 elif str(icp_descriptor
.get("port-security-enabled")).lower() == "true":
1239 db_interface
["port_security"] = 1
1240 if icp
.get("ip-address"):
1241 if not icp_vld
.get("ip-profile-ref"):
1243 db_interface
["ip_address"] = str(icp
.get("ip-address"))
1244 except KeyError as e
:
1245 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1246 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1248 vnf
=vnfd_id
, vdu
=vdu_id
, iface
=iface
["name"],
1249 cp
=iface
.get("internal-connection-point-ref"), msg
=str(e
)),
1250 httperrors
.Bad_Request
)
1251 if iface
.get("position"):
1252 db_interface
["created_at"] = int(iface
.get("position")) * 50
1253 if iface
.get("mac-address"):
1254 db_interface
["mac"] = str(iface
.get("mac-address"))
1255 db_interfaces
.append(db_interface
)
1259 "name": get_str(vdu
, "name", 250) + "-flv",
1260 "vcpus": int(vdu
["vm-flavor"].get("vcpu-count", 1)),
1261 "ram": int(vdu
["vm-flavor"].get("memory-mb", 1)),
1262 "disk": int(vdu
["vm-flavor"].get("storage-gb", 0)),
1264 # TODO revise the case of several numa-node-policy node
1268 extended
["devices"] = devices
1269 if flavor_epa_interfaces
:
1270 numa
["interfaces"] = flavor_epa_interfaces
1271 if vdu
.get("guest-epa"): # TODO or dedicated_int:
1272 epa_vcpu_set
= False
1273 if vdu
["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1274 numa_node_policy
= vdu
["guest-epa"].get("numa-node-policy")
1275 if numa_node_policy
.get("node"):
1276 numa_node
= next(iter(numa_node_policy
["node"].values()))
1277 if numa_node
.get("num-cores"):
1278 numa
["cores"] = numa_node
["num-cores"]
1280 if numa_node
.get("paired-threads"):
1281 if numa_node
["paired-threads"].get("num-paired-threads"):
1282 numa
["paired-threads"] = int(numa_node
["paired-threads"]["num-paired-threads"])
1284 if len(numa_node
["paired-threads"].get("paired-thread-ids")):
1285 numa
["paired-threads-id"] = []
1286 for pair
in numa_node
["paired-threads"]["paired-thread-ids"].values():
1287 numa
["paired-threads-id"].append(
1288 (str(pair
["thread-a"]), str(pair
["thread-b"]))
1290 if numa_node
.get("num-threads"):
1291 numa
["threads"] = int(numa_node
["num-threads"])
1293 if numa_node
.get("memory-mb"):
1294 numa
["memory"] = max(int(numa_node
["memory-mb"] / 1024), 1)
1295 if vdu
["guest-epa"].get("mempage-size"):
1296 if vdu
["guest-epa"]["mempage-size"] != "SMALL":
1297 numa
["memory"] = max(int(db_flavor
["ram"] / 1024), 1)
1298 if vdu
["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set
:
1299 if vdu
["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1300 if vdu
["guest-epa"].get("cpu-thread-pinning-policy") and \
1301 vdu
["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1302 numa
["cores"] = max(db_flavor
["vcpus"], 1)
1304 numa
["threads"] = max(db_flavor
["vcpus"], 1)
1306 if vdu
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
1307 cpuquota
= get_resource_allocation_params(vdu
["guest-epa"].get("cpu-quota"))
1309 extended
["cpu-quota"] = cpuquota
1310 if vdu
["guest-epa"].get("mem-quota"):
1311 vduquota
= get_resource_allocation_params(vdu
["guest-epa"].get("mem-quota"))
1313 extended
["mem-quota"] = vduquota
1314 if vdu
["guest-epa"].get("disk-io-quota"):
1315 diskioquota
= get_resource_allocation_params(vdu
["guest-epa"].get("disk-io-quota"))
1317 extended
["disk-io-quota"] = diskioquota
1318 if vdu
["guest-epa"].get("vif-quota"):
1319 vifquota
= get_resource_allocation_params(vdu
["guest-epa"].get("vif-quota"))
1321 extended
["vif-quota"] = vifquota
1323 extended
["numas"] = [numa
]
1325 extended_text
= yaml
.safe_dump(extended
, default_flow_style
=True, width
=256)
1326 db_flavor
["extended"] = extended_text
1327 # look if flavor exist
1328 temp_flavor_dict
= {'disk': db_flavor
.get('disk', 0),
1329 'ram': db_flavor
.get('ram'),
1330 'vcpus': db_flavor
.get('vcpus'),
1331 'extended': db_flavor
.get('extended')
1333 existing_flavors
= mydb
.get_rows(FROM
="flavors", WHERE
=temp_flavor_dict
)
1334 if existing_flavors
:
1335 flavor_uuid
= existing_flavors
[0]["uuid"]
1337 flavor_uuid
= str(uuid4())
1338 uuid_list
.append(flavor_uuid
)
1339 db_flavor
["uuid"] = flavor_uuid
1340 db_flavors
.append(db_flavor
)
1341 db_vm
["flavor_id"] = flavor_uuid
1343 # VNF affinity and antiaffinity
1344 for pg
in vnfd
.get("placement-groups").values():
1345 pg_name
= get_str(pg
, "name", 255)
1346 for vdu
in pg
.get("member-vdus").values():
1347 vdu_id
= get_str(vdu
, "member-vdu-ref", 255)
1348 if vdu_id
not in vdu_id2db_table_index
:
1349 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1350 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
1351 vnf
=vnfd_id
, pg
=pg_name
, vdu
=vdu_id
),
1352 httperrors
.Bad_Request
)
1353 db_vms
[vdu_id2db_table_index
[vdu_id
]]["availability_zone"] = pg_name
1354 # TODO consider the case of isolation and not colocation
1355 # if pg.get("strategy") == "ISOLATION":
1357 # VNF mgmt configuration
1358 if vnfd
["mgmt-interface"].get("vdu-id"):
1359 mgmt_vdu_id
= get_str(vnfd
["mgmt-interface"], "vdu-id", 255)
1360 if mgmt_vdu_id
not in vdu_id2uuid
:
1361 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1362 "'{vdu}'. Reference to a non-existing vdu".format(
1363 vnf
=vnfd_id
, vdu
=mgmt_vdu_id
),
1364 httperrors
.Bad_Request
)
1365 mgmt_access
["vm_id"] = vdu_id2uuid
[mgmt_vdu_id
]
1366 mgmt_access
["vdu-id"] = mgmt_vdu_id
1367 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1368 if vdu_id2cp_name
.get(mgmt_vdu_id
):
1369 if cp_name2db_interface
[vdu_id2cp_name
[mgmt_vdu_id
]]:
1370 cp_name2db_interface
[vdu_id2cp_name
[mgmt_vdu_id
]]["type"] = "mgmt"
1372 if vnfd
["mgmt-interface"].get("ip-address"):
1373 mgmt_access
["ip-address"] = str(vnfd
["mgmt-interface"].get("ip-address"))
1374 if vnfd
["mgmt-interface"].get("cp") and vnfd
.get("vdu"):
1375 if vnfd
["mgmt-interface"]["cp"] not in cp_name2iface_uuid
:
1376 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
1377 "Reference to a non-existing connection-point".format(
1378 vnf
=vnfd_id
, cp
=vnfd
["mgmt-interface"]["cp"]),
1379 httperrors
.Bad_Request
)
1380 mgmt_access
["vm_id"] = cp_name2vm_uuid
[vnfd
["mgmt-interface"]["cp"]]
1381 mgmt_access
["interface_id"] = cp_name2iface_uuid
[vnfd
["mgmt-interface"]["cp"]]
1382 mgmt_access
["vdu-id"] = cp_name2vdu_id
[vnfd
["mgmt-interface"]["cp"]]
1383 # mark this interface as of type mgmt
1384 if cp_name2db_interface
[vnfd
["mgmt-interface"]["cp"]]:
1385 cp_name2db_interface
[vnfd
["mgmt-interface"]["cp"]]["type"] = "mgmt"
1387 default_user
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1390 mgmt_access
["default_user"] = default_user
1392 required
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1395 mgmt_access
["required"] = required
1397 password_
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}),
1400 mgmt_access
["password"] = password_
1403 db_vnf
["mgmt_access"] = yaml
.safe_dump(mgmt_access
, default_flow_style
=True, width
=256)
1405 db_vnfs
.append(db_vnf
)
1409 {"images": db_images
},
1410 {"flavors": db_flavors
},
1411 {"ip_profiles": db_ip_profiles
},
1413 {"interfaces": db_interfaces
},
1416 logger
.debug("create_vnf Deployment done vnfDict: %s",
1417 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False) )
1418 mydb
.new_rows(db_tables
, uuid_list
)
1419 return vnfd_uuid_list
1420 except NfvoException
:
1422 except Exception as e
:
1423 logger
.error("Exception {}".format(e
))
1424 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
1427 @deprecated("Use new_vnfd_v3")
1428 def new_vnf(mydb
, tenant_id
, vnf_descriptor
):
1429 global global_config
1431 # Step 1. Check the VNF descriptor
1432 check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=1)
1433 # Step 2. Check tenant exist
1435 if tenant_id
!= "any":
1436 check_tenant(mydb
, tenant_id
)
1437 if "tenant_id" in vnf_descriptor
["vnf"]:
1438 if vnf_descriptor
["vnf"]["tenant_id"] != tenant_id
:
1439 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor
["vnf"]["tenant_id"], tenant_id
),
1440 httperrors
.Unauthorized
)
1442 vnf_descriptor
['vnf']['tenant_id'] = tenant_id
1443 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1444 if global_config
["auto_push_VNF_to_VIMs"]:
1445 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1447 # Step 4. Review the descriptor and add missing fields
1448 #print vnf_descriptor
1449 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1450 vnf_name
= vnf_descriptor
['vnf']['name']
1451 vnf_descriptor
['vnf']['description'] = vnf_descriptor
['vnf'].get("description", vnf_name
)
1452 if "physical" in vnf_descriptor
['vnf']:
1453 del vnf_descriptor
['vnf']['physical']
1454 #print vnf_descriptor
1456 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1457 logger
.debug('BEGIN creation of VNF "%s"' % vnf_name
)
1458 logger
.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name
,len(vnf_descriptor
['vnf']['VNFC'])))
1460 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1461 VNFCDict
= {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1462 rollback_list
= [] # It will contain the new images created in mano. It is used for rollback
1464 logger
.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1465 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1467 VNFCitem
["name"] = vnfc
['name']
1468 VNFCitem
["availability_zone"] = vnfc
.get('availability_zone')
1469 VNFCitem
["description"] = vnfc
.get("description", 'VM {} of the VNF {}'.format(vnfc
['name'],vnf_name
))
1471 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
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"] = {}
1481 devices
= vnfc
.get("devices")
1483 myflavorDict
["extended"]["devices"] = devices
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
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
1495 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1497 # print "Error creating flavor: unknown processor model. Rollback successful."
1498 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1500 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1501 myflavorDict
['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1503 if 'numas' in vnfc
and len(vnfc
['numas'])>0:
1504 myflavorDict
['extended']['numas'] = vnfc
['numas']
1508 # Step 6.2 New flavors are created in the VIM
1509 flavor_id
= create_or_use_flavor(mydb
, vims
, myflavorDict
, rollback_list
)
1511 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1512 VNFCitem
["flavor_id"] = flavor_id
1513 VNFCDict
[vnfc
['name']] = VNFCitem
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'])
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)
1544 # Step 7. Storing the VNF descriptor in the repository
1545 if "descriptor" not in vnf_descriptor
["vnf"]:
1546 vnf_descriptor
["vnf"]["descriptor"] = yaml
.safe_dump(vnf_descriptor
, indent
=4, explicit_start
=True, default_flow_style
=False)
1548 # Step 8. Adding the VNF to the NFVO DB
1549 vnf_id
= mydb
.new_vnf_as_a_whole(tenant_id
,vnf_name
,vnf_descriptor
,VNFCDict
)
1551 except (db_base_Exception
, vimconn
.VimConnException
, KeyError) as e
:
1552 _
, message
= rollback(mydb
, vims
, rollback_list
)
1553 if isinstance(e
, db_base_Exception
):
1554 error_text
= "Exception at database"
1555 elif isinstance(e
, KeyError):
1556 error_text
= "KeyError exception "
1557 e
.http_code
= httperrors
.Internal_Server_Error
1559 error_text
= "Exception at VIM"
1560 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
1561 #logger.error("start_scenario %s", error_text)
1562 raise NfvoException(error_text
, e
.http_code
)
1565 @deprecated("Use new_vnfd_v3")
1566 def new_vnf_v02(mydb
, tenant_id
, vnf_descriptor
):
1567 global global_config
1569 # Step 1. Check the VNF descriptor
1570 check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=2)
1571 # Step 2. Check tenant exist
1573 if tenant_id
!= "any":
1574 check_tenant(mydb
, tenant_id
)
1575 if "tenant_id" in vnf_descriptor
["vnf"]:
1576 if vnf_descriptor
["vnf"]["tenant_id"] != tenant_id
:
1577 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor
["vnf"]["tenant_id"], tenant_id
),
1578 httperrors
.Unauthorized
)
1580 vnf_descriptor
['vnf']['tenant_id'] = tenant_id
1581 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1582 if global_config
["auto_push_VNF_to_VIMs"]:
1583 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1585 # Step 4. Review the descriptor and add missing fields
1586 #print vnf_descriptor
1587 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1588 vnf_name
= vnf_descriptor
['vnf']['name']
1589 vnf_descriptor
['vnf']['description'] = vnf_descriptor
['vnf'].get("description", vnf_name
)
1590 if "physical" in vnf_descriptor
['vnf']:
1591 del vnf_descriptor
['vnf']['physical']
1592 #print vnf_descriptor
1594 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1595 logger
.debug('BEGIN creation of VNF "%s"' % vnf_name
)
1596 logger
.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name
,len(vnf_descriptor
['vnf']['VNFC'])))
1598 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1599 VNFCDict
= {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1600 rollback_list
= [] # It will contain the new images created in mano. It is used for rollback
1602 logger
.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1603 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1605 VNFCitem
["name"] = vnfc
['name']
1606 VNFCitem
["description"] = vnfc
.get("description", 'VM {} of the VNF {}'.format(vnfc
['name'],vnf_name
))
1608 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
1611 myflavorDict
["name"] = vnfc
['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
1612 myflavorDict
["description"] = VNFCitem
["description"]
1613 myflavorDict
["ram"] = vnfc
.get("ram", 0)
1614 myflavorDict
["vcpus"] = vnfc
.get("vcpus", 0)
1615 myflavorDict
["disk"] = vnfc
.get("disk", 0)
1616 myflavorDict
["extended"] = {}
1618 devices
= vnfc
.get("devices")
1620 myflavorDict
["extended"]["devices"] = devices
1623 # Mapping from processor models to rankings should be available somehow in the NFVO. They could be taken from VIM or directly from a new database table
1624 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1626 # Previous code has been commented
1627 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1628 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1629 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1630 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1632 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1634 # print "Error creating flavor: unknown processor model. Rollback successful."
1635 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1637 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1638 myflavorDict
['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1640 if 'numas' in vnfc
and len(vnfc
['numas'])>0:
1641 myflavorDict
['extended']['numas'] = vnfc
['numas']
1645 # Step 6.2 New flavors are created in the VIM
1646 flavor_id
= create_or_use_flavor(mydb
, vims
, myflavorDict
, rollback_list
)
1648 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1649 VNFCitem
["flavor_id"] = flavor_id
1650 VNFCDict
[vnfc
['name']] = VNFCitem
1652 logger
.debug("Creating new images in the VIM for each VNFC")
1653 # Step 6.3 New images are created in the VIM
1654 #For each VNFC, we must create the appropriate image.
1655 #This "for" loop might be integrated with the previous one
1656 #In case this integration is made, the VNFCDict might become a VNFClist.
1657 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1658 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
1660 image_dict
['name']=vnfc
.get('image name',vnf_name
+"-"+vnfc
['name']+"-img")
1661 image_dict
['universal_name']=vnfc
.get('image name')
1662 image_dict
['description']=vnfc
.get('image name', VNFCDict
[vnfc
['name']]['description'])
1663 image_dict
['location']=vnfc
.get('VNFC image')
1664 #image_dict['new_location']=vnfc.get('image location')
1665 image_dict
['checksum']=vnfc
.get('image checksum')
1666 image_metadata_dict
= vnfc
.get('image metadata', None)
1667 image_metadata_str
= None
1668 if image_metadata_dict
is not None:
1669 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
1670 image_dict
['metadata']=image_metadata_str
1671 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1672 image_id
= create_or_use_image(mydb
, vims
, image_dict
, rollback_list
)
1673 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1674 VNFCDict
[vnfc
['name']]["image_id"] = image_id
1675 VNFCDict
[vnfc
['name']]["image_path"] = vnfc
.get('VNFC image')
1676 VNFCDict
[vnfc
['name']]["count"] = vnfc
.get('count', 1)
1677 if vnfc
.get("boot-data"):
1678 VNFCDict
[vnfc
['name']]["boot_data"] = yaml
.safe_dump(vnfc
["boot-data"], default_flow_style
=True, width
=256)
1680 # Step 7. Storing the VNF descriptor in the repository
1681 if "descriptor" not in vnf_descriptor
["vnf"]:
1682 vnf_descriptor
["vnf"]["descriptor"] = yaml
.safe_dump(vnf_descriptor
, indent
=4, explicit_start
=True, default_flow_style
=False)
1684 # Step 8. Adding the VNF to the NFVO DB
1685 vnf_id
= mydb
.new_vnf_as_a_whole2(tenant_id
,vnf_name
,vnf_descriptor
,VNFCDict
)
1687 except (db_base_Exception
, vimconn
.VimConnException
, KeyError) as e
:
1688 _
, message
= rollback(mydb
, vims
, rollback_list
)
1689 if isinstance(e
, db_base_Exception
):
1690 error_text
= "Exception at database"
1691 elif isinstance(e
, KeyError):
1692 error_text
= "KeyError exception "
1693 e
.http_code
= httperrors
.Internal_Server_Error
1695 error_text
= "Exception at VIM"
1696 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
1697 #logger.error("start_scenario %s", error_text)
1698 raise NfvoException(error_text
, e
.http_code
)
1701 def get_vnf_id(mydb
, tenant_id
, vnf_id
):
1702 #check valid tenant_id
1703 check_tenant(mydb
, tenant_id
)
1706 if tenant_id
!= "any":
1707 where_or
["tenant_id"] = tenant_id
1708 where_or
["public"] = True
1709 vnf
= mydb
.get_table_by_uuid_name('vnfs', vnf_id
, "VNF", WHERE_OR
=where_or
, WHERE_AND_OR
="AND")
1711 vnf_id
= vnf
["uuid"]
1712 filter_keys
= ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
1713 filtered_content
= dict( (k
,v
) for k
,v
in vnf
.items() if k
in filter_keys
)
1714 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1715 data
={'vnf' : filtered_content
}
1717 content
= mydb
.get_rows(FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id',
1718 SELECT
=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1720 WHERE
={'vnfs.uuid': vnf_id
} )
1721 if len(content
) != 0:
1722 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
1723 # change boot_data into boot-data
1725 if vm
.get("boot_data"):
1726 vm
["boot-data"] = yaml
.safe_load(vm
["boot_data"])
1729 data
['vnf']['VNFC'] = content
1730 #TODO: GET all the information from a VNFC and include it in the output.
1733 content
= mydb
.get_rows(FROM
='vnfs join nets on vnfs.uuid=nets.vnf_id',
1734 SELECT
=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1735 WHERE
={'vnfs.uuid': vnf_id
} )
1736 data
['vnf']['nets'] = content
1738 #GET ip-profile for each net
1739 for net
in data
['vnf']['nets']:
1740 ipprofiles
= mydb
.get_rows(FROM
='ip_profiles',
1741 SELECT
=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1742 WHERE
={'net_id': net
["uuid"]} )
1743 if len(ipprofiles
)==1:
1744 net
["ip_profile"] = ipprofiles
[0]
1745 elif len(ipprofiles
)>1:
1746 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net
['uuid']), httperrors
.Bad_Request
)
1749 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
1751 #GET External Interfaces
1752 content
= mydb
.get_rows(FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces on vms.uuid=interfaces.vm_id',\
1753 SELECT
=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1754 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
1755 WHERE
={'vnfs.uuid': vnf_id
, 'interfaces.external_name<>': None} )
1757 data
['vnf']['external-connections'] = content
1762 def delete_vnf(mydb
,tenant_id
,vnf_id
,datacenter
=None,vim_tenant
=None):
1763 # Check tenant exist
1764 if tenant_id
!= "any":
1765 check_tenant(mydb
, tenant_id
)
1766 # Get the URL of the VIM from the nfvo_tenant and the datacenter
1767 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1771 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1773 if tenant_id
!= "any":
1774 where_or
["tenant_id"] = tenant_id
1775 where_or
["public"] = True
1776 vnf
= mydb
.get_table_by_uuid_name('vnfs', vnf_id
, "VNF", WHERE_OR
=where_or
, WHERE_AND_OR
="AND")
1777 vnf_id
= vnf
["uuid"]
1779 # "Getting the list of flavors and tenants of the VNF"
1780 flavorList
= get_flavorlist(mydb
, vnf_id
)
1781 if len(flavorList
)==0:
1782 logger
.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id
)
1784 imageList
= get_imagelist(mydb
, vnf_id
)
1785 if len(imageList
)==0:
1786 logger
.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id
)
1788 deleted
= mydb
.delete_row_by_id('vnfs', vnf_id
)
1790 raise NfvoException("vnf '{}' not found".format(vnf_id
), httperrors
.Not_Found
)
1793 for flavor
in flavorList
:
1794 #check if flavor is used by other vnf
1796 c
= mydb
.get_rows(FROM
='vms', WHERE
={'flavor_id':flavor
} )
1798 logger
.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor
)
1800 #flavor not used, must be deleted
1802 c
= mydb
.get_rows(FROM
='datacenters_flavors', WHERE
={'flavor_id': flavor
})
1803 for flavor_vim
in c
:
1804 if not flavor_vim
['created']: # skip this flavor because not created by openmano
1808 for vim
in vims
.values():
1809 if vim
["config"]["datacenter_tenant_id"] == flavor_vim
["datacenter_vim_id"]:
1815 myvim
.delete_flavor(flavor_vim
["vim_id"])
1816 except vimconn
.VimConnNotFoundException
:
1817 logger
.warn("VIM flavor %s not exist at datacenter %s", flavor_vim
["vim_id"],
1818 flavor_vim
["datacenter_vim_id"] )
1819 except vimconn
.VimConnException
as e
:
1820 logger
.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1821 flavor_vim
["vim_id"], flavor_vim
["datacenter_vim_id"], type(e
).__name
__, str(e
))
1822 undeletedItems
.append("flavor {} from VIM {}".format(flavor_vim
["vim_id"],
1823 flavor_vim
["datacenter_vim_id"]))
1824 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1825 mydb
.delete_row_by_id('flavors', flavor
)
1826 except db_base_Exception
as e
:
1827 logger
.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor
, str(e
))
1828 undeletedItems
.append("flavor {}".format(flavor
))
1831 for image
in imageList
:
1833 #check if image is used by other vnf
1834 c
= mydb
.get_rows(FROM
='vms', WHERE
=[{'image_id': image
}, {'image_list LIKE ': '%' + image
+ '%'}])
1836 logger
.debug("Image '%s' not deleted because it is being used by another VNF", image
)
1838 #image not used, must be deleted
1840 c
= mydb
.get_rows(FROM
='datacenters_images', WHERE
={'image_id':image
})
1842 if image_vim
["datacenter_vim_id"] not in vims
: # TODO change to datacenter_tenant_id
1844 if image_vim
['created']=='false': #skip this image because not created by openmano
1846 myvim
=vims
[ image_vim
["datacenter_id"] ]
1848 myvim
.delete_image(image_vim
["vim_id"])
1849 except vimconn
.VimConnNotFoundException
as e
:
1850 logger
.warn("VIM image %s not exist at datacenter %s", image_vim
["vim_id"], image_vim
["datacenter_id"] )
1851 except vimconn
.VimConnException
as e
:
1852 logger
.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1853 image_vim
["vim_id"], image_vim
["datacenter_id"], type(e
).__name
__, str(e
))
1854 undeletedItems
.append("image {} from VIM {}".format(image_vim
["vim_id"], image_vim
["datacenter_id"] ))
1855 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1856 mydb
.delete_row_by_id('images', image
)
1857 except db_base_Exception
as e
:
1858 logger
.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image
, str(e
))
1859 undeletedItems
.append("image {}".format(image
))
1861 return vnf_id
+ " " + vnf
["name"]
1863 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
1866 @deprecated("Not used")
1867 def get_hosts_info(mydb
, nfvo_tenant_id
, datacenter_name
=None):
1868 result
, vims
= get_vim(mydb
, nfvo_tenant_id
, None, datacenter_name
)
1872 return -httperrors
.Not_Found
, "datacenter '{}' not found".format(datacenter_name
)
1873 myvim
= next(iter(vims
.values()))
1874 result
,servers
= myvim
.get_hosts_info()
1876 return result
, servers
1877 topology
= {'name':myvim
['name'] , 'servers': servers
}
1878 return result
, topology
1881 def get_hosts(mydb
, nfvo_tenant_id
):
1882 vims
= get_vim(mydb
, nfvo_tenant_id
)
1884 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id
)), httperrors
.Not_Found
)
1886 #print "nfvo.datacenter_action() error. Several datacenters found"
1887 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors
.Conflict
)
1888 myvim
= next(iter(vims
.values()))
1890 hosts
= myvim
.get_hosts()
1891 logger
.debug('VIM hosts response: '+ yaml
.safe_dump(hosts
, indent
=4, default_flow_style
=False))
1893 datacenter
= {'Datacenters': [ {'name':myvim
['name'],'servers':[]} ] }
1895 server
={'name':host
['name'], 'vms':[]}
1896 for vm
in host
['instances']:
1897 #get internal name and model
1899 c
= mydb
.get_rows(SELECT
=('name',), FROM
='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1900 WHERE
={'vim_vm_id':vm
['id']} )
1902 logger
.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm
['id']))
1904 server
['vms'].append( {'name':vm
['name'] , 'model':c
[0]['name']} )
1906 except db_base_Exception
as e
:
1907 logger
.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm
['id'], str(e
)))
1908 datacenter
['Datacenters'][0]['servers'].append(server
)
1909 #return -400, "en construccion"
1911 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1913 except vimconn
.VimConnException
as e
:
1914 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e
)), e
.http_code
)
1917 @deprecated("Use new_nsd_v3")
1918 def new_scenario(mydb
, tenant_id
, topo
):
1920 # result, vims = get_vim(mydb, tenant_id)
1922 # return result, vims
1924 if tenant_id
!= "any":
1925 check_tenant(mydb
, tenant_id
)
1926 if "tenant_id" in topo
:
1927 if topo
["tenant_id"] != tenant_id
:
1928 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo
["tenant_id"], tenant_id
),
1929 httperrors
.Unauthorized
)
1933 #1.1: get VNFs and external_networks (other_nets).
1935 other_nets
={} #external_networks, bridge_networks and data_networkds
1936 nodes
= topo
['topology']['nodes']
1937 for k
in nodes
.keys():
1938 if nodes
[k
]['type'] == 'VNF':
1940 vnfs
[k
]['ifaces'] = {}
1941 elif nodes
[k
]['type'] == 'other_network' or nodes
[k
]['type'] == 'external_network':
1942 other_nets
[k
] = nodes
[k
]
1943 other_nets
[k
]['external']=True
1944 elif nodes
[k
]['type'] == 'network':
1945 other_nets
[k
] = nodes
[k
]
1946 other_nets
[k
]['external']=False
1949 #1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1950 for name
,vnf
in vnfs
.items():
1951 where
= {"OR": {"tenant_id": tenant_id
, 'public': "true"}}
1953 error_pos
= "'topology':'nodes':'" + name
+ "'"
1955 error_text
+= " 'vnf_id' " + vnf
['vnf_id']
1956 where
['uuid'] = vnf
['vnf_id']
1957 if 'VNF model' in vnf
:
1958 error_text
+= " 'VNF model' " + vnf
['VNF model']
1959 where
['name'] = vnf
['VNF model']
1961 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos
, httperrors
.Bad_Request
)
1963 vnf_db
= mydb
.get_rows(SELECT
=('uuid','name','description'),
1967 raise NfvoException("unknown" + error_text
+ " at " + error_pos
, httperrors
.Not_Found
)
1969 raise NfvoException("more than one" + error_text
+ " at " + error_pos
+ " Concrete with 'vnf_id'", httperrors
.Conflict
)
1970 vnf
['uuid']=vnf_db
[0]['uuid']
1971 vnf
['description']=vnf_db
[0]['description']
1972 #get external interfaces
1973 ext_ifaces
= mydb
.get_rows(SELECT
=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1974 FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1975 WHERE
={'vnfs.uuid':vnf
['uuid'], 'external_name<>': None} )
1976 for ext_iface
in ext_ifaces
:
1977 vnf
['ifaces'][ ext_iface
['name'] ] = {'uuid':ext_iface
['iface_uuid'], 'type':ext_iface
['type']}
1979 #1.4 get list of connections
1980 conections
= topo
['topology']['connections']
1981 conections_list
= []
1982 conections_list_name
= []
1983 for k
in conections
.keys():
1984 if type(conections
[k
]['nodes'])==dict: #dict with node:iface pairs
1985 ifaces_list
= conections
[k
]['nodes'].items()
1986 elif type(conections
[k
]['nodes'])==list: #list with dictionary
1988 conection_pair_list
= map(lambda x
: x
.items(), conections
[k
]['nodes'] )
1989 for k2
in conection_pair_list
:
1992 con_type
= conections
[k
].get("type", "link")
1993 if con_type
!= "link":
1995 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k
)), httperrors
.Bad_Request
)
1996 other_nets
[k
] = {'external': False}
1997 if conections
[k
].get("graph"):
1998 other_nets
[k
]["graph"] = conections
[k
]["graph"]
1999 ifaces_list
.append( (k
, None) )
2002 if con_type
== "external_network":
2003 other_nets
[k
]['external'] = True
2004 if conections
[k
].get("model"):
2005 other_nets
[k
]["model"] = conections
[k
]["model"]
2007 other_nets
[k
]["model"] = k
2008 if con_type
== "dataplane_net" or con_type
== "bridge_net":
2009 other_nets
[k
]["model"] = con_type
2011 conections_list_name
.append(k
)
2012 conections_list
.append(set(ifaces_list
)) #from list to set to operate as a set (this conversion removes elements that are repeated in a list)
2013 #print set(ifaces_list)
2014 #check valid VNF and iface names
2015 for iface
in ifaces_list
:
2016 if iface
[0] not in vnfs
and iface
[0] not in other_nets
:
2017 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
2018 str(k
), iface
[0]), httperrors
.Not_Found
)
2019 if iface
[0] in vnfs
and iface
[1] not in vnfs
[ iface
[0] ]['ifaces']:
2020 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
2021 str(k
), iface
[0], iface
[1]), httperrors
.Not_Found
)
2023 #1.5 unify connections from the pair list to a consolidated list
2025 while index
< len(conections_list
):
2027 while index2
< len(conections_list
):
2028 if len(conections_list
[index
] & conections_list
[index2
])>0: #common interface, join nets
2029 conections_list
[index
] |
= conections_list
[index2
]
2030 del conections_list
[index2
]
2031 del conections_list_name
[index2
]
2034 conections_list
[index
] = list(conections_list
[index
]) # from set to list again
2036 #for k in conections_list:
2041 #1.6 Delete non external nets
2042 # for k in other_nets.keys():
2043 # if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
2044 # for con in conections_list:
2046 # for index in range(0,len(con)):
2047 # if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
2048 # for index in delete_indexes:
2051 #1.7: Check external_ports are present at database table datacenter_nets
2052 for k
,net
in other_nets
.items():
2053 error_pos
= "'topology':'nodes':'" + k
+ "'"
2054 if net
['external']==False:
2055 if 'name' not in net
:
2057 if 'model' not in net
:
2058 raise NfvoException("needed a 'model' at " + error_pos
, httperrors
.Bad_Request
)
2059 if net
['model']=='bridge_net':
2060 net
['type']='bridge';
2061 elif net
['model']=='dataplane_net':
2064 raise NfvoException("unknown 'model' '"+ net
['model'] +"' at " + error_pos
, httperrors
.Not_Found
)
2066 #IF we do not want to check that external network exist at datacenter
2071 # if 'net_id' in net:
2072 # error_text += " 'net_id' " + net['net_id']
2073 # WHERE_['uuid'] = net['net_id']
2074 # if 'model' in net:
2075 # error_text += " 'model' " + net['model']
2076 # WHERE_['name'] = net['model']
2077 # if len(WHERE_) == 0:
2078 # return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
2079 # r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2080 # FROM='datacenter_nets', WHERE=WHERE_ )
2082 # print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2084 # print "nfvo.new_scenario Error" +error_text+ " is not present at database"
2085 # return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
2087 # print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
2088 # return -httperrors.Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
2089 # other_nets[k].update(net_db[0])
2092 net_nb
=0 #Number of nets
2093 for con
in conections_list
:
2094 #check if this is connected to a external net
2098 for index
in range(0,len(con
)):
2099 #check if this is connected to a external net
2100 for net_key
in other_nets
.keys():
2101 if con
[index
][0]==net_key
:
2102 if other_net_index
>=0:
2103 error_text
= "There is some interface connected both to net '{}' and net '{}'".format(
2104 con
[other_net_index
][0], net_key
)
2105 #print "nfvo.new_scenario " + error_text
2106 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2108 other_net_index
= index
2109 net_target
= net_key
2111 #print "other_net_index", other_net_index
2113 if other_net_index
>=0:
2114 del con
[other_net_index
]
2115 #IF we do not want to check that external network exist at datacenter
2116 if other_nets
[net_target
]['external'] :
2117 if "name" not in other_nets
[net_target
]:
2118 other_nets
[net_target
]['name'] = other_nets
[net_target
]['model']
2119 if other_nets
[net_target
]["type"] == "external_network":
2120 if vnfs
[ con
[0][0] ]['ifaces'][ con
[0][1] ]["type"] == "data":
2121 other_nets
[net_target
]["type"] = "data"
2123 other_nets
[net_target
]["type"] = "bridge"
2125 # if other_nets[net_target]['external'] :
2126 # type_='data' if len(con)>1 else 'ptp' #an external net is connected to a external port, so it is ptp if only one connection is done to this net
2127 # if type_=='data' and other_nets[net_target]['type']=="ptp":
2128 # error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2129 # print "nfvo.new_scenario " + error_text
2130 # return -httperrors.Bad_Request, error_text
2133 vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['net_key'] = net_target
2136 net_type_bridge
=False
2138 net_target
= "__-__net"+str(net_nb
)
2139 net_list
[net_target
] = {'name': conections_list_name
[net_nb
], #"net-"+str(net_nb),
2140 'description':"net-{} in scenario {}".format(net_nb
,topo
['name']),
2143 vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['net_key'] = net_target
2144 iface_type
= vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['type']
2145 if iface_type
=='mgmt' or iface_type
=='bridge':
2146 net_type_bridge
= True
2148 net_type_data
= True
2149 if net_type_bridge
and net_type_data
:
2150 error_text
= "Error connection interfaces of bridge type with data type. Firs node {}, iface {}".format(iface
[0], iface
[1])
2151 #print "nfvo.new_scenario " + error_text
2152 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2153 elif net_type_bridge
:
2156 type_
='data' if len(con
)>2 else 'ptp'
2157 net_list
[net_target
]['type'] = type_
2160 error_text
= "Error connection node {} : {} does not match any VNF or interface".format(iface
[0], iface
[1])
2161 #print "nfvo.new_scenario " + error_text
2163 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2165 #1.8: Connect to management net all not already connected interfaces of type 'mgmt'
2166 #1.8.1 obtain management net
2167 mgmt_net
= mydb
.get_rows(SELECT
=('uuid','name','description','type','shared'),
2168 FROM
='datacenter_nets', WHERE
={'name':'mgmt'} )
2169 #1.8.2 check all interfaces from all vnfs
2171 add_mgmt_net
= False
2172 for vnf
in vnfs
.values():
2173 for iface
in vnf
['ifaces'].values():
2174 if iface
['type']=='mgmt' and 'net_key' not in iface
:
2175 #iface not connected
2176 iface
['net_key'] = 'mgmt'
2178 if add_mgmt_net
and 'mgmt' not in net_list
:
2179 net_list
['mgmt']=mgmt_net
[0]
2180 net_list
['mgmt']['external']=True
2181 net_list
['mgmt']['graph']={'visible':False}
2183 net_list
.update(other_nets
)
2185 #print 'net_list', net_list
2190 #2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
2191 c
= mydb
.new_scenario( { 'vnfs':vnfs
, 'nets':net_list
,
2192 'tenant_id':tenant_id
, 'name':topo
['name'],
2193 'description':topo
.get('description',topo
['name']),
2194 'public': topo
.get('public', False)
2200 @deprecated("Use new_nsd_v3")
2201 def new_scenario_v02(mydb
, tenant_id
, scenario_dict
, version
):
2202 """ This creates a new scenario for version 0.2 and 0.3"""
2203 scenario
= scenario_dict
["scenario"]
2204 if tenant_id
!= "any":
2205 check_tenant(mydb
, tenant_id
)
2206 if "tenant_id" in scenario
:
2207 if scenario
["tenant_id"] != tenant_id
:
2208 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
2209 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
2210 scenario
["tenant_id"], tenant_id
), httperrors
.Unauthorized
)
2214 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
2215 for name
,vnf
in scenario
["vnfs"].items():
2216 where
= {"OR": {"tenant_id": tenant_id
, 'public': "true"}}
2218 error_pos
= "'scenario':'vnfs':'" + name
+ "'"
2220 error_text
+= " 'vnf_id' " + vnf
['vnf_id']
2221 where
['uuid'] = vnf
['vnf_id']
2222 if 'vnf_name' in vnf
:
2223 error_text
+= " 'vnf_name' " + vnf
['vnf_name']
2224 where
['name'] = vnf
['vnf_name']
2226 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos
, httperrors
.Bad_Request
)
2227 vnf_db
= mydb
.get_rows(SELECT
=('uuid', 'name', 'description'),
2230 if len(vnf_db
) == 0:
2231 raise NfvoException("Unknown" + error_text
+ " at " + error_pos
, httperrors
.Not_Found
)
2232 elif len(vnf_db
) > 1:
2233 raise NfvoException("More than one" + error_text
+ " at " + error_pos
+ " Concrete with 'vnf_id'", httperrors
.Conflict
)
2234 vnf
['uuid'] = vnf_db
[0]['uuid']
2235 vnf
['description'] = vnf_db
[0]['description']
2237 # get external interfaces
2238 ext_ifaces
= mydb
.get_rows(SELECT
=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2239 FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
2240 WHERE
={'vnfs.uuid':vnf
['uuid'], 'external_name<>': None} )
2241 for ext_iface
in ext_ifaces
:
2242 vnf
['ifaces'][ ext_iface
['name'] ] = {'uuid':ext_iface
['iface_uuid'], 'type': ext_iface
['type']}
2243 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
2245 # 2: Insert net_key and ip_address at every vnf interface
2246 for net_name
, net
in scenario
["networks"].items():
2247 net_type_bridge
= False
2248 net_type_data
= False
2249 for iface_dict
in net
["interfaces"]:
2250 if version
== "0.2":
2251 temp_dict
= iface_dict
2253 elif version
== "0.3":
2254 temp_dict
= {iface_dict
["vnf"] : iface_dict
["vnf_interface"]}
2255 ip_address
= iface_dict
.get('ip_address', None)
2256 for vnf
, iface
in temp_dict
.items():
2257 if vnf
not in scenario
["vnfs"]:
2258 error_text
= "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2260 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2261 raise NfvoException(error_text
, httperrors
.Not_Found
)
2262 if iface
not in scenario
["vnfs"][vnf
]['ifaces']:
2263 error_text
= "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2264 .format(net_name
, iface
)
2265 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2266 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2267 if "net_key" in scenario
["vnfs"][vnf
]['ifaces'][iface
]:
2268 error_text
= "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2269 "'{}'".format(net_name
, iface
,scenario
["vnfs"][vnf
]['ifaces'][iface
]['net_key'])
2270 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2271 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2272 scenario
["vnfs"][vnf
]['ifaces'][ iface
]['net_key'] = net_name
2273 scenario
["vnfs"][vnf
]['ifaces'][iface
]['ip_address'] = ip_address
2274 iface_type
= scenario
["vnfs"][vnf
]['ifaces'][iface
]['type']
2275 if iface_type
== 'mgmt' or iface_type
== 'bridge':
2276 net_type_bridge
= True
2278 net_type_data
= True
2280 if net_type_bridge
and net_type_data
:
2281 error_text
= "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2283 # logger.debug("nfvo.new_scenario " + error_text)
2284 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2285 elif net_type_bridge
:
2288 type_
= 'data' if len(net
["interfaces"]) > 2 else 'ptp'
2290 if net
.get("implementation"): # for v0.3
2291 if type_
== "bridge" and net
["implementation"] == "underlay":
2292 error_text
= "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2293 "'network':'{}'".format(net_name
)
2294 # logger.debug(error_text)
2295 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2296 elif type_
!= "bridge" and net
["implementation"] == "overlay":
2297 error_text
= "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2298 "'network':'{}'".format(net_name
)
2299 # logger.debug(error_text)
2300 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2301 net
.pop("implementation")
2302 if "type" in net
and version
== "0.3": # for v0.3
2303 if type_
== "data" and net
["type"] == "e-line":
2304 error_text
= "Error connecting more than 2 interfaces of data type to a network declared as type "\
2305 "'e-line' at 'network':'{}'".format(net_name
)
2306 # logger.debug(error_text)
2307 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2308 elif type_
== "ptp" and net
["type"] == "e-lan":
2312 net
['name'] = net_name
2313 net
['external'] = net
.get('external', False)
2315 # 3: insert at database
2316 scenario
["nets"] = scenario
["networks"]
2317 scenario
['tenant_id'] = tenant_id
2318 scenario_id
= mydb
.new_scenario(scenario
)
2322 def new_nsd_v3(mydb
, tenant_id
, nsd_descriptor
):
2324 Parses an OSM IM nsd_catalog and insert at DB
2327 :param nsd_descriptor:
2328 :return: The list of created NSD ids
2331 mynsd
= nsd_catalog
.nsd()
2333 pybindJSONDecoder
.load_ietf_json(nsd_descriptor
, None, None, obj
=mynsd
, skip_unknown
=True)
2334 except Exception as e
:
2335 raise NfvoException("Error. Invalid NS descriptor format: " + str(e
), httperrors
.Bad_Request
)
2339 db_sce_interfaces
= []
2342 db_sce_rsp_hops
= []
2343 db_sce_classifiers
= []
2344 db_sce_classifier_matches
= []
2346 db_ip_profiles_index
= 0
2349 for nsd_yang
in mynsd
.nsd_catalog
.nsd
.values():
2350 nsd
= nsd_yang
.get()
2353 scenario_uuid
= str(uuid4())
2354 uuid_list
.append(scenario_uuid
)
2355 nsd_uuid_list
.append(scenario_uuid
)
2357 "uuid": scenario_uuid
,
2358 "osm_id": get_str(nsd
, "id", 255),
2359 "name": get_str(nsd
, "name", 255),
2360 "description": get_str(nsd
, "description", 255),
2361 "tenant_id": tenant_id
,
2362 "vendor": get_str(nsd
, "vendor", 255),
2363 "short_name": get_str(nsd
, "short-name", 255),
2364 "descriptor": str(nsd_descriptor
)[:60000],
2366 db_scenarios
.append(db_scenario
)
2368 # table sce_vnfs (constituent-vnfd)
2369 vnf_index2scevnf_uuid
= {}
2370 vnf_index2vnf_uuid
= {}
2371 for vnf
in nsd
.get("constituent-vnfd").values():
2372 existing_vnf
= mydb
.get_rows(FROM
="vnfs", WHERE
={'osm_id': str(vnf
["vnfd-id-ref"])[:255],
2373 'tenant_id': tenant_id
})
2374 if not existing_vnf
:
2375 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2376 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2377 str(nsd
["id"]), str(vnf
["vnfd-id-ref"])[:255]),
2378 httperrors
.Bad_Request
)
2379 sce_vnf_uuid
= str(uuid4())
2380 uuid_list
.append(sce_vnf_uuid
)
2382 "uuid": sce_vnf_uuid
,
2383 "scenario_id": scenario_uuid
,
2384 # "name": get_str(vnf, "member-vnf-index", 255),
2385 "name": existing_vnf
[0]["name"][:200] + "." + get_str(vnf
, "member-vnf-index", 50),
2386 "vnf_id": existing_vnf
[0]["uuid"],
2387 "member_vnf_index": str(vnf
["member-vnf-index"]),
2388 # TODO 'start-by-default': True
2390 vnf_index2scevnf_uuid
[str(vnf
['member-vnf-index'])] = sce_vnf_uuid
2391 vnf_index2vnf_uuid
[str(vnf
['member-vnf-index'])] = existing_vnf
[0]["uuid"]
2392 db_sce_vnfs
.append(db_sce_vnf
)
2394 # table ip_profiles (ip-profiles)
2395 ip_profile_name2db_table_index
= {}
2396 for ip_profile
in nsd
.get("ip-profiles").values():
2398 "ip_version": str(ip_profile
["ip-profile-params"].get("ip-version", "ipv4")),
2399 "subnet_address": str(ip_profile
["ip-profile-params"].get("subnet-address")),
2400 "gateway_address": str(ip_profile
["ip-profile-params"].get("gateway-address")),
2401 "dhcp_enabled": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2402 "dhcp_start_address": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("start-address")),
2403 "dhcp_count": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("count")),
2406 for dns
in ip_profile
["ip-profile-params"]["dns-server"].values():
2407 dns_list
.append(str(dns
.get("address")))
2408 db_ip_profile
["dns_address"] = ";".join(dns_list
)
2409 if ip_profile
["ip-profile-params"].get('security-group'):
2410 db_ip_profile
["security_group"] = ip_profile
["ip-profile-params"]['security-group']
2411 ip_profile_name2db_table_index
[str(ip_profile
["name"])] = db_ip_profiles_index
2412 db_ip_profiles_index
+= 1
2413 db_ip_profiles
.append(db_ip_profile
)
2415 # table sce_nets (internal-vld)
2416 for vld
in nsd
.get("vld").values():
2417 sce_net_uuid
= str(uuid4())
2418 uuid_list
.append(sce_net_uuid
)
2420 "uuid": sce_net_uuid
,
2421 "name": get_str(vld
, "name", 255),
2422 "scenario_id": scenario_uuid
,
2424 "multipoint": not vld
.get("type") == "ELINE",
2425 "osm_id": get_str(vld
, "id", 255),
2427 "description": get_str(vld
, "description", 255),
2429 # guess type of network
2430 if vld
.get("mgmt-network"):
2431 db_sce_net
["type"] = "bridge"
2432 db_sce_net
["external"] = True
2433 elif vld
.get("provider-network").get("overlay-type") == "VLAN":
2434 db_sce_net
["type"] = "data"
2436 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2437 db_sce_net
["type"] = None
2438 db_sce_nets
.append(db_sce_net
)
2440 # ip-profile, link db_ip_profile with db_sce_net
2441 if vld
.get("ip-profile-ref"):
2442 ip_profile_name
= vld
.get("ip-profile-ref")
2443 if ip_profile_name
not in ip_profile_name2db_table_index
:
2444 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2445 " Reference to a non-existing 'ip_profiles'".format(
2446 str(nsd
["id"]), str(vld
["id"]), str(vld
["ip-profile-ref"])),
2447 httperrors
.Bad_Request
)
2448 db_ip_profiles
[ip_profile_name2db_table_index
[ip_profile_name
]]["sce_net_id"] = sce_net_uuid
2449 elif vld
.get("vim-network-name"):
2450 db_sce_net
["vim_network_name"] = get_str(vld
, "vim-network-name", 255)
2452 # table sce_interfaces (vld:vnfd-connection-point-ref)
2453 for iface
in vld
.get("vnfd-connection-point-ref").values():
2454 # Check if there are VDUs in the descriptor
2455 vnf_index
= str(iface
['member-vnf-index-ref'])
2456 existing_vdus
= mydb
.get_rows(SELECT
=('vms.uuid'), FROM
="vms", WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
]})
2458 # check correct parameters
2459 if vnf_index
not in vnf_index2vnf_uuid
:
2460 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2461 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2462 "'nsd':'constituent-vnfd'".format(
2463 str(nsd
["id"]), str(vld
["id"]), str(iface
["member-vnf-index-ref"])),
2464 httperrors
.Bad_Request
)
2466 existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid', 'i.type as iface_type'),
2467 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2468 WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2469 'external_name': get_str(iface
, "vnfd-connection-point-ref",
2471 if not existing_ifaces
:
2472 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2473 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2474 "connection-point name at VNFD '{}'".format(
2475 str(nsd
["id"]), str(vld
["id"]), str(iface
["vnfd-connection-point-ref"]),
2476 str(iface
.get("vnfd-id-ref"))[:255]),
2477 httperrors
.Bad_Request
)
2478 interface_uuid
= existing_ifaces
[0]["uuid"]
2479 if existing_ifaces
[0]["iface_type"] == "data":
2480 db_sce_net
["type"] = "data"
2481 sce_interface_uuid
= str(uuid4())
2482 uuid_list
.append(sce_net_uuid
)
2483 iface_ip_address
= None
2484 if iface
.get("ip-address"):
2485 iface_ip_address
= str(iface
.get("ip-address"))
2486 db_sce_interface
= {
2487 "uuid": sce_interface_uuid
,
2488 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2489 "sce_net_id": sce_net_uuid
,
2490 "interface_id": interface_uuid
,
2491 "ip_address": iface_ip_address
,
2493 db_sce_interfaces
.append(db_sce_interface
)
2494 if not db_sce_net
["type"]:
2495 db_sce_net
["type"] = "bridge"
2497 # table sce_vnffgs (vnffgd)
2498 for vnffg
in nsd
.get("vnffgd").values():
2499 sce_vnffg_uuid
= str(uuid4())
2500 uuid_list
.append(sce_vnffg_uuid
)
2502 "uuid": sce_vnffg_uuid
,
2503 "name": get_str(vnffg
, "name", 255),
2504 "scenario_id": scenario_uuid
,
2505 "vendor": get_str(vnffg
, "vendor", 255),
2506 "description": get_str(vld
, "description", 255),
2508 db_sce_vnffgs
.append(db_sce_vnffg
)
2511 for rsp
in vnffg
.get("rsp").values():
2512 sce_rsp_uuid
= str(uuid4())
2513 uuid_list
.append(sce_rsp_uuid
)
2515 "uuid": sce_rsp_uuid
,
2516 "name": get_str(rsp
, "name", 255),
2517 "sce_vnffg_id": sce_vnffg_uuid
,
2518 "id": get_str(rsp
, "id", 255), # only useful to link with classifiers; will be removed later in the code
2520 db_sce_rsps
.append(db_sce_rsp
)
2521 for iface
in rsp
.get("vnfd-connection-point-ref").values():
2522 vnf_index
= str(iface
['member-vnf-index-ref'])
2523 if_order
= int(iface
['order'])
2524 # check correct parameters
2525 if vnf_index
not in vnf_index2vnf_uuid
:
2526 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2527 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2528 "'nsd':'constituent-vnfd'".format(
2529 str(nsd
["id"]), str(rsp
["id"]), str(iface
["member-vnf-index-ref"])),
2530 httperrors
.Bad_Request
)
2532 ingress_existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2533 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2535 'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2536 'external_name': get_str(iface
, "vnfd-ingress-connection-point-ref",
2538 if not ingress_existing_ifaces
:
2539 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2540 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
2541 "connection-point name at VNFD '{}'".format(
2542 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-ingress-connection-point-ref"]),
2543 str(iface
.get("vnfd-id-ref"))[:255]), httperrors
.Bad_Request
)
2545 egress_existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2546 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2548 'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2549 'external_name': get_str(iface
, "vnfd-egress-connection-point-ref",
2551 if not egress_existing_ifaces
:
2552 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2553 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2554 "connection-point name at VNFD '{}'".format(
2555 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-egress-connection-point-ref"]),
2556 str(iface
.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request
)
2558 ingress_interface_uuid
= ingress_existing_ifaces
[0]["uuid"]
2559 egress_interface_uuid
= egress_existing_ifaces
[0]["uuid"]
2560 sce_rsp_hop_uuid
= str(uuid4())
2561 uuid_list
.append(sce_rsp_hop_uuid
)
2563 "uuid": sce_rsp_hop_uuid
,
2564 "if_order": if_order
,
2565 "ingress_interface_id": ingress_interface_uuid
,
2566 "egress_interface_id": egress_interface_uuid
,
2567 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2568 "sce_rsp_id": sce_rsp_uuid
,
2570 db_sce_rsp_hops
.append(db_sce_rsp_hop
)
2572 # deal with classifiers
2573 for classifier
in vnffg
.get("classifier").values():
2574 sce_classifier_uuid
= str(uuid4())
2575 uuid_list
.append(sce_classifier_uuid
)
2578 vnf_index
= str(classifier
['member-vnf-index-ref'])
2579 if vnf_index
not in vnf_index2vnf_uuid
:
2580 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2581 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2582 "'nsd':'constituent-vnfd'".format(
2583 str(nsd
["id"]), str(classifier
["id"]), str(classifier
["member-vnf-index-ref"])),
2584 httperrors
.Bad_Request
)
2585 existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2586 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2587 WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2588 'external_name': get_str(classifier
, "vnfd-connection-point-ref",
2590 if not existing_ifaces
:
2591 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2592 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2593 "connection-point name at VNFD '{}'".format(
2594 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-connection-point-ref"]),
2595 str(iface
.get("vnfd-id-ref"))[:255]),
2596 httperrors
.Bad_Request
)
2597 interface_uuid
= existing_ifaces
[0]["uuid"]
2599 db_sce_classifier
= {
2600 "uuid": sce_classifier_uuid
,
2601 "name": get_str(classifier
, "name", 255),
2602 "sce_vnffg_id": sce_vnffg_uuid
,
2603 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2604 "interface_id": interface_uuid
,
2606 rsp_id
= get_str(classifier
, "rsp-id-ref", 255)
2607 rsp
= next((item
for item
in db_sce_rsps
if item
["id"] == rsp_id
), None)
2608 db_sce_classifier
["sce_rsp_id"] = rsp
["uuid"]
2609 db_sce_classifiers
.append(db_sce_classifier
)
2611 for match
in classifier
.get("match-attributes").values():
2612 sce_classifier_match_uuid
= str(uuid4())
2613 uuid_list
.append(sce_classifier_match_uuid
)
2614 db_sce_classifier_match
= {
2615 "uuid": sce_classifier_match_uuid
,
2616 "ip_proto": get_str(match
, "ip-proto", 2),
2617 "source_ip": get_str(match
, "source-ip-address", 16),
2618 "destination_ip": get_str(match
, "destination-ip-address", 16),
2619 "source_port": get_str(match
, "source-port", 5),
2620 "destination_port": get_str(match
, "destination-port", 5),
2621 "sce_classifier_id": sce_classifier_uuid
,
2623 db_sce_classifier_matches
.append(db_sce_classifier_match
)
2626 # remove unneeded id's in sce_rsps
2627 for rsp
in db_sce_rsps
:
2631 {"scenarios": db_scenarios
},
2632 {"sce_nets": db_sce_nets
},
2633 {"ip_profiles": db_ip_profiles
},
2634 {"sce_vnfs": db_sce_vnfs
},
2635 {"sce_interfaces": db_sce_interfaces
},
2636 {"sce_vnffgs": db_sce_vnffgs
},
2637 {"sce_rsps": db_sce_rsps
},
2638 {"sce_rsp_hops": db_sce_rsp_hops
},
2639 {"sce_classifiers": db_sce_classifiers
},
2640 {"sce_classifier_matches": db_sce_classifier_matches
},
2643 logger
.debug("new_nsd_v3 done: %s",
2644 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False) )
2645 mydb
.new_rows(db_tables
, uuid_list
)
2646 return nsd_uuid_list
2647 except NfvoException
:
2649 except Exception as e
:
2650 logger
.error("Exception {}".format(e
))
2651 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
2654 def edit_scenario(mydb
, tenant_id
, scenario_id
, data
):
2655 data
["uuid"] = scenario_id
2656 data
["tenant_id"] = tenant_id
2657 c
= mydb
.edit_scenario( data
)
2661 @deprecated("Use create_instance")
2662 def start_scenario(mydb
, tenant_id
, scenario_id
, instance_scenario_name
, instance_scenario_description
, datacenter
=None,vim_tenant
=None, startvms
=True):
2663 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2664 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
, vim_tenant
=vim_tenant
)
2665 vims
= {datacenter_id
: myvim
}
2666 myvim_tenant
= myvim
['tenant_id']
2667 datacenter_name
= myvim
['name']
2671 #print "Checking that the scenario_id exists and getting the scenario dictionary"
2672 scenarioDict
= mydb
.get_scenario(scenario_id
, tenant_id
, datacenter_id
=datacenter_id
)
2673 scenarioDict
['datacenter2tenant'] = { datacenter_id
: myvim
['config']['datacenter_tenant_id'] }
2674 scenarioDict
['datacenter_id'] = datacenter_id
2675 #print '================scenarioDict======================='
2676 #print json.dumps(scenarioDict, indent=4)
2677 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
2679 logger
.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict
['name'],len(scenarioDict
['vnfs']))
2680 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2682 auxNetDict
= {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2683 auxNetDict
['scenario'] = {}
2685 logger
.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2686 for sce_net
in scenarioDict
['nets']:
2687 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
2689 myNetName
= "{}.{}".format(instance_scenario_name
, sce_net
['name'])
2690 myNetName
= myNetName
[0:255] #limit length
2691 myNetType
= sce_net
['type']
2693 myNetDict
["name"] = myNetName
2694 myNetDict
["type"] = myNetType
2695 myNetDict
["tenant_id"] = myvim_tenant
2696 myNetIPProfile
= sce_net
.get('ip_profile', None)
2697 myProviderNetwork
= sce_net
.get('provider_network', None)
2699 #We should use the dictionary as input parameter for new_network
2701 if not sce_net
["external"]:
2702 network_id
, _
= myvim
.new_network(myNetName
, myNetType
, myNetIPProfile
, provider_network_profile
=myProviderNetwork
)
2703 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2704 sce_net
['vim_id'] = network_id
2705 auxNetDict
['scenario'][sce_net
['uuid']] = network_id
2706 rollbackList
.append({'what':'network','where':'vim','vim_id':datacenter_id
,'uuid':network_id
})
2707 sce_net
["created"] = True
2709 if sce_net
['vim_id'] == None:
2710 error_text
= "Error, datacenter '{}' does not have external network '{}'.".format(
2711 datacenter_name
, sce_net
['name'])
2712 _
, message
= rollback(mydb
, vims
, rollbackList
)
2713 logger
.error("nfvo.start_scenario: %s", error_text
)
2714 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2715 logger
.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict
['name'],sce_net
['vim_id'])
2716 auxNetDict
['scenario'][sce_net
['uuid']] = sce_net
['vim_id']
2718 logger
.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2719 #For each vnf net, we create it and we add it to instanceNetlist.
2721 for sce_vnf
in scenarioDict
['vnfs']:
2722 for net
in sce_vnf
['nets']:
2723 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
2725 myNetName
= "{}.{}".format(instance_scenario_name
,net
['name'])
2726 myNetName
= myNetName
[0:255] #limit length
2727 myNetType
= net
['type']
2729 myNetDict
["name"] = myNetName
2730 myNetDict
["type"] = myNetType
2731 myNetDict
["tenant_id"] = myvim_tenant
2732 myNetIPProfile
= net
.get('ip_profile', None)
2733 myProviderNetwork
= sce_net
.get('provider_network', None)
2736 #We should use the dictionary as input parameter for new_network
2737 network_id
, _
= myvim
.new_network(myNetName
, myNetType
, myNetIPProfile
, provider_network_profile
=myProviderNetwork
)
2738 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2739 net
['vim_id'] = network_id
2740 if sce_vnf
['uuid'] not in auxNetDict
:
2741 auxNetDict
[sce_vnf
['uuid']] = {}
2742 auxNetDict
[sce_vnf
['uuid']][net
['uuid']] = network_id
2743 rollbackList
.append({'what':'network','where':'vim','vim_id':datacenter_id
,'uuid':network_id
})
2744 net
["created"] = True
2746 #print "auxNetDict:"
2747 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
2749 logger
.debug("start_scenario 3. Creating new vm instances in the VIM")
2750 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2752 for sce_vnf
in scenarioDict
['vnfs']:
2753 vnf_availability_zones
= []
2754 for vm
in sce_vnf
['vms']:
2755 vm_av
= vm
.get('availability_zone')
2756 if vm_av
and vm_av
not in vnf_availability_zones
:
2757 vnf_availability_zones
.append(vm_av
)
2759 # check if there is enough availability zones available at vim level.
2760 if myvims
[datacenter_id
].availability_zone
and vnf_availability_zones
:
2761 if len(vnf_availability_zones
) > len(myvims
[datacenter_id
].availability_zone
):
2762 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors
.Bad_Request
)
2764 for vm
in sce_vnf
['vms']:
2767 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
2768 myVMDict
['name'] = "{}.{}.{}".format(instance_scenario_name
,sce_vnf
['name'],chr(96+i
))
2769 #myVMDict['description'] = vm['description']
2770 myVMDict
['description'] = myVMDict
['name'][0:99]
2772 myVMDict
['start'] = "no"
2773 myVMDict
['name'] = myVMDict
['name'][0:255] #limit name length
2774 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
2776 #create image at vim in case it not exist
2777 image_dict
= mydb
.get_table_by_uuid_name("images", vm
['image_id'])
2778 image_id
= create_or_use_image(mydb
, vims
, image_dict
, [], True)
2779 vm
['vim_image_id'] = image_id
2781 #create flavor at vim in case it not exist
2782 flavor_dict
= mydb
.get_table_by_uuid_name("flavors", vm
['flavor_id'])
2783 if flavor_dict
['extended']!=None:
2784 flavor_dict
['extended']= yaml
.load(flavor_dict
['extended'], Loader
=yaml
.Loader
)
2785 flavor_id
= create_or_use_flavor(mydb
, vims
, flavor_dict
, [], True)
2786 vm
['vim_flavor_id'] = flavor_id
2789 myVMDict
['imageRef'] = vm
['vim_image_id']
2790 myVMDict
['flavorRef'] = vm
['vim_flavor_id']
2791 myVMDict
['networks'] = []
2792 for iface
in vm
['interfaces']:
2794 if iface
['type']=="data":
2795 netDict
['type'] = iface
['model']
2796 elif "model" in iface
and iface
["model"]!=None:
2797 netDict
['model']=iface
['model']
2798 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2799 #discover type of interface looking at flavor
2800 for numa
in flavor_dict
.get('extended',{}).get('numas',[]):
2801 for flavor_iface
in numa
.get('interfaces',[]):
2802 if flavor_iface
.get('name') == iface
['internal_name']:
2803 if flavor_iface
['dedicated'] == 'yes':
2804 netDict
['type']="PF" #passthrough
2805 elif flavor_iface
['dedicated'] == 'no':
2806 netDict
['type']="VF" #siov
2807 elif flavor_iface
['dedicated'] == 'yes:sriov':
2808 netDict
['type']="VFnotShared" #sriov but only one sriov on the PF
2809 netDict
["mac_address"] = flavor_iface
.get("mac_address")
2811 netDict
["use"]=iface
['type']
2812 if netDict
["use"]=="data" and not netDict
.get("type"):
2813 #print "netDict", netDict
2814 #print "iface", iface
2815 e_text
= "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".format(
2816 sce_vnf
['name'], vm
['name'], iface
['internal_name'])
2817 if flavor_dict
.get('extended')==None:
2818 raise NfvoException(e_text
+ "After database migration some information is not available. \
2819 Try to delete and create the scenarios and VNFs again", httperrors
.Conflict
)
2821 raise NfvoException(e_text
, httperrors
.Internal_Server_Error
)
2822 if netDict
["use"]=="mgmt" or netDict
["use"]=="bridge":
2823 netDict
["type"]="virtual"
2824 if "vpci" in iface
and iface
["vpci"] is not None:
2825 netDict
['vpci'] = iface
['vpci']
2826 if "mac" in iface
and iface
["mac"] is not None:
2827 netDict
['mac_address'] = iface
['mac']
2828 if "port-security" in iface
and iface
["port-security"] is not None:
2829 netDict
['port_security'] = iface
['port-security']
2830 if "floating-ip" in iface
and iface
["floating-ip"] is not None:
2831 netDict
['floating_ip'] = iface
['floating-ip']
2832 netDict
['name'] = iface
['internal_name']
2833 if iface
['net_id'] is None:
2834 for vnf_iface
in sce_vnf
["interfaces"]:
2837 if vnf_iface
['interface_id']==iface
['uuid']:
2838 netDict
['net_id'] = auxNetDict
['scenario'][ vnf_iface
['sce_net_id'] ]
2841 netDict
['net_id'] = auxNetDict
[ sce_vnf
['uuid'] ][ iface
['net_id'] ]
2842 #skip bridge ifaces not connected to any net
2843 #if 'net_id' not in netDict or netDict['net_id']==None:
2845 myVMDict
['networks'].append(netDict
)
2846 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2847 #print myVMDict['name']
2848 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2849 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2850 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2852 if 'availability_zone' in myVMDict
:
2853 av_index
= vnf_availability_zones
.index(myVMDict
['availability_zone'])
2857 vm_id
, _
= myvim
.new_vminstance(myVMDict
['name'], myVMDict
['description'], myVMDict
.get('start', None),
2858 myVMDict
['imageRef'], myVMDict
['flavorRef'], myVMDict
['networks'],
2859 availability_zone_index
=av_index
,
2860 availability_zone_list
=vnf_availability_zones
)
2861 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2862 vm
['vim_id'] = vm_id
2863 rollbackList
.append({'what':'vm','where':'vim','vim_id':datacenter_id
,'uuid':vm_id
})
2864 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2865 for net
in myVMDict
['networks']:
2867 for iface
in vm
['interfaces']:
2868 if net
["name"]==iface
["internal_name"]:
2869 iface
["vim_id"]=net
["vim_id"]
2872 logger
.debug("start scenario Deployment done")
2873 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2874 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
2875 instance_id
= mydb
.new_instance_scenario_as_a_whole(tenant_id
,instance_scenario_name
, instance_scenario_description
, scenarioDict
)
2876 return mydb
.get_instance_scenario(instance_id
)
2878 except (db_base_Exception
, vimconn
.VimConnException
) as e
:
2879 _
, message
= rollback(mydb
, vims
, rollbackList
)
2880 if isinstance(e
, db_base_Exception
):
2881 error_text
= "Exception at database"
2883 error_text
= "Exception at VIM"
2884 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
2885 #logger.error("start_scenario %s", error_text)
2886 raise NfvoException(error_text
, e
.http_code
)
2888 def unify_cloud_config(cloud_config_preserve
, cloud_config
):
2889 """ join the cloud config information into cloud_config_preserve.
2890 In case of conflict cloud_config_preserve preserves
2893 if not cloud_config_preserve
and not cloud_config
:
2896 new_cloud_config
= {"key-pairs":[], "users":[]}
2898 if cloud_config_preserve
:
2899 for key
in cloud_config_preserve
.get("key-pairs", () ):
2900 if key
not in new_cloud_config
["key-pairs"]:
2901 new_cloud_config
["key-pairs"].append(key
)
2903 for key
in cloud_config
.get("key-pairs", () ):
2904 if key
not in new_cloud_config
["key-pairs"]:
2905 new_cloud_config
["key-pairs"].append(key
)
2906 if not new_cloud_config
["key-pairs"]:
2907 del new_cloud_config
["key-pairs"]
2911 new_cloud_config
["users"] += cloud_config
.get("users", () )
2912 if cloud_config_preserve
:
2913 new_cloud_config
["users"] += cloud_config_preserve
.get("users", () )
2914 index_to_delete
= []
2915 users
= new_cloud_config
.get("users", [])
2916 for index0
in range(0,len(users
)):
2917 if index0
in index_to_delete
:
2919 for index1
in range(index0
+1,len(users
)):
2920 if index1
in index_to_delete
:
2922 if users
[index0
]["name"] == users
[index1
]["name"]:
2923 index_to_delete
.append(index1
)
2924 for key
in users
[index1
].get("key-pairs",()):
2925 if "key-pairs" not in users
[index0
]:
2926 users
[index0
]["key-pairs"] = [key
]
2927 elif key
not in users
[index0
]["key-pairs"]:
2928 users
[index0
]["key-pairs"].append(key
)
2929 index_to_delete
.sort(reverse
=True)
2930 for index
in index_to_delete
:
2932 if not new_cloud_config
["users"]:
2933 del new_cloud_config
["users"]
2936 if cloud_config
and cloud_config
.get("boot-data-drive") != None:
2937 new_cloud_config
["boot-data-drive"] = cloud_config
["boot-data-drive"]
2938 if cloud_config_preserve
and cloud_config_preserve
.get("boot-data-drive") != None:
2939 new_cloud_config
["boot-data-drive"] = cloud_config_preserve
["boot-data-drive"]
2942 new_cloud_config
["user-data"] = []
2943 if cloud_config
and cloud_config
.get("user-data"):
2944 if isinstance(cloud_config
["user-data"], list):
2945 new_cloud_config
["user-data"] += cloud_config
["user-data"]
2947 new_cloud_config
["user-data"].append(cloud_config
["user-data"])
2948 if cloud_config_preserve
and cloud_config_preserve
.get("user-data"):
2949 if isinstance(cloud_config_preserve
["user-data"], list):
2950 new_cloud_config
["user-data"] += cloud_config_preserve
["user-data"]
2952 new_cloud_config
["user-data"].append(cloud_config_preserve
["user-data"])
2953 if not new_cloud_config
["user-data"]:
2954 del new_cloud_config
["user-data"]
2957 new_cloud_config
["config-files"] = []
2958 if cloud_config
and cloud_config
.get("config-files") != None:
2959 new_cloud_config
["config-files"] += cloud_config
["config-files"]
2960 if cloud_config_preserve
:
2961 for file in cloud_config_preserve
.get("config-files", ()):
2962 for index
in range(0, len(new_cloud_config
["config-files"])):
2963 if new_cloud_config
["config-files"][index
]["dest"] == file["dest"]:
2964 new_cloud_config
["config-files"][index
] = file
2967 new_cloud_config
["config-files"].append(file)
2968 if not new_cloud_config
["config-files"]:
2969 del new_cloud_config
["config-files"]
2970 return new_cloud_config
2973 def get_vim_thread(mydb
, tenant_id
, datacenter_id_name
=None, datacenter_tenant_id
=None):
2975 datacenter_id
= None
2976 datacenter_name
= None
2979 if datacenter_tenant_id
:
2980 thread_id
= datacenter_tenant_id
2981 thread
= vim_threads
["running"].get(datacenter_tenant_id
)
2983 where_
={"td.nfvo_tenant_id": tenant_id
}
2984 if datacenter_id_name
:
2985 if utils
.check_valid_uuid