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
import vimconn
43 from uuid
import uuid4
44 from osm_ro
.db_base
import db_base_Exception
46 from osm_ro
import nfvo_db
47 from threading
import Lock
50 from osm_ro
.sdn
import Sdn
, SdnException
as ovimException
51 # from lib_osm_openvim.ovim import ovimException
52 # from unittest.mock import MagicMock
53 # class ovimException(Exception):
57 from Crypto
.PublicKey
import RSA
59 import osm_im
.vnfd
as vnfd_catalog
60 import osm_im
.nsd
as nsd_catalog
61 from pyangbind
.lib
.serialise
import pybindJSONDecoder
62 from copy
import deepcopy
63 from pkg_resources
import iter_entry_points
67 from .wim
import sdnconn
68 from .wim
.wimconn_dummy
import DummyConnector
69 from .wim
.failing_connector
import FailingConnector
70 from .http_tools
import errors
as httperrors
71 from .wim
.engine
import WimEngine
72 from .wim
.persistence
import WimPersistence
73 from copy
import deepcopy
74 from pprint
import pformat
81 global sdnconn_imported
84 global default_volume_size
85 default_volume_size
= '5' #size in GB
90 plugins
= {} # dictionary with VIM type as key, loaded module as value
91 vim_threads
= {"running":{}, "deleting": {}, "names": []} # threads running for attached-VIMs
92 vim_persistent_info
= {}
94 sdnconn_imported
= {} # dictionary with WIM type as key, loaded module as value
95 wim_threads
= {"running":{}, "deleting": {}, "names": []} # threads running for attached-WIMs
96 wim_persistent_info
= {}
99 logger
= logging
.getLogger('openmano.nfvo')
107 class NfvoException(httperrors
.HttpMappedError
):
108 """Common Class for NFVO errors"""
110 def _load_plugin(name
, type="vim"):
111 # type can be vim or sdn
114 for v
in iter_entry_points('osm_ro{}.plugins'.format(type), name
):
115 plugins
[name
] = v
.load()
116 except Exception as e
:
117 logger
.critical("Cannot load osm_{}: {}".format(name
, e
))
119 plugins
[name
] = FailingConnector("Cannot load osm_{}: {}".format(name
, e
))
120 if name
and name
not in plugins
:
121 error_text
= "Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been" \
122 " registered".format(t
=type, n
=name
)
123 logger
.critical(error_text
)
124 plugins
[name
] = FailingConnector(error_text
)
125 # raise NfvoException("Cannot load a module for {t} type '{n}'. The plugin 'osm_{n}' has not been registered".
126 # format(t=type, n=name), httperrors.Bad_Request)
131 if task_id
<= last_task_id
:
132 task_id
= last_task_id
+ 0.000001
133 last_task_id
= task_id
134 return "ACTION-{:.6f}".format(task_id
)
135 # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6))
138 def new_task(name
, params
, depends
=None):
140 task_id
= get_task_id()
141 task
= {"status": "enqueued", "id": task_id
, "name": name
, "params": params
}
143 task
["depends"] = depends
148 return True if id[:5] == "TASK-" else False
150 def get_process_id():
152 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
153 will provide a random one
156 # Try getting docker id. If fails, get pid
158 with
open("/proc/self/cgroup", "r") as f
:
159 text_id_
= f
.readline()
160 _
, _
, text_id
= text_id_
.rpartition("/")
161 text_id
= text_id
.replace("\n", "")[:12]
167 return "".join(random_choice("0123456789abcdef") for _
in range(12))
169 def get_non_used_vim_name(datacenter_name
, datacenter_id
):
170 return "{}:{}:{}".format(
171 worker_id
[:12], datacenter_id
.replace("-", "")[:32], datacenter_name
[:16]
175 def get_non_used_wim_name(wim_name
, wim_id
, tenant_name
, tenant_id
):
177 if name
not in wim_threads
["names"]:
178 wim_threads
["names"].append(name
)
180 name
= wim_name
[:16] + "." + tenant_name
[:16]
181 if name
not in wim_threads
["names"]:
182 wim_threads
["names"].append(name
)
184 name
= wim_id
+ "-" + tenant_id
185 wim_threads
["names"].append(name
)
189 def start_service(mydb
, persistence
=None, wim
=None):
190 global db
, global_config
, plugins
, ovim
, worker_id
191 db
= nfvo_db
.nfvo_db(lock
=db_lock
)
193 db
.connect(global_config
['db_host'], global_config
['db_user'], global_config
['db_passwd'], global_config
['db_name'])
195 persistence
= persistence
or WimPersistence(db
)
198 worker_id
= get_process_id()
199 if "rosdn_dummy" not in plugins
:
200 plugins
["rosdn_dummy"] = DummyConnector
201 # starts ovim library
202 ovim
= Sdn(db
, plugins
)
205 wim_engine
= wim
or WimEngine(persistence
, plugins
)
206 wim_engine
.ovim
= ovim
210 #delete old unneeded vim_wim_actions
214 from_
= 'tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join '\
215 'datacenter_tenants as dt on td.datacenter_tenant_id=dt.uuid'
216 select_
= ('type', 'd.config as config', 'd.uuid as datacenter_id', 'vim_url', 'vim_url_admin',
217 'd.name as datacenter_name', 'dt.uuid as datacenter_tenant_id',
218 'dt.vim_tenant_name as vim_tenant_name', 'dt.vim_tenant_id as vim_tenant_id',
219 'user', 'passwd', 'dt.config as dt_config', 'nfvo_tenant_id')
220 vims
= mydb
.get_rows(FROM
=from_
, SELECT
=select_
)
222 extra
={'datacenter_tenant_id': vim
.get('datacenter_tenant_id'),
223 'datacenter_id': vim
.get('datacenter_id')}
225 extra
.update(yaml
.load(vim
["config"], Loader
=yaml
.Loader
))
226 if vim
.get('dt_config'):
227 extra
.update(yaml
.load(vim
["dt_config"], Loader
=yaml
.Loader
))
228 plugin_name
= "rovim_" + vim
["type"]
229 if plugin_name
not in plugins
:
230 _load_plugin(plugin_name
, type="vim")
232 thread_id
= vim
['datacenter_tenant_id']
233 vim_persistent_info
[thread_id
] = {}
236 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
237 myvim
= plugins
[plugin_name
].vimconnector(
238 uuid
=vim
['datacenter_id'], name
=vim
['datacenter_name'],
239 tenant_id
=vim
['vim_tenant_id'], tenant_name
=vim
['vim_tenant_name'],
240 url
=vim
['vim_url'], url_admin
=vim
['vim_url_admin'],
241 user
=vim
['user'], passwd
=vim
['passwd'],
242 config
=extra
, persistent_info
=vim_persistent_info
[thread_id
]
244 except vimconn
.vimconnException
as e
:
246 logger
.error("Cannot launch thread for VIM {} '{}': {}".format(vim
['datacenter_name'],
247 vim
['datacenter_id'], e
))
248 except Exception as e
:
249 logger
.critical("Cannot launch thread for VIM {} '{}': {}".format(vim
['datacenter_name'],
250 vim
['datacenter_id'], e
))
251 # raise NfvoException("Error at VIM {}; {}: {}".format(vim["type"], type(e).__name__, e),
252 # httperrors.Internal_Server_Error)
253 thread_name
= get_non_used_vim_name(vim
['datacenter_name'], vim
['datacenter_id'])
254 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, None,
255 vim
['datacenter_tenant_id'], db
=db
)
257 vim_threads
["running"][thread_id
] = new_thread
258 wims
= mydb
.get_rows(FROM
="wim_accounts join wims on wim_accounts.wim_id=wims.uuid",
259 WHERE
={"sdn": "true"},
260 SELECT
=("wim_accounts.uuid as uuid", "type", "wim_accounts.name as name"))
262 plugin_name
= "rosdn_" + wim
["type"]
263 if plugin_name
not in plugins
:
264 _load_plugin(plugin_name
, type="sdn")
266 thread_id
= wim
['uuid']
267 thread_name
= get_non_used_vim_name(wim
['name'], wim
['uuid'])
268 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, wim
['uuid'], None, db
=db
)
270 vim_threads
["running"][thread_id
] = new_thread
271 wim_engine
.start_threads()
272 except db_base_Exception
as e
:
273 raise NfvoException(str(e
) + " at nfvo.get_vim", e
.http_code
)
274 except ovimException
as e
:
276 if message
[:22] == "DATABASE wrong version":
277 message
= "DATABASE wrong version of lib_osm_openvim {msg} -d{dbname} -u{dbuser} -p{dbpass} {ver}' "\
278 "at host {dbhost}".format(
279 msg
=message
[22:-3], dbname
=global_config
["db_ovim_name"],
280 dbuser
=global_config
["db_ovim_user"], dbpass
=global_config
["db_ovim_passwd"],
281 ver
=message
[-3:-1], dbhost
=global_config
["db_ovim_host"])
282 raise NfvoException(message
, httperrors
.Bad_Request
)
286 global ovim
, global_config
289 for thread_id
, thread
in vim_threads
["running"].items():
290 thread
.insert_task("exit")
291 vim_threads
["deleting"][thread_id
] = thread
292 vim_threads
["running"] = {}
295 wim_engine
.stop_threads()
297 if global_config
and global_config
.get("console_thread"):
298 for thread
in global_config
["console_thread"]:
299 thread
.terminate
= True
302 return ("openmanod version {} {}\n(c) Copyright Telefonica".format(global_config
["version"],
303 global_config
["version_date"] ))
307 Clean unused or old entries at database to avoid unlimited growing
308 :param mydb: database connector
311 # get and delete unused vim_wim_actions: all elements deleted, one week before, instance not present
312 now
= t
.time()-3600*24*7
313 instance_action_id
= None
316 actions_to_delete
= mydb
.get_rows(
317 SELECT
=("item", "item_id", "instance_action_id"),
318 FROM
="vim_wim_actions as va join instance_actions as ia on va.instance_action_id=ia.uuid "
319 "left join instance_scenarios as i on ia.instance_id=i.uuid",
320 WHERE
={"va.action": "DELETE", "va.modified_at<": now
, "i.uuid": None,
321 "va.status": ("DONE", "SUPERSEDED")},
324 for to_delete
in actions_to_delete
:
325 mydb
.delete_row(FROM
="vim_wim_actions", WHERE
=to_delete
)
326 if instance_action_id
!= to_delete
["instance_action_id"]:
327 instance_action_id
= to_delete
["instance_action_id"]
328 mydb
.delete_row(FROM
="instance_actions", WHERE
={"uuid": instance_action_id
})
329 nb_deleted
+= len(actions_to_delete
)
330 if len(actions_to_delete
) < 100:
333 mydb
.update_rows("vim_wim_actions", UPDATE
={"worker": None}, WHERE
={"worker<>": None})
336 logger
.debug("Removed {} unused vim_wim_actions".format(nb_deleted
))
339 def get_flavorlist(mydb
, vnf_id
, nfvo_tenant
=None):
341 return result, content:
342 <0, error_text upon error
343 nb_records, flavor_list on success
346 WHERE_dict
['vnf_id'] = vnf_id
347 if nfvo_tenant
is not None:
348 WHERE_dict
['nfvo_tenant_id'] = nfvo_tenant
350 #result, content = mydb.get_table(FROM='vms join vnfs on vms.vnf_id = vnfs.uuid',SELECT=('uuid'),WHERE=WHERE_dict )
351 #result, content = mydb.get_table(FROM='vms',SELECT=('vim_flavor_id',),WHERE=WHERE_dict )
352 flavors
= mydb
.get_rows(FROM
='vms join flavors on vms.flavor_id=flavors.uuid',SELECT
=('flavor_id',),WHERE
=WHERE_dict
)
353 #print "get_flavor_list result:", result
354 #print "get_flavor_list content:", content
356 for flavor
in flavors
:
357 flavorList
.append(flavor
['flavor_id'])
361 def get_imagelist(mydb
, vnf_id
, nfvo_tenant
=None):
363 Get used images of all vms belonging to this VNFD
364 :param mydb: database conector
365 :param vnf_id: vnfd uuid
366 :param nfvo_tenant: tenant, not used
367 :return: The list of image uuid used
370 vms
= mydb
.get_rows(SELECT
=('image_id','image_list'), FROM
='vms', WHERE
={'vnf_id': vnf_id
})
372 if vm
["image_id"] and vm
["image_id"] not in image_list
:
373 image_list
.append(vm
["image_id"])
375 vm_image_list
= yaml
.load(vm
["image_list"], Loader
=yaml
.Loader
)
376 for image_dict
in vm_image_list
:
377 if image_dict
["image_id"] not in image_list
:
378 image_list
.append(image_dict
["image_id"])
382 def get_vim(mydb
, nfvo_tenant
=None, datacenter_id
=None, datacenter_name
=None, datacenter_tenant_id
=None,
383 vim_tenant
=None, vim_tenant_name
=None, vim_user
=None, vim_passwd
=None, ignore_errors
=False):
384 '''Obtain a dictionary of VIM (datacenter) classes with some of the input parameters
385 return dictionary with {datacenter_id: vim_class, ... }. vim_class contain:
386 'nfvo_tenant_id','datacenter_id','vim_tenant_id','vim_url','vim_url_admin','datacenter_name','type','user','passwd'
387 raise exception upon error
391 if nfvo_tenant
is not None: WHERE_dict
['nfvo_tenant_id'] = nfvo_tenant
392 if datacenter_id
is not None: WHERE_dict
['d.uuid'] = datacenter_id
393 if datacenter_tenant_id
is not None: WHERE_dict
['datacenter_tenant_id'] = datacenter_tenant_id
394 if datacenter_name
is not None: WHERE_dict
['d.name'] = datacenter_name
395 if vim_tenant
is not None: WHERE_dict
['dt.vim_tenant_id'] = vim_tenant
396 if vim_tenant_name
is not None: WHERE_dict
['vim_tenant_name'] = vim_tenant_name
397 if nfvo_tenant
or vim_tenant
or vim_tenant_name
or datacenter_tenant_id
:
398 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'
399 select_
= ('type','d.config as config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name',
400 'dt.uuid as datacenter_tenant_id','dt.vim_tenant_name as vim_tenant_name','dt.vim_tenant_id as vim_tenant_id',
401 'user','passwd', 'dt.config as dt_config')
403 from_
= 'datacenters as d'
404 select_
= ('type','config','d.uuid as datacenter_id', 'vim_url', 'vim_url_admin', 'd.name as datacenter_name')
406 vims
= mydb
.get_rows(FROM
=from_
, SELECT
=select_
, WHERE
=WHERE_dict
)
409 extra
={'datacenter_tenant_id': vim
.get('datacenter_tenant_id'),
410 'datacenter_id': vim
.get('datacenter_id'),
411 '_vim_type_internal': vim
.get('type')}
413 extra
.update(yaml
.load(vim
["config"], Loader
=yaml
.Loader
))
414 if vim
.get('dt_config'):
415 extra
.update(yaml
.load(vim
["dt_config"], Loader
=yaml
.Loader
))
416 plugin_name
= "rovim_" + vim
["type"]
417 if plugin_name
not in plugins
:
419 _load_plugin(plugin_name
, type="vim")
420 except NfvoException
as e
:
422 logger
.error("{}".format(e
))
427 if 'datacenter_tenant_id' in vim
:
428 thread_id
= vim
["datacenter_tenant_id"]
429 if thread_id
not in vim_persistent_info
:
430 vim_persistent_info
[thread_id
] = {}
431 persistent_info
= vim_persistent_info
[thread_id
]
435 # return -httperrors.Bad_Request, "You must provide a valid tenant name or uuid for VIM %s" % ( vim["type"])
436 vim_dict
[vim
['datacenter_id']] = plugins
[plugin_name
].vimconnector(
437 uuid
=vim
['datacenter_id'], name
=vim
['datacenter_name'],
438 tenant_id
=vim
.get('vim_tenant_id',vim_tenant
),
439 tenant_name
=vim
.get('vim_tenant_name',vim_tenant_name
),
440 url
=vim
['vim_url'], url_admin
=vim
['vim_url_admin'],
441 user
=vim
.get('user',vim_user
), passwd
=vim
.get('passwd',vim_passwd
),
442 config
=extra
, persistent_info
=persistent_info
444 except Exception as e
:
446 logger
.error("Error at VIM {}; {}: {}".format(vim
["type"], type(e
).__name
__, str(e
)))
448 http_code
= httperrors
.Internal_Server_Error
449 if isinstance(e
, vimconn
.vimconnException
):
450 http_code
= e
.http_code
451 raise NfvoException("Error at VIM {}; {}: {}".format(vim
["type"], type(e
).__name
__, str(e
)), http_code
)
453 except db_base_Exception
as e
:
454 raise NfvoException(str(e
) + " at nfvo.get_vim", e
.http_code
)
457 def rollback(mydb
, vims
, rollback_list
):
459 #delete things by reverse order
460 for i
in range(len(rollback_list
)-1, -1, -1):
461 item
= rollback_list
[i
]
462 if item
["where"]=="vim":
463 if item
["vim_id"] not in vims
:
465 if is_task_id(item
["uuid"]):
467 vim
= vims
[item
["vim_id"]]
469 if item
["what"]=="image":
470 vim
.delete_image(item
["uuid"])
471 mydb
.delete_row(FROM
="datacenters_images", WHERE
={"datacenter_vim_id": vim
["id"], "vim_id":item
["uuid"]})
472 elif item
["what"]=="flavor":
473 vim
.delete_flavor(item
["uuid"])
474 mydb
.delete_row(FROM
="datacenters_flavors", WHERE
={"datacenter_vim_id": vim
["id"], "vim_id":item
["uuid"]})
475 elif item
["what"]=="network":
476 vim
.delete_network(item
["uuid"])
477 elif item
["what"]=="vm":
478 vim
.delete_vminstance(item
["uuid"])
479 except vimconn
.vimconnException
as e
:
480 logger
.error("Error in rollback. Not possible to delete VIM %s '%s'. Message: %s", item
['what'], item
["uuid"], str(e
))
481 undeleted_items
.append("{} {} from VIM {}".format(item
['what'], item
["uuid"], vim
["name"]))
482 except db_base_Exception
as e
:
483 logger
.error("Error in rollback. Not possible to delete %s '%s' from DB.datacenters Message: %s", item
['what'], item
["uuid"], str(e
))
487 if item
["what"]=="image":
488 mydb
.delete_row(FROM
="images", WHERE
={"uuid": item
["uuid"]})
489 elif item
["what"]=="flavor":
490 mydb
.delete_row(FROM
="flavors", WHERE
={"uuid": item
["uuid"]})
491 except db_base_Exception
as e
:
492 logger
.error("Error in rollback. Not possible to delete %s '%s' from DB. Message: %s", item
['what'], item
["uuid"], str(e
))
493 undeleted_items
.append("{} '{}'".format(item
['what'], item
["uuid"]))
494 if len(undeleted_items
)==0:
495 return True," Rollback successful."
497 return False," Rollback fails to delete: " + str(undeleted_items
)
500 def check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=1):
502 #create a dictionary with vnfc-name: vnfc:interface-list key:values pairs
504 for vnfc
in vnf_descriptor
["vnf"]["VNFC"]:
506 #dataplane interfaces
507 for numa
in vnfc
.get("numas",() ):
508 for interface
in numa
.get("interfaces",()):
509 if interface
["name"] in name_dict
:
511 "Error at vnf:VNFC[name:'{}']:numas:interfaces:name, interface name '{}' already used in this VNFC".format(
512 vnfc
["name"], interface
["name"]),
513 httperrors
.Bad_Request
)
514 name_dict
[ interface
["name"] ] = "underlay"
516 for interface
in vnfc
.get("bridge-ifaces",() ):
517 if interface
["name"] in name_dict
:
519 "Error at vnf:VNFC[name:'{}']:bridge-ifaces:name, interface name '{}' already used in this VNFC".format(
520 vnfc
["name"], interface
["name"]),
521 httperrors
.Bad_Request
)
522 name_dict
[ interface
["name"] ] = "overlay"
523 vnfc_interfaces
[ vnfc
["name"] ] = name_dict
524 # check bood-data info
525 # if "boot-data" in vnfc:
526 # # check that user-data is incompatible with users and config-files
527 # if (vnfc["boot-data"].get("users") or vnfc["boot-data"].get("config-files")) and vnfc["boot-data"].get("user-data"):
528 # raise NfvoException(
529 # "Error at vnf:VNFC:boot-data, fields 'users' and 'config-files' are not compatible with 'user-data'",
530 # httperrors.Bad_Request)
532 #check if the info in external_connections matches with the one in the vnfcs
534 for external_connection
in vnf_descriptor
["vnf"].get("external-connections",() ):
535 if external_connection
["name"] in name_list
:
537 "Error at vnf:external-connections:name, value '{}' already used as an external-connection".format(
538 external_connection
["name"]),
539 httperrors
.Bad_Request
)
540 name_list
.append(external_connection
["name"])
541 if external_connection
["VNFC"] not in vnfc_interfaces
:
543 "Error at vnf:external-connections[name:'{}']:VNFC, value '{}' does not match any VNFC".format(
544 external_connection
["name"], external_connection
["VNFC"]),
545 httperrors
.Bad_Request
)
547 if external_connection
["local_iface_name"] not in vnfc_interfaces
[ external_connection
["VNFC"] ]:
549 "Error at vnf:external-connections[name:'{}']:local_iface_name, value '{}' does not match any interface of this VNFC".format(
550 external_connection
["name"],
551 external_connection
["local_iface_name"]),
552 httperrors
.Bad_Request
)
554 #check if the info in internal_connections matches with the one in the vnfcs
556 for internal_connection
in vnf_descriptor
["vnf"].get("internal-connections",() ):
557 if internal_connection
["name"] in name_list
:
559 "Error at vnf:internal-connections:name, value '{}' already used as an internal-connection".format(
560 internal_connection
["name"]),
561 httperrors
.Bad_Request
)
562 name_list
.append(internal_connection
["name"])
563 #We should check that internal-connections of type "ptp" have only 2 elements
565 if len(internal_connection
["elements"])>2 and (internal_connection
.get("type") == "ptp" or internal_connection
.get("type") == "e-line"):
567 "Error at 'vnf:internal-connections[name:'{}']:elements', size must be 2 for a '{}' type. Consider change it to '{}' type".format(
568 internal_connection
["name"],
569 'ptp' if vnf_descriptor_version
==1 else 'e-line',
570 'data' if vnf_descriptor_version
==1 else "e-lan"),
571 httperrors
.Bad_Request
)
572 for port
in internal_connection
["elements"]:
574 iface
= port
["local_iface_name"]
575 if vnf
not in vnfc_interfaces
:
577 "Error at vnf:internal-connections[name:'{}']:elements[]:VNFC, value '{}' does not match any VNFC".format(
578 internal_connection
["name"], vnf
),
579 httperrors
.Bad_Request
)
580 if iface
not in vnfc_interfaces
[ vnf
]:
582 "Error at vnf:internal-connections[name:'{}']:elements[]:local_iface_name, value '{}' does not match any interface of this VNFC".format(
583 internal_connection
["name"], iface
),
584 httperrors
.Bad_Request
)
585 return -httperrors
.Bad_Request
,
586 if vnf_descriptor_version
==1 and "type" not in internal_connection
:
587 if vnfc_interfaces
[vnf
][iface
] == "overlay":
588 internal_connection
["type"] = "bridge"
590 internal_connection
["type"] = "data"
591 if vnf_descriptor_version
==2 and "implementation" not in internal_connection
:
592 if vnfc_interfaces
[vnf
][iface
] == "overlay":
593 internal_connection
["implementation"] = "overlay"
595 internal_connection
["implementation"] = "underlay"
596 if (internal_connection
.get("type") == "data" or internal_connection
.get("type") == "ptp" or \
597 internal_connection
.get("implementation") == "underlay") and vnfc_interfaces
[vnf
][iface
] == "overlay":
599 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
600 internal_connection
["name"],
601 iface
, 'bridge' if vnf_descriptor_version
==1 else 'overlay',
602 'data' if vnf_descriptor_version
==1 else 'underlay'),
603 httperrors
.Bad_Request
)
604 if (internal_connection
.get("type") == "bridge" or internal_connection
.get("implementation") == "overlay") and \
605 vnfc_interfaces
[vnf
][iface
] == "underlay":
607 "Error at vnf:internal-connections[name:'{}']:elements[]:{}, interface of type {} connected to an {} network".format(
608 internal_connection
["name"], iface
,
609 'data' if vnf_descriptor_version
==1 else 'underlay',
610 'bridge' if vnf_descriptor_version
==1 else 'overlay'),
611 httperrors
.Bad_Request
)
614 def create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
=None):
616 if only_create_at_vim
:
617 image_mano_id
= image_dict
['uuid']
618 if return_on_error
== None:
619 return_on_error
= True
621 if image_dict
['location']:
622 images
= mydb
.get_rows(FROM
="images", WHERE
={'location':image_dict
['location'], 'metadata':image_dict
['metadata']})
624 images
= mydb
.get_rows(FROM
="images", WHERE
={'universal_name':image_dict
['universal_name'], 'checksum':image_dict
['checksum']})
626 image_mano_id
= images
[0]['uuid']
628 #create image in MANO DB
629 temp_image_dict
={'name':image_dict
['name'], 'description':image_dict
.get('description',None),
630 'location':image_dict
['location'], 'metadata':image_dict
.get('metadata',None),
631 'universal_name':image_dict
['universal_name'] , 'checksum':image_dict
['checksum']
633 #temp_image_dict['location'] = image_dict.get('new_location') if image_dict['location'] is None
634 image_mano_id
= mydb
.new_row('images', temp_image_dict
, add_uuid
=True)
635 rollback_list
.append({"where":"mano", "what":"image","uuid":image_mano_id
})
636 #create image at every vim
637 for vim_id
,vim
in vims
.items():
638 datacenter_vim_id
= vim
["config"]["datacenter_tenant_id"]
639 image_created
="false"
641 image_db
= mydb
.get_rows(FROM
="datacenters_images",
642 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'image_id': image_mano_id
})
643 #look at VIM if this image exist
645 if image_dict
['location'] is not None:
646 image_vim_id
= vim
.get_image_id_from_path(image_dict
['location'])
649 filter_dict
['name'] = image_dict
['universal_name']
650 if image_dict
.get('checksum') != None:
651 filter_dict
['checksum'] = image_dict
['checksum']
652 #logger.debug('>>>>>>>> Filter dict: %s', str(filter_dict))
653 vim_images
= vim
.get_image_list(filter_dict
)
654 #logger.debug('>>>>>>>> VIM images: %s', str(vim_images))
655 if len(vim_images
) > 1:
656 raise vimconn
.vimconnException("More than one candidate VIM image found for filter: {}".format(str(filter_dict
)), httperrors
.Conflict
)
657 elif len(vim_images
) == 0:
658 raise vimconn
.vimconnNotFoundException("Image not found at VIM with filter: '{}'".format(str(filter_dict
)))
660 #logger.debug('>>>>>>>> VIM image 0: %s', str(vim_images[0]))
661 image_vim_id
= vim_images
[0]['id']
663 except vimconn
.vimconnNotFoundException
as e
:
664 #Create the image in VIM only if image_dict['location'] or image_dict['new_location'] is not None
666 #image_dict['location']=image_dict.get('new_location') if image_dict['location'] is None
667 if image_dict
['location']:
668 image_vim_id
= vim
.new_image(image_dict
)
669 rollback_list
.append({"where":"vim", "vim_id": vim_id
, "what":"image","uuid":image_vim_id
})
672 #If we reach this point, then the image has image name, and optionally checksum, and could not be found
673 raise vimconn
.vimconnException(str(e
))
674 except vimconn
.vimconnException
as e
:
676 logger
.error("Error creating image at VIM '%s': %s", vim
["name"], str(e
))
679 logger
.warn("Error creating image at VIM '%s': %s", vim
["name"], str(e
))
681 except vimconn
.vimconnException
as e
:
683 logger
.error("Error contacting VIM to know if the image exists at VIM: %s", str(e
))
685 logger
.warn("Error contacting VIM to know if the image exists at VIM: %s", str(e
))
688 #if we reach here, the image has been created or existed
690 #add new vim_id at datacenters_images
691 mydb
.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id
,
692 'image_id':image_mano_id
,
693 'vim_id': image_vim_id
,
694 'created':image_created
})
695 elif image_db
[0]["vim_id"]!=image_vim_id
:
696 #modify existing vim_id at datacenters_images
697 mydb
.update_rows('datacenters_images', UPDATE
={'vim_id':image_vim_id
}, WHERE
={'datacenter_vim_id':vim_id
, 'image_id':image_mano_id
})
699 return image_vim_id
if only_create_at_vim
else image_mano_id
702 def create_or_use_flavor(mydb
, vims
, flavor_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
= None):
703 temp_flavor_dict
= {'disk':flavor_dict
.get('disk',0),
704 'ram':flavor_dict
.get('ram'),
705 'vcpus':flavor_dict
.get('vcpus'),
707 if 'extended' in flavor_dict
and flavor_dict
['extended']==None:
708 del flavor_dict
['extended']
709 if 'extended' in flavor_dict
:
710 temp_flavor_dict
['extended']=yaml
.safe_dump(flavor_dict
['extended'],default_flow_style
=True,width
=256)
712 #look if flavor exist
713 if only_create_at_vim
:
714 flavor_mano_id
= flavor_dict
['uuid']
715 if return_on_error
== None:
716 return_on_error
= True
718 flavors
= mydb
.get_rows(FROM
="flavors", WHERE
=temp_flavor_dict
)
720 flavor_mano_id
= flavors
[0]['uuid']
723 #create one by one the images of aditional disks
724 dev_image_list
=[] #list of images
725 if 'extended' in flavor_dict
and flavor_dict
['extended']!=None:
727 for device
in flavor_dict
['extended'].get('devices',[]):
728 if "image" not in device
and "image name" not in device
:
731 image_dict
['name']=device
.get('image name',flavor_dict
['name']+str(dev_nb
)+"-img")
732 image_dict
['universal_name']=device
.get('image name')
733 image_dict
['description']=flavor_dict
['name']+str(dev_nb
)+"-img"
734 image_dict
['location']=device
.get('image')
735 #image_dict['new_location']=vnfc.get('image location')
736 image_dict
['checksum']=device
.get('image checksum')
737 image_metadata_dict
= device
.get('image metadata', None)
738 image_metadata_str
= None
739 if image_metadata_dict
!= None:
740 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
741 image_dict
['metadata']=image_metadata_str
742 image_id
= create_or_use_image(mydb
, vims
, image_dict
, rollback_list
)
743 #print "Additional disk image id for VNFC %s: %s" % (flavor_dict['name']+str(dev_nb)+"-img", image_id)
744 dev_image_list
.append(image_id
)
746 temp_flavor_dict
['name'] = flavor_dict
['name']
747 temp_flavor_dict
['description'] = flavor_dict
.get('description',None)
748 content
= mydb
.new_row('flavors', temp_flavor_dict
, add_uuid
=True)
749 flavor_mano_id
= content
750 rollback_list
.append({"where":"mano", "what":"flavor","uuid":flavor_mano_id
})
751 #create flavor at every vim
752 if 'uuid' in flavor_dict
:
753 del flavor_dict
['uuid']
755 for vim_id
,vim
in vims
.items():
756 datacenter_vim_id
= vim
["config"]["datacenter_tenant_id"]
757 flavor_created
="false"
759 flavor_db
= mydb
.get_rows(FROM
="datacenters_flavors",
760 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
})
761 #look at VIM if this flavor exist SKIPPED
762 #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location'])
764 # print "Error contacting VIM to know if the flavor %s existed previously." %flavor_vim_id
768 # Create the flavor in VIM
769 # Translate images at devices from MANO id to VIM id
771 if 'extended' in flavor_dict
and flavor_dict
['extended']!=None and "devices" in flavor_dict
['extended']:
772 # make a copy of original devices
775 for device
in flavor_dict
["extended"].get("devices",[]):
778 devices_original
.append(dev
)
779 if 'image' in device
:
781 if 'image metadata' in device
:
782 del device
['image metadata']
783 if 'image checksum' in device
:
784 del device
['image checksum']
786 for index
in range(0,len(devices_original
)) :
787 device
=devices_original
[index
]
788 if "image" not in device
and "image name" not in device
:
789 # if 'size' in device:
790 disk_list
.append({'size': device
.get('size', default_volume_size
), 'name': device
.get('name')})
793 image_dict
['name']=device
.get('image name',flavor_dict
['name']+str(dev_nb
)+"-img")
794 image_dict
['universal_name']=device
.get('image name')
795 image_dict
['description']=flavor_dict
['name']+str(dev_nb
)+"-img"
796 image_dict
['location']=device
.get('image')
797 # image_dict['new_location']=device.get('image location')
798 image_dict
['checksum']=device
.get('image checksum')
799 image_metadata_dict
= device
.get('image metadata', None)
800 image_metadata_str
= None
801 if image_metadata_dict
!= None:
802 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
803 image_dict
['metadata']=image_metadata_str
804 image_mano_id
=create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=False, return_on_error
=return_on_error
)
805 image_dict
["uuid"]=image_mano_id
806 image_vim_id
=create_or_use_image(mydb
, vims
, image_dict
, rollback_list
, only_create_at_vim
=True, return_on_error
=return_on_error
)
808 #save disk information (image must be based on and size
809 disk_list
.append({'image_id': image_vim_id
, 'size': device
.get('size', default_volume_size
)})
811 flavor_dict
["extended"]["devices"][index
]['imageRef']=image_vim_id
814 #check that this vim_id exist in VIM, if not create
815 flavor_vim_id
=flavor_db
[0]["vim_id"]
817 vim
.get_flavor(flavor_vim_id
)
818 continue #flavor exist
819 except vimconn
.vimconnException
:
821 #create flavor at vim
822 logger
.debug("nfvo.create_or_use_flavor() adding flavor to VIM %s", vim
["name"])
825 flavor_vim_id
=vim
.get_flavor_id_from_data(flavor_dict
)
826 flavor_created
="false"
827 except vimconn
.vimconnException
as e
:
830 if not flavor_vim_id
:
831 flavor_vim_id
= vim
.new_flavor(flavor_dict
)
832 rollback_list
.append({"where":"vim", "vim_id": vim_id
, "what":"flavor","uuid":flavor_vim_id
})
833 flavor_created
="true"
834 except vimconn
.vimconnException
as e
:
836 logger
.error("Error creating flavor at VIM %s: %s.", vim
["name"], str(e
))
838 logger
.warn("Error creating flavor at VIM %s: %s.", vim
["name"], str(e
))
841 #if reach here the flavor has been create or exist
842 if len(flavor_db
)==0:
843 #add new vim_id at datacenters_flavors
844 extended_devices_yaml
= None
845 if len(disk_list
) > 0:
846 extended_devices
= dict()
847 extended_devices
['disks'] = disk_list
848 extended_devices_yaml
= yaml
.safe_dump(extended_devices
,default_flow_style
=True,width
=256)
849 mydb
.new_row('datacenters_flavors',
850 {'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
, 'vim_id': flavor_vim_id
,
851 'created': flavor_created
, 'extended': extended_devices_yaml
})
852 elif flavor_db
[0]["vim_id"]!=flavor_vim_id
:
853 #modify existing vim_id at datacenters_flavors
854 mydb
.update_rows('datacenters_flavors', UPDATE
={'vim_id':flavor_vim_id
},
855 WHERE
={'datacenter_vim_id': datacenter_vim_id
, 'flavor_id': flavor_mano_id
})
857 return flavor_vim_id
if only_create_at_vim
else flavor_mano_id
860 def get_str(obj
, field
, length
):
862 Obtain the str value,
867 value
= obj
.get(field
)
868 if value
is not None:
869 value
= str(value
)[:length
]
872 def _lookfor_or_create_image(db_image
, mydb
, descriptor
):
874 fill image content at db_image dictionary. Check if the image with this image and checksum exist
875 :param db_image: dictionary to insert data
876 :param mydb: database connector
877 :param descriptor: yang descriptor
878 :return: uuid if the image exist at DB, or None if a new image must be created with the data filled at db_image
881 db_image
["name"] = get_str(descriptor
, "image", 255)
882 db_image
["checksum"] = get_str(descriptor
, "image-checksum", 32)
883 if not db_image
["checksum"]: # Ensure that if empty string, None is stored
884 db_image
["checksum"] = None
885 if db_image
["name"].startswith("/"):
886 db_image
["location"] = db_image
["name"]
887 existing_images
= mydb
.get_rows(FROM
="images", WHERE
={'location': db_image
["location"]})
889 db_image
["universal_name"] = db_image
["name"]
890 existing_images
= mydb
.get_rows(FROM
="images", WHERE
={'universal_name': db_image
['universal_name'],
891 'checksum': db_image
['checksum']})
893 return existing_images
[0]["uuid"]
895 image_uuid
= str(uuid4())
896 db_image
["uuid"] = image_uuid
899 def get_resource_allocation_params(quota_descriptor
):
901 read the quota_descriptor from vnfd and fetch the resource allocation properties from the descriptor object
902 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
903 :return: quota params for limit, reserve, shares from the descriptor object
906 if quota_descriptor
.get("limit"):
907 quota
["limit"] = int(quota_descriptor
["limit"])
908 if quota_descriptor
.get("reserve"):
909 quota
["reserve"] = int(quota_descriptor
["reserve"])
910 if quota_descriptor
.get("shares"):
911 quota
["shares"] = int(quota_descriptor
["shares"])
914 def new_vnfd_v3(mydb
, tenant_id
, vnf_descriptor
):
916 Parses an OSM IM vnfd_catalog and insert at DB
919 :param vnf_descriptor:
920 :return: The list of cretated vnf ids
923 myvnfd
= vnfd_catalog
.vnfd()
925 pybindJSONDecoder
.load_ietf_json(vnf_descriptor
, None, None, obj
=myvnfd
, path_helper
=True,
927 except Exception as e
:
928 raise NfvoException("Error. Invalid VNF descriptor format " + str(e
), httperrors
.Bad_Request
)
936 db_ip_profiles_index
= 0
940 vnfd_catalog_descriptor
= vnf_descriptor
.get("vnfd:vnfd-catalog")
941 if not vnfd_catalog_descriptor
:
942 vnfd_catalog_descriptor
= vnf_descriptor
.get("vnfd-catalog")
943 vnfd_descriptor_list
= vnfd_catalog_descriptor
.get("vnfd")
944 if not vnfd_descriptor_list
:
945 vnfd_descriptor_list
= vnfd_catalog_descriptor
.get("vnfd:vnfd")
946 for vnfd_yang
in myvnfd
.vnfd_catalog
.vnfd
.values():
947 vnfd
= vnfd_yang
.get()
950 vnf_uuid
= str(uuid4())
951 uuid_list
.append(vnf_uuid
)
952 vnfd_uuid_list
.append(vnf_uuid
)
953 vnfd_id
= get_str(vnfd
, "id", 255)
957 "name": get_str(vnfd
, "name", 255),
958 "description": get_str(vnfd
, "description", 255),
959 "tenant_id": tenant_id
,
960 "vendor": get_str(vnfd
, "vendor", 255),
961 "short_name": get_str(vnfd
, "short-name", 255),
962 "descriptor": str(vnf_descriptor
)[:60000]
965 for vnfd_descriptor
in vnfd_descriptor_list
:
966 if vnfd_descriptor
["id"] == str(vnfd
["id"]):
969 # table ip_profiles (ip-profiles)
970 ip_profile_name2db_table_index
= {}
971 for ip_profile
in vnfd
.get("ip-profiles").values():
973 "ip_version": str(ip_profile
["ip-profile-params"].get("ip-version", "ipv4")),
974 "subnet_address": str(ip_profile
["ip-profile-params"].get("subnet-address")),
975 "gateway_address": str(ip_profile
["ip-profile-params"].get("gateway-address")),
976 "dhcp_enabled": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("enabled", True)),
977 "dhcp_start_address": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("start-address")),
978 "dhcp_count": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("count")),
981 for dns
in ip_profile
["ip-profile-params"]["dns-server"].values():
982 dns_list
.append(str(dns
.get("address")))
983 db_ip_profile
["dns_address"] = ";".join(dns_list
)
984 if ip_profile
["ip-profile-params"].get('security-group'):
985 db_ip_profile
["security_group"] = ip_profile
["ip-profile-params"]['security-group']
986 ip_profile_name2db_table_index
[str(ip_profile
["name"])] = db_ip_profiles_index
987 db_ip_profiles_index
+= 1
988 db_ip_profiles
.append(db_ip_profile
)
990 # table nets (internal-vld)
991 net_id2uuid
= {} # for mapping interface with network
992 net_id2index
= {} # for mapping interface with network
993 for vld
in vnfd
.get("internal-vld").values():
994 net_uuid
= str(uuid4())
995 uuid_list
.append(net_uuid
)
997 "name": get_str(vld
, "name", 255),
1000 "description": get_str(vld
, "description", 255),
1001 "osm_id": get_str(vld
, "id", 255),
1002 "type": "bridge", # TODO adjust depending on connection point type
1004 net_id2uuid
[vld
.get("id")] = net_uuid
1005 net_id2index
[vld
.get("id")] = len(db_nets
)
1006 db_nets
.append(db_net
)
1007 # ip-profile, link db_ip_profile with db_sce_net
1008 if vld
.get("ip-profile-ref"):
1009 ip_profile_name
= vld
.get("ip-profile-ref")
1010 if ip_profile_name
not in ip_profile_name2db_table_index
:
1011 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vld[{}]':'ip-profile-ref':"
1012 "'{}'. Reference to a non-existing 'ip_profiles'".format(
1013 str(vnfd
["id"]), str(vld
["id"]), str(vld
["ip-profile-ref"])),
1014 httperrors
.Bad_Request
)
1015 db_ip_profiles
[ip_profile_name2db_table_index
[ip_profile_name
]]["net_id"] = net_uuid
1016 else: #check no ip-address has been defined
1017 for icp
in vld
.get("internal-connection-point").values():
1018 if icp
.get("ip-address"):
1019 raise NfvoException("Error at 'vnfd[{}]':'vld[{}]':'internal-connection-point[{}]' "
1020 "contains an ip-address but no ip-profile has been defined at VLD".format(
1021 str(vnfd
["id"]), str(vld
["id"]), str(icp
["id"])),
1022 httperrors
.Bad_Request
)
1024 # connection points vaiable declaration
1025 cp_name2iface_uuid
= {}
1027 cp_name2vm_uuid
= {}
1028 cp_name2db_interface
= {}
1029 vdu_id2cp_name
= {} # stored only when one external connection point is presented at this VDU
1033 vdu_id2db_table_index
= {}
1035 for vdu
in vnfd
.get("vdu").values():
1037 for vdu_descriptor
in vnfd_descriptor
["vdu"]:
1038 if vdu_descriptor
["id"] == str(vdu
["id"]):
1040 vm_uuid
= str(uuid4())
1041 uuid_list
.append(vm_uuid
)
1042 vdu_id
= get_str(vdu
, "id", 255)
1046 "name": get_str(vdu
, "name", 255),
1047 "description": get_str(vdu
, "description", 255),
1048 "pdu_type": get_str(vdu
, "pdu-type", 255),
1051 vdu_id2uuid
[db_vm
["osm_id"]] = vm_uuid
1052 vdu_id2db_table_index
[db_vm
["osm_id"]] = db_vms_index
1053 if vdu
.get("count"):
1054 db_vm
["count"] = int(vdu
["count"])
1057 image_present
= False
1058 if vdu
.get("image"):
1059 image_present
= True
1061 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, vdu
)
1063 image_uuid
= db_image
["uuid"]
1064 db_images
.append(db_image
)
1065 db_vm
["image_id"] = image_uuid
1066 if vdu
.get("alternative-images"):
1067 vm_alternative_images
= []
1068 for alt_image
in vdu
.get("alternative-images").values():
1070 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, alt_image
)
1072 image_uuid
= db_image
["uuid"]
1073 db_images
.append(db_image
)
1074 vm_alternative_images
.append({
1075 "image_id": image_uuid
,
1076 "vim_type": str(alt_image
["vim-type"]),
1077 # "universal_name": str(alt_image["image"]),
1078 # "checksum": str(alt_image["image-checksum"]) if alt_image.get("image-checksum") else None
1081 db_vm
["image_list"] = yaml
.safe_dump(vm_alternative_images
, default_flow_style
=True, width
=256)
1085 if vdu
.get("volumes"):
1086 for volume_key
in vdu
["volumes"]:
1087 volume
= vdu
["volumes"][volume_key
]
1088 if not image_present
:
1089 # Convert the first volume to vnfc.image
1090 image_present
= True
1092 image_uuid
= _lookfor_or_create_image(db_image
, mydb
, volume
)
1094 image_uuid
= db_image
["uuid"]
1095 db_images
.append(db_image
)
1096 db_vm
["image_id"] = image_uuid
1098 # Add Openmano devices
1099 device
= {"name": str(volume
.get("name"))}
1100 device
["type"] = str(volume
.get("device-type"))
1101 if volume
.get("size"):
1102 device
["size"] = int(volume
["size"])
1103 if volume
.get("image"):
1104 device
["image name"] = str(volume
["image"])
1105 if volume
.get("image-checksum"):
1106 device
["image checksum"] = str(volume
["image-checksum"])
1108 devices
.append(device
)
1110 if not db_vm
.get("image_id"):
1111 if not db_vm
["pdu_type"]:
1112 raise NfvoException("Not defined image for VDU")
1113 # create a fake image
1117 if vdu
.get("cloud-init"):
1118 boot_data
["user-data"] = str(vdu
["cloud-init"])
1119 elif vdu
.get("cloud-init-file"):
1120 # TODO Where this file content is present???
1121 # boot_data["user-data"] = vnfd_yang.files[vdu["cloud-init-file"]]
1122 boot_data
["user-data"] = str(vdu
["cloud-init-file"])
1124 if vdu
.get("supplemental-boot-data"):
1125 if vdu
["supplemental-boot-data"].get('boot-data-drive'):
1126 boot_data
['boot-data-drive'] = True
1127 if vdu
["supplemental-boot-data"].get('config-file'):
1128 om_cfgfile_list
= list()
1129 for custom_config_file
in vdu
["supplemental-boot-data"]['config-file'].values():
1130 # TODO Where this file content is present???
1131 cfg_source
= str(custom_config_file
["source"])
1132 om_cfgfile_list
.append({"dest": custom_config_file
["dest"],
1133 "content": cfg_source
})
1134 boot_data
['config-files'] = om_cfgfile_list
1136 db_vm
["boot_data"] = yaml
.safe_dump(boot_data
, default_flow_style
=True, width
=256)
1138 db_vms
.append(db_vm
)
1141 # table interfaces (internal/external interfaces)
1142 flavor_epa_interfaces
= []
1143 # for iface in chain(vdu.get("internal-interface").values(), vdu.get("external-interface").values()):
1144 for iface
in vdu
.get("interface").values():
1145 flavor_epa_interface
= {}
1146 iface_uuid
= str(uuid4())
1147 uuid_list
.append(iface_uuid
)
1150 "internal_name": get_str(iface
, "name", 255),
1153 flavor_epa_interface
["name"] = db_interface
["internal_name"]
1154 if iface
.get("virtual-interface").get("vpci"):
1155 db_interface
["vpci"] = get_str(iface
.get("virtual-interface"), "vpci", 12)
1156 flavor_epa_interface
["vpci"] = db_interface
["vpci"]
1158 if iface
.get("virtual-interface").get("bandwidth"):
1159 bps
= int(iface
.get("virtual-interface").get("bandwidth"))
1160 db_interface
["bw"] = int(math
.ceil(bps
/ 1000000.0))
1161 flavor_epa_interface
["bandwidth"] = "{} Mbps".format(db_interface
["bw"])
1163 if iface
.get("virtual-interface").get("type") == "OM-MGMT":
1164 db_interface
["type"] = "mgmt"
1165 elif iface
.get("virtual-interface").get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1166 db_interface
["type"] = "bridge"
1167 db_interface
["model"] = get_str(iface
.get("virtual-interface"), "type", 12)
1168 elif iface
.get("virtual-interface").get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1169 db_interface
["type"] = "data"
1170 db_interface
["model"] = get_str(iface
.get("virtual-interface"), "type", 12)
1171 flavor_epa_interface
["dedicated"] = "no" if iface
["virtual-interface"]["type"] == "SR-IOV" \
1173 flavor_epa_interfaces
.append(flavor_epa_interface
)
1175 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{}]':'vdu[{}]':'interface':'virtual"
1176 "-interface':'type':'{}'. Interface type is not supported".format(
1177 vnfd_id
, vdu_id
, iface
.get("virtual-interface").get("type")),
1178 httperrors
.Bad_Request
)
1180 if iface
.get("mgmt-interface"):
1181 db_interface
["type"] = "mgmt"
1183 if iface
.get("external-connection-point-ref"):
1185 cp
= vnfd
.get("connection-point")[iface
.get("external-connection-point-ref")]
1186 db_interface
["external_name"] = get_str(cp
, "name", 255)
1187 cp_name2iface_uuid
[db_interface
["external_name"]] = iface_uuid
1188 cp_name2vdu_id
[db_interface
["external_name"]] = vdu_id
1189 cp_name2vm_uuid
[db_interface
["external_name"]] = vm_uuid
1190 cp_name2db_interface
[db_interface
["external_name"]] = db_interface
1191 for cp_descriptor
in vnfd_descriptor
["connection-point"]:
1192 if cp_descriptor
["name"] == db_interface
["external_name"]:
1197 if vdu_id
in vdu_id2cp_name
:
1198 vdu_id2cp_name
[vdu_id
] = None # more than two connection point for this VDU
1200 vdu_id2cp_name
[vdu_id
] = db_interface
["external_name"]
1203 if str(cp_descriptor
.get("port-security-enabled")).lower() == "false":
1204 db_interface
["port_security"] = 0
1205 elif str(cp_descriptor
.get("port-security-enabled")).lower() == "true":
1206 db_interface
["port_security"] = 1
1208 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1209 "'interface[{iface}]':'vnfd-connection-point-ref':'{cp}' is not present"
1210 " at connection-point".format(
1211 vnf
=vnfd_id
, vdu
=vdu_id
, iface
=iface
["name"],
1212 cp
=iface
.get("vnfd-connection-point-ref")),
1213 httperrors
.Bad_Request
)
1214 elif iface
.get("internal-connection-point-ref"):
1216 for icp_descriptor
in vdu_descriptor
["internal-connection-point"]:
1217 if icp_descriptor
["id"] == str(iface
.get("internal-connection-point-ref")):
1220 raise KeyError("does not exist at vdu:internal-connection-point")
1223 for vld
in vnfd
.get("internal-vld").values():
1224 for cp
in vld
.get("internal-connection-point").values():
1225 if cp
.get("id-ref") == iface
.get("internal-connection-point-ref"):
1227 raise KeyError("is referenced by more than one 'internal-vld'")
1231 raise KeyError("is not referenced by any 'internal-vld'")
1233 # set network type as data
1234 if iface
.get("virtual-interface") and iface
["virtual-interface"].get("type") in \
1235 ("SR-IOV", "PCI-PASSTHROUGH"):
1236 db_nets
[net_id2index
[icp_vld
.get("id")]]["type"] = "data"
1237 db_interface
["net_id"] = net_id2uuid
[icp_vld
.get("id")]
1238 if str(icp_descriptor
.get("port-security-enabled")).lower() == "false":
1239 db_interface
["port_security"] = 0
1240 elif str(icp_descriptor
.get("port-security-enabled")).lower() == "true":
1241 db_interface
["port_security"] = 1
1242 if icp
.get("ip-address"):
1243 if not icp_vld
.get("ip-profile-ref"):
1245 db_interface
["ip_address"] = str(icp
.get("ip-address"))
1246 except KeyError as e
:
1247 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'vdu[{vdu}]':"
1248 "'interface[{iface}]':'internal-connection-point-ref':'{cp}'"
1250 vnf
=vnfd_id
, vdu
=vdu_id
, iface
=iface
["name"],
1251 cp
=iface
.get("internal-connection-point-ref"), msg
=str(e
)),
1252 httperrors
.Bad_Request
)
1253 if iface
.get("position"):
1254 db_interface
["created_at"] = int(iface
.get("position")) * 50
1255 if iface
.get("mac-address"):
1256 db_interface
["mac"] = str(iface
.get("mac-address"))
1257 db_interfaces
.append(db_interface
)
1261 "name": get_str(vdu
, "name", 250) + "-flv",
1262 "vcpus": int(vdu
["vm-flavor"].get("vcpu-count", 1)),
1263 "ram": int(vdu
["vm-flavor"].get("memory-mb", 1)),
1264 "disk": int(vdu
["vm-flavor"].get("storage-gb", 0)),
1266 # TODO revise the case of several numa-node-policy node
1270 extended
["devices"] = devices
1271 if flavor_epa_interfaces
:
1272 numa
["interfaces"] = flavor_epa_interfaces
1273 if vdu
.get("guest-epa"): # TODO or dedicated_int:
1274 epa_vcpu_set
= False
1275 if vdu
["guest-epa"].get("numa-node-policy"): # TODO or dedicated_int:
1276 numa_node_policy
= vdu
["guest-epa"].get("numa-node-policy")
1277 if numa_node_policy
.get("node"):
1278 numa_node
= next(iter(numa_node_policy
["node"].values()))
1279 if numa_node
.get("num-cores"):
1280 numa
["cores"] = numa_node
["num-cores"]
1282 if numa_node
.get("paired-threads"):
1283 if numa_node
["paired-threads"].get("num-paired-threads"):
1284 numa
["paired-threads"] = int(numa_node
["paired-threads"]["num-paired-threads"])
1286 if len(numa_node
["paired-threads"].get("paired-thread-ids")):
1287 numa
["paired-threads-id"] = []
1288 for pair
in numa_node
["paired-threads"]["paired-thread-ids"].values():
1289 numa
["paired-threads-id"].append(
1290 (str(pair
["thread-a"]), str(pair
["thread-b"]))
1292 if numa_node
.get("num-threads"):
1293 numa
["threads"] = int(numa_node
["num-threads"])
1295 if numa_node
.get("memory-mb"):
1296 numa
["memory"] = max(int(numa_node
["memory-mb"] / 1024), 1)
1297 if vdu
["guest-epa"].get("mempage-size"):
1298 if vdu
["guest-epa"]["mempage-size"] != "SMALL":
1299 numa
["memory"] = max(int(db_flavor
["ram"] / 1024), 1)
1300 if vdu
["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set
:
1301 if vdu
["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
1302 if vdu
["guest-epa"].get("cpu-thread-pinning-policy") and \
1303 vdu
["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
1304 numa
["cores"] = max(db_flavor
["vcpus"], 1)
1306 numa
["threads"] = max(db_flavor
["vcpus"], 1)
1308 if vdu
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
1309 cpuquota
= get_resource_allocation_params(vdu
["guest-epa"].get("cpu-quota"))
1311 extended
["cpu-quota"] = cpuquota
1312 if vdu
["guest-epa"].get("mem-quota"):
1313 vduquota
= get_resource_allocation_params(vdu
["guest-epa"].get("mem-quota"))
1315 extended
["mem-quota"] = vduquota
1316 if vdu
["guest-epa"].get("disk-io-quota"):
1317 diskioquota
= get_resource_allocation_params(vdu
["guest-epa"].get("disk-io-quota"))
1319 extended
["disk-io-quota"] = diskioquota
1320 if vdu
["guest-epa"].get("vif-quota"):
1321 vifquota
= get_resource_allocation_params(vdu
["guest-epa"].get("vif-quota"))
1323 extended
["vif-quota"] = vifquota
1325 extended
["numas"] = [numa
]
1327 extended_text
= yaml
.safe_dump(extended
, default_flow_style
=True, width
=256)
1328 db_flavor
["extended"] = extended_text
1329 # look if flavor exist
1330 temp_flavor_dict
= {'disk': db_flavor
.get('disk', 0),
1331 'ram': db_flavor
.get('ram'),
1332 'vcpus': db_flavor
.get('vcpus'),
1333 'extended': db_flavor
.get('extended')
1335 existing_flavors
= mydb
.get_rows(FROM
="flavors", WHERE
=temp_flavor_dict
)
1336 if existing_flavors
:
1337 flavor_uuid
= existing_flavors
[0]["uuid"]
1339 flavor_uuid
= str(uuid4())
1340 uuid_list
.append(flavor_uuid
)
1341 db_flavor
["uuid"] = flavor_uuid
1342 db_flavors
.append(db_flavor
)
1343 db_vm
["flavor_id"] = flavor_uuid
1345 # VNF affinity and antiaffinity
1346 for pg
in vnfd
.get("placement-groups").values():
1347 pg_name
= get_str(pg
, "name", 255)
1348 for vdu
in pg
.get("member-vdus").values():
1349 vdu_id
= get_str(vdu
, "member-vdu-ref", 255)
1350 if vdu_id
not in vdu_id2db_table_index
:
1351 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'placement-groups[{pg}]':"
1352 "'member-vdus':'{vdu}'. Reference to a non-existing vdu".format(
1353 vnf
=vnfd_id
, pg
=pg_name
, vdu
=vdu_id
),
1354 httperrors
.Bad_Request
)
1355 db_vms
[vdu_id2db_table_index
[vdu_id
]]["availability_zone"] = pg_name
1356 # TODO consider the case of isolation and not colocation
1357 # if pg.get("strategy") == "ISOLATION":
1359 # VNF mgmt configuration
1360 if vnfd
["mgmt-interface"].get("vdu-id"):
1361 mgmt_vdu_id
= get_str(vnfd
["mgmt-interface"], "vdu-id", 255)
1362 if mgmt_vdu_id
not in vdu_id2uuid
:
1363 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'vdu-id':"
1364 "'{vdu}'. Reference to a non-existing vdu".format(
1365 vnf
=vnfd_id
, vdu
=mgmt_vdu_id
),
1366 httperrors
.Bad_Request
)
1367 mgmt_access
["vm_id"] = vdu_id2uuid
[mgmt_vdu_id
]
1368 mgmt_access
["vdu-id"] = mgmt_vdu_id
1369 # if only one cp is defined by this VDU, mark this interface as of type "mgmt"
1370 if vdu_id2cp_name
.get(mgmt_vdu_id
):
1371 if cp_name2db_interface
[vdu_id2cp_name
[mgmt_vdu_id
]]:
1372 cp_name2db_interface
[vdu_id2cp_name
[mgmt_vdu_id
]]["type"] = "mgmt"
1374 if vnfd
["mgmt-interface"].get("ip-address"):
1375 mgmt_access
["ip-address"] = str(vnfd
["mgmt-interface"].get("ip-address"))
1376 if vnfd
["mgmt-interface"].get("cp") and vnfd
.get("vdu"):
1377 if vnfd
["mgmt-interface"]["cp"] not in cp_name2iface_uuid
:
1378 raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
1379 "Reference to a non-existing connection-point".format(
1380 vnf
=vnfd_id
, cp
=vnfd
["mgmt-interface"]["cp"]),
1381 httperrors
.Bad_Request
)
1382 mgmt_access
["vm_id"] = cp_name2vm_uuid
[vnfd
["mgmt-interface"]["cp"]]
1383 mgmt_access
["interface_id"] = cp_name2iface_uuid
[vnfd
["mgmt-interface"]["cp"]]
1384 mgmt_access
["vdu-id"] = cp_name2vdu_id
[vnfd
["mgmt-interface"]["cp"]]
1385 # mark this interface as of type mgmt
1386 if cp_name2db_interface
[vnfd
["mgmt-interface"]["cp"]]:
1387 cp_name2db_interface
[vnfd
["mgmt-interface"]["cp"]]["type"] = "mgmt"
1389 default_user
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1392 mgmt_access
["default_user"] = default_user
1394 required
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}).get("ssh-access", {}),
1397 mgmt_access
["required"] = required
1399 password_
= get_str(vnfd
.get("vnf-configuration", {}).get("config-access", {}),
1402 mgmt_access
["password"] = password_
1405 db_vnf
["mgmt_access"] = yaml
.safe_dump(mgmt_access
, default_flow_style
=True, width
=256)
1407 db_vnfs
.append(db_vnf
)
1411 {"images": db_images
},
1412 {"flavors": db_flavors
},
1413 {"ip_profiles": db_ip_profiles
},
1415 {"interfaces": db_interfaces
},
1418 logger
.debug("create_vnf Deployment done vnfDict: %s",
1419 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False) )
1420 mydb
.new_rows(db_tables
, uuid_list
)
1421 return vnfd_uuid_list
1422 except NfvoException
:
1424 except Exception as e
:
1425 logger
.error("Exception {}".format(e
))
1426 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
1429 @deprecated("Use new_vnfd_v3")
1430 def new_vnf(mydb
, tenant_id
, vnf_descriptor
):
1431 global global_config
1433 # Step 1. Check the VNF descriptor
1434 check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=1)
1435 # Step 2. Check tenant exist
1437 if tenant_id
!= "any":
1438 check_tenant(mydb
, tenant_id
)
1439 if "tenant_id" in vnf_descriptor
["vnf"]:
1440 if vnf_descriptor
["vnf"]["tenant_id"] != tenant_id
:
1441 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor
["vnf"]["tenant_id"], tenant_id
),
1442 httperrors
.Unauthorized
)
1444 vnf_descriptor
['vnf']['tenant_id'] = tenant_id
1445 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1446 if global_config
["auto_push_VNF_to_VIMs"]:
1447 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1449 # Step 4. Review the descriptor and add missing fields
1450 #print vnf_descriptor
1451 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1452 vnf_name
= vnf_descriptor
['vnf']['name']
1453 vnf_descriptor
['vnf']['description'] = vnf_descriptor
['vnf'].get("description", vnf_name
)
1454 if "physical" in vnf_descriptor
['vnf']:
1455 del vnf_descriptor
['vnf']['physical']
1456 #print vnf_descriptor
1458 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1459 logger
.debug('BEGIN creation of VNF "%s"' % vnf_name
)
1460 logger
.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name
,len(vnf_descriptor
['vnf']['VNFC'])))
1462 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1463 VNFCDict
= {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1464 rollback_list
= [] # It will contain the new images created in mano. It is used for rollback
1466 logger
.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1467 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1469 VNFCitem
["name"] = vnfc
['name']
1470 VNFCitem
["availability_zone"] = vnfc
.get('availability_zone')
1471 VNFCitem
["description"] = vnfc
.get("description", 'VM {} of the VNF {}'.format(vnfc
['name'],vnf_name
))
1473 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
1476 myflavorDict
["name"] = vnfc
['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
1477 myflavorDict
["description"] = VNFCitem
["description"]
1478 myflavorDict
["ram"] = vnfc
.get("ram", 0)
1479 myflavorDict
["vcpus"] = vnfc
.get("vcpus", 0)
1480 myflavorDict
["disk"] = vnfc
.get("disk", 0)
1481 myflavorDict
["extended"] = {}
1483 devices
= vnfc
.get("devices")
1485 myflavorDict
["extended"]["devices"] = devices
1488 # 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
1489 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1491 # Previous code has been commented
1492 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1493 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1494 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1495 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1497 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1499 # print "Error creating flavor: unknown processor model. Rollback successful."
1500 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1502 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1503 myflavorDict
['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1505 if 'numas' in vnfc
and len(vnfc
['numas'])>0:
1506 myflavorDict
['extended']['numas'] = vnfc
['numas']
1510 # Step 6.2 New flavors are created in the VIM
1511 flavor_id
= create_or_use_flavor(mydb
, vims
, myflavorDict
, rollback_list
)
1513 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1514 VNFCitem
["flavor_id"] = flavor_id
1515 VNFCDict
[vnfc
['name']] = VNFCitem
1517 logger
.debug("Creating new images in the VIM for each VNFC")
1518 # Step 6.3 New images are created in the VIM
1519 #For each VNFC, we must create the appropriate image.
1520 #This "for" loop might be integrated with the previous one
1521 #In case this integration is made, the VNFCDict might become a VNFClist.
1522 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1523 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
1525 image_dict
['name']=vnfc
.get('image name',vnf_name
+"-"+vnfc
['name']+"-img")
1526 image_dict
['universal_name']=vnfc
.get('image name')
1527 image_dict
['description']=vnfc
.get('image name', VNFCDict
[vnfc
['name']]['description'])
1528 image_dict
['location']=vnfc
.get('VNFC image')
1529 #image_dict['new_location']=vnfc.get('image location')
1530 image_dict
['checksum']=vnfc
.get('image checksum')
1531 image_metadata_dict
= vnfc
.get('image metadata', None)
1532 image_metadata_str
= None
1533 if image_metadata_dict
is not None:
1534 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
1535 image_dict
['metadata']=image_metadata_str
1536 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1537 image_id
= create_or_use_image(mydb
, vims
, image_dict
, rollback_list
)
1538 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1539 VNFCDict
[vnfc
['name']]["image_id"] = image_id
1540 VNFCDict
[vnfc
['name']]["image_path"] = vnfc
.get('VNFC image')
1541 VNFCDict
[vnfc
['name']]["count"] = vnfc
.get('count', 1)
1542 if vnfc
.get("boot-data"):
1543 VNFCDict
[vnfc
['name']]["boot_data"] = yaml
.safe_dump(vnfc
["boot-data"], default_flow_style
=True, width
=256)
1546 # Step 7. Storing the VNF descriptor in the repository
1547 if "descriptor" not in vnf_descriptor
["vnf"]:
1548 vnf_descriptor
["vnf"]["descriptor"] = yaml
.safe_dump(vnf_descriptor
, indent
=4, explicit_start
=True, default_flow_style
=False)
1550 # Step 8. Adding the VNF to the NFVO DB
1551 vnf_id
= mydb
.new_vnf_as_a_whole(tenant_id
,vnf_name
,vnf_descriptor
,VNFCDict
)
1553 except (db_base_Exception
, vimconn
.vimconnException
, KeyError) as e
:
1554 _
, message
= rollback(mydb
, vims
, rollback_list
)
1555 if isinstance(e
, db_base_Exception
):
1556 error_text
= "Exception at database"
1557 elif isinstance(e
, KeyError):
1558 error_text
= "KeyError exception "
1559 e
.http_code
= httperrors
.Internal_Server_Error
1561 error_text
= "Exception at VIM"
1562 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
1563 #logger.error("start_scenario %s", error_text)
1564 raise NfvoException(error_text
, e
.http_code
)
1567 @deprecated("Use new_vnfd_v3")
1568 def new_vnf_v02(mydb
, tenant_id
, vnf_descriptor
):
1569 global global_config
1571 # Step 1. Check the VNF descriptor
1572 check_vnf_descriptor(vnf_descriptor
, vnf_descriptor_version
=2)
1573 # Step 2. Check tenant exist
1575 if tenant_id
!= "any":
1576 check_tenant(mydb
, tenant_id
)
1577 if "tenant_id" in vnf_descriptor
["vnf"]:
1578 if vnf_descriptor
["vnf"]["tenant_id"] != tenant_id
:
1579 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(vnf_descriptor
["vnf"]["tenant_id"], tenant_id
),
1580 httperrors
.Unauthorized
)
1582 vnf_descriptor
['vnf']['tenant_id'] = tenant_id
1583 # Step 3. Get the URL of the VIM from the nfvo_tenant and the datacenter
1584 if global_config
["auto_push_VNF_to_VIMs"]:
1585 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1587 # Step 4. Review the descriptor and add missing fields
1588 #print vnf_descriptor
1589 #logger.debug("Refactoring VNF descriptor with fields: description, public (default: true)")
1590 vnf_name
= vnf_descriptor
['vnf']['name']
1591 vnf_descriptor
['vnf']['description'] = vnf_descriptor
['vnf'].get("description", vnf_name
)
1592 if "physical" in vnf_descriptor
['vnf']:
1593 del vnf_descriptor
['vnf']['physical']
1594 #print vnf_descriptor
1596 # Step 6. For each VNFC in the descriptor, flavors and images are created in the VIM
1597 logger
.debug('BEGIN creation of VNF "%s"' % vnf_name
)
1598 logger
.debug("VNF %s: consisting of %d VNFC(s)" % (vnf_name
,len(vnf_descriptor
['vnf']['VNFC'])))
1600 #For each VNFC, we add it to the VNFCDict and we create a flavor.
1601 VNFCDict
= {} # Dictionary, key: VNFC name, value: dict with the relevant information to create the VNF and VMs in the MANO database
1602 rollback_list
= [] # It will contain the new images created in mano. It is used for rollback
1604 logger
.debug("Creating additional disk images and new flavors in the VIM for each VNFC")
1605 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1607 VNFCitem
["name"] = vnfc
['name']
1608 VNFCitem
["description"] = vnfc
.get("description", 'VM {} of the VNF {}'.format(vnfc
['name'],vnf_name
))
1610 #print "Flavor name: %s. Description: %s" % (VNFCitem["name"]+"-flv", VNFCitem["description"])
1613 myflavorDict
["name"] = vnfc
['name']+"-flv" #Maybe we could rename the flavor by using the field "image name" if exists
1614 myflavorDict
["description"] = VNFCitem
["description"]
1615 myflavorDict
["ram"] = vnfc
.get("ram", 0)
1616 myflavorDict
["vcpus"] = vnfc
.get("vcpus", 0)
1617 myflavorDict
["disk"] = vnfc
.get("disk", 0)
1618 myflavorDict
["extended"] = {}
1620 devices
= vnfc
.get("devices")
1622 myflavorDict
["extended"]["devices"] = devices
1625 # 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
1626 # Another option is that the processor in the VNF descriptor specifies directly the ranking of the host
1628 # Previous code has been commented
1629 #if vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz" :
1630 # myflavorDict["flavor"]['extended']['processor_ranking'] = 200
1631 #elif vnfc['processor']['model'] == "Intel(R) Xeon(R) CPU E5-2697 v2 @ 2.70GHz" :
1632 # myflavorDict["flavor"]['extended']['processor_ranking'] = 300
1634 # result2, message = rollback(myvim, myvimURL, myvim_tenant, flavorList, imageList)
1636 # print "Error creating flavor: unknown processor model. Rollback successful."
1637 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback successful."
1639 # return -httperrors.Bad_Request, "Error creating flavor: unknown processor model. Rollback fail: you need to access VIM and delete the following %s" % message
1640 myflavorDict
['extended']['processor_ranking'] = 100 #Hardcoded value, while we decide when the mapping is done
1642 if 'numas' in vnfc
and len(vnfc
['numas'])>0:
1643 myflavorDict
['extended']['numas'] = vnfc
['numas']
1647 # Step 6.2 New flavors are created in the VIM
1648 flavor_id
= create_or_use_flavor(mydb
, vims
, myflavorDict
, rollback_list
)
1650 #print "Flavor id for VNFC %s: %s" % (vnfc['name'],flavor_id)
1651 VNFCitem
["flavor_id"] = flavor_id
1652 VNFCDict
[vnfc
['name']] = VNFCitem
1654 logger
.debug("Creating new images in the VIM for each VNFC")
1655 # Step 6.3 New images are created in the VIM
1656 #For each VNFC, we must create the appropriate image.
1657 #This "for" loop might be integrated with the previous one
1658 #In case this integration is made, the VNFCDict might become a VNFClist.
1659 for vnfc
in vnf_descriptor
['vnf']['VNFC']:
1660 #print "Image name: %s. Description: %s" % (vnfc['name']+"-img", VNFCDict[vnfc['name']]['description'])
1662 image_dict
['name']=vnfc
.get('image name',vnf_name
+"-"+vnfc
['name']+"-img")
1663 image_dict
['universal_name']=vnfc
.get('image name')
1664 image_dict
['description']=vnfc
.get('image name', VNFCDict
[vnfc
['name']]['description'])
1665 image_dict
['location']=vnfc
.get('VNFC image')
1666 #image_dict['new_location']=vnfc.get('image location')
1667 image_dict
['checksum']=vnfc
.get('image checksum')
1668 image_metadata_dict
= vnfc
.get('image metadata', None)
1669 image_metadata_str
= None
1670 if image_metadata_dict
is not None:
1671 image_metadata_str
= yaml
.safe_dump(image_metadata_dict
,default_flow_style
=True,width
=256)
1672 image_dict
['metadata']=image_metadata_str
1673 #print "create_or_use_image", mydb, vims, image_dict, rollback_list
1674 image_id
= create_or_use_image(mydb
, vims
, image_dict
, rollback_list
)
1675 #print "Image id for VNFC %s: %s" % (vnfc['name'],image_id)
1676 VNFCDict
[vnfc
['name']]["image_id"] = image_id
1677 VNFCDict
[vnfc
['name']]["image_path"] = vnfc
.get('VNFC image')
1678 VNFCDict
[vnfc
['name']]["count"] = vnfc
.get('count', 1)
1679 if vnfc
.get("boot-data"):
1680 VNFCDict
[vnfc
['name']]["boot_data"] = yaml
.safe_dump(vnfc
["boot-data"], default_flow_style
=True, width
=256)
1682 # Step 7. Storing the VNF descriptor in the repository
1683 if "descriptor" not in vnf_descriptor
["vnf"]:
1684 vnf_descriptor
["vnf"]["descriptor"] = yaml
.safe_dump(vnf_descriptor
, indent
=4, explicit_start
=True, default_flow_style
=False)
1686 # Step 8. Adding the VNF to the NFVO DB
1687 vnf_id
= mydb
.new_vnf_as_a_whole2(tenant_id
,vnf_name
,vnf_descriptor
,VNFCDict
)
1689 except (db_base_Exception
, vimconn
.vimconnException
, KeyError) as e
:
1690 _
, message
= rollback(mydb
, vims
, rollback_list
)
1691 if isinstance(e
, db_base_Exception
):
1692 error_text
= "Exception at database"
1693 elif isinstance(e
, KeyError):
1694 error_text
= "KeyError exception "
1695 e
.http_code
= httperrors
.Internal_Server_Error
1697 error_text
= "Exception at VIM"
1698 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
1699 #logger.error("start_scenario %s", error_text)
1700 raise NfvoException(error_text
, e
.http_code
)
1703 def get_vnf_id(mydb
, tenant_id
, vnf_id
):
1704 #check valid tenant_id
1705 check_tenant(mydb
, tenant_id
)
1708 if tenant_id
!= "any":
1709 where_or
["tenant_id"] = tenant_id
1710 where_or
["public"] = True
1711 vnf
= mydb
.get_table_by_uuid_name('vnfs', vnf_id
, "VNF", WHERE_OR
=where_or
, WHERE_AND_OR
="AND")
1713 vnf_id
= vnf
["uuid"]
1714 filter_keys
= ('uuid', 'name', 'description', 'public', "tenant_id", "osm_id", "created_at")
1715 filtered_content
= dict( (k
,v
) for k
,v
in vnf
.items() if k
in filter_keys
)
1716 #change_keys_http2db(filtered_content, http2db_vnf, reverse=True)
1717 data
={'vnf' : filtered_content
}
1719 content
= mydb
.get_rows(FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id',
1720 SELECT
=('vms.uuid as uuid', 'vms.osm_id as osm_id', 'vms.name as name', 'vms.description as description',
1722 WHERE
={'vnfs.uuid': vnf_id
} )
1723 if len(content
) != 0:
1724 #raise NfvoException("vnf '{}' not found".format(vnf_id), httperrors.Not_Found)
1725 # change boot_data into boot-data
1727 if vm
.get("boot_data"):
1728 vm
["boot-data"] = yaml
.safe_load(vm
["boot_data"])
1731 data
['vnf']['VNFC'] = content
1732 #TODO: GET all the information from a VNFC and include it in the output.
1735 content
= mydb
.get_rows(FROM
='vnfs join nets on vnfs.uuid=nets.vnf_id',
1736 SELECT
=('nets.uuid as uuid','nets.name as name','nets.description as description', 'nets.type as type', 'nets.multipoint as multipoint'),
1737 WHERE
={'vnfs.uuid': vnf_id
} )
1738 data
['vnf']['nets'] = content
1740 #GET ip-profile for each net
1741 for net
in data
['vnf']['nets']:
1742 ipprofiles
= mydb
.get_rows(FROM
='ip_profiles',
1743 SELECT
=('ip_version','subnet_address','gateway_address','dns_address','dhcp_enabled','dhcp_start_address','dhcp_count'),
1744 WHERE
={'net_id': net
["uuid"]} )
1745 if len(ipprofiles
)==1:
1746 net
["ip_profile"] = ipprofiles
[0]
1747 elif len(ipprofiles
)>1:
1748 raise NfvoException("More than one ip-profile found with this criteria: net_id='{}'".format(net
['uuid']), httperrors
.Bad_Request
)
1751 #TODO: For each net, GET its elements and relevant info per element (VNFC, iface, ip_address) and include them in the output.
1753 #GET External Interfaces
1754 content
= mydb
.get_rows(FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces on vms.uuid=interfaces.vm_id',\
1755 SELECT
=('interfaces.uuid as uuid','interfaces.external_name as external_name', 'vms.name as vm_name', 'interfaces.vm_id as vm_id', \
1756 'interfaces.internal_name as internal_name', 'interfaces.type as type', 'interfaces.vpci as vpci','interfaces.bw as bw'),\
1757 WHERE
={'vnfs.uuid': vnf_id
, 'interfaces.external_name<>': None} )
1759 data
['vnf']['external-connections'] = content
1764 def delete_vnf(mydb
,tenant_id
,vnf_id
,datacenter
=None,vim_tenant
=None):
1765 # Check tenant exist
1766 if tenant_id
!= "any":
1767 check_tenant(mydb
, tenant_id
)
1768 # Get the URL of the VIM from the nfvo_tenant and the datacenter
1769 vims
= get_vim(mydb
, tenant_id
, ignore_errors
=True)
1773 # Checking if it is a valid uuid and, if not, getting the uuid assuming that the name was provided"
1775 if tenant_id
!= "any":
1776 where_or
["tenant_id"] = tenant_id
1777 where_or
["public"] = True
1778 vnf
= mydb
.get_table_by_uuid_name('vnfs', vnf_id
, "VNF", WHERE_OR
=where_or
, WHERE_AND_OR
="AND")
1779 vnf_id
= vnf
["uuid"]
1781 # "Getting the list of flavors and tenants of the VNF"
1782 flavorList
= get_flavorlist(mydb
, vnf_id
)
1783 if len(flavorList
)==0:
1784 logger
.warn("delete_vnf error. No flavors found for the VNF id '%s'", vnf_id
)
1786 imageList
= get_imagelist(mydb
, vnf_id
)
1787 if len(imageList
)==0:
1788 logger
.warn( "delete_vnf error. No images found for the VNF id '%s'", vnf_id
)
1790 deleted
= mydb
.delete_row_by_id('vnfs', vnf_id
)
1792 raise NfvoException("vnf '{}' not found".format(vnf_id
), httperrors
.Not_Found
)
1795 for flavor
in flavorList
:
1796 #check if flavor is used by other vnf
1798 c
= mydb
.get_rows(FROM
='vms', WHERE
={'flavor_id':flavor
} )
1800 logger
.debug("Flavor '%s' not deleted because it is being used by another VNF", flavor
)
1802 #flavor not used, must be deleted
1804 c
= mydb
.get_rows(FROM
='datacenters_flavors', WHERE
={'flavor_id': flavor
})
1805 for flavor_vim
in c
:
1806 if not flavor_vim
['created']: # skip this flavor because not created by openmano
1810 for vim
in vims
.values():
1811 if vim
["config"]["datacenter_tenant_id"] == flavor_vim
["datacenter_vim_id"]:
1817 myvim
.delete_flavor(flavor_vim
["vim_id"])
1818 except vimconn
.vimconnNotFoundException
:
1819 logger
.warn("VIM flavor %s not exist at datacenter %s", flavor_vim
["vim_id"],
1820 flavor_vim
["datacenter_vim_id"] )
1821 except vimconn
.vimconnException
as e
:
1822 logger
.error("Not possible to delete VIM flavor %s from datacenter %s: %s %s",
1823 flavor_vim
["vim_id"], flavor_vim
["datacenter_vim_id"], type(e
).__name
__, str(e
))
1824 undeletedItems
.append("flavor {} from VIM {}".format(flavor_vim
["vim_id"],
1825 flavor_vim
["datacenter_vim_id"]))
1826 # delete flavor from Database, using table flavors and with cascade foreign key also at datacenters_flavors
1827 mydb
.delete_row_by_id('flavors', flavor
)
1828 except db_base_Exception
as e
:
1829 logger
.error("delete_vnf_error. Not possible to get flavor details and delete '%s'. %s", flavor
, str(e
))
1830 undeletedItems
.append("flavor {}".format(flavor
))
1833 for image
in imageList
:
1835 #check if image is used by other vnf
1836 c
= mydb
.get_rows(FROM
='vms', WHERE
=[{'image_id': image
}, {'image_list LIKE ': '%' + image
+ '%'}])
1838 logger
.debug("Image '%s' not deleted because it is being used by another VNF", image
)
1840 #image not used, must be deleted
1842 c
= mydb
.get_rows(FROM
='datacenters_images', WHERE
={'image_id':image
})
1844 if image_vim
["datacenter_vim_id"] not in vims
: # TODO change to datacenter_tenant_id
1846 if image_vim
['created']=='false': #skip this image because not created by openmano
1848 myvim
=vims
[ image_vim
["datacenter_id"] ]
1850 myvim
.delete_image(image_vim
["vim_id"])
1851 except vimconn
.vimconnNotFoundException
as e
:
1852 logger
.warn("VIM image %s not exist at datacenter %s", image_vim
["vim_id"], image_vim
["datacenter_id"] )
1853 except vimconn
.vimconnException
as e
:
1854 logger
.error("Not possible to delete VIM image %s from datacenter %s: %s %s",
1855 image_vim
["vim_id"], image_vim
["datacenter_id"], type(e
).__name
__, str(e
))
1856 undeletedItems
.append("image {} from VIM {}".format(image_vim
["vim_id"], image_vim
["datacenter_id"] ))
1857 #delete image from Database, using table images and with cascade foreign key also at datacenters_images
1858 mydb
.delete_row_by_id('images', image
)
1859 except db_base_Exception
as e
:
1860 logger
.error("delete_vnf_error. Not possible to get image details and delete '%s'. %s", image
, str(e
))
1861 undeletedItems
.append("image {}".format(image
))
1863 return vnf_id
+ " " + vnf
["name"]
1865 # return "delete_vnf. Undeleted: %s" %(undeletedItems)
1868 @deprecated("Not used")
1869 def get_hosts_info(mydb
, nfvo_tenant_id
, datacenter_name
=None):
1870 result
, vims
= get_vim(mydb
, nfvo_tenant_id
, None, datacenter_name
)
1874 return -httperrors
.Not_Found
, "datacenter '{}' not found".format(datacenter_name
)
1875 myvim
= next(iter(vims
.values()))
1876 result
,servers
= myvim
.get_hosts_info()
1878 return result
, servers
1879 topology
= {'name':myvim
['name'] , 'servers': servers
}
1880 return result
, topology
1883 def get_hosts(mydb
, nfvo_tenant_id
):
1884 vims
= get_vim(mydb
, nfvo_tenant_id
)
1886 raise NfvoException("No datacenter found for tenant '{}'".format(str(nfvo_tenant_id
)), httperrors
.Not_Found
)
1888 #print "nfvo.datacenter_action() error. Several datacenters found"
1889 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors
.Conflict
)
1890 myvim
= next(iter(vims
.values()))
1892 hosts
= myvim
.get_hosts()
1893 logger
.debug('VIM hosts response: '+ yaml
.safe_dump(hosts
, indent
=4, default_flow_style
=False))
1895 datacenter
= {'Datacenters': [ {'name':myvim
['name'],'servers':[]} ] }
1897 server
={'name':host
['name'], 'vms':[]}
1898 for vm
in host
['instances']:
1899 #get internal name and model
1901 c
= mydb
.get_rows(SELECT
=('name',), FROM
='instance_vms as iv join vms on iv.vm_id=vms.uuid',\
1902 WHERE
={'vim_vm_id':vm
['id']} )
1904 logger
.warn("nfvo.get_hosts virtual machine at VIM '{}' not found at tidnfvo".format(vm
['id']))
1906 server
['vms'].append( {'name':vm
['name'] , 'model':c
[0]['name']} )
1908 except db_base_Exception
as e
:
1909 logger
.warn("nfvo.get_hosts virtual machine at VIM '{}' error {}".format(vm
['id'], str(e
)))
1910 datacenter
['Datacenters'][0]['servers'].append(server
)
1911 #return -400, "en construccion"
1913 #print 'datacenters '+ json.dumps(datacenter, indent=4)
1915 except vimconn
.vimconnException
as e
:
1916 raise NfvoException("Not possible to get_host_list from VIM: {}".format(str(e
)), e
.http_code
)
1919 @deprecated("Use new_nsd_v3")
1920 def new_scenario(mydb
, tenant_id
, topo
):
1922 # result, vims = get_vim(mydb, tenant_id)
1924 # return result, vims
1926 if tenant_id
!= "any":
1927 check_tenant(mydb
, tenant_id
)
1928 if "tenant_id" in topo
:
1929 if topo
["tenant_id"] != tenant_id
:
1930 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(topo
["tenant_id"], tenant_id
),
1931 httperrors
.Unauthorized
)
1935 #1.1: get VNFs and external_networks (other_nets).
1937 other_nets
={} #external_networks, bridge_networks and data_networkds
1938 nodes
= topo
['topology']['nodes']
1939 for k
in nodes
.keys():
1940 if nodes
[k
]['type'] == 'VNF':
1942 vnfs
[k
]['ifaces'] = {}
1943 elif nodes
[k
]['type'] == 'other_network' or nodes
[k
]['type'] == 'external_network':
1944 other_nets
[k
] = nodes
[k
]
1945 other_nets
[k
]['external']=True
1946 elif nodes
[k
]['type'] == 'network':
1947 other_nets
[k
] = nodes
[k
]
1948 other_nets
[k
]['external']=False
1951 #1.2: Check that VNF are present at database table vnfs. Insert uuid, description and external interfaces
1952 for name
,vnf
in vnfs
.items():
1953 where
= {"OR": {"tenant_id": tenant_id
, 'public': "true"}}
1955 error_pos
= "'topology':'nodes':'" + name
+ "'"
1957 error_text
+= " 'vnf_id' " + vnf
['vnf_id']
1958 where
['uuid'] = vnf
['vnf_id']
1959 if 'VNF model' in vnf
:
1960 error_text
+= " 'VNF model' " + vnf
['VNF model']
1961 where
['name'] = vnf
['VNF model']
1963 raise NfvoException("Descriptor need a 'vnf_id' or 'VNF model' field at " + error_pos
, httperrors
.Bad_Request
)
1965 vnf_db
= mydb
.get_rows(SELECT
=('uuid','name','description'),
1969 raise NfvoException("unknown" + error_text
+ " at " + error_pos
, httperrors
.Not_Found
)
1971 raise NfvoException("more than one" + error_text
+ " at " + error_pos
+ " Concrete with 'vnf_id'", httperrors
.Conflict
)
1972 vnf
['uuid']=vnf_db
[0]['uuid']
1973 vnf
['description']=vnf_db
[0]['description']
1974 #get external interfaces
1975 ext_ifaces
= mydb
.get_rows(SELECT
=('external_name as name','i.uuid as iface_uuid', 'i.type as type'),
1976 FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
1977 WHERE
={'vnfs.uuid':vnf
['uuid'], 'external_name<>': None} )
1978 for ext_iface
in ext_ifaces
:
1979 vnf
['ifaces'][ ext_iface
['name'] ] = {'uuid':ext_iface
['iface_uuid'], 'type':ext_iface
['type']}
1981 #1.4 get list of connections
1982 conections
= topo
['topology']['connections']
1983 conections_list
= []
1984 conections_list_name
= []
1985 for k
in conections
.keys():
1986 if type(conections
[k
]['nodes'])==dict: #dict with node:iface pairs
1987 ifaces_list
= conections
[k
]['nodes'].items()
1988 elif type(conections
[k
]['nodes'])==list: #list with dictionary
1990 conection_pair_list
= map(lambda x
: x
.items(), conections
[k
]['nodes'] )
1991 for k2
in conection_pair_list
:
1994 con_type
= conections
[k
].get("type", "link")
1995 if con_type
!= "link":
1997 raise NfvoException("Format error. Reapeted network name at 'topology':'connections':'{}'".format(str(k
)), httperrors
.Bad_Request
)
1998 other_nets
[k
] = {'external': False}
1999 if conections
[k
].get("graph"):
2000 other_nets
[k
]["graph"] = conections
[k
]["graph"]
2001 ifaces_list
.append( (k
, None) )
2004 if con_type
== "external_network":
2005 other_nets
[k
]['external'] = True
2006 if conections
[k
].get("model"):
2007 other_nets
[k
]["model"] = conections
[k
]["model"]
2009 other_nets
[k
]["model"] = k
2010 if con_type
== "dataplane_net" or con_type
== "bridge_net":
2011 other_nets
[k
]["model"] = con_type
2013 conections_list_name
.append(k
)
2014 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)
2015 #print set(ifaces_list)
2016 #check valid VNF and iface names
2017 for iface
in ifaces_list
:
2018 if iface
[0] not in vnfs
and iface
[0] not in other_nets
:
2019 raise NfvoException("format error. Invalid VNF name at 'topology':'connections':'{}':'nodes':'{}'".format(
2020 str(k
), iface
[0]), httperrors
.Not_Found
)
2021 if iface
[0] in vnfs
and iface
[1] not in vnfs
[ iface
[0] ]['ifaces']:
2022 raise NfvoException("format error. Invalid interface name at 'topology':'connections':'{}':'nodes':'{}':'{}'".format(
2023 str(k
), iface
[0], iface
[1]), httperrors
.Not_Found
)
2025 #1.5 unify connections from the pair list to a consolidated list
2027 while index
< len(conections_list
):
2029 while index2
< len(conections_list
):
2030 if len(conections_list
[index
] & conections_list
[index2
])>0: #common interface, join nets
2031 conections_list
[index
] |
= conections_list
[index2
]
2032 del conections_list
[index2
]
2033 del conections_list_name
[index2
]
2036 conections_list
[index
] = list(conections_list
[index
]) # from set to list again
2038 #for k in conections_list:
2043 #1.6 Delete non external nets
2044 # for k in other_nets.keys():
2045 # if other_nets[k]['model']=='bridge' or other_nets[k]['model']=='dataplane_net' or other_nets[k]['model']=='bridge_net':
2046 # for con in conections_list:
2048 # for index in range(0,len(con)):
2049 # if con[index][0] == k: delete_indexes.insert(0,index) #order from higher to lower
2050 # for index in delete_indexes:
2053 #1.7: Check external_ports are present at database table datacenter_nets
2054 for k
,net
in other_nets
.items():
2055 error_pos
= "'topology':'nodes':'" + k
+ "'"
2056 if net
['external']==False:
2057 if 'name' not in net
:
2059 if 'model' not in net
:
2060 raise NfvoException("needed a 'model' at " + error_pos
, httperrors
.Bad_Request
)
2061 if net
['model']=='bridge_net':
2062 net
['type']='bridge';
2063 elif net
['model']=='dataplane_net':
2066 raise NfvoException("unknown 'model' '"+ net
['model'] +"' at " + error_pos
, httperrors
.Not_Found
)
2068 #IF we do not want to check that external network exist at datacenter
2073 # if 'net_id' in net:
2074 # error_text += " 'net_id' " + net['net_id']
2075 # WHERE_['uuid'] = net['net_id']
2076 # if 'model' in net:
2077 # error_text += " 'model' " + net['model']
2078 # WHERE_['name'] = net['model']
2079 # if len(WHERE_) == 0:
2080 # return -httperrors.Bad_Request, "needed a 'net_id' or 'model' at " + error_pos
2081 # r,net_db = mydb.get_table(SELECT=('uuid','name','description','type','shared'),
2082 # FROM='datacenter_nets', WHERE=WHERE_ )
2084 # print "nfvo.new_scenario Error getting datacenter_nets",r,net_db
2086 # print "nfvo.new_scenario Error" +error_text+ " is not present at database"
2087 # return -httperrors.Bad_Request, "unknown " +error_text+ " at " + error_pos
2089 # print "nfvo.new_scenario Error more than one external_network for " +error_text+ " is present at database"
2090 # return -httperrors.Bad_Request, "more than one external_network for " +error_text+ "at "+ error_pos + " Concrete with 'net_id'"
2091 # other_nets[k].update(net_db[0])
2094 net_nb
=0 #Number of nets
2095 for con
in conections_list
:
2096 #check if this is connected to a external net
2100 for index
in range(0,len(con
)):
2101 #check if this is connected to a external net
2102 for net_key
in other_nets
.keys():
2103 if con
[index
][0]==net_key
:
2104 if other_net_index
>=0:
2105 error_text
= "There is some interface connected both to net '{}' and net '{}'".format(
2106 con
[other_net_index
][0], net_key
)
2107 #print "nfvo.new_scenario " + error_text
2108 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2110 other_net_index
= index
2111 net_target
= net_key
2113 #print "other_net_index", other_net_index
2115 if other_net_index
>=0:
2116 del con
[other_net_index
]
2117 #IF we do not want to check that external network exist at datacenter
2118 if other_nets
[net_target
]['external'] :
2119 if "name" not in other_nets
[net_target
]:
2120 other_nets
[net_target
]['name'] = other_nets
[net_target
]['model']
2121 if other_nets
[net_target
]["type"] == "external_network":
2122 if vnfs
[ con
[0][0] ]['ifaces'][ con
[0][1] ]["type"] == "data":
2123 other_nets
[net_target
]["type"] = "data"
2125 other_nets
[net_target
]["type"] = "bridge"
2127 # if other_nets[net_target]['external'] :
2128 # 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
2129 # if type_=='data' and other_nets[net_target]['type']=="ptp":
2130 # error_text = "Error connecting %d nodes on a not multipoint net %s" % (len(con), net_target)
2131 # print "nfvo.new_scenario " + error_text
2132 # return -httperrors.Bad_Request, error_text
2135 vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['net_key'] = net_target
2138 net_type_bridge
=False
2140 net_target
= "__-__net"+str(net_nb
)
2141 net_list
[net_target
] = {'name': conections_list_name
[net_nb
], #"net-"+str(net_nb),
2142 'description':"net-{} in scenario {}".format(net_nb
,topo
['name']),
2145 vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['net_key'] = net_target
2146 iface_type
= vnfs
[ iface
[0] ]['ifaces'][ iface
[1] ]['type']
2147 if iface_type
=='mgmt' or iface_type
=='bridge':
2148 net_type_bridge
= True
2150 net_type_data
= True
2151 if net_type_bridge
and net_type_data
:
2152 error_text
= "Error connection interfaces of bridge type with data type. Firs node {}, iface {}".format(iface
[0], iface
[1])
2153 #print "nfvo.new_scenario " + error_text
2154 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2155 elif net_type_bridge
:
2158 type_
='data' if len(con
)>2 else 'ptp'
2159 net_list
[net_target
]['type'] = type_
2162 error_text
= "Error connection node {} : {} does not match any VNF or interface".format(iface
[0], iface
[1])
2163 #print "nfvo.new_scenario " + error_text
2165 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2167 #1.8: Connect to management net all not already connected interfaces of type 'mgmt'
2168 #1.8.1 obtain management net
2169 mgmt_net
= mydb
.get_rows(SELECT
=('uuid','name','description','type','shared'),
2170 FROM
='datacenter_nets', WHERE
={'name':'mgmt'} )
2171 #1.8.2 check all interfaces from all vnfs
2173 add_mgmt_net
= False
2174 for vnf
in vnfs
.values():
2175 for iface
in vnf
['ifaces'].values():
2176 if iface
['type']=='mgmt' and 'net_key' not in iface
:
2177 #iface not connected
2178 iface
['net_key'] = 'mgmt'
2180 if add_mgmt_net
and 'mgmt' not in net_list
:
2181 net_list
['mgmt']=mgmt_net
[0]
2182 net_list
['mgmt']['external']=True
2183 net_list
['mgmt']['graph']={'visible':False}
2185 net_list
.update(other_nets
)
2187 #print 'net_list', net_list
2192 #2: insert scenario. filling tables scenarios,sce_vnfs,sce_interfaces,sce_nets
2193 c
= mydb
.new_scenario( { 'vnfs':vnfs
, 'nets':net_list
,
2194 'tenant_id':tenant_id
, 'name':topo
['name'],
2195 'description':topo
.get('description',topo
['name']),
2196 'public': topo
.get('public', False)
2202 @deprecated("Use new_nsd_v3")
2203 def new_scenario_v02(mydb
, tenant_id
, scenario_dict
, version
):
2204 """ This creates a new scenario for version 0.2 and 0.3"""
2205 scenario
= scenario_dict
["scenario"]
2206 if tenant_id
!= "any":
2207 check_tenant(mydb
, tenant_id
)
2208 if "tenant_id" in scenario
:
2209 if scenario
["tenant_id"] != tenant_id
:
2210 # print "nfvo.new_scenario_v02() tenant '%s' not found" % tenant_id
2211 raise NfvoException("VNF can not have a different tenant owner '{}', must be '{}'".format(
2212 scenario
["tenant_id"], tenant_id
), httperrors
.Unauthorized
)
2216 # 1: Check that VNF are present at database table vnfs and update content into scenario dict
2217 for name
,vnf
in scenario
["vnfs"].items():
2218 where
= {"OR": {"tenant_id": tenant_id
, 'public': "true"}}
2220 error_pos
= "'scenario':'vnfs':'" + name
+ "'"
2222 error_text
+= " 'vnf_id' " + vnf
['vnf_id']
2223 where
['uuid'] = vnf
['vnf_id']
2224 if 'vnf_name' in vnf
:
2225 error_text
+= " 'vnf_name' " + vnf
['vnf_name']
2226 where
['name'] = vnf
['vnf_name']
2228 raise NfvoException("Needed a 'vnf_id' or 'vnf_name' at " + error_pos
, httperrors
.Bad_Request
)
2229 vnf_db
= mydb
.get_rows(SELECT
=('uuid', 'name', 'description'),
2232 if len(vnf_db
) == 0:
2233 raise NfvoException("Unknown" + error_text
+ " at " + error_pos
, httperrors
.Not_Found
)
2234 elif len(vnf_db
) > 1:
2235 raise NfvoException("More than one" + error_text
+ " at " + error_pos
+ " Concrete with 'vnf_id'", httperrors
.Conflict
)
2236 vnf
['uuid'] = vnf_db
[0]['uuid']
2237 vnf
['description'] = vnf_db
[0]['description']
2239 # get external interfaces
2240 ext_ifaces
= mydb
.get_rows(SELECT
=('external_name as name', 'i.uuid as iface_uuid', 'i.type as type'),
2241 FROM
='vnfs join vms on vnfs.uuid=vms.vnf_id join interfaces as i on vms.uuid=i.vm_id',
2242 WHERE
={'vnfs.uuid':vnf
['uuid'], 'external_name<>': None} )
2243 for ext_iface
in ext_ifaces
:
2244 vnf
['ifaces'][ ext_iface
['name'] ] = {'uuid':ext_iface
['iface_uuid'], 'type': ext_iface
['type']}
2245 # TODO? get internal-connections from db.nets and their profiles, and update scenario[vnfs][internal-connections] accordingly
2247 # 2: Insert net_key and ip_address at every vnf interface
2248 for net_name
, net
in scenario
["networks"].items():
2249 net_type_bridge
= False
2250 net_type_data
= False
2251 for iface_dict
in net
["interfaces"]:
2252 if version
== "0.2":
2253 temp_dict
= iface_dict
2255 elif version
== "0.3":
2256 temp_dict
= {iface_dict
["vnf"] : iface_dict
["vnf_interface"]}
2257 ip_address
= iface_dict
.get('ip_address', None)
2258 for vnf
, iface
in temp_dict
.items():
2259 if vnf
not in scenario
["vnfs"]:
2260 error_text
= "Error at 'networks':'{}':'interfaces' VNF '{}' not match any VNF at 'vnfs'".format(
2262 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2263 raise NfvoException(error_text
, httperrors
.Not_Found
)
2264 if iface
not in scenario
["vnfs"][vnf
]['ifaces']:
2265 error_text
= "Error at 'networks':'{}':'interfaces':'{}' interface not match any VNF interface"\
2266 .format(net_name
, iface
)
2267 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2268 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2269 if "net_key" in scenario
["vnfs"][vnf
]['ifaces'][iface
]:
2270 error_text
= "Error at 'networks':'{}':'interfaces':'{}' interface already connected at network"\
2271 "'{}'".format(net_name
, iface
,scenario
["vnfs"][vnf
]['ifaces'][iface
]['net_key'])
2272 # logger.debug("nfvo.new_scenario_v02 " + error_text)
2273 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2274 scenario
["vnfs"][vnf
]['ifaces'][ iface
]['net_key'] = net_name
2275 scenario
["vnfs"][vnf
]['ifaces'][iface
]['ip_address'] = ip_address
2276 iface_type
= scenario
["vnfs"][vnf
]['ifaces'][iface
]['type']
2277 if iface_type
== 'mgmt' or iface_type
== 'bridge':
2278 net_type_bridge
= True
2280 net_type_data
= True
2282 if net_type_bridge
and net_type_data
:
2283 error_text
= "Error connection interfaces of 'bridge' type and 'data' type at 'networks':'{}':'interfaces'"\
2285 # logger.debug("nfvo.new_scenario " + error_text)
2286 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2287 elif net_type_bridge
:
2290 type_
= 'data' if len(net
["interfaces"]) > 2 else 'ptp'
2292 if net
.get("implementation"): # for v0.3
2293 if type_
== "bridge" and net
["implementation"] == "underlay":
2294 error_text
= "Error connecting interfaces of data type to a network declared as 'underlay' at "\
2295 "'network':'{}'".format(net_name
)
2296 # logger.debug(error_text)
2297 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2298 elif type_
!= "bridge" and net
["implementation"] == "overlay":
2299 error_text
= "Error connecting interfaces of data type to a network declared as 'overlay' at "\
2300 "'network':'{}'".format(net_name
)
2301 # logger.debug(error_text)
2302 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2303 net
.pop("implementation")
2304 if "type" in net
and version
== "0.3": # for v0.3
2305 if type_
== "data" and net
["type"] == "e-line":
2306 error_text
= "Error connecting more than 2 interfaces of data type to a network declared as type "\
2307 "'e-line' at 'network':'{}'".format(net_name
)
2308 # logger.debug(error_text)
2309 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2310 elif type_
== "ptp" and net
["type"] == "e-lan":
2314 net
['name'] = net_name
2315 net
['external'] = net
.get('external', False)
2317 # 3: insert at database
2318 scenario
["nets"] = scenario
["networks"]
2319 scenario
['tenant_id'] = tenant_id
2320 scenario_id
= mydb
.new_scenario(scenario
)
2324 def new_nsd_v3(mydb
, tenant_id
, nsd_descriptor
):
2326 Parses an OSM IM nsd_catalog and insert at DB
2329 :param nsd_descriptor:
2330 :return: The list of created NSD ids
2333 mynsd
= nsd_catalog
.nsd()
2335 pybindJSONDecoder
.load_ietf_json(nsd_descriptor
, None, None, obj
=mynsd
, skip_unknown
=True)
2336 except Exception as e
:
2337 raise NfvoException("Error. Invalid NS descriptor format: " + str(e
), httperrors
.Bad_Request
)
2341 db_sce_interfaces
= []
2344 db_sce_rsp_hops
= []
2345 db_sce_classifiers
= []
2346 db_sce_classifier_matches
= []
2348 db_ip_profiles_index
= 0
2351 for nsd_yang
in mynsd
.nsd_catalog
.nsd
.values():
2352 nsd
= nsd_yang
.get()
2355 scenario_uuid
= str(uuid4())
2356 uuid_list
.append(scenario_uuid
)
2357 nsd_uuid_list
.append(scenario_uuid
)
2359 "uuid": scenario_uuid
,
2360 "osm_id": get_str(nsd
, "id", 255),
2361 "name": get_str(nsd
, "name", 255),
2362 "description": get_str(nsd
, "description", 255),
2363 "tenant_id": tenant_id
,
2364 "vendor": get_str(nsd
, "vendor", 255),
2365 "short_name": get_str(nsd
, "short-name", 255),
2366 "descriptor": str(nsd_descriptor
)[:60000],
2368 db_scenarios
.append(db_scenario
)
2370 # table sce_vnfs (constituent-vnfd)
2371 vnf_index2scevnf_uuid
= {}
2372 vnf_index2vnf_uuid
= {}
2373 for vnf
in nsd
.get("constituent-vnfd").values():
2374 existing_vnf
= mydb
.get_rows(FROM
="vnfs", WHERE
={'osm_id': str(vnf
["vnfd-id-ref"])[:255],
2375 'tenant_id': tenant_id
})
2376 if not existing_vnf
:
2377 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'constituent-vnfd':'vnfd-id-ref':"
2378 "'{}'. Reference to a non-existing VNFD in the catalog".format(
2379 str(nsd
["id"]), str(vnf
["vnfd-id-ref"])[:255]),
2380 httperrors
.Bad_Request
)
2381 sce_vnf_uuid
= str(uuid4())
2382 uuid_list
.append(sce_vnf_uuid
)
2384 "uuid": sce_vnf_uuid
,
2385 "scenario_id": scenario_uuid
,
2386 # "name": get_str(vnf, "member-vnf-index", 255),
2387 "name": existing_vnf
[0]["name"][:200] + "." + get_str(vnf
, "member-vnf-index", 50),
2388 "vnf_id": existing_vnf
[0]["uuid"],
2389 "member_vnf_index": str(vnf
["member-vnf-index"]),
2390 # TODO 'start-by-default': True
2392 vnf_index2scevnf_uuid
[str(vnf
['member-vnf-index'])] = sce_vnf_uuid
2393 vnf_index2vnf_uuid
[str(vnf
['member-vnf-index'])] = existing_vnf
[0]["uuid"]
2394 db_sce_vnfs
.append(db_sce_vnf
)
2396 # table ip_profiles (ip-profiles)
2397 ip_profile_name2db_table_index
= {}
2398 for ip_profile
in nsd
.get("ip-profiles").values():
2400 "ip_version": str(ip_profile
["ip-profile-params"].get("ip-version", "ipv4")),
2401 "subnet_address": str(ip_profile
["ip-profile-params"].get("subnet-address")),
2402 "gateway_address": str(ip_profile
["ip-profile-params"].get("gateway-address")),
2403 "dhcp_enabled": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("enabled", True)),
2404 "dhcp_start_address": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("start-address")),
2405 "dhcp_count": str(ip_profile
["ip-profile-params"]["dhcp-params"].get("count")),
2408 for dns
in ip_profile
["ip-profile-params"]["dns-server"].values():
2409 dns_list
.append(str(dns
.get("address")))
2410 db_ip_profile
["dns_address"] = ";".join(dns_list
)
2411 if ip_profile
["ip-profile-params"].get('security-group'):
2412 db_ip_profile
["security_group"] = ip_profile
["ip-profile-params"]['security-group']
2413 ip_profile_name2db_table_index
[str(ip_profile
["name"])] = db_ip_profiles_index
2414 db_ip_profiles_index
+= 1
2415 db_ip_profiles
.append(db_ip_profile
)
2417 # table sce_nets (internal-vld)
2418 for vld
in nsd
.get("vld").values():
2419 sce_net_uuid
= str(uuid4())
2420 uuid_list
.append(sce_net_uuid
)
2422 "uuid": sce_net_uuid
,
2423 "name": get_str(vld
, "name", 255),
2424 "scenario_id": scenario_uuid
,
2426 "multipoint": not vld
.get("type") == "ELINE",
2427 "osm_id": get_str(vld
, "id", 255),
2429 "description": get_str(vld
, "description", 255),
2431 # guess type of network
2432 if vld
.get("mgmt-network"):
2433 db_sce_net
["type"] = "bridge"
2434 db_sce_net
["external"] = True
2435 elif vld
.get("provider-network").get("overlay-type") == "VLAN":
2436 db_sce_net
["type"] = "data"
2438 # later on it will be fixed to bridge or data depending on the type of interfaces attached to it
2439 db_sce_net
["type"] = None
2440 db_sce_nets
.append(db_sce_net
)
2442 # ip-profile, link db_ip_profile with db_sce_net
2443 if vld
.get("ip-profile-ref"):
2444 ip_profile_name
= vld
.get("ip-profile-ref")
2445 if ip_profile_name
not in ip_profile_name2db_table_index
:
2446 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'ip-profile-ref':'{}'."
2447 " Reference to a non-existing 'ip_profiles'".format(
2448 str(nsd
["id"]), str(vld
["id"]), str(vld
["ip-profile-ref"])),
2449 httperrors
.Bad_Request
)
2450 db_ip_profiles
[ip_profile_name2db_table_index
[ip_profile_name
]]["sce_net_id"] = sce_net_uuid
2451 elif vld
.get("vim-network-name"):
2452 db_sce_net
["vim_network_name"] = get_str(vld
, "vim-network-name", 255)
2454 # table sce_interfaces (vld:vnfd-connection-point-ref)
2455 for iface
in vld
.get("vnfd-connection-point-ref").values():
2456 # Check if there are VDUs in the descriptor
2457 vnf_index
= str(iface
['member-vnf-index-ref'])
2458 existing_vdus
= mydb
.get_rows(SELECT
=('vms.uuid'), FROM
="vms", WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
]})
2460 # check correct parameters
2461 if vnf_index
not in vnf_index2vnf_uuid
:
2462 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2463 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2464 "'nsd':'constituent-vnfd'".format(
2465 str(nsd
["id"]), str(vld
["id"]), str(iface
["member-vnf-index-ref"])),
2466 httperrors
.Bad_Request
)
2468 existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid', 'i.type as iface_type'),
2469 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2470 WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2471 'external_name': get_str(iface
, "vnfd-connection-point-ref",
2473 if not existing_ifaces
:
2474 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
2475 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2476 "connection-point name at VNFD '{}'".format(
2477 str(nsd
["id"]), str(vld
["id"]), str(iface
["vnfd-connection-point-ref"]),
2478 str(iface
.get("vnfd-id-ref"))[:255]),
2479 httperrors
.Bad_Request
)
2480 interface_uuid
= existing_ifaces
[0]["uuid"]
2481 if existing_ifaces
[0]["iface_type"] == "data":
2482 db_sce_net
["type"] = "data"
2483 sce_interface_uuid
= str(uuid4())
2484 uuid_list
.append(sce_net_uuid
)
2485 iface_ip_address
= None
2486 if iface
.get("ip-address"):
2487 iface_ip_address
= str(iface
.get("ip-address"))
2488 db_sce_interface
= {
2489 "uuid": sce_interface_uuid
,
2490 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2491 "sce_net_id": sce_net_uuid
,
2492 "interface_id": interface_uuid
,
2493 "ip_address": iface_ip_address
,
2495 db_sce_interfaces
.append(db_sce_interface
)
2496 if not db_sce_net
["type"]:
2497 db_sce_net
["type"] = "bridge"
2499 # table sce_vnffgs (vnffgd)
2500 for vnffg
in nsd
.get("vnffgd").values():
2501 sce_vnffg_uuid
= str(uuid4())
2502 uuid_list
.append(sce_vnffg_uuid
)
2504 "uuid": sce_vnffg_uuid
,
2505 "name": get_str(vnffg
, "name", 255),
2506 "scenario_id": scenario_uuid
,
2507 "vendor": get_str(vnffg
, "vendor", 255),
2508 "description": get_str(vld
, "description", 255),
2510 db_sce_vnffgs
.append(db_sce_vnffg
)
2513 for rsp
in vnffg
.get("rsp").values():
2514 sce_rsp_uuid
= str(uuid4())
2515 uuid_list
.append(sce_rsp_uuid
)
2517 "uuid": sce_rsp_uuid
,
2518 "name": get_str(rsp
, "name", 255),
2519 "sce_vnffg_id": sce_vnffg_uuid
,
2520 "id": get_str(rsp
, "id", 255), # only useful to link with classifiers; will be removed later in the code
2522 db_sce_rsps
.append(db_sce_rsp
)
2523 for iface
in rsp
.get("vnfd-connection-point-ref").values():
2524 vnf_index
= str(iface
['member-vnf-index-ref'])
2525 if_order
= int(iface
['order'])
2526 # check correct parameters
2527 if vnf_index
not in vnf_index2vnf_uuid
:
2528 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2529 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2530 "'nsd':'constituent-vnfd'".format(
2531 str(nsd
["id"]), str(rsp
["id"]), str(iface
["member-vnf-index-ref"])),
2532 httperrors
.Bad_Request
)
2534 ingress_existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2535 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2537 'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2538 'external_name': get_str(iface
, "vnfd-ingress-connection-point-ref",
2540 if not ingress_existing_ifaces
:
2541 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2542 "-ref':'vnfd-ingress-connection-point-ref':'{}'. Reference to a non-existing "
2543 "connection-point name at VNFD '{}'".format(
2544 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-ingress-connection-point-ref"]),
2545 str(iface
.get("vnfd-id-ref"))[:255]), httperrors
.Bad_Request
)
2547 egress_existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2548 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2550 'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2551 'external_name': get_str(iface
, "vnfd-egress-connection-point-ref",
2553 if not egress_existing_ifaces
:
2554 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2555 "-ref':'vnfd-egress-connection-point-ref':'{}'. Reference to a non-existing "
2556 "connection-point name at VNFD '{}'".format(
2557 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-egress-connection-point-ref"]),
2558 str(iface
.get("vnfd-id-ref"))[:255]), HTTP_Bad_Request
)
2560 ingress_interface_uuid
= ingress_existing_ifaces
[0]["uuid"]
2561 egress_interface_uuid
= egress_existing_ifaces
[0]["uuid"]
2562 sce_rsp_hop_uuid
= str(uuid4())
2563 uuid_list
.append(sce_rsp_hop_uuid
)
2565 "uuid": sce_rsp_hop_uuid
,
2566 "if_order": if_order
,
2567 "ingress_interface_id": ingress_interface_uuid
,
2568 "egress_interface_id": egress_interface_uuid
,
2569 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2570 "sce_rsp_id": sce_rsp_uuid
,
2572 db_sce_rsp_hops
.append(db_sce_rsp_hop
)
2574 # deal with classifiers
2575 for classifier
in vnffg
.get("classifier").values():
2576 sce_classifier_uuid
= str(uuid4())
2577 uuid_list
.append(sce_classifier_uuid
)
2580 vnf_index
= str(classifier
['member-vnf-index-ref'])
2581 if vnf_index
not in vnf_index2vnf_uuid
:
2582 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'classifier[{}]':'vnfd-connection-point"
2583 "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
2584 "'nsd':'constituent-vnfd'".format(
2585 str(nsd
["id"]), str(classifier
["id"]), str(classifier
["member-vnf-index-ref"])),
2586 httperrors
.Bad_Request
)
2587 existing_ifaces
= mydb
.get_rows(SELECT
=('i.uuid as uuid',),
2588 FROM
="interfaces as i join vms on i.vm_id=vms.uuid",
2589 WHERE
={'vnf_id': vnf_index2vnf_uuid
[vnf_index
],
2590 'external_name': get_str(classifier
, "vnfd-connection-point-ref",
2592 if not existing_ifaces
:
2593 raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'rsp[{}]':'vnfd-connection-point"
2594 "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
2595 "connection-point name at VNFD '{}'".format(
2596 str(nsd
["id"]), str(rsp
["id"]), str(iface
["vnfd-connection-point-ref"]),
2597 str(iface
.get("vnfd-id-ref"))[:255]),
2598 httperrors
.Bad_Request
)
2599 interface_uuid
= existing_ifaces
[0]["uuid"]
2601 db_sce_classifier
= {
2602 "uuid": sce_classifier_uuid
,
2603 "name": get_str(classifier
, "name", 255),
2604 "sce_vnffg_id": sce_vnffg_uuid
,
2605 "sce_vnf_id": vnf_index2scevnf_uuid
[vnf_index
],
2606 "interface_id": interface_uuid
,
2608 rsp_id
= get_str(classifier
, "rsp-id-ref", 255)
2609 rsp
= next((item
for item
in db_sce_rsps
if item
["id"] == rsp_id
), None)
2610 db_sce_classifier
["sce_rsp_id"] = rsp
["uuid"]
2611 db_sce_classifiers
.append(db_sce_classifier
)
2613 for match
in classifier
.get("match-attributes").values():
2614 sce_classifier_match_uuid
= str(uuid4())
2615 uuid_list
.append(sce_classifier_match_uuid
)
2616 db_sce_classifier_match
= {
2617 "uuid": sce_classifier_match_uuid
,
2618 "ip_proto": get_str(match
, "ip-proto", 2),
2619 "source_ip": get_str(match
, "source-ip-address", 16),
2620 "destination_ip": get_str(match
, "destination-ip-address", 16),
2621 "source_port": get_str(match
, "source-port", 5),
2622 "destination_port": get_str(match
, "destination-port", 5),
2623 "sce_classifier_id": sce_classifier_uuid
,
2625 db_sce_classifier_matches
.append(db_sce_classifier_match
)
2628 # remove unneeded id's in sce_rsps
2629 for rsp
in db_sce_rsps
:
2633 {"scenarios": db_scenarios
},
2634 {"sce_nets": db_sce_nets
},
2635 {"ip_profiles": db_ip_profiles
},
2636 {"sce_vnfs": db_sce_vnfs
},
2637 {"sce_interfaces": db_sce_interfaces
},
2638 {"sce_vnffgs": db_sce_vnffgs
},
2639 {"sce_rsps": db_sce_rsps
},
2640 {"sce_rsp_hops": db_sce_rsp_hops
},
2641 {"sce_classifiers": db_sce_classifiers
},
2642 {"sce_classifier_matches": db_sce_classifier_matches
},
2645 logger
.debug("new_nsd_v3 done: %s",
2646 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False) )
2647 mydb
.new_rows(db_tables
, uuid_list
)
2648 return nsd_uuid_list
2649 except NfvoException
:
2651 except Exception as e
:
2652 logger
.error("Exception {}".format(e
))
2653 raise # NfvoException("Exception {}".format(e), httperrors.Bad_Request)
2656 def edit_scenario(mydb
, tenant_id
, scenario_id
, data
):
2657 data
["uuid"] = scenario_id
2658 data
["tenant_id"] = tenant_id
2659 c
= mydb
.edit_scenario( data
)
2663 @deprecated("Use create_instance")
2664 def start_scenario(mydb
, tenant_id
, scenario_id
, instance_scenario_name
, instance_scenario_description
, datacenter
=None,vim_tenant
=None, startvms
=True):
2665 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
2666 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
, vim_tenant
=vim_tenant
)
2667 vims
= {datacenter_id
: myvim
}
2668 myvim_tenant
= myvim
['tenant_id']
2669 datacenter_name
= myvim
['name']
2673 #print "Checking that the scenario_id exists and getting the scenario dictionary"
2674 scenarioDict
= mydb
.get_scenario(scenario_id
, tenant_id
, datacenter_id
=datacenter_id
)
2675 scenarioDict
['datacenter2tenant'] = { datacenter_id
: myvim
['config']['datacenter_tenant_id'] }
2676 scenarioDict
['datacenter_id'] = datacenter_id
2677 #print '================scenarioDict======================='
2678 #print json.dumps(scenarioDict, indent=4)
2679 #print 'BEGIN launching instance scenario "%s" based on "%s"' % (instance_scenario_name,scenarioDict['name'])
2681 logger
.debug("start_scenario Scenario %s: consisting of %d VNF(s)", scenarioDict
['name'],len(scenarioDict
['vnfs']))
2682 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2684 auxNetDict
= {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id
2685 auxNetDict
['scenario'] = {}
2687 logger
.debug("start_scenario 1. Creating new nets (sce_nets) in the VIM")
2688 for sce_net
in scenarioDict
['nets']:
2689 #print "Net name: %s. Description: %s" % (sce_net["name"], sce_net["description"])
2691 myNetName
= "{}.{}".format(instance_scenario_name
, sce_net
['name'])
2692 myNetName
= myNetName
[0:255] #limit length
2693 myNetType
= sce_net
['type']
2695 myNetDict
["name"] = myNetName
2696 myNetDict
["type"] = myNetType
2697 myNetDict
["tenant_id"] = myvim_tenant
2698 myNetIPProfile
= sce_net
.get('ip_profile', None)
2699 myProviderNetwork
= sce_net
.get('provider_network', None)
2701 #We should use the dictionary as input parameter for new_network
2703 if not sce_net
["external"]:
2704 network_id
, _
= myvim
.new_network(myNetName
, myNetType
, myNetIPProfile
, provider_network_profile
=myProviderNetwork
)
2705 #print "New VIM network created for scenario %s. Network id: %s" % (scenarioDict['name'],network_id)
2706 sce_net
['vim_id'] = network_id
2707 auxNetDict
['scenario'][sce_net
['uuid']] = network_id
2708 rollbackList
.append({'what':'network','where':'vim','vim_id':datacenter_id
,'uuid':network_id
})
2709 sce_net
["created"] = True
2711 if sce_net
['vim_id'] == None:
2712 error_text
= "Error, datacenter '{}' does not have external network '{}'.".format(
2713 datacenter_name
, sce_net
['name'])
2714 _
, message
= rollback(mydb
, vims
, rollbackList
)
2715 logger
.error("nfvo.start_scenario: %s", error_text
)
2716 raise NfvoException(error_text
, httperrors
.Bad_Request
)
2717 logger
.debug("Using existent VIM network for scenario %s. Network id %s", scenarioDict
['name'],sce_net
['vim_id'])
2718 auxNetDict
['scenario'][sce_net
['uuid']] = sce_net
['vim_id']
2720 logger
.debug("start_scenario 2. Creating new nets (vnf internal nets) in the VIM")
2721 #For each vnf net, we create it and we add it to instanceNetlist.
2723 for sce_vnf
in scenarioDict
['vnfs']:
2724 for net
in sce_vnf
['nets']:
2725 #print "Net name: %s. Description: %s" % (net["name"], net["description"])
2727 myNetName
= "{}.{}".format(instance_scenario_name
,net
['name'])
2728 myNetName
= myNetName
[0:255] #limit length
2729 myNetType
= net
['type']
2731 myNetDict
["name"] = myNetName
2732 myNetDict
["type"] = myNetType
2733 myNetDict
["tenant_id"] = myvim_tenant
2734 myNetIPProfile
= net
.get('ip_profile', None)
2735 myProviderNetwork
= sce_net
.get('provider_network', None)
2738 #We should use the dictionary as input parameter for new_network
2739 network_id
, _
= myvim
.new_network(myNetName
, myNetType
, myNetIPProfile
, provider_network_profile
=myProviderNetwork
)
2740 #print "VIM network id for scenario %s: %s" % (scenarioDict['name'],network_id)
2741 net
['vim_id'] = network_id
2742 if sce_vnf
['uuid'] not in auxNetDict
:
2743 auxNetDict
[sce_vnf
['uuid']] = {}
2744 auxNetDict
[sce_vnf
['uuid']][net
['uuid']] = network_id
2745 rollbackList
.append({'what':'network','where':'vim','vim_id':datacenter_id
,'uuid':network_id
})
2746 net
["created"] = True
2748 #print "auxNetDict:"
2749 #print yaml.safe_dump(auxNetDict, indent=4, default_flow_style=False)
2751 logger
.debug("start_scenario 3. Creating new vm instances in the VIM")
2752 #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
2754 for sce_vnf
in scenarioDict
['vnfs']:
2755 vnf_availability_zones
= []
2756 for vm
in sce_vnf
['vms']:
2757 vm_av
= vm
.get('availability_zone')
2758 if vm_av
and vm_av
not in vnf_availability_zones
:
2759 vnf_availability_zones
.append(vm_av
)
2761 # check if there is enough availability zones available at vim level.
2762 if myvims
[datacenter_id
].availability_zone
and vnf_availability_zones
:
2763 if len(vnf_availability_zones
) > len(myvims
[datacenter_id
].availability_zone
):
2764 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors
.Bad_Request
)
2766 for vm
in sce_vnf
['vms']:
2769 #myVMDict['name'] = "%s-%s-%s" % (scenarioDict['name'],sce_vnf['name'], vm['name'])
2770 myVMDict
['name'] = "{}.{}.{}".format(instance_scenario_name
,sce_vnf
['name'],chr(96+i
))
2771 #myVMDict['description'] = vm['description']
2772 myVMDict
['description'] = myVMDict
['name'][0:99]
2774 myVMDict
['start'] = "no"
2775 myVMDict
['name'] = myVMDict
['name'][0:255] #limit name length
2776 #print "VM name: %s. Description: %s" % (myVMDict['name'], myVMDict['name'])
2778 #create image at vim in case it not exist
2779 image_dict
= mydb
.get_table_by_uuid_name("images", vm
['image_id'])
2780 image_id
= create_or_use_image(mydb
, vims
, image_dict
, [], True)
2781 vm
['vim_image_id'] = image_id
2783 #create flavor at vim in case it not exist
2784 flavor_dict
= mydb
.get_table_by_uuid_name("flavors", vm
['flavor_id'])
2785 if flavor_dict
['extended']!=None:
2786 flavor_dict
['extended']= yaml
.load(flavor_dict
['extended'], Loader
=yaml
.Loader
)
2787 flavor_id
= create_or_use_flavor(mydb
, vims
, flavor_dict
, [], True)
2788 vm
['vim_flavor_id'] = flavor_id
2791 myVMDict
['imageRef'] = vm
['vim_image_id']
2792 myVMDict
['flavorRef'] = vm
['vim_flavor_id']
2793 myVMDict
['networks'] = []
2794 for iface
in vm
['interfaces']:
2796 if iface
['type']=="data":
2797 netDict
['type'] = iface
['model']
2798 elif "model" in iface
and iface
["model"]!=None:
2799 netDict
['model']=iface
['model']
2800 #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model
2801 #discover type of interface looking at flavor
2802 for numa
in flavor_dict
.get('extended',{}).get('numas',[]):
2803 for flavor_iface
in numa
.get('interfaces',[]):
2804 if flavor_iface
.get('name') == iface
['internal_name']:
2805 if flavor_iface
['dedicated'] == 'yes':
2806 netDict
['type']="PF" #passthrough
2807 elif flavor_iface
['dedicated'] == 'no':
2808 netDict
['type']="VF" #siov
2809 elif flavor_iface
['dedicated'] == 'yes:sriov':
2810 netDict
['type']="VFnotShared" #sriov but only one sriov on the PF
2811 netDict
["mac_address"] = flavor_iface
.get("mac_address")
2813 netDict
["use"]=iface
['type']
2814 if netDict
["use"]=="data" and not netDict
.get("type"):
2815 #print "netDict", netDict
2816 #print "iface", iface
2817 e_text
= "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".format(
2818 sce_vnf
['name'], vm
['name'], iface
['internal_name'])
2819 if flavor_dict
.get('extended')==None:
2820 raise NfvoException(e_text
+ "After database migration some information is not available. \
2821 Try to delete and create the scenarios and VNFs again", httperrors
.Conflict
)
2823 raise NfvoException(e_text
, httperrors
.Internal_Server_Error
)
2824 if netDict
["use"]=="mgmt" or netDict
["use"]=="bridge":
2825 netDict
["type"]="virtual"
2826 if "vpci" in iface
and iface
["vpci"] is not None:
2827 netDict
['vpci'] = iface
['vpci']
2828 if "mac" in iface
and iface
["mac"] is not None:
2829 netDict
['mac_address'] = iface
['mac']
2830 if "port-security" in iface
and iface
["port-security"] is not None:
2831 netDict
['port_security'] = iface
['port-security']
2832 if "floating-ip" in iface
and iface
["floating-ip"] is not None:
2833 netDict
['floating_ip'] = iface
['floating-ip']
2834 netDict
['name'] = iface
['internal_name']
2835 if iface
['net_id'] is None:
2836 for vnf_iface
in sce_vnf
["interfaces"]:
2839 if vnf_iface
['interface_id']==iface
['uuid']:
2840 netDict
['net_id'] = auxNetDict
['scenario'][ vnf_iface
['sce_net_id'] ]
2843 netDict
['net_id'] = auxNetDict
[ sce_vnf
['uuid'] ][ iface
['net_id'] ]
2844 #skip bridge ifaces not connected to any net
2845 #if 'net_id' not in netDict or netDict['net_id']==None:
2847 myVMDict
['networks'].append(netDict
)
2848 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2849 #print myVMDict['name']
2850 #print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
2851 #print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
2852 #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
2854 if 'availability_zone' in myVMDict
:
2855 av_index
= vnf_availability_zones
.index(myVMDict
['availability_zone'])
2859 vm_id
, _
= myvim
.new_vminstance(myVMDict
['name'], myVMDict
['description'], myVMDict
.get('start', None),
2860 myVMDict
['imageRef'], myVMDict
['flavorRef'], myVMDict
['networks'],
2861 availability_zone_index
=av_index
,
2862 availability_zone_list
=vnf_availability_zones
)
2863 #print "VIM vm instance id (server id) for scenario %s: %s" % (scenarioDict['name'],vm_id)
2864 vm
['vim_id'] = vm_id
2865 rollbackList
.append({'what':'vm','where':'vim','vim_id':datacenter_id
,'uuid':vm_id
})
2866 #put interface uuid back to scenario[vnfs][vms[[interfaces]
2867 for net
in myVMDict
['networks']:
2869 for iface
in vm
['interfaces']:
2870 if net
["name"]==iface
["internal_name"]:
2871 iface
["vim_id"]=net
["vim_id"]
2874 logger
.debug("start scenario Deployment done")
2875 #print yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)
2876 #r,c = mydb.new_instance_scenario_as_a_whole(nfvo_tenant,scenarioDict['name'],scenarioDict)
2877 instance_id
= mydb
.new_instance_scenario_as_a_whole(tenant_id
,instance_scenario_name
, instance_scenario_description
, scenarioDict
)
2878 return mydb
.get_instance_scenario(instance_id
)
2880 except (db_base_Exception
, vimconn
.vimconnException
) as e
:
2881 _
, message
= rollback(mydb
, vims
, rollbackList
)
2882 if isinstance(e
, db_base_Exception
):
2883 error_text
= "Exception at database"
2885 error_text
= "Exception at VIM"
2886 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
2887 #logger.error("start_scenario %s", error_text)
2888 raise NfvoException(error_text
, e
.http_code
)
2890 def unify_cloud_config(cloud_config_preserve
, cloud_config
):
2891 """ join the cloud config information into cloud_config_preserve.
2892 In case of conflict cloud_config_preserve preserves
2895 if not cloud_config_preserve
and not cloud_config
:
2898 new_cloud_config
= {"key-pairs":[], "users":[]}
2900 if cloud_config_preserve
:
2901 for key
in cloud_config_preserve
.get("key-pairs", () ):
2902 if key
not in new_cloud_config
["key-pairs"]:
2903 new_cloud_config
["key-pairs"].append(key
)
2905 for key
in cloud_config
.get("key-pairs", () ):
2906 if key
not in new_cloud_config
["key-pairs"]:
2907 new_cloud_config
["key-pairs"].append(key
)
2908 if not new_cloud_config
["key-pairs"]:
2909 del new_cloud_config
["key-pairs"]
2913 new_cloud_config
["users"] += cloud_config
.get("users", () )
2914 if cloud_config_preserve
:
2915 new_cloud_config
["users"] += cloud_config_preserve
.get("users", () )
2916 index_to_delete
= []
2917 users
= new_cloud_config
.get("users", [])
2918 for index0
in range(0,len(users
)):
2919 if index0
in index_to_delete
:
2921 for index1
in range(index0
+1,len(users
)):
2922 if index1
in index_to_delete
:
2924 if users
[index0
]["name"] == users
[index1
]["name"]:
2925 index_to_delete
.append(index1
)
2926 for key
in users
[index1
].get("key-pairs",()):
2927 if "key-pairs" not in users
[index0
]:
2928 users
[index0
]["key-pairs"] = [key
]
2929 elif key
not in users
[index0
]["key-pairs"]:
2930 users
[index0
]["key-pairs"].append(key
)
2931 index_to_delete
.sort(reverse
=True)
2932 for index
in index_to_delete
:
2934 if not new_cloud_config
["users"]:
2935 del new_cloud_config
["users"]
2938 if cloud_config
and cloud_config
.get("boot-data-drive") != None:
2939 new_cloud_config
["boot-data-drive"] = cloud_config
["boot-data-drive"]
2940 if cloud_config_preserve
and cloud_config_preserve
.get("boot-data-drive") != None:
2941 new_cloud_config
["boot-data-drive"] = cloud_config_preserve
["boot-data-drive"]
2944 new_cloud_config
["user-data"] = []
2945 if cloud_config
and cloud_config
.get("user-data"):
2946 if isinstance(cloud_config
["user-data"], list):
2947 new_cloud_config
["user-data"] += cloud_config
["user-data"]
2949 new_cloud_config
["user-data"].append(cloud_config
["user-data"])
2950 if cloud_config_preserve
and cloud_config_preserve
.get("user-data"):
2951 if isinstance(cloud_config_preserve
["user-data"], list):
2952 new_cloud_config
["user-data"] += cloud_config_preserve
["user-data"]
2954 new_cloud_config
["user-data"].append(cloud_config_preserve
["user-data"])
2955 if not new_cloud_config
["user-data"]:
2956 del new_cloud_config
["user-data"]
2959 new_cloud_config
["config-files"] = []
2960 if cloud_config
and cloud_config
.get("config-files") != None:
2961 new_cloud_config
["config-files"] += cloud_config
["config-files"]
2962 if cloud_config_preserve
:
2963 for file in cloud_config_preserve
.get("config-files", ()):
2964 for index
in range(0, len(new_cloud_config
["config-files"])):
2965 if new_cloud_config
["config-files"][index
]["dest"] == file["dest"]:
2966 new_cloud_config
["config-files"][index
] = file
2969 new_cloud_config
["config-files"].append(file)
2970 if not new_cloud_config
["config-files"]:
2971 del new_cloud_config
["config-files"]
2972 return new_cloud_config
2975 def get_vim_thread(mydb
, tenant_id
, datacenter_id_name
=None, datacenter_tenant_id
=None):
2976 datacenter_id
= None
2977 datacenter_name
= None
2980 if datacenter_tenant_id
:
2981 thread_id
= datacenter_tenant_id
2982 thread
= vim_threads
["running"].get(datacenter_tenant_id
)
2984 where_
={"td.nfvo_tenant_id": tenant_id
}
2985 if datacenter_id_name
:
2986 if utils
.check_valid_uuid(datacenter_id_name
):
2987 datacenter_id
= datacenter_id_name
2988 where_
["dt.datacenter_id"] = datacenter_id
2990 datacenter_name
= datacenter_id_name
2991 where_
["d.name"] = datacenter_name
2992 if datacenter_tenant_id
:
2993 where_
["dt.uuid"] = datacenter_tenant_id
2994 datacenters
= mydb
.get_rows(
2995 SELECT
=("dt.uuid as datacenter_tenant_id, d.name as datacenter_name",),
2996 FROM
="datacenter_tenants as dt join tenants_datacenters as td on dt.uuid=td.datacenter_tenant_id "
2997 "join datacenters as d on d.uuid=dt.datacenter_id",
2999 if len(datacenters
) > 1:
3000 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors
.Conflict
)
3002 thread_id
= datacenters
[0]["datacenter_tenant_id"]
3003 datacenter_name
= datacenters
[0]["datacenter_name"]
3004 thread
= vim_threads
["running"].get(thread_id
)
3006 thread_name
= get_non_used_vim_name(datacenter_name
, datacenter_id
)
3007 thread
= vim_thread(task_lock
, plugins
, thread_name
, None,
3010 vim_threads
["running"][thread_id
] = thread
3012 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name
)), httperrors
.Not_Found
)
3013 return thread_id
, thread
3014 except db_base_Exception
as e
:
3015 raise NfvoException("{} {}".format(type(e
).__name
__ , str(e
)), e
.http_code
)
3018 def get_datacenter_uuid(mydb
, tenant_id
, datacenter_id_name
):
3020 if utils
.check_valid_uuid(datacenter_id_name
):
3021 WHERE_dict
['d.uuid'] = datacenter_id_name
3023 WHERE_dict
['d.name'] = datacenter_id_name
3026 WHERE_dict
['nfvo_tenant_id'] = tenant_id
3027 from_
= "tenants_datacenters as td join datacenters as d on td.datacenter_id=d.uuid join datacenter_tenants as" \
3028 " dt on td.datacenter_tenant_id=dt.uuid"
3030 from_
= 'datacenters as d'
3031 vimaccounts
= mydb
.get_rows(FROM
=from_
, SELECT
=("d.uuid as uuid, d.name as name",), WHERE
=WHERE_dict
)
3032 if len(vimaccounts
) == 0:
3033 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name
)), httperrors
.Not_Found
)
3034 elif len(vimaccounts
)>1:
3035 #print "nfvo.datacenter_action() error. Several datacenters found"
3036 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors
.Conflict
)
3037 return vimaccounts
[0]["uuid"], vimaccounts
[0]["name"]
3040 def get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter_id_name
=None, **extra_filter
):
3041 datacenter_id
= None
3042 datacenter_name
= None
3043 if datacenter_id_name
:
3044 if utils
.check_valid_uuid(datacenter_id_name
):
3045 datacenter_id
= datacenter_id_name
3047 datacenter_name
= datacenter_id_name
3048 vims
= get_vim(mydb
, tenant_id
, datacenter_id
, datacenter_name
, **extra_filter
)
3050 raise NfvoException("datacenter '{}' not found".format(str(datacenter_id_name
)), httperrors
.Not_Found
)
3052 #print "nfvo.datacenter_action() error. Several datacenters found"
3053 raise NfvoException("More than one datacenters found, try to identify with uuid", httperrors
.Conflict
)
3054 for vim_id
, vim_content
in vims
.items():
3055 return vim_id
, vim_content
3059 """Takes dict d and updates it with the values in dict u.
3060 It merges all depth levels"""
3061 for k
, v
in u
.items():
3062 if isinstance(v
, collections
.Mapping
):
3063 r
= update(d
.get(k
, {}), v
)
3070 def _get_wim(db
, wim_account_id
):
3071 # get wim from wim_account
3072 wim_accounts
= db
.get_rows(FROM
='wim_accounts', WHERE
={"uuid": wim_account_id
})
3073 if not wim_accounts
:
3074 raise NfvoException("Not found sdn id={}".format(wim_account_id
), http_code
=httperrors
.Not_Found
)
3075 return wim_accounts
[0]["wim_id"]
3078 def create_instance(mydb
, tenant_id
, instance_dict
):
3079 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
3080 # logger.debug("Creating instance...")
3082 scenario
= instance_dict
["scenario"]
3084 # find main datacenter
3086 myvim_threads_id
= {}
3087 datacenter
= instance_dict
.get("datacenter")
3088 default_wim_account
= instance_dict
.get("wim_account")
3089 default_datacenter_id
, vim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
3090 myvims
[default_datacenter_id
] = vim
3091 myvim_threads_id
[default_datacenter_id
], _
= get_vim_thread(mydb
, tenant_id
, default_datacenter_id
)
3092 tenant
= mydb
.get_rows_by_id('nfvo_tenants', tenant_id
)
3093 # myvim_tenant = myvim['tenant_id']
3096 # print "Checking that the scenario exists and getting the scenario dictionary"
3097 if isinstance(scenario
, str):
3098 scenarioDict
= mydb
.get_scenario(scenario
, tenant_id
, datacenter_vim_id
=myvim_threads_id
[default_datacenter_id
],
3099 datacenter_id
=default_datacenter_id
)
3101 scenarioDict
= scenario
3102 scenarioDict
["uuid"] = None
3104 # logger.debug(">>>>>> Dictionaries before merging")
3105 # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256)))
3106 # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256)))
3108 db_instance_vnfs
= []
3109 db_instance_vms
= []
3110 db_instance_interfaces
= []
3111 db_instance_sfis
= []
3112 db_instance_sfs
= []
3113 db_instance_classifications
= []
3114 db_instance_sfps
= []
3119 instance_name
= instance_dict
["name"]
3120 instance_uuid
= str(uuid4())
3121 uuid_list
.append(instance_uuid
)
3122 db_instance_scenario
= {
3123 "uuid": instance_uuid
,
3124 "name": instance_name
,
3125 "tenant_id": tenant_id
,
3126 "scenario_id": scenarioDict
['uuid'],
3127 "datacenter_id": default_datacenter_id
,
3128 # filled bellow 'datacenter_tenant_id'
3129 "description": instance_dict
.get("description"),
3131 if scenarioDict
.get("cloud-config"):
3132 db_instance_scenario
["cloud_config"] = yaml
.safe_dump(scenarioDict
["cloud-config"],
3133 default_flow_style
=True, width
=256)
3134 instance_action_id
= get_task_id()
3135 db_instance_action
= {
3136 "uuid": instance_action_id
, # same uuid for the instance and the action on create
3137 "tenant_id": tenant_id
,
3138 "instance_id": instance_uuid
,
3139 "description": "CREATE",
3142 # Auxiliary dictionaries from x to y
3143 sce_net2wim_instance
= {}
3144 sce_net2instance
= {}
3145 net2task_id
= {'scenario': {}}
3146 # Mapping between local networks and WIMs
3149 def ip_profile_IM2RO(ip_profile_im
):
3150 # translate from input format to database format
3152 if 'subnet-address' in ip_profile_im
:
3153 ip_profile_ro
['subnet_address'] = ip_profile_im
['subnet-address']
3154 if 'ip-version' in ip_profile_im
:
3155 ip_profile_ro
['ip_version'] = ip_profile_im
['ip-version']
3156 if 'gateway-address' in ip_profile_im
:
3157 ip_profile_ro
['gateway_address'] = ip_profile_im
['gateway-address']
3158 if 'dns-address' in ip_profile_im
:
3159 ip_profile_ro
['dns_address'] = ip_profile_im
['dns-address']
3160 if isinstance(ip_profile_ro
['dns_address'], (list, tuple)):
3161 ip_profile_ro
['dns_address'] = ";".join(ip_profile_ro
['dns_address'])
3162 if 'dhcp' in ip_profile_im
:
3163 ip_profile_ro
['dhcp_start_address'] = ip_profile_im
['dhcp'].get('start-address')
3164 ip_profile_ro
['dhcp_enabled'] = ip_profile_im
['dhcp'].get('enabled', True)
3165 ip_profile_ro
['dhcp_count'] = ip_profile_im
['dhcp'].get('count')
3166 return ip_profile_ro
3168 # logger.debug("Creating instance from scenario-dict:\n%s",
3169 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
3171 # 0 check correct parameters
3172 for net_name
, net_instance_desc
in instance_dict
.get("networks", {}).items():
3173 for scenario_net
in scenarioDict
['nets']:
3174 if net_name
== scenario_net
.get("name") or net_name
== scenario_net
.get("osm_id") or net_name
== scenario_net
.get("uuid"):
3177 raise NfvoException("Invalid scenario network name or id '{}' at instance:networks".format(net_name
),
3178 httperrors
.Bad_Request
)
3179 if "sites" not in net_instance_desc
:
3180 net_instance_desc
["sites"] = [ {} ]
3181 site_without_datacenter_field
= False
3182 for site
in net_instance_desc
["sites"]:
3183 if site
.get("datacenter"):
3184 site
["datacenter"], _
= get_datacenter_uuid(mydb
, tenant_id
, site
["datacenter"])
3185 if site
["datacenter"] not in myvims
:
3186 # Add this datacenter to myvims
3187 d
, v
= get_datacenter_by_name_uuid(mydb
, tenant_id
, site
["datacenter"])
3189 myvim_threads_id
[d
], _
= get_vim_thread(mydb
, tenant_id
, site
["datacenter"])
3190 site
["datacenter"] = d
# change name to id
3192 if site_without_datacenter_field
:
3193 raise NfvoException("Found more than one entries without datacenter field at "
3194 "instance:networks:{}:sites".format(net_name
), httperrors
.Bad_Request
)
3195 site_without_datacenter_field
= True
3196 site
["datacenter"] = default_datacenter_id
# change name to id
3198 for vnf_name
, vnf_instance_desc
in instance_dict
.get("vnfs",{}).items():
3199 for scenario_vnf
in scenarioDict
['vnfs']:
3200 if vnf_name
== scenario_vnf
['member_vnf_index'] or vnf_name
== scenario_vnf
['uuid'] or vnf_name
== scenario_vnf
['name']:
3203 raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_name
), httperrors
.Bad_Request
)
3204 if "datacenter" in vnf_instance_desc
:
3205 # Add this datacenter to myvims
3206 vnf_instance_desc
["datacenter"], _
= get_datacenter_uuid(mydb
, tenant_id
, vnf_instance_desc
["datacenter"])
3207 if vnf_instance_desc
["datacenter"] not in myvims
:
3208 d
, v
= get_datacenter_by_name_uuid(mydb
, tenant_id
, vnf_instance_desc
["datacenter"])
3210 myvim_threads_id
[d
], _
= get_vim_thread(mydb
, tenant_id
, vnf_instance_desc
["datacenter"])
3211 scenario_vnf
["datacenter"] = vnf_instance_desc
["datacenter"]
3213 for net_id
, net_instance_desc
in vnf_instance_desc
.get("networks", {}).items():
3214 for scenario_net
in scenario_vnf
['nets']:
3215 if net_id
== scenario_net
['osm_id'] or net_id
== scenario_net
['uuid'] or net_id
== scenario_net
["name"]:
3218 raise NfvoException("Invalid net id or name '{}' at instance:vnfs:networks".format(net_id
), httperrors
.Bad_Request
)
3219 if net_instance_desc
.get("vim-network-name"):
3220 scenario_net
["vim-network-name"] = net_instance_desc
["vim-network-name"]
3221 if net_instance_desc
.get("vim-network-id"):
3222 scenario_net
["vim-network-id"] = net_instance_desc
["vim-network-id"]
3223 if net_instance_desc
.get("name"):
3224 scenario_net
["name"] = net_instance_desc
["name"]
3225 if 'ip-profile' in net_instance_desc
:
3226 ipprofile_db
= ip_profile_IM2RO(net_instance_desc
['ip-profile'])
3227 if 'ip_profile' not in scenario_net
:
3228 scenario_net
['ip_profile'] = ipprofile_db
3230 update(scenario_net
['ip_profile'], ipprofile_db
)
3232 if net_instance_desc
.get('provider-network'):
3233 provider_network_db
= net_instance_desc
['provider-network']
3234 if 'provider_network' not in scenario_net
:
3235 scenario_net
['provider_network'] = provider_network_db
3237 update(scenario_net
['provider_network'], provider_network_db
)
3239 for vdu_id
, vdu_instance_desc
in vnf_instance_desc
.get("vdus", {}).items():
3240 for scenario_vm
in scenario_vnf
['vms']:
3241 if vdu_id
== scenario_vm
['osm_id'] or vdu_id
== scenario_vm
["name"]:
3244 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id
), httperrors
.Bad_Request
)
3245 scenario_vm
["instance_parameters"] = vdu_instance_desc
3246 for iface_id
, iface_instance_desc
in vdu_instance_desc
.get("interfaces", {}).items():
3247 for scenario_interface
in scenario_vm
['interfaces']:
3248 if iface_id
== scenario_interface
['internal_name'] or iface_id
== scenario_interface
["external_name"]:
3249 scenario_interface
.update(iface_instance_desc
)
3252 raise NfvoException("Invalid vdu id or name '{}' at instance:vnfs:vdus".format(vdu_id
), httperrors
.Bad_Request
)
3254 # 0.1 parse cloud-config parameters
3255 cloud_config
= unify_cloud_config(instance_dict
.get("cloud-config"), scenarioDict
.get("cloud-config"))
3257 # 0.2 merge instance information into scenario
3258 # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict)
3259 # However, this is not possible yet.
3260 for net_name
, net_instance_desc
in instance_dict
.get("networks", {}).items():
3261 for scenario_net
in scenarioDict
['nets']:
3262 if net_name
== scenario_net
.get("name") or net_name
== scenario_net
.get("osm_id") or net_name
== scenario_net
.get("uuid"):
3263 if "wim_account" in net_instance_desc
and net_instance_desc
["wim_account"] is not None:
3264 scenario_net
["wim_account"] = net_instance_desc
["wim_account"]
3265 if 'ip-profile' in net_instance_desc
:
3266 ipprofile_db
= ip_profile_IM2RO(net_instance_desc
['ip-profile'])
3267 if 'ip_profile' not in scenario_net
:
3268 scenario_net
['ip_profile'] = ipprofile_db
3270 update(scenario_net
['ip_profile'], ipprofile_db
)
3271 if 'provider-network' in net_instance_desc
:
3272 provider_network_db
= net_instance_desc
['provider-network']
3274 if 'provider-network' not in scenario_net
:
3275 scenario_net
['provider_network'] = provider_network_db
3277 update(scenario_net
['provider-network'], provider_network_db
)
3279 for interface
in net_instance_desc
.get('interfaces', ()):
3280 if 'ip_address' in interface
:
3281 for vnf
in scenarioDict
['vnfs']:
3282 if interface
['vnf'] == vnf
['name']:
3283 for vnf_interface
in vnf
['interfaces']:
3284 if interface
['vnf_interface'] == vnf_interface
['external_name']:
3285 vnf_interface
['ip_address'] = interface
['ip_address']
3287 # logger.debug(">>>>>>>> Merged dictionary")
3288 # logger.debug("Creating instance scenario-dict MERGED:\n%s",
3289 # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False))
3292 # 1. Creating new nets (sce_nets) in the VIM"
3293 number_mgmt_networks
= 0
3294 db_instance_nets
= []
3295 db_instance_wim_nets
= []
3296 for sce_net
in scenarioDict
['nets']:
3298 sce_net_uuid
= sce_net
.get('uuid', sce_net
["name"])
3299 # get involved datacenters where this network need to be created
3300 involved_datacenters
= []
3301 for sce_vnf
in scenarioDict
.get("vnfs", ()):
3302 vnf_datacenter
= sce_vnf
.get("datacenter", default_datacenter_id
)
3303 if vnf_datacenter
in involved_datacenters
:
3305 if sce_vnf
.get("interfaces"):
3306 for sce_vnf_ifaces
in sce_vnf
["interfaces"]:
3307 if sce_vnf_ifaces
.get("sce_net_id") == sce_net
["uuid"]:
3308 involved_datacenters
.append(vnf_datacenter
)
3310 if not involved_datacenters
:
3311 involved_datacenters
.append(default_datacenter_id
)
3312 target_wim_account
= sce_net
.get("wim_account", default_wim_account
)
3315 # TODO: use this information during network creation
3316 wim_account_id
= wim_account_name
= None
3317 if len(involved_datacenters
) > 1 and 'uuid' in sce_net
:
3318 if target_wim_account
is None or target_wim_account
is True: # automatic selection of WIM
3319 # OBS: sce_net without uuid are used internally to VNFs
3320 # and the assumption is that VNFs will not be split among
3321 # different datacenters
3322 wim_account
= wim_engine
.find_suitable_wim_account(
3323 involved_datacenters
, tenant_id
)
3324 wim_account_id
= wim_account
['uuid']
3325 wim_account_name
= wim_account
['name']
3326 wim_usage
[sce_net
['uuid']] = wim_account_id
3327 elif isinstance(target_wim_account
, str): # manual selection of WIM
3328 wim_account
.persist
.get_wim_account_by(target_wim_account
, tenant_id
)
3329 wim_account_id
= wim_account
['uuid']
3330 wim_account_name
= wim_account
['name']
3331 wim_usage
[sce_net
['uuid']] = wim_account_id
3332 else: # not WIM usage
3333 wim_usage
[sce_net
['uuid']] = False
3337 if instance_dict
.get("networks"):
3338 if sce_net
.get("uuid") in instance_dict
["networks"]:
3339 descriptor_net
= instance_dict
["networks"][sce_net
["uuid"]]
3340 descriptor_net_name
= sce_net
["uuid"]
3341 elif sce_net
.get("osm_id") in instance_dict
["networks"]:
3342 descriptor_net
= instance_dict
["networks"][sce_net
["osm_id"]]
3343 descriptor_net_name
= sce_net
["osm_id"]
3344 elif sce_net
["name"] in instance_dict
["networks"]:
3345 descriptor_net
= instance_dict
["networks"][sce_net
["name"]]
3346 descriptor_net_name
= sce_net
["name"]
3347 net_name
= descriptor_net
.get("vim-network-name")
3348 # add datacenters from instantiation parameters
3349 if descriptor_net
.get("sites"):
3350 for site
in descriptor_net
["sites"]:
3351 if site
.get("datacenter") and site
["datacenter"] not in involved_datacenters
:
3352 involved_datacenters
.append(site
["datacenter"])
3353 sce_net2instance
[sce_net_uuid
] = {}
3354 sce_net2wim_instance
[sce_net_uuid
] = {}
3355 net2task_id
['scenario'][sce_net_uuid
] = {}
3358 related_network
= None
3359 if descriptor_net
.get("use-network"):
3360 target_instance_nets
= mydb
.get_rows(
3362 FROM
="instance_nets",
3363 WHERE
={"instance_scenario_id": descriptor_net
["use-network"]["instance_scenario_id"],
3364 "osm_id": descriptor_net
["use-network"]["osm_id"]},
3366 if not target_instance_nets
:
3367 raise NfvoException(
3368 "Cannot find the target network at instance:networks[{}]:use-network".format(descriptor_net_name
),
3369 httperrors
.Bad_Request
)
3371 use_network
= target_instance_nets
[0]["related"]
3373 if sce_net
["external"]:
3374 number_mgmt_networks
+= 1
3376 for datacenter_id
in involved_datacenters
:
3378 netmap_create
= None
3379 if descriptor_net
.get("sites"):
3380 for site
in descriptor_net
["sites"]:
3381 if site
.get("datacenter") == datacenter_id
:
3382 netmap_use
= site
.get("netmap-use")
3383 netmap_create
= site
.get("netmap-create")
3386 vim
= myvims
[datacenter_id
]
3387 myvim_thread_id
= myvim_threads_id
[datacenter_id
]
3389 net_type
= sce_net
['type']
3391 lookfor_filter
= {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True
3394 if sce_net
["external"]:
3395 net_name
= sce_net
["name"]
3397 net_name
= "{}-{}".format(instance_name
, sce_net
["name"])
3398 net_name
= net_name
[:255] # limit length
3400 if netmap_use
or netmap_create
:
3401 create_network
= False
3402 lookfor_network
= False
3404 lookfor_network
= True
3405 if utils
.check_valid_uuid(netmap_use
):
3406 lookfor_filter
["id"] = netmap_use
3408 lookfor_filter
["name"] = netmap_use
3410 create_network
= True
3411 net_vim_name
= net_name
3412 if isinstance(netmap_create
, str):
3413 net_vim_name
= netmap_create
3414 elif sce_net
.get("vim_network_name"):
3415 create_network
= False
3416 lookfor_network
= True
3417 lookfor_filter
["name"] = sce_net
.get("vim_network_name")
3418 elif sce_net
["external"]:
3419 if sce_net
.get('vim_id'):
3420 # there is a netmap at datacenter_nets database # TODO REVISE!!!!
3421 create_network
= False
3422 lookfor_network
= True
3423 lookfor_filter
["id"] = sce_net
['vim_id']
3424 elif vim
["config"].get("management_network_id") or vim
["config"].get("management_network_name"):
3425 if number_mgmt_networks
> 1:
3426 raise NfvoException("Found several VLD of type mgmt. "
3427 "You must concrete what vim-network must be use for each one",
3428 httperrors
.Bad_Request
)
3429 create_network
= False
3430 lookfor_network
= True
3431 if vim
["config"].get("management_network_id"):
3432 lookfor_filter
["id"] = vim
["config"]["management_network_id"]
3434 lookfor_filter
["name"] = vim
["config"]["management_network_name"]
3436 # There is not a netmap, look at datacenter for a net with this name and create if not found
3437 create_network
= True
3438 lookfor_network
= True
3439 lookfor_filter
["name"] = sce_net
["name"]
3440 net_vim_name
= sce_net
["name"]
3442 net_vim_name
= net_name
3443 create_network
= True
3444 lookfor_network
= False
3448 task_action
= "CREATE"
3449 task_extra
["params"] = (net_vim_name
, net_type
, sce_net
.get('ip_profile', None), False,
3450 sce_net
.get('provider_network', None), wim_account_name
)
3453 task_extra
["find"] = (lookfor_filter
,)
3454 elif lookfor_network
:
3455 task_action
= "FIND"
3456 task_extra
["params"] = (lookfor_filter
,)
3458 # fill database content
3459 net_uuid
= str(uuid4())
3460 uuid_list
.append(net_uuid
)
3461 sce_net2instance
[sce_net_uuid
][datacenter_id
] = net_uuid
3462 if not related_network
: # all db_instance_nets will have same related
3463 related_network
= use_network
or net_uuid
3465 sdn_controller
= vim
.config
.get('sdn-controller')
3466 sce_net2wim_instance
[sce_net_uuid
][datacenter_id
] = None
3467 if sdn_controller
and net_type
in ("data", "ptp"):
3468 wim_id
= _get_wim(mydb
, sdn_controller
)
3469 sdn_net_id
= str(uuid4())
3470 sce_net2wim_instance
[sce_net_uuid
][datacenter_id
] = sdn_net_id
3471 task_extra
["sdn_net_id"] = sdn_net_id
3472 db_instance_wim_nets
.append({
3474 "instance_scenario_id": instance_uuid
,
3475 "sce_net_id": sce_net
.get("uuid"),
3477 "wim_account_id": sdn_controller
,
3478 'status': 'BUILD', # if create_network else "ACTIVE"
3479 "related": related_network
,
3480 'multipoint': True if net_type
=="data" else False,
3481 "created": create_network
, # TODO py3
3485 task_wim_extra
= {"params": [net_type
, wim_account_name
]}
3486 # add sdn interfaces
3487 if sce_net
.get('provider_network') and sce_net
['provider_network'].get("sdn-ports"):
3488 task_wim_extra
["sdn-ports"] = sce_net
['provider_network'].get("sdn-ports")
3490 "instance_action_id": instance_action_id
,
3491 "status": "SCHEDULED",
3492 "task_index": task_index
,
3493 # "datacenter_vim_id": myvim_thread_id,
3494 "wim_account_id": sdn_controller
,
3495 "action": task_action
,
3496 "item": "instance_wim_nets",
3497 "item_id": sdn_net_id
,
3498 "related": related_network
,
3499 "extra": yaml
.safe_dump(task_wim_extra
, default_flow_style
=True, width
=256)
3502 db_vim_actions
.append(db_vim_action
)
3505 "osm_id": sce_net
.get("osm_id") or sce_net
["name"],
3506 "related": related_network
,
3508 "vim_name": net_vim_name
,
3509 "instance_scenario_id": instance_uuid
,
3510 "sce_net_id": sce_net
.get("uuid"),
3511 "created": create_network
,
3512 'datacenter_id': datacenter_id
,
3513 'datacenter_tenant_id': myvim_thread_id
,
3514 'status': 'BUILD', # if create_network else "ACTIVE"
3515 'sdn_net_id': sdn_net_id
,
3517 db_instance_nets
.append(db_net
)
3519 "instance_action_id": instance_action_id
,
3520 "status": "SCHEDULED",
3521 "task_index": task_index
,
3522 "datacenter_vim_id": myvim_thread_id
,
3523 "action": task_action
,
3524 "item": "instance_nets",
3525 "item_id": net_uuid
,
3526 "related": related_network
,
3527 "extra": yaml
.safe_dump(task_extra
, default_flow_style
=True, width
=256)
3529 net2task_id
['scenario'][sce_net_uuid
][datacenter_id
] = task_index
3531 db_vim_actions
.append(db_vim_action
)
3533 if 'ip_profile' in sce_net
:
3535 'instance_net_id': net_uuid
,
3536 'ip_version': sce_net
['ip_profile']['ip_version'],
3537 'subnet_address': sce_net
['ip_profile']['subnet_address'],
3538 'gateway_address': sce_net
['ip_profile']['gateway_address'],
3539 'dns_address': sce_net
['ip_profile']['dns_address'],
3540 'dhcp_enabled': sce_net
['ip_profile']['dhcp_enabled'],
3541 'dhcp_start_address': sce_net
['ip_profile']['dhcp_start_address'],
3542 'dhcp_count': sce_net
['ip_profile']['dhcp_count'],
3544 db_ip_profiles
.append(db_ip_profile
)
3548 "default_datacenter_id": default_datacenter_id
,
3549 "myvim_threads_id": myvim_threads_id
,
3550 "instance_uuid": instance_uuid
,
3551 "instance_name": instance_name
,
3552 "instance_action_id": instance_action_id
,
3554 "cloud_config": cloud_config
,
3555 "RO_pub_key": tenant
[0].get('RO_pub_key'),
3556 "instance_parameters": instance_dict
,
3559 "task_index": task_index
,
3560 "uuid_list": uuid_list
,
3561 "db_instance_nets": db_instance_nets
,
3562 "db_instance_wim_nets": db_instance_wim_nets
,
3563 "db_vim_actions": db_vim_actions
,
3564 "db_ip_profiles": db_ip_profiles
,
3565 "db_instance_vnfs": db_instance_vnfs
,
3566 "db_instance_vms": db_instance_vms
,
3567 "db_instance_interfaces": db_instance_interfaces
,
3568 "net2task_id": net2task_id
,
3569 "sce_net2instance": sce_net2instance
,
3570 "sce_net2wim_instance": sce_net2wim_instance
,
3572 # sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name'])
3573 for sce_vnf
in scenarioDict
.get('vnfs', ()): # sce_vnf_list:
3574 instantiate_vnf(mydb
, sce_vnf
, vnf_params
, vnf_params_out
, rollbackList
)
3575 task_index
= vnf_params_out
["task_index"]
3576 uuid_list
= vnf_params_out
["uuid_list"]
3579 # task_depends_on = []
3580 for vnffg
in scenarioDict
.get('vnffgs', ()):
3581 for rsp
in vnffg
['rsps']:
3583 for cp
in rsp
['connection_points']:
3584 count
= mydb
.get_rows(
3586 FROM
="vms join interfaces on vms.uuid=interfaces.vm_id join sce_rsp_hops as h "
3587 "on interfaces.uuid=h.ingress_interface_id",
3588 WHERE
={'h.uuid': cp
['uuid']})[0]['count']
3589 instance_vnf
= next((item
for item
in db_instance_vnfs
if item
['sce_vnf_id'] == cp
['sce_vnf_id']), None)
3590 instance_vms
= [item
for item
in db_instance_vms
if item
['instance_vnf_id'] == instance_vnf
['uuid']]
3592 for instance_vm
in instance_vms
:
3593 action
= next((item
for item
in db_vim_actions
if item
['item_id'] == instance_vm
['uuid']), None)
3595 dependencies
.append(action
['task_index'])
3596 # TODO: throw exception if count != len(instance_vms)
3597 # TODO: and action shouldn't ever be None
3599 for i
in range(count
):
3601 sfi_uuid
= str(uuid4())
3603 "ingress_interface_id": cp
["ingress_interface_id"],
3604 "egress_interface_id": cp
["egress_interface_id"]
3606 uuid_list
.append(sfi_uuid
)
3609 "related": sfi_uuid
,
3610 "instance_scenario_id": instance_uuid
,
3611 'sce_rsp_hop_id': cp
['uuid'],
3612 'datacenter_id': datacenter_id
,
3613 'datacenter_tenant_id': myvim_thread_id
,
3614 "vim_sfi_id": None, # vim thread will populate
3616 db_instance_sfis
.append(db_sfi
)
3618 "instance_action_id": instance_action_id
,
3619 "task_index": task_index
,
3620 "datacenter_vim_id": myvim_thread_id
,
3622 "status": "SCHEDULED",
3623 "item": "instance_sfis",
3624 "item_id": sfi_uuid
,
3625 "related": sfi_uuid
,
3626 "extra": yaml
.safe_dump({"params": extra_params
, "depends_on": [dependencies
[i
]]},
3627 default_flow_style
=True, width
=256)
3629 sfis_created
.append(task_index
)
3631 db_vim_actions
.append(db_vim_action
)
3633 sf_uuid
= str(uuid4())
3634 uuid_list
.append(sf_uuid
)
3638 "instance_scenario_id": instance_uuid
,
3639 'sce_rsp_hop_id': cp
['uuid'],
3640 'datacenter_id': datacenter_id
,
3641 'datacenter_tenant_id': myvim_thread_id
,
3642 "vim_sf_id": None, # vim thread will populate
3644 db_instance_sfs
.append(db_sf
)
3646 "instance_action_id": instance_action_id
,
3647 "task_index": task_index
,
3648 "datacenter_vim_id": myvim_thread_id
,
3650 "status": "SCHEDULED",
3651 "item": "instance_sfs",
3654 "extra": yaml
.safe_dump({"params": "", "depends_on": sfis_created
},
3655 default_flow_style
=True, width
=256)
3657 sfs_created
.append(task_index
)
3659 db_vim_actions
.append(db_vim_action
)
3660 classifier
= rsp
['classifier']
3662 # TODO the following ~13 lines can be reused for the sfi case
3663 count
= mydb
.get_rows(
3664 SELECT
=('vms.count'),
3665 FROM
="vms join interfaces on vms.uuid=interfaces.vm_id join sce_classifiers as c on interfaces.uuid=c.interface_id",
3666 WHERE
={'c.uuid': classifier
['uuid']})[0]['count']
3667 instance_vnf
= next((item
for item
in db_instance_vnfs
if item
['sce_vnf_id'] == classifier
['sce_vnf_id']), None)
3668 instance_vms
= [item
for item
in db_instance_vms
if item
['instance_vnf_id'] == instance_vnf
['uuid']]
3670 for instance_vm
in instance_vms
:
3671 action
= next((item
for item
in db_vim_actions
if item
['item_id'] == instance_vm
['uuid']), None)
3673 dependencies
.append(action
['task_index'])
3674 # TODO: throw exception if count != len(instance_vms)
3675 # TODO: and action shouldn't ever be None
3676 classifications_created
= []
3677 for i
in range(count
):
3678 for match
in classifier
['matches']:
3679 # create classifications
3680 classification_uuid
= str(uuid4())
3681 uuid_list
.append(classification_uuid
)
3682 db_classification
= {
3683 "uuid": classification_uuid
,
3684 "related": classification_uuid
,
3685 "instance_scenario_id": instance_uuid
,
3686 'sce_classifier_match_id': match
['uuid'],
3687 'datacenter_id': datacenter_id
,
3688 'datacenter_tenant_id': myvim_thread_id
,
3689 "vim_classification_id": None, # vim thread will populate
3691 db_instance_classifications
.append(db_classification
)
3692 classification_params
= {
3693 "ip_proto": match
["ip_proto"],
3694 "source_ip": match
["source_ip"],
3695 "destination_ip": match
["destination_ip"],
3696 "source_port": match
["source_port"],
3697 "destination_port": match
["destination_port"],
3698 "logical_source_port": classifier
["interface_id"]
3701 "instance_action_id": instance_action_id
,
3702 "task_index": task_index
,
3703 "datacenter_vim_id": myvim_thread_id
,
3705 "status": "SCHEDULED",
3706 "item": "instance_classifications",
3707 "item_id": classification_uuid
,
3708 "related": classification_uuid
,
3709 "extra": yaml
.safe_dump({"params": classification_params
, "depends_on": [dependencies
[i
]]},
3710 default_flow_style
=True, width
=256)
3712 classifications_created
.append(task_index
)
3714 db_vim_actions
.append(db_vim_action
)
3717 sfp_uuid
= str(uuid4())
3718 uuid_list
.append(sfp_uuid
)
3721 "related": sfp_uuid
,
3722 "instance_scenario_id": instance_uuid
,
3723 'sce_rsp_id': rsp
['uuid'],
3724 'datacenter_id': datacenter_id
,
3725 'datacenter_tenant_id': myvim_thread_id
,
3726 "vim_sfp_id": None, # vim thread will populate
3728 db_instance_sfps
.append(db_sfp
)
3730 "instance_action_id": instance_action_id
,
3731 "task_index": task_index
,
3732 "datacenter_vim_id": myvim_thread_id
,
3734 "status": "SCHEDULED",
3735 "item": "instance_sfps",
3736 "item_id": sfp_uuid
,
3737 "related": sfp_uuid
,
3738 "extra": yaml
.safe_dump({"params": "", "depends_on": sfs_created
+ classifications_created
},
3739 default_flow_style
=True, width
=256)
3742 db_vim_actions
.append(db_vim_action
)
3743 db_instance_action
["number_tasks"] = task_index
3746 logger
.debug('wim_usage:\n%s\n\n', pformat(wim_usage
))
3747 wan_links
= wim_engine
.derive_wan_links(wim_usage
, db_instance_nets
, tenant_id
)
3748 wim_actions
= wim_engine
.create_actions(wan_links
)
3749 wim_actions
, db_instance_action
= (
3750 wim_engine
.incorporate_actions(wim_actions
, db_instance_action
))
3753 scenarioDict
["datacenter2tenant"] = myvim_threads_id
3755 db_instance_scenario
['datacenter_tenant_id'] = myvim_threads_id
[default_datacenter_id
]
3756 db_instance_scenario
['datacenter_id'] = default_datacenter_id
3758 {"instance_scenarios": db_instance_scenario
},
3759 {"instance_vnfs": db_instance_vnfs
},
3760 {"instance_nets": db_instance_nets
},
3761 {"ip_profiles": db_ip_profiles
},
3762 {"instance_vms": db_instance_vms
},
3763 {"instance_interfaces": db_instance_interfaces
},
3764 {"instance_actions": db_instance_action
},
3765 {"instance_sfis": db_instance_sfis
},
3766 {"instance_sfs": db_instance_sfs
},
3767 {"instance_classifications": db_instance_classifications
},
3768 {"instance_sfps": db_instance_sfps
},
3769 {"instance_wim_nets": db_instance_wim_nets
+ wan_links
},
3770 {"vim_wim_actions": db_vim_actions
+ wim_actions
}
3773 logger
.debug("create_instance done DB tables: %s",
3774 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False) )
3775 mydb
.new_rows(db_tables
, uuid_list
)
3776 for myvim_thread_id
in myvim_threads_id
.values():
3777 vim_threads
["running"][myvim_thread_id
].insert_task(db_vim_actions
)
3779 wim_engine
.dispatch(wim_actions
)
3781 returned_instance
= mydb
.get_instance_scenario(instance_uuid
)
3782 returned_instance
["action_id"] = instance_action_id
3783 return returned_instance
3784 except (NfvoException
, vimconn
.vimconnException
, sdnconn
.SdnConnectorError
, db_base_Exception
) as e
:
3785 message
= rollback(mydb
, myvims
, rollbackList
)
3786 if isinstance(e
, db_base_Exception
):
3787 error_text
= "database Exception"
3788 elif isinstance(e
, vimconn
.vimconnException
):
3789 error_text
= "VIM Exception"
3790 elif isinstance(e
, sdnconn
.SdnConnectorError
):
3791 error_text
= "WIM Exception"
3793 error_text
= "Exception"
3794 error_text
+= " {} {}. {}".format(type(e
).__name
__, str(e
), message
)
3795 # logger.error("create_instance: %s", error_text)
3797 raise NfvoException(error_text
, e
.http_code
)
3800 def instantiate_vnf(mydb
, sce_vnf
, params
, params_out
, rollbackList
):
3801 default_datacenter_id
= params
["default_datacenter_id"]
3802 myvim_threads_id
= params
["myvim_threads_id"]
3803 instance_uuid
= params
["instance_uuid"]
3804 instance_name
= params
["instance_name"]
3805 instance_action_id
= params
["instance_action_id"]
3806 myvims
= params
["myvims"]
3807 cloud_config
= params
["cloud_config"]
3808 RO_pub_key
= params
["RO_pub_key"]
3810 task_index
= params_out
["task_index"]
3811 uuid_list
= params_out
["uuid_list"]
3812 db_instance_nets
= params_out
["db_instance_nets"]
3813 db_instance_wim_nets
= params_out
["db_instance_wim_nets"]
3814 db_vim_actions
= params_out
["db_vim_actions"]
3815 db_ip_profiles
= params_out
["db_ip_profiles"]
3816 db_instance_vnfs
= params_out
["db_instance_vnfs"]
3817 db_instance_vms
= params_out
["db_instance_vms"]
3818 db_instance_interfaces
= params_out
["db_instance_interfaces"]
3819 net2task_id
= params_out
["net2task_id"]
3820 sce_net2instance
= params_out
["sce_net2instance"]
3821 sce_net2wim_instance
= params_out
["sce_net2wim_instance"]
3823 vnf_net2instance
= {}
3824 vnf_net2wim_instance
= {}
3826 # 2. Creating new nets (vnf internal nets) in the VIM"
3827 # For each vnf net, we create it and we add it to instanceNetlist.
3828 if sce_vnf
.get("datacenter"):
3829 vim
= myvims
[sce_vnf
["datacenter"]]
3830 datacenter_id
= sce_vnf
["datacenter"]
3831 myvim_thread_id
= myvim_threads_id
[sce_vnf
["datacenter"]]
3833 vim
= myvims
[default_datacenter_id
]
3834 datacenter_id
= default_datacenter_id
3835 myvim_thread_id
= myvim_threads_id
[default_datacenter_id
]
3836 for net
in sce_vnf
['nets']:
3838 # descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {})
3839 # net_name = descriptor_net.get("name")
3842 net_name
= "{}-{}".format(instance_name
, net
["name"])
3843 net_name
= net_name
[:255] # limit length
3844 net_type
= net
['type']
3846 if sce_vnf
['uuid'] not in vnf_net2instance
:
3847 vnf_net2instance
[sce_vnf
['uuid']] = {}
3848 if sce_vnf
['uuid'] not in net2task_id
:
3849 net2task_id
[sce_vnf
['uuid']] = {}
3851 # fill database content
3852 net_uuid
= str(uuid4())
3853 uuid_list
.append(net_uuid
)
3854 vnf_net2instance
[sce_vnf
['uuid']][net
['uuid']] = net_uuid
3856 sdn_controller
= vim
.config
.get('sdn-controller')
3858 if sdn_controller
and net_type
in ("data", "ptp"):
3859 wim_id
= _get_wim(mydb
, sdn_controller
)
3860 sdn_net_id
= str(uuid4())
3861 db_instance_wim_nets
.append({
3863 "instance_scenario_id": instance_uuid
,
3865 "wim_account_id": sdn_controller
,
3866 'status': 'BUILD', # if create_network else "ACTIVE"
3867 "related": net_uuid
,
3868 'multipoint': True if net_type
== "data" else False,
3869 "created": True, # TODO py3
3872 vnf_net2wim_instance
[net_uuid
] = sdn_net_id
3876 "related": net_uuid
,
3878 "vim_name": net_name
,
3879 "instance_scenario_id": instance_uuid
,
3880 "net_id": net
["uuid"],
3882 'datacenter_id': datacenter_id
,
3883 'datacenter_tenant_id': myvim_thread_id
,
3884 'sdn_net_id': sdn_net_id
,
3886 db_instance_nets
.append(db_net
)
3889 if net
.get("vim-network-name"):
3890 lookfor_filter
["name"] = net
["vim-network-name"]
3891 if net
.get("vim-network-id"):
3892 lookfor_filter
["id"] = net
["vim-network-id"]
3894 task_action
= "FIND"
3895 task_extra
= {"params": (lookfor_filter
,)}
3897 task_action
= "CREATE"
3898 task_extra
= {"params": (net_name
, net_type
, net
.get('ip_profile', None))}
3900 task_extra
["sdn_net_id"] = sdn_net_id
3903 task_wim_extra
= {"params": [net_type
, None]}
3905 "instance_action_id": instance_action_id
,
3906 "status": "SCHEDULED",
3907 "task_index": task_index
,
3908 # "datacenter_vim_id": myvim_thread_id,
3909 "wim_account_id": sdn_controller
,
3910 "action": task_action
,
3911 "item": "instance_wim_nets",
3912 "item_id": sdn_net_id
,
3913 "related": net_uuid
,
3914 "extra": yaml
.safe_dump(task_wim_extra
, default_flow_style
=True, width
=256)
3917 db_vim_actions
.append(db_vim_action
)
3919 "instance_action_id": instance_action_id
,
3920 "task_index": task_index
,
3921 "datacenter_vim_id": myvim_thread_id
,
3922 "status": "SCHEDULED",
3923 "action": task_action
,
3924 "item": "instance_nets",
3925 "item_id": net_uuid
,
3926 "related": net_uuid
,
3927 "extra": yaml
.safe_dump(task_extra
, default_flow_style
=True, width
=256)
3929 net2task_id
[sce_vnf
['uuid']][net
['uuid']] = task_index
3931 db_vim_actions
.append(db_vim_action
)
3933 if 'ip_profile' in net
:
3935 'instance_net_id': net_uuid
,
3936 'ip_version': net
['ip_profile']['ip_version'],
3937 'subnet_address': net
['ip_profile']['subnet_address'],
3938 'gateway_address': net
['ip_profile']['gateway_address'],
3939 'dns_address': net
['ip_profile']['dns_address'],
3940 'dhcp_enabled': net
['ip_profile']['dhcp_enabled'],
3941 'dhcp_start_address': net
['ip_profile']['dhcp_start_address'],
3942 'dhcp_count': net
['ip_profile']['dhcp_count'],
3944 db_ip_profiles
.append(db_ip_profile
)
3946 # print "vnf_net2instance:"
3947 # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False)
3949 # 3. Creating new vm instances in the VIM
3950 # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict)
3952 if sce_vnf
.get('mgmt_access'):
3953 ssh_access
= sce_vnf
['mgmt_access'].get('config-access', {}).get('ssh-access')
3954 vnf_availability_zones
= []
3955 for vm
in sce_vnf
.get('vms'):
3956 vm_av
= vm
.get('availability_zone')
3957 if vm_av
and vm_av
not in vnf_availability_zones
:
3958 vnf_availability_zones
.append(vm_av
)
3960 # check if there is enough availability zones available at vim level.
3961 if myvims
[datacenter_id
].availability_zone
and vnf_availability_zones
:
3962 if len(vnf_availability_zones
) > len(myvims
[datacenter_id
].availability_zone
):
3963 raise NfvoException('No enough availability zones at VIM for this deployment', httperrors
.Bad_Request
)
3965 if sce_vnf
.get("datacenter"):
3966 vim
= myvims
[sce_vnf
["datacenter"]]
3967 myvim_thread_id
= myvim_threads_id
[sce_vnf
["datacenter"]]
3968 datacenter_id
= sce_vnf
["datacenter"]
3970 vim
= myvims
[default_datacenter_id
]
3971 myvim_thread_id
= myvim_threads_id
[default_datacenter_id
]
3972 datacenter_id
= default_datacenter_id
3973 sce_vnf
["datacenter_id"] = datacenter_id
3976 vnf_uuid
= str(uuid4())
3977 uuid_list
.append(vnf_uuid
)
3980 'instance_scenario_id': instance_uuid
,
3981 'vnf_id': sce_vnf
['vnf_id'],
3982 'sce_vnf_id': sce_vnf
['uuid'],
3983 'datacenter_id': datacenter_id
,
3984 'datacenter_tenant_id': myvim_thread_id
,
3986 db_instance_vnfs
.append(db_instance_vnf
)
3988 for vm
in sce_vnf
['vms']:
3990 if vm
.get("pdu_type"):
3994 sce_vnf_name
= sce_vnf
['member_vnf_index'] if sce_vnf
['member_vnf_index'] else sce_vnf
['name']
3995 myVMDict
['name'] = "{}-{}-{}".format(instance_name
[:64], sce_vnf_name
[:64], vm
["name"][:64])
3996 myVMDict
['description'] = myVMDict
['name'][0:99]
3998 # myVMDict['start'] = "no"
3999 if vm
.get("instance_parameters") and vm
["instance_parameters"].get("name"):
4000 myVMDict
['name'] = vm
["instance_parameters"].get("name")
4001 myVMDict
['name'] = myVMDict
['name'][0:255] # limit name length
4002 # create image at vim in case it not exist
4003 image_uuid
= vm
['image_id']
4004 if vm
.get("image_list"):
4005 for alternative_image
in vm
["image_list"]:
4006 if alternative_image
["vim_type"] == vim
["config"]["_vim_type_internal"]:
4007 image_uuid
= alternative_image
['image_id']
4009 image_dict
= mydb
.get_table_by_uuid_name("images", image_uuid
)
4010 image_id
= create_or_use_image(mydb
, {datacenter_id
: vim
}, image_dict
, [], True)
4011 vm
['vim_image_id'] = image_id
4013 # create flavor at vim in case it not exist
4014 flavor_dict
= mydb
.get_table_by_uuid_name("flavors", vm
['flavor_id'])
4015 if flavor_dict
['extended'] != None:
4016 flavor_dict
['extended'] = yaml
.load(flavor_dict
['extended'], Loader
=yaml
.Loader
)
4017 flavor_id
= create_or_use_flavor(mydb
, {datacenter_id
: vim
}, flavor_dict
, rollbackList
, True)
4019 # Obtain information for additional disks
4020 extended_flavor_dict
= mydb
.get_rows(FROM
='datacenters_flavors', SELECT
=('extended',),
4021 WHERE
={'vim_id': flavor_id
})
4022 if not extended_flavor_dict
:
4023 raise NfvoException("flavor '{}' not found".format(flavor_id
), httperrors
.Not_Found
)
4025 # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0], Loader=yaml.Loader)
4026 myVMDict
['disks'] = None
4027 extended_info
= extended_flavor_dict
[0]['extended']
4028 if extended_info
!= None:
4029 extended_flavor_dict_yaml
= yaml
.load(extended_info
, Loader
=yaml
.Loader
)
4030 if 'disks' in extended_flavor_dict_yaml
:
4031 myVMDict
['disks'] = extended_flavor_dict_yaml
['disks']
4032 if vm
.get("instance_parameters") and vm
["instance_parameters"].get("devices"):
4033 for disk
in myVMDict
['disks']:
4034 if disk
.get("name") in vm
["instance_parameters"]["devices"]:
4035 disk
.update(vm
["instance_parameters"]["devices"][disk
.get("name")])
4037 vm
['vim_flavor_id'] = flavor_id
4038 myVMDict
['imageRef'] = vm
['vim_image_id']
4039 myVMDict
['flavorRef'] = vm
['vim_flavor_id']
4040 myVMDict
['availability_zone'] = vm
.get('availability_zone')
4041 myVMDict
['networks'] = []
4042 task_depends_on
= []
4043 # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true
4044 is_management_vm
= False
4046 for iface
in vm
['interfaces']:
4048 if iface
['type'] == "data":
4049 netDict
['type'] = iface
['model']
4050 elif "model" in iface
and iface
["model"] != None:
4051 netDict
['model'] = iface
['model']
4052 # TODO in future, remove this because mac_address will not be set, and the type of PV,VF
4053 # is obtained from iterface table model
4054 # discover type of interface looking at flavor
4055 for numa
in flavor_dict
.get('extended', {}).get('numas', []):
4056 for flavor_iface
in numa
.get('interfaces', []):
4057 if flavor_iface
.get('name') == iface
['internal_name']:
4058 if flavor_iface
['dedicated'] == 'yes':
4059 netDict
['type'] = "PF" # passthrough
4060 elif flavor_iface
['dedicated'] == 'no':
4061 netDict
['type'] = "VF" # siov
4062 elif flavor_iface
['dedicated'] == 'yes:sriov':
4063 netDict
['type'] = "VFnotShared" # sriov but only one sriov on the PF
4064 netDict
["mac_address"] = flavor_iface
.get("mac_address")
4066 netDict
["use"] = iface
['type']
4067 if netDict
["use"] == "data" and not netDict
.get("type"):
4068 # print "netDict", netDict
4069 # print "iface", iface
4070 e_text
= "Cannot determine the interface type PF or VF of VNF '{}' VM '{}' iface '{}'".fromat(
4071 sce_vnf
['name'], vm
['name'], iface
['internal_name'])
4072 if flavor_dict
.get('extended') == None:
4073 raise NfvoException(e_text
+ "After database migration some information is not available. \
4074 Try to delete and create the scenarios and VNFs again", httperrors
.Conflict
)
4076 raise NfvoException(e_text
, httperrors
.Internal_Server_Error
)
4077 if netDict
["use"] == "mgmt":
4078 is_management_vm
= True
4079 netDict
["type"] = "virtual"
4080 if netDict
["use"] == "bridge":
4081 netDict
["type"] = "virtual"
4082 if iface
.get("vpci"):
4083 netDict
['vpci'] = iface
['vpci']
4084 if iface
.get("mac"):
4085 netDict
['mac_address'] = iface
['mac']
4086 if iface
.get("mac_address"):
4087 netDict
['mac_address'] = iface
['mac_address']
4088 if iface
.get("ip_address"):
4089 netDict
['ip_address'] = iface
['ip_address']
4090 if iface
.get("port-security") is not None:
4091 netDict
['port_security'] = iface
['port-security']
4092 if iface
.get("floating-ip") is not None:
4093 netDict
['floating_ip'] = iface
['floating-ip']
4094 netDict
['name'] = iface
['internal_name']
4095 if iface
['net_id'] is None:
4096 for vnf_iface
in sce_vnf
["interfaces"]:
4099 if vnf_iface
['interface_id'] == iface
['uuid']:
4100 netDict
['net_id'] = "TASK-{}".format(
4101 net2task_id
['scenario'][vnf_iface
['sce_net_id']][datacenter_id
])
4102 instance_net_id
= sce_net2instance
[vnf_iface
['sce_net_id']][datacenter_id
]
4103 instance_wim_net_id
= sce_net2wim_instance
[vnf_iface
['sce_net_id']][datacenter_id
]
4104 task_depends_on
.append(net2task_id
['scenario'][vnf_iface
['sce_net_id']][datacenter_id
])
4107 netDict
['net_id'] = "TASK-{}".format(net2task_id
[sce_vnf
['uuid']][iface
['net_id']])
4108 instance_net_id
= vnf_net2instance
[sce_vnf
['uuid']][iface
['net_id']]
4109 instance_wim_net_id
= vnf_net2wim_instance
.get(instance_net_id
)
4110 task_depends_on
.append(net2task_id
[sce_vnf
['uuid']][iface
['net_id']])
4111 # skip bridge ifaces not connected to any net
4112 if 'net_id' not in netDict
or netDict
['net_id'] == None:
4114 myVMDict
['networks'].append(netDict
)
4117 # 'instance_vm_id': instance_vm_uuid,
4118 "instance_net_id": instance_net_id
,
4119 "instance_wim_net_id": instance_wim_net_id
,
4120 'interface_id': iface
['uuid'],
4121 # 'vim_interface_id': ,
4122 'type': 'external' if iface
['external_name'] is not None else 'internal',
4123 'model': iface
['model'],
4124 'ip_address': iface
.get('ip_address'),
4125 'mac_address': iface
.get('mac'),
4126 'floating_ip': int(iface
.get('floating-ip', False)),
4127 'port_security': int(iface
.get('port-security', True))
4129 db_vm_ifaces
.append(db_vm_iface
)
4130 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
4131 # print myVMDict['name']
4132 # print "networks", yaml.safe_dump(myVMDict['networks'], indent=4, default_flow_style=False)
4133 # print "interfaces", yaml.safe_dump(vm['interfaces'], indent=4, default_flow_style=False)
4134 # print ">>>>>>>>>>>>>>>>>>>>>>>>>>>"
4136 # We add the RO key to cloud_config if vnf will need ssh access
4137 cloud_config_vm
= cloud_config
4138 if is_management_vm
and params
["instance_parameters"].get("mgmt_keys"):
4139 cloud_config_vm
= unify_cloud_config({"key-pairs": params
["instance_parameters"]["mgmt_keys"]},
4142 if vm
.get("instance_parameters") and "mgmt_keys" in vm
["instance_parameters"]:
4143 if vm
["instance_parameters"]["mgmt_keys"]:
4144 cloud_config_vm
= unify_cloud_config({"key-pairs": vm
["instance_parameters"]["mgmt_keys"]},
4147 cloud_config_vm
= unify_cloud_config(cloud_config_vm
, {"key-pairs": [RO_pub_key
]})
4148 if vm
.get("boot_data"):
4149 cloud_config_vm
= unify_cloud_config(vm
["boot_data"], cloud_config_vm
)
4151 if myVMDict
.get('availability_zone'):
4152 av_index
= vnf_availability_zones
.index(myVMDict
['availability_zone'])
4155 for vm_index
in range(0, vm
.get('count', 1)):
4156 vm_name
= myVMDict
['name'] + "-" + str(vm_index
+1)
4157 task_params
= (vm_name
, myVMDict
['description'], myVMDict
.get('start', None),
4158 myVMDict
['imageRef'], myVMDict
['flavorRef'], myVMDict
['networks'], cloud_config_vm
,
4159 myVMDict
['disks'], av_index
, vnf_availability_zones
)
4160 # put interface uuid back to scenario[vnfs][vms[[interfaces]
4161 for net
in myVMDict
['networks']:
4163 for iface
in vm
['interfaces']:
4164 if net
["name"] == iface
["internal_name"]:
4165 iface
["vim_id"] = net
["vim_id"]
4167 vm_uuid
= str(uuid4())
4168 uuid_list
.append(vm_uuid
)
4172 'instance_vnf_id': vnf_uuid
,
4173 # TODO delete "vim_vm_id": vm_id,
4174 "vm_id": vm
["uuid"],
4175 "vim_name": vm_name
,
4178 db_instance_vms
.append(db_vm
)
4181 for db_vm_iface
in db_vm_ifaces
:
4182 iface_uuid
= str(uuid4())
4183 uuid_list
.append(iface_uuid
)
4184 db_vm_iface_instance
= {
4186 "instance_vm_id": vm_uuid
4188 db_vm_iface_instance
.update(db_vm_iface
)
4189 if db_vm_iface_instance
.get("ip_address"): # increment ip_address
4190 ip
= db_vm_iface_instance
.get("ip_address")
4195 ip
= ip
[i
:] + str(int(ip
[:i
]) + 1)
4196 db_vm_iface_instance
["ip_address"] = ip
4198 db_vm_iface_instance
["ip_address"] = None
4199 db_instance_interfaces
.append(db_vm_iface_instance
)
4200 myVMDict
['networks'][iface_index
]["uuid"] = iface_uuid
4204 "instance_action_id": instance_action_id
,
4205 "task_index": task_index
,
4206 "datacenter_vim_id": myvim_thread_id
,
4208 "status": "SCHEDULED",
4209 "item": "instance_vms",
4212 "extra": yaml
.safe_dump({"params": task_params
, "depends_on": task_depends_on
},
4213 default_flow_style
=True, width
=256)
4216 db_vim_actions
.append(db_vim_action
)
4217 params_out
["task_index"] = task_index
4218 params_out
["uuid_list"] = uuid_list
4221 def delete_instance(mydb
, tenant_id
, instance_id
):
4222 # print "Checking that the instance_id exists and getting the instance dictionary"
4223 instanceDict
= mydb
.get_instance_scenario(instance_id
, tenant_id
)
4224 # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4225 tenant_id
= instanceDict
["tenant_id"]
4228 # We need to retrieve the WIM Actions now, before the instance_scenario is
4229 # deleted. The reason for that is that: ON CASCADE rules will delete the
4230 # instance_wim_nets record in the database
4231 wim_actions
= wim_engine
.delete_actions(instance_scenario_id
=instance_id
)
4234 # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
4235 # 1. Delete from Database
4236 message
= mydb
.delete_instance_scenario(instance_id
, tenant_id
)
4238 # 2. delete from VIM
4242 vimthread_affected
= {}
4243 net2vm_dependencies
= {}
4246 instance_action_id
= get_task_id()
4248 db_instance_action
= {
4249 "uuid": instance_action_id
, # same uuid for the instance and the action on create
4250 "tenant_id": tenant_id
,
4251 "instance_id": instance_id
,
4252 "description": "DELETE",
4253 # "number_tasks": 0 # filled bellow
4256 # 2.1 deleting VNFFGs
4257 for sfp
in instanceDict
.get('sfps', ()):
4258 vimthread_affected
[sfp
["datacenter_tenant_id"]] = None
4259 datacenter_key
= (sfp
["datacenter_id"], sfp
["datacenter_tenant_id"])
4260 if datacenter_key
not in myvims
:
4262 _
, myvim_thread
= get_vim_thread(mydb
, tenant_id
, sfp
["datacenter_id"], sfp
["datacenter_tenant_id"])
4263 except NfvoException
as e
:
4264 logger
.error(str(e
))
4266 myvim_threads
[datacenter_key
] = myvim_thread
4267 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=sfp
["datacenter_id"],
4268 datacenter_tenant_id
=sfp
["datacenter_tenant_id"])
4270 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfp
["datacenter_id"], sfp
["datacenter_tenant_id"]))
4271 myvims
[datacenter_key
] = None
4273 myvims
[datacenter_key
] = next(iter(vims
.values()))
4274 myvim
= myvims
[datacenter_key
]
4275 myvim_thread
= myvim_threads
[datacenter_key
]
4278 error_msg
+= "\n vim_sfp_id={} cannot be deleted because datacenter={} not found".format(sfp
['vim_sfp_id'], sfp
["datacenter_id"])
4280 extra
= {"params": (sfp
['vim_sfp_id'])}
4282 "instance_action_id": instance_action_id
,
4283 "task_index": task_index
,
4284 "datacenter_vim_id": sfp
["datacenter_tenant_id"],
4286 "status": "SCHEDULED",
4287 "item": "instance_sfps",
4288 "item_id": sfp
["uuid"],
4289 "related": sfp
["related"],
4290 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4293 db_vim_actions
.append(db_vim_action
)
4295 for classification
in instanceDict
['classifications']:
4296 vimthread_affected
[classification
["datacenter_tenant_id"]] = None
4297 datacenter_key
= (classification
["datacenter_id"], classification
["datacenter_tenant_id"])
4298 if datacenter_key
not in myvims
:
4300 _
, myvim_thread
= get_vim_thread(mydb
, tenant_id
, classification
["datacenter_id"], classification
["datacenter_tenant_id"])
4301 except NfvoException
as e
:
4302 logger
.error(str(e
))
4304 myvim_threads
[datacenter_key
] = myvim_thread
4305 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=classification
["datacenter_id"],
4306 datacenter_tenant_id
=classification
["datacenter_tenant_id"])
4308 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(classification
["datacenter_id"],
4309 classification
["datacenter_tenant_id"]))
4310 myvims
[datacenter_key
] = None
4312 myvims
[datacenter_key
] = next(iter(vims
.values()))
4313 myvim
= myvims
[datacenter_key
]
4314 myvim_thread
= myvim_threads
[datacenter_key
]
4317 error_msg
+= "\n vim_classification_id={} cannot be deleted because datacenter={} not found".format(classification
['vim_classification_id'],
4318 classification
["datacenter_id"])
4320 depends_on
= [action
["task_index"] for action
in db_vim_actions
if action
["item"] == "instance_sfps"]
4321 extra
= {"params": (classification
['vim_classification_id']), "depends_on": depends_on
}
4323 "instance_action_id": instance_action_id
,
4324 "task_index": task_index
,
4325 "datacenter_vim_id": classification
["datacenter_tenant_id"],
4327 "status": "SCHEDULED",
4328 "item": "instance_classifications",
4329 "item_id": classification
["uuid"],
4330 "related": classification
["related"],
4331 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4334 db_vim_actions
.append(db_vim_action
)
4336 for sf
in instanceDict
.get('sfs', ()):
4337 vimthread_affected
[sf
["datacenter_tenant_id"]] = None
4338 datacenter_key
= (sf
["datacenter_id"], sf
["datacenter_tenant_id"])
4339 if datacenter_key
not in myvims
:
4341 _
, myvim_thread
= get_vim_thread(mydb
, tenant_id
, sf
["datacenter_id"], sf
["datacenter_tenant_id"])
4342 except NfvoException
as e
:
4343 logger
.error(str(e
))
4345 myvim_threads
[datacenter_key
] = myvim_thread
4346 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=sf
["datacenter_id"],
4347 datacenter_tenant_id
=sf
["datacenter_tenant_id"])
4349 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sf
["datacenter_id"], sf
["datacenter_tenant_id"]))
4350 myvims
[datacenter_key
] = None
4352 myvims
[datacenter_key
] = next(iter(vims
.values()))
4353 myvim
= myvims
[datacenter_key
]
4354 myvim_thread
= myvim_threads
[datacenter_key
]
4357 error_msg
+= "\n vim_sf_id={} cannot be deleted because datacenter={} not found".format(sf
['vim_sf_id'], sf
["datacenter_id"])
4359 depends_on
= [action
["task_index"] for action
in db_vim_actions
if action
["item"] == "instance_sfps"]
4360 extra
= {"params": (sf
['vim_sf_id']), "depends_on": depends_on
}
4362 "instance_action_id": instance_action_id
,
4363 "task_index": task_index
,
4364 "datacenter_vim_id": sf
["datacenter_tenant_id"],
4366 "status": "SCHEDULED",
4367 "item": "instance_sfs",
4368 "item_id": sf
["uuid"],
4369 "related": sf
["related"],
4370 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4373 db_vim_actions
.append(db_vim_action
)
4375 for sfi
in instanceDict
.get('sfis', ()):
4376 vimthread_affected
[sfi
["datacenter_tenant_id"]] = None
4377 datacenter_key
= (sfi
["datacenter_id"], sfi
["datacenter_tenant_id"])
4378 if datacenter_key
not in myvims
:
4380 _
, myvim_thread
= get_vim_thread(mydb
, tenant_id
, sfi
["datacenter_id"], sfi
["datacenter_tenant_id"])
4381 except NfvoException
as e
:
4382 logger
.error(str(e
))
4384 myvim_threads
[datacenter_key
] = myvim_thread
4385 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=sfi
["datacenter_id"],
4386 datacenter_tenant_id
=sfi
["datacenter_tenant_id"])
4388 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sfi
["datacenter_id"], sfi
["datacenter_tenant_id"]))
4389 myvims
[datacenter_key
] = None
4391 myvims
[datacenter_key
] = next(iter(vims
.values()))
4392 myvim
= myvims
[datacenter_key
]
4393 myvim_thread
= myvim_threads
[datacenter_key
]
4396 error_msg
+= "\n vim_sfi_id={} cannot be deleted because datacenter={} not found".format(sfi
['vim_sfi_id'], sfi
["datacenter_id"])
4398 depends_on
= [action
["task_index"] for action
in db_vim_actions
if action
["item"] == "instance_sfs"]
4399 extra
= {"params": (sfi
['vim_sfi_id']), "depends_on": depends_on
}
4401 "instance_action_id": instance_action_id
,
4402 "task_index": task_index
,
4403 "datacenter_vim_id": sfi
["datacenter_tenant_id"],
4405 "status": "SCHEDULED",
4406 "item": "instance_sfis",
4407 "item_id": sfi
["uuid"],
4408 "related": sfi
["related"],
4409 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4412 db_vim_actions
.append(db_vim_action
)
4416 for sce_vnf
in instanceDict
.get('vnfs', ()):
4417 datacenter_key
= (sce_vnf
["datacenter_id"], sce_vnf
["datacenter_tenant_id"])
4418 vimthread_affected
[sce_vnf
["datacenter_tenant_id"]] = None
4419 if datacenter_key
not in myvims
:
4421 _
, myvim_thread
= get_vim_thread(mydb
, tenant_id
, sce_vnf
["datacenter_id"], sce_vnf
["datacenter_tenant_id"])
4422 except NfvoException
as e
:
4423 logger
.error(str(e
))
4425 myvim_threads
[datacenter_key
] = myvim_thread
4426 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=sce_vnf
["datacenter_id"],
4427 datacenter_tenant_id
=sce_vnf
["datacenter_tenant_id"])
4429 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf
["datacenter_id"],
4430 sce_vnf
["datacenter_tenant_id"]))
4431 myvims
[datacenter_key
] = None
4433 myvims
[datacenter_key
] = next(iter(vims
.values()))
4434 myvim
= myvims
[datacenter_key
]
4435 myvim_thread
= myvim_threads
[datacenter_key
]
4437 for vm
in sce_vnf
['vms']:
4439 error_msg
+= "\n VM id={} cannot be deleted because datacenter={} not found".format(vm
['vim_vm_id'], sce_vnf
["datacenter_id"])
4441 sfi_dependencies
= [action
["task_index"] for action
in db_vim_actions
if action
["item"] == "instance_sfis"]
4443 "instance_action_id": instance_action_id
,
4444 "task_index": task_index
,
4445 "datacenter_vim_id": sce_vnf
["datacenter_tenant_id"],
4447 "status": "SCHEDULED",
4448 "item": "instance_vms",
4449 "item_id": vm
["uuid"],
4450 "related": vm
["related"],
4451 "extra": yaml
.safe_dump({"params": vm
["interfaces"], "depends_on": sfi_dependencies
},
4452 default_flow_style
=True, width
=256)
4454 db_vim_actions
.append(db_vim_action
)
4455 for interface
in vm
["interfaces"]:
4456 if not interface
.get("instance_net_id"):
4458 if interface
["instance_net_id"] not in net2vm_dependencies
:
4459 net2vm_dependencies
[interface
["instance_net_id"]] = []
4460 net2vm_dependencies
[interface
["instance_net_id"]].append(task_index
)
4465 for net
in instanceDict
['nets']:
4466 vimthread_affected
[net
["datacenter_tenant_id"]] = None
4467 datacenter_key
= (net
["datacenter_id"], net
["datacenter_tenant_id"])
4468 if datacenter_key
not in myvims
:
4470 _
,myvim_thread
= get_vim_thread(mydb
, tenant_id
, net
["datacenter_id"], net
["datacenter_tenant_id"])
4471 except NfvoException
as e
:
4472 logger
.error(str(e
))
4474 myvim_threads
[datacenter_key
] = myvim_thread
4475 vims
= get_vim(mydb
, tenant_id
, datacenter_id
=net
["datacenter_id"],
4476 datacenter_tenant_id
=net
["datacenter_tenant_id"])
4478 logger
.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net
["datacenter_id"], net
["datacenter_tenant_id"]))
4479 myvims
[datacenter_key
] = None
4481 myvims
[datacenter_key
] = next(iter(vims
.values()))
4482 myvim
= myvims
[datacenter_key
]
4483 myvim_thread
= myvim_threads
[datacenter_key
]
4486 error_msg
+= "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net
['vim_net_id'], net
["datacenter_id"])
4488 extra
= {"params": (net
['vim_net_id'], net
['sdn_net_id'])}
4489 if net2vm_dependencies
.get(net
["uuid"]):
4490 extra
["depends_on"] = net2vm_dependencies
[net
["uuid"]]
4491 sfi_dependencies
= [action
["task_index"] for action
in db_vim_actions
if action
["item"] == "instance_sfis"]
4492 if len(sfi_dependencies
) > 0:
4493 if "depends_on" in extra
:
4494 extra
["depends_on"] += sfi_dependencies
4496 extra
["depends_on"] = sfi_dependencies
4498 "instance_action_id": instance_action_id
,
4499 "task_index": task_index
,
4500 "datacenter_vim_id": net
["datacenter_tenant_id"],
4502 "status": "SCHEDULED",
4503 "item": "instance_nets",
4504 "item_id": net
["uuid"],
4505 "related": net
["related"],
4506 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4509 db_vim_actions
.append(db_vim_action
)
4510 for sdn_net
in instanceDict
['sdn_nets']:
4511 if not sdn_net
["sdn"]:
4515 "instance_action_id": instance_action_id
,
4516 "task_index": task_index
,
4517 "wim_account_id": sdn_net
["wim_account_id"],
4519 "status": "SCHEDULED",
4520 "item": "instance_wim_nets",
4521 "item_id": sdn_net
["uuid"],
4522 "related": sdn_net
["related"],
4523 "extra": yaml
.safe_dump(extra
, default_flow_style
=True, width
=256)
4526 db_vim_actions
.append(db_vim_action
)
4528 db_instance_action
["number_tasks"] = task_index
4531 wim_actions
, db_instance_action
= (
4532 wim_engine
.incorporate_actions(wim_actions
, db_instance_action
))
4536 {"instance_actions": db_instance_action
},
4537 {"vim_wim_actions": db_vim_actions
+ wim_actions
}
4540 logger
.debug("delete_instance done DB tables: %s",
4541 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False))
4542 mydb
.new_rows(db_tables
, ())
4543 for myvim_thread_id
in vimthread_affected
.keys():
4544 vim_threads
["running"][myvim_thread_id
].insert_task(db_vim_actions
)
4546 wim_engine
.dispatch(wim_actions
)
4548 if len(error_msg
) > 0:
4549 return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\
4550 '(error: 404) from VIM: {}'.format(instance_action_id
, message
, error_msg
)
4552 return "action_id={} instance {} deleted".format(instance_action_id
, message
)
4554 def get_instance_id(mydb
, tenant_id
, instance_id
):
4556 #check valid tenant_id
4557 check_tenant(mydb
, tenant_id
)
4560 instance_dict
= mydb
.get_instance_scenario(instance_id
, tenant_id
, verbose
=True)
4562 # for net in instance_dict["nets"]:
4563 # if net.get("sdn_net_id"):
4564 # net_sdn = ovim.show_network(net["sdn_net_id"])
4565 # net["sdn_info"] = {
4566 # "admin_state_up": net_sdn.get("admin_state_up"),
4567 # "flows": net_sdn.get("flows"),
4568 # "last_error": net_sdn.get("last_error"),
4569 # "ports": net_sdn.get("ports"),
4570 # "type": net_sdn.get("type"),
4571 # "status": net_sdn.get("status"),
4572 # "vlan": net_sdn.get("vlan"),
4574 return instance_dict
4576 @deprecated("Instance is automatically refreshed by vim_threads")
4577 def refresh_instance(mydb
, nfvo_tenant
, instanceDict
, datacenter
=None, vim_tenant
=None):
4578 '''Refreshes a scenario instance. It modifies instanceDict'''
4580 - result: <0 if there is any unexpected error, n>=0 if no errors where n is the number of vms and nets that couldn't be updated in the database
4583 # # Assumption: nfvo_tenant and instance_id were checked before entering into this function
4584 # #print "nfvo.refresh_instance begins"
4585 # #print json.dumps(instanceDict, indent=4)
4587 # #print "Getting the VIM URL and the VIM tenant_id"
4590 # # 1. Getting VIM vm and net list
4591 # vms_updated = [] #List of VM instance uuids in openmano that were updated
4594 # for sce_vnf in instanceDict['vnfs']:
4595 # datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"])
4596 # if datacenter_key not in vm_list:
4597 # vm_list[datacenter_key] = []
4598 # if datacenter_key not in myvims:
4599 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=sce_vnf["datacenter_id"],
4600 # datacenter_tenant_id=sce_vnf["datacenter_tenant_id"])
4601 # if len(vims) == 0:
4602 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]))
4603 # myvims[datacenter_key] = None
4605 # myvims[datacenter_key] = next(iter(vims.values()))
4606 # for vm in sce_vnf['vms']:
4607 # vm_list[datacenter_key].append(vm['vim_vm_id'])
4608 # vms_notupdated.append(vm["uuid"])
4610 # nets_updated = [] #List of VM instance uuids in openmano that were updated
4611 # nets_notupdated=[]
4613 # for net in instanceDict['nets']:
4614 # datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"])
4615 # if datacenter_key not in net_list:
4616 # net_list[datacenter_key] = []
4617 # if datacenter_key not in myvims:
4618 # vims = get_vim(mydb, nfvo_tenant, datacenter_id=net["datacenter_id"],
4619 # datacenter_tenant_id=net["datacenter_tenant_id"])
4620 # if len(vims) == 0:
4621 # logger.error("datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"]))
4622 # myvims[datacenter_key] = None
4624 # myvims[datacenter_key] = next(iter(vims.values()))
4626 # net_list[datacenter_key].append(net['vim_net_id'])
4627 # nets_notupdated.append(net["uuid"])
4629 # # 1. Getting the status of all VMs
4631 # for datacenter_key in myvims:
4632 # if not vm_list.get(datacenter_key):
4636 # if not myvims[datacenter_key]:
4637 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4640 # vm_dict.update(myvims[datacenter_key].refresh_vms_status(vm_list[datacenter_key]) )
4642 # except vimconn.vimconnException as e:
4643 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4644 # failed_message = str(e)
4646 # for vm in vm_list[datacenter_key]:
4647 # vm_dict[vm] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4649 # # 2. Update the status of VMs in the instanceDict, while collects the VMs whose status changed
4650 # for sce_vnf in instanceDict['vnfs']:
4651 # for vm in sce_vnf['vms']:
4652 # vm_id = vm['vim_vm_id']
4653 # interfaces = vm_dict[vm_id].pop('interfaces', [])
4654 # #2.0 look if contain manamgement interface, and if not change status from ACTIVE:NoMgmtIP to ACTIVE
4655 # has_mgmt_iface = False
4656 # for iface in vm["interfaces"]:
4657 # if iface["type"]=="mgmt":
4658 # has_mgmt_iface = True
4659 # if vm_dict[vm_id]['status'] == "ACTIVE:NoMgmtIP" and not has_mgmt_iface:
4660 # vm_dict[vm_id]['status'] = "ACTIVE"
4661 # if vm_dict[vm_id].get('error_msg') and len(vm_dict[vm_id]['error_msg']) >= 1024:
4662 # vm_dict[vm_id]['error_msg'] = vm_dict[vm_id]['error_msg'][:516] + " ... " + vm_dict[vm_id]['error_msg'][-500:]
4663 # if vm['status'] != vm_dict[vm_id]['status'] or vm.get('error_msg')!=vm_dict[vm_id].get('error_msg') or vm.get('vim_info')!=vm_dict[vm_id].get('vim_info'):
4664 # vm['status'] = vm_dict[vm_id]['status']
4665 # vm['error_msg'] = vm_dict[vm_id].get('error_msg')
4666 # vm['vim_info'] = vm_dict[vm_id].get('vim_info')
4667 # # 2.1. Update in openmano DB the VMs whose status changed
4669 # updates = mydb.update_rows('instance_vms', UPDATE=vm_dict[vm_id], WHERE={'uuid':vm["uuid"]})
4670 # vms_notupdated.remove(vm["uuid"])
4672 # vms_updated.append(vm["uuid"])
4673 # except db_base_Exception as e:
4674 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4675 # # 2.2. Update in openmano DB the interface VMs
4676 # for interface in interfaces:
4677 # #translate from vim_net_id to instance_net_id
4678 # network_id_list=[]
4679 # for net in instanceDict['nets']:
4680 # if net["vim_net_id"] == interface["vim_net_id"]:
4681 # network_id_list.append(net["uuid"])
4682 # if not network_id_list:
4684 # del interface["vim_net_id"]
4686 # for network_id in network_id_list:
4687 # mydb.update_rows('instance_interfaces', UPDATE=interface, WHERE={'instance_vm_id':vm["uuid"], "instance_net_id":network_id})
4688 # except db_base_Exception as e:
4689 # logger.error( "nfvo.refresh_instance error with vm=%s, interface_net_id=%s", vm["uuid"], network_id)
4691 # # 3. Getting the status of all nets
4693 # for datacenter_key in myvims:
4694 # if not net_list.get(datacenter_key):
4697 # failed_message = ""
4698 # if not myvims[datacenter_key]:
4699 # failed_message = "datacenter '{}' with datacenter_tenant_id '{}' not found".format(net["datacenter_id"], net["datacenter_tenant_id"])
4702 # net_dict.update(myvims[datacenter_key].refresh_nets_status(net_list[datacenter_key]) )
4704 # except vimconn.vimconnException as e:
4705 # logger.error("VIM exception %s %s", type(e).__name__, str(e))
4706 # failed_message = str(e)
4708 # for net in net_list[datacenter_key]:
4709 # net_dict[net] = {'status': "VIM_ERROR", 'error_msg': failed_message}
4711 # # 4. Update the status of nets in the instanceDict, while collects the nets whose status changed
4712 # # TODO: update nets inside a vnf
4713 # for net in instanceDict['nets']:
4714 # net_id = net['vim_net_id']
4715 # if net_dict[net_id].get('error_msg') and len(net_dict[net_id]['error_msg']) >= 1024:
4716 # net_dict[net_id]['error_msg'] = net_dict[net_id]['error_msg'][:516] + " ... " + net_dict[vm_id]['error_msg'][-500:]
4717 # if net['status'] != net_dict[net_id]['status'] or net.get('error_msg')!=net_dict[net_id].get('error_msg') or net.get('vim_info')!=net_dict[net_id].get('vim_info'):
4718 # net['status'] = net_dict[net_id]['status']
4719 # net['error_msg'] = net_dict[net_id].get('error_msg')
4720 # net['vim_info'] = net_dict[net_id].get('vim_info')
4721 # # 5.1. Update in openmano DB the nets whose status changed
4723 # updated = mydb.update_rows('instance_nets', UPDATE=net_dict[net_id], WHERE={'uuid':net["uuid"]})
4724 # nets_notupdated.remove(net["uuid"])
4726 # nets_updated.append(net["uuid"])
4727 # except db_base_Exception as e:
4728 # logger.error("nfvo.refresh_instance error database update: %s", str(e))
4730 # # Returns appropriate output
4731 # #print "nfvo.refresh_instance finishes"
4732 # logger.debug("VMs updated in the database: %s; nets updated in the database %s; VMs not updated: %s; nets not updated: %s",
4733 # str(vms_updated), str(nets_updated), str(vms_notupdated), str(nets_notupdated))
4734 instance_id
= instanceDict
['uuid']
4735 # if len(vms_notupdated)+len(nets_notupdated)>0:
4736 # error_msg = "VMs not updated: " + str(vms_notupdated) + "; nets not updated: " + str(nets_notupdated)
4737 # return len(vms_notupdated)+len(nets_notupdated), 'Scenario instance ' + instance_id + ' refreshed but some elements could not be updated in the database: ' + error_msg
4739 return 0, 'Scenario instance ' + instance_id
+ ' refreshed.'
4741 def instance_action(mydb
,nfvo_tenant
,instance_id
, action_dict
):
4742 #print "Checking that the instance_id exists and getting the instance dictionary"
4743 instanceDict
= mydb
.get_instance_scenario(instance_id
, nfvo_tenant
)
4744 #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False)
4746 #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id"
4747 vims
= get_vim(mydb
, nfvo_tenant
, instanceDict
['datacenter_id'])
4749 raise NfvoException("datacenter '{}' not found".format(str(instanceDict
['datacenter_id'])), httperrors
.Not_Found
)
4750 myvim
= next(iter(vims
.values()))
4755 myvim_threads_id
= {}
4756 if action_dict
.get("vdu-scaling"):
4757 db_instance_vms
= []
4759 db_instance_interfaces
= []
4760 instance_action_id
= get_task_id()
4761 db_instance_action
= {
4762 "uuid": instance_action_id
, # same uuid for the instance and the action on create
4763 "tenant_id": nfvo_tenant
,
4764 "instance_id": instance_id
,
4765 "description": "SCALE",
4767 vm_result
["instance_action_id"] = instance_action_id
4768 vm_result
["created"] = []
4769 vm_result
["deleted"] = []
4771 for vdu
in action_dict
["vdu-scaling"]:
4772 vdu_id
= vdu
.get("vdu-id")
4773 osm_vdu_id
= vdu
.get("osm_vdu_id")
4774 member_vnf_index
= vdu
.get("member-vnf-index")
4775 vdu_count
= vdu
.get("count", 1)
4777 target_vms
= mydb
.get_rows(
4778 FROM
="instance_vms as vms join instance_vnfs as vnfs on vms.instance_vnf_id=vnfs.uuid",
4779 WHERE
={"vms.uuid": vdu_id
},
4780 ORDER_BY
="vms.created_at"
4783 raise NfvoException("Cannot find the vdu with id {}".format(vdu_id
), httperrors
.Not_Found
)
4785 if not osm_vdu_id
and not member_vnf_index
:
4786 raise NfvoException("Invalid input vdu parameters. Must supply either 'vdu-id' of 'osm_vdu_id','member-vnf-index'")
4787 target_vms
= mydb
.get_rows(
4788 # SELECT=("ivms.uuid", "ivnfs.datacenter_id", "ivnfs.datacenter_tenant_id"),
4789 FROM
="instance_vms as ivms join instance_vnfs as ivnfs on ivms.instance_vnf_id=ivnfs.uuid"\
4790 " join sce_vnfs as svnfs on ivnfs.sce_vnf_id=svnfs.uuid"\
4791 " join vms on ivms.vm_id=vms.uuid",
4792 WHERE
={"vms.osm_id": osm_vdu_id
, "svnfs.member_vnf_index": member_vnf_index
,
4793 "ivnfs.instance_scenario_id": instance_id
},
4794 ORDER_BY
="ivms.created_at"
4797 raise NfvoException("Cannot find the vdu with osm_vdu_id {} and member-vnf-index {}".format(osm_vdu_id
, member_vnf_index
), httperrors
.Not_Found
)
4798 vdu_id
= target_vms
[-1]["uuid"]
4799 target_vm
= target_vms
[-1]
4800 datacenter
= target_vm
["datacenter_id"]
4801 myvim_threads_id
[datacenter
], _
= get_vim_thread(mydb
, nfvo_tenant
, datacenter
)
4803 if vdu
["type"] == "delete":
4804 for index
in range(0, vdu_count
):
4805 target_vm
= target_vms
[-1-index
]
4806 vdu_id
= target_vm
["uuid"]
4808 vm_interfaces
= None
4809 for sce_vnf
in instanceDict
['vnfs']:
4810 for vm
in sce_vnf
['vms']:
4811 if vm
["uuid"] == vdu_id
:
4812 # TODO revise this should not be vm["uuid"] instance_vms["vm_id"]
4813 vm_interfaces
= vm
["interfaces"]
4817 "instance_action_id": instance_action_id
,
4818 "task_index": task_index
,
4819 "datacenter_vim_id": target_vm
["datacenter_tenant_id"],
4821 "status": "SCHEDULED",
4822 "item": "instance_vms",
4824 "related": target_vm
["related"],
4825 "extra": yaml
.safe_dump({"params": vm_interfaces
},
4826 default_flow_style
=True, width
=256)
4828 # get affected instance_interfaces (deleted on cascade) to check if a wim_network must be updated
4829 deleted_interfaces
= mydb
.get_rows(
4830 SELECT
=("instance_wim_net_id", ),
4831 FROM
="instance_interfaces",
4832 WHERE
={"instance_vm_id": vdu_id
, "instance_wim_net_id<>": None},
4834 for deleted_interface
in deleted_interfaces
:
4835 db_vim_actions
.append({"TO-UPDATE": {}, "WHERE": {
4836 "item": "instance_wim_nets", "item_id": deleted_interface
["instance_wim_net_id"]}})
4839 db_vim_actions
.append(db_vim_action
)
4840 vm_result
["deleted"].append(vdu_id
)
4841 # delete from database
4842 db_instance_vms
.append({"TO-DELETE": vdu_id
})
4844 else: # vdu["type"] == "create":
4846 where
= {"item": "instance_vms", "item_id": target_vm
["uuid"], "action": "CREATE"}
4848 vim_action_to_clone
= mydb
.get_rows(FROM
="vim_wim_actions", WHERE
=where
)
4849 if not vim_action_to_clone
:
4850 raise NfvoException("Cannot find the vim_action at database with {}".format(where
), httperrors
.Internal_Server_Error
)
4851 vim_action_to_clone
= vim_action_to_clone
[0]
4852 extra
= yaml
.safe_load(vim_action_to_clone
["extra"])
4854 # generate a new depends_on. Convert format TASK-Y into new format TASK-ACTION-XXXX.XXXX.Y
4855 # TODO do the same for flavor and image when available
4856 task_depends_on
= []
4857 task_params
= extra
["params"]
4858 task_params_networks
= deepcopy(task_params
[5])
4859 for iface
in task_params
[5]:
4860 if iface
["net_id"].startswith("TASK-"):
4861 if "." not in iface
["net_id"]:
4862 task_depends_on
.append("{}.{}".format(vim_action_to_clone
["instance_action_id"],
4863 iface
["net_id"][5:]))
4864 iface
["net_id"] = "TASK-{}.{}".format(vim_action_to_clone
["instance_action_id"],
4865 iface
["net_id"][5:])
4867 task_depends_on
.append(iface
["net_id"][5:])
4868 if "mac_address" in iface
:
4869 del iface
["mac_address"]
4871 vm_ifaces_to_clone
= mydb
.get_rows(FROM
="instance_interfaces", WHERE
={"instance_vm_id": target_vm
["uuid"]})
4872 for index
in range(0, vdu_count
):
4873 vm_uuid
= str(uuid4())
4874 vm_name
= target_vm
.get('vim_name')
4876 suffix
= vm_name
.rfind("-")
4877 vm_name
= vm_name
[:suffix
+1] + str(index
+ 1 + int(vm_name
[suffix
+1:]))
4883 'instance_vnf_id': target_vm
['instance_vnf_id'],
4884 'vm_id': target_vm
['vm_id'],
4885 'vim_name': vm_name
,
4887 db_instance_vms
.append(db_instance_vm
)
4889 for vm_iface
in vm_ifaces_to_clone
:
4890 iface_uuid
= str(uuid4())
4891 iface2iface
[vm_iface
["uuid"]] = iface_uuid
4894 'instance_vm_id': vm_uuid
,
4895 "instance_net_id": vm_iface
["instance_net_id"],
4896 "instance_wim_net_id": vm_iface
["instance_wim_net_id"],
4897 'interface_id': vm_iface
['interface_id'],
4898 'type': vm_iface
['type'],
4899 'model': vm_iface
['model'],
4900 'floating_ip': vm_iface
['floating_ip'],
4901 'port_security': vm_iface
['port_security']
4903 db_instance_interfaces
.append(db_vm_iface
)
4904 if db_vm_iface
["instance_wim_net_id"]:
4905 db_vim_actions
.append({"TO-UPDATE": {}, "WHERE": {
4906 "item": "instance_wim_nets", "item_id": db_vm_iface
["instance_wim_net_id"]}})
4907 task_params_copy
= deepcopy(task_params
)
4908 for iface
in task_params_copy
[5]:
4909 iface
["uuid"] = iface2iface
[iface
["uuid"]]
4910 # increment ip_address
4911 if iface
.get("ip_address"):
4913 ip
= iface
["ip_address"]
4917 ip
= ip
[i
:] + str(int(ip
[:i
]) + 1)
4918 iface
["ip_address"] = ip
4920 iface
["ip_address"] = None
4922 task_params_copy
[0] = vm_name
4924 "instance_action_id": instance_action_id
,
4925 "task_index": task_index
,
4926 "datacenter_vim_id": vim_action_to_clone
["datacenter_vim_id"],
4928 "status": "SCHEDULED",
4929 "item": "instance_vms",
4934 # TODO examinar parametros, quitar MAC o incrementar. Incrementar IP y colocar las dependencias con ACTION-asdfasd.
4937 "extra": yaml
.safe_dump({"params": task_params_copy
, "depends_on": task_depends_on
}, default_flow_style
=True, width
=256)
4940 db_vim_actions
.append(db_vim_action
)
4941 vm_result
["created"].append(vm_uuid
)
4943 db_instance_action
["number_tasks"] = task_index
4945 {"instance_vms": db_instance_vms
},
4946 {"instance_interfaces": db_instance_interfaces
},
4947 {"instance_actions": db_instance_action
},
4949 # {"instance_sfis": db_instance_sfis},
4950 # {"instance_sfs": db_instance_sfs},
4951 # {"instance_classifications": db_instance_classifications},
4952 # {"instance_sfps": db_instance_sfps},
4953 {"vim_wim_actions": db_vim_actions
}
4955 logger
.debug("create_vdu done DB tables: %s",
4956 yaml
.safe_dump(db_tables
, indent
=4, default_flow_style
=False))
4957 mydb
.new_rows(db_tables
, [])
4958 for myvim_thread
in myvim_threads_id
.values():
4959 vim_threads
["running"][myvim_thread
].insert_task(db_vim_actions
)
4963 input_vnfs
= action_dict
.pop("vnfs", [])
4964 input_vms
= action_dict
.pop("vms", [])
4965 action_over_all
= True if not input_vnfs
and not input_vms
else False
4966 for sce_vnf
in instanceDict
['vnfs']:
4967 for vm
in sce_vnf
['vms']:
4968 if not action_over_all
and sce_vnf
['uuid'] not in input_vnfs
and sce_vnf
['vnf_name'] not in input_vnfs
and \
4969 sce_vnf
['member_vnf_index'] not in input_vnfs
and \
4970 vm
['uuid'] not in input_vms
and vm
['name'] not in input_vms
and \
4971 sce_vnf
['member_vnf_index'] + "-" + vm
['vdu_osm_id'] not in input_vms
: # TODO conside vm_count_index
4974 if "add_public_key" in action_dict
:
4975 if sce_vnf
.get('mgmt_access'):
4976 mgmt_access
= yaml
.load(sce_vnf
['mgmt_access'], Loader
=yaml
.Loader
)
4977 if not input_vms
and mgmt_access
.get("vdu-id") != vm
['vdu_osm_id']:
4979 default_user
= mgmt_access
.get("default-user")
4980 password
= mgmt_access
.get("password")
4981 if mgmt_access
.get(vm
['vdu_osm_id']):
4982 default_user
= mgmt_access
[vm
['vdu_osm_id']].get("default-user", default_user
)
4983 password
= mgmt_access
[vm
['vdu_osm_id']].get("password", password
)
4985 tenant
= mydb
.get_rows_by_id('nfvo_tenants', nfvo_tenant
)
4987 if 'ip_address' in vm
:
4988 mgmt_ip
= vm
['ip_address'].split(';')
4989 priv_RO_key
= decrypt_key(tenant
[0]['encrypted_RO_priv_key'], tenant
[0]['uuid'])
4990 data
= myvim
.inject_user_key(mgmt_ip
[0], action_dict
.get('user', default_user
),
4991 action_dict
['add_public_key'],
4992 password
=password
, ro_key
=priv_RO_key
)
4993 vm_result
[ vm
['uuid'] ] = {"vim_result": 200,
4994 "description": "Public key injected",
4998 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm
['uuid']),
4999 httperrors
.Internal_Server_Error
)
5001 raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm
['uuid']),
5002 httperrors
.Internal_Server_Error
)
5004 data
= myvim
.action_vminstance(vm
['vim_vm_id'], action_dict
)
5005 if "console" in action_dict
:
5006 if not global_config
["http_console_proxy"]:
5007 vm_result
[ vm
['uuid'] ] = {"vim_result": 200,
5008 "description": "{protocol}//{ip}:{port}/{suffix}".format(
5009 protocol
=data
["protocol"],
5010 ip
= data
["server"],
5011 port
= data
["port"],
5012 suffix
= data
["suffix"]),
5016 elif data
["server"]=="127.0.0.1" or data
["server"]=="localhost":
5017 vm_result
[ vm
['uuid'] ] = {"vim_result": -httperrors
.Unauthorized
,
5018 "description": "this console is only reachable by local interface",
5023 #print "console data", data
5025 console_thread
= create_or_use_console_proxy_thread(data
["server"], data
["port"])
5026 vm_result
[ vm
['uuid'] ] = {"vim_result": 200,
5027 "description": "{protocol}//{ip}:{port}/{suffix}".format(
5028 protocol
=data
["protocol"],
5029 ip
= global_config
["http_console_host"],
5030 port
= console_thread
.port
,
5031 suffix
= data
["suffix"]),
5035 except NfvoException
as e
:
5036 vm_result
[ vm
['uuid'] ] = {"vim_result": e
.http_code
, "name":vm
['name'], "description": str(e
)}
5040 vm_result
[ vm
['uuid'] ] = {"vim_result": 200, "description": "ok", "name":vm
['name']}
5042 except vimconn
.vimconnException
as e
:
5043 vm_result
[ vm
['uuid'] ] = {"vim_result": e
.http_code
, "name":vm
['name'], "description": str(e
)}
5046 if vm_ok
==0: #all goes wrong
5051 def instance_action_get(mydb
, nfvo_tenant
, instance_id
, action_id
):
5053 if nfvo_tenant
and nfvo_tenant
!= "any":
5054 filter["tenant_id"] = nfvo_tenant
5055 if instance_id
and instance_id
!= "any":
5056 filter["instance_id"] = instance_id
5058 filter["uuid"] = action_id
5059 rows
= mydb
.get_rows(FROM
="instance_actions", WHERE
=filter)
5062 raise NfvoException("Not found any action with this criteria", httperrors
.Not_Found
)
5063 vim_wim_actions
= mydb
.get_rows(FROM
="vim_wim_actions", WHERE
={"instance_action_id": action_id
})
5064 rows
[0]["vim_wim_actions"] = vim_wim_actions
5065 # for backward compatibility set vim_actions = vim_wim_actions
5066 rows
[0]["vim_actions"] = vim_wim_actions
5067 return {"actions": rows
}
5070 def create_or_use_console_proxy_thread(console_server
, console_port
):
5071 #look for a non-used port
5072 console_thread_key
= console_server
+ ":" + str(console_port
)
5073 if console_thread_key
in global_config
["console_thread"]:
5074 #global_config["console_thread"][console_thread_key].start_timeout()
5075 return global_config
["console_thread"][console_thread_key
]
5077 for port
in global_config
["console_port_iterator"]():
5078 #print "create_or_use_console_proxy_thread() port:", port
5079 if port
in global_config
["console_ports"]:
5082 clithread
= cli
.ConsoleProxyThread(global_config
['http_host'], port
, console_server
, console_port
)
5084 global_config
["console_thread"][console_thread_key
] = clithread
5085 global_config
["console_ports"][port
] = console_thread_key
5087 except cli
.ConsoleProxyExceptionPortUsed
as e
:
5088 #port used, try with onoher
5090 except cli
.ConsoleProxyException
as e
:
5091 raise NfvoException(str(e
), httperrors
.Bad_Request
)
5092 raise NfvoException("Not found any free 'http_console_ports'", httperrors
.Conflict
)
5095 def check_tenant(mydb
, tenant_id
):
5096 '''check that tenant exists at database'''
5097 tenant
= mydb
.get_rows(FROM
='nfvo_tenants', SELECT
=('uuid',), WHERE
={'uuid': tenant_id
})
5099 raise NfvoException("tenant '{}' not found".format(tenant_id
), httperrors
.Not_Found
)
5102 def new_tenant(mydb
, tenant_dict
):
5104 tenant_uuid
= str(uuid4())
5105 tenant_dict
['uuid'] = tenant_uuid
5107 pub_key
, priv_key
= create_RO_keypair(tenant_uuid
)
5108 tenant_dict
['RO_pub_key'] = pub_key
5109 tenant_dict
['encrypted_RO_priv_key'] = priv_key
5110 mydb
.new_row("nfvo_tenants", tenant_dict
, confidential_data
=True)
5111 except db_base_Exception
as e
:
5112 raise NfvoException("Error creating the new tenant: {} ".format(tenant_dict
['name']) + str(e
), e
.http_code
)
5115 def delete_tenant(mydb
, tenant
):
5116 #get nfvo_tenant info
5118 tenant_dict
= mydb
.get_table_by_uuid_name('nfvo_tenants', tenant
, 'tenant')
5119 mydb
.delete_row_by_id("nfvo_tenants", tenant_dict
['uuid'])
5120 return tenant_dict
['uuid'] + " " + tenant_dict
["name"]
5123 def new_datacenter(mydb
, datacenter_descriptor
):
5124 sdn_port_mapping
= None
5125 if "config" in datacenter_descriptor
:
5126 sdn_port_mapping
= datacenter_descriptor
["config"].pop("sdn-port-mapping", None)
5127 datacenter_descriptor
["config"] = yaml
.safe_dump(datacenter_descriptor
["config"], default_flow_style
=True,
5129 # Check that datacenter-type is correct
5130 datacenter_type
= datacenter_descriptor
.get("type", "openvim");
5131 # module_info = None
5133 for url_field
in ('vim_url', 'vim_url_admin'):
5134 # It is common that users copy and paste the URL from the VIM website
5135 # (example OpenStack), therefore a common mistake is to include blank
5136 # characters at the end of the URL. Let's remove it and just in case,
5137 # lets remove trailing slash as well.
5138 url
= datacenter_descriptor
.get(url_field
)
5140 datacenter_descriptor
[url_field
] = url
.strip(string
.whitespace
+ '/')
5143 plugin_name
= "rovim_" + datacenter_type
5144 if plugin_name
not in plugins
:
5145 _load_plugin(plugin_name
, type="vim")
5147 datacenter_id
= mydb
.new_row("datacenters", datacenter_descriptor
, add_uuid
=True, confidential_data
=True)
5148 if sdn_port_mapping
:
5150 datacenter_sdn_port_mapping_set(mydb
, None, datacenter_id
, sdn_port_mapping
)
5151 except Exception as e
:
5152 mydb
.delete_row_by_id("datacenters", datacenter_id
) # Rollback
5154 return datacenter_id
5157 def edit_datacenter(mydb
, datacenter_id_name
, datacenter_descriptor
):
5158 # obtain data, check that only one exist
5159 datacenter
= mydb
.get_table_by_uuid_name('datacenters', datacenter_id_name
)
5162 datacenter_id
= datacenter
['uuid']
5163 where
= {'uuid': datacenter
['uuid']}
5164 remove_port_mapping
= False
5165 new_sdn_port_mapping
= None
5166 if "config" in datacenter_descriptor
:
5167 if datacenter_descriptor
['config'] != None:
5169 new_config_dict
= datacenter_descriptor
["config"]
5170 if "sdn-port-mapping" in new_config_dict
:
5171 remove_port_mapping
= True
5172 new_sdn_port_mapping
= new_config_dict
.pop("sdn-port-mapping")
5173 # delete null fields
5175 for k
in new_config_dict
:
5176 if new_config_dict
[k
] is None:
5178 if k
== 'sdn-controller':
5179 remove_port_mapping
= True
5181 config_text
= datacenter
.get("config")
5184 config_dict
= yaml
.load(config_text
, Loader
=yaml
.Loader
)
5185 config_dict
.update(new_config_dict
)
5186 # delete null fields
5189 except Exception as e
:
5190 raise NfvoException("Bad format at datacenter:config " + str(e
), httperrors
.Bad_Request
)
5192 datacenter_descriptor
["config"] = yaml
.safe_dump(config_dict
, default_flow_style
=True, width
=256)
5194 datacenter_descriptor
["config"] = None
5195 if remove_port_mapping
:
5197 datacenter_sdn_port_mapping_delete(mydb
, None, datacenter_id
)
5198 except ovimException
as e
:
5199 raise NfvoException("Error deleting datacenter-port-mapping " + str(e
), httperrors
.Conflict
)
5201 mydb
.update_rows('datacenters', datacenter_descriptor
, where
)
5202 if new_sdn_port_mapping
:
5204 datacenter_sdn_port_mapping_set(mydb
, None, datacenter_id
, new_sdn_port_mapping
)
5205 except ovimException
as e
:
5207 mydb
.update_rows('datacenters', datacenter
, where
)
5208 raise NfvoException("Error adding datacenter-port-mapping " + str(e
), httperrors
.Conflict
)
5209 return datacenter_id
5212 def delete_datacenter(mydb
, datacenter
):
5213 #get nfvo_tenant info
5214 datacenter_dict
= mydb
.get_table_by_uuid_name('datacenters', datacenter
, 'datacenter')
5215 mydb
.delete_row_by_id("datacenters", datacenter_dict
['uuid'])
5217 datacenter_sdn_port_mapping_delete(mydb
, None, datacenter_dict
['uuid'])
5218 except ovimException
as e
:
5219 raise NfvoException("Error deleting datacenter-port-mapping " + str(e
))
5220 return datacenter_dict
['uuid'] + " " + datacenter_dict
['name']
5223 def create_vim_account(mydb
, nfvo_tenant
, datacenter_id
, name
=None, vim_id
=None, vim_tenant
=None, vim_tenant_name
=None,
5224 vim_username
=None, vim_password
=None, config
=None):
5225 # get datacenter info
5227 if not datacenter_id
:
5229 raise NfvoException("You must provide 'vim_id", http_code
=httperrors
.Bad_Request
)
5230 datacenter_id
= vim_id
5231 datacenter_id
, datacenter_name
= get_datacenter_uuid(mydb
, None, datacenter_id
)
5233 create_vim_tenant
= True if not vim_tenant
and not vim_tenant_name
else False
5235 # get nfvo_tenant info
5236 tenant_dict
= mydb
.get_table_by_uuid_name('nfvo_tenants', nfvo_tenant
)
5237 if vim_tenant_name
==None:
5238 vim_tenant_name
=tenant_dict
['name']
5240 tenants_datacenter_dict
={"nfvo_tenant_id":tenant_dict
['uuid'], "datacenter_id":datacenter_id
}
5241 # #check that this association does not exist before
5242 # tenants_datacenters = mydb.get_rows(FROM='tenants_datacenters', WHERE=tenants_datacenter_dict)
5243 # if len(tenants_datacenters)>0:
5244 # raise NfvoException("datacenter '{}' and tenant'{}' are already attached".format(datacenter_id, tenant_dict['uuid']), httperrors.Conflict)
5246 vim_tenant_id_exist_atdb
=False
5247 if not create_vim_tenant
:
5248 where_
={"datacenter_id": datacenter_id
}
5249 if vim_tenant
!=None:
5250 where_
["vim_tenant_id"] = vim_tenant
5251 if vim_tenant_name
!=None:
5252 where_
["vim_tenant_name"] = vim_tenant_name
5253 #check if vim_tenant_id is already at database
5254 datacenter_tenants_dict
= mydb
.get_rows(FROM
='datacenter_tenants', WHERE
=where_
)
5255 if len(datacenter_tenants_dict
)>=1:
5256 datacenter_tenants_dict
= datacenter_tenants_dict
[0]
5257 vim_tenant_id_exist_atdb
=True
5258 #TODO check if a field has changed and edit entry at datacenter_tenants at DB
5260 datacenter_tenants_dict
= {}
5261 #insert at table datacenter_tenants
5262 else: #if vim_tenant==None:
5263 #create tenant at VIM if not provided
5265 _
, myvim
= get_datacenter_by_name_uuid(mydb
, None, datacenter
, vim_user
=vim_username
,
5266 vim_passwd
=vim_password
)
5267 datacenter_name
= myvim
["name"]
5268 vim_tenant
= myvim
.new_tenant(vim_tenant_name
, "created by openmano for datacenter "+datacenter_name
)
5269 except vimconn
.vimconnException
as e
:
5270 raise NfvoException("Not possible to create vim_tenant {} at VIM: {}".format(vim_tenant_id
, str(e
)), httperrors
.Internal_Server_Error
)
5271 datacenter_tenants_dict
= {}
5272 datacenter_tenants_dict
["created"]="true"
5274 #fill datacenter_tenants table
5275 if not vim_tenant_id_exist_atdb
:
5276 datacenter_tenants_dict
["vim_tenant_id"] = vim_tenant
5277 datacenter_tenants_dict
["vim_tenant_name"] = vim_tenant_name
5278 datacenter_tenants_dict
["user"] = vim_username
5279 datacenter_tenants_dict
["passwd"] = vim_password
5280 datacenter_tenants_dict
["datacenter_id"] = datacenter_id
5282 datacenter_tenants_dict
["name"] = name
5284 datacenter_tenants_dict
["name"] = datacenter_name
5286 datacenter_tenants_dict
["config"] = yaml
.safe_dump(config
, default_flow_style
=True, width
=256)
5287 id_
= mydb
.new_row('datacenter_tenants', datacenter_tenants_dict
, add_uuid
=True, confidential_data
=True)
5288 datacenter_tenants_dict
["uuid"] = id_
5290 #fill tenants_datacenters table
5291 datacenter_tenant_id
= datacenter_tenants_dict
["uuid"]
5292 tenants_datacenter_dict
["datacenter_tenant_id"] = datacenter_tenant_id
5293 mydb
.new_row('tenants_datacenters', tenants_datacenter_dict
)
5296 thread_name
= get_non_used_vim_name(datacenter_name
, datacenter_id
)
5297 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, None, datacenter_tenant_id
, db
=db
)
5299 thread_id
= datacenter_tenants_dict
["uuid"]
5300 vim_threads
["running"][thread_id
] = new_thread
5302 except vimconn
.vimconnException
as e
:
5303 raise NfvoException(str(e
), httperrors
.Bad_Request
)
5306 def edit_vim_account(mydb
, nfvo_tenant
, datacenter_tenant_id
, datacenter_id
=None, name
=None, vim_tenant
=None,
5307 vim_tenant_name
=None, vim_username
=None, vim_password
=None, config
=None):
5309 # get vim_account; check is valid for this tenant
5310 from_
= "datacenter_tenants as dt JOIN tenants_datacenters as td ON dt.uuid=td.datacenter_tenant_id"
5311 where_
= {"td.nfvo_tenant_id": nfvo_tenant
}
5312 if datacenter_tenant_id
:
5313 where_
["dt.uuid"] = datacenter_tenant_id
5315 where_
["dt.datacenter_id"] = datacenter_id
5316 vim_accounts
= mydb
.get_rows(SELECT
="dt.uuid as uuid, config", FROM
=from_
, WHERE
=where_
)
5317 if not vim_accounts
:
5318 raise NfvoException("vim_account not found for this tenant", http_code
=httperrors
.Not_Found
)
5319 elif len(vim_accounts
) > 1:
5320 raise NfvoException("found more than one vim_account for this tenant", http_code
=httperrors
.Conflict
)
5321 datacenter_tenant_id
= vim_accounts
[0]["uuid"]
5322 original_config
= vim_accounts
[0]["config"]
5326 original_config_dict
= yaml
.load(original_config
, Loader
=yaml
.Loader
)
5327 original_config_dict
.update(config
)
5328 update
["config"] = yaml
.safe_dump(original_config_dict
, default_flow_style
=True, width
=256)
5330 update_
['name'] = name
5332 update_
['vim_tenant_id'] = vim_tenant
5334 update_
['vim_tenant_name'] = vim_tenant_name
5336 update_
['user'] = vim_username
5338 update_
['passwd'] = vim_password
5340 mydb
.update_rows("datacenter_tenants", UPDATE
=update_
, WHERE
={"uuid": datacenter_tenant_id
})
5342 vim_threads
["running"][datacenter_tenant_id
].insert_task("reload")
5343 return datacenter_tenant_id
5345 def delete_vim_account(mydb
, tenant_id
, vim_account_id
, datacenter
=None):
5346 #get nfvo_tenant info
5347 if not tenant_id
or tenant_id
=="any":
5350 tenant_dict
= mydb
.get_table_by_uuid_name('nfvo_tenants', tenant_id
)
5351 tenant_uuid
= tenant_dict
['uuid']
5353 #check that this association exist before
5354 tenants_datacenter_dict
= {}
5356 datacenter_id
, _
= get_datacenter_uuid(mydb
, tenant_uuid
, datacenter
)
5357 tenants_datacenter_dict
["datacenter_id"] = datacenter_id
5358 elif vim_account_id
:
5359 tenants_datacenter_dict
["datacenter_tenant_id"] = vim_account_id
5361 tenants_datacenter_dict
["nfvo_tenant_id"] = tenant_uuid
5362 tenant_datacenter_list
= mydb
.get_rows(FROM
='tenants_datacenters', WHERE
=tenants_datacenter_dict
)
5363 if len(tenant_datacenter_list
)==0 and tenant_uuid
:
5364 raise NfvoException("datacenter '{}' and tenant '{}' are not attached".format(datacenter_id
, tenant_dict
['uuid']), httperrors
.Not_Found
)
5366 #delete this association
5367 mydb
.delete_row(FROM
='tenants_datacenters', WHERE
=tenants_datacenter_dict
)
5369 #get vim_tenant info and deletes
5371 for tenant_datacenter_item
in tenant_datacenter_list
:
5372 vim_tenant_dict
= mydb
.get_table_by_uuid_name('datacenter_tenants', tenant_datacenter_item
['datacenter_tenant_id'])
5373 #try to delete vim:tenant
5375 mydb
.delete_row_by_id('datacenter_tenants', tenant_datacenter_item
['datacenter_tenant_id'])
5376 if vim_tenant_dict
['created']=='true':
5377 #delete tenant at VIM if created by NFVO
5379 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5380 myvim
.delete_tenant(vim_tenant_dict
['vim_tenant_id'])
5381 except vimconn
.vimconnException
as e
:
5382 warning
= "Not possible to delete vim_tenant_id {} from VIM: {} ".format(vim_tenant_dict
['vim_tenant_id'], str(e
))
5383 logger
.warn(warning
)
5384 except db_base_Exception
as e
:
5385 logger
.error("Cannot delete datacenter_tenants " + str(e
))
5386 pass # the error will be caused because dependencies, vim_tenant can not be deleted
5387 thread_id
= tenant_datacenter_item
["datacenter_tenant_id"]
5388 thread
= vim_threads
["running"].get(thread_id
)
5390 thread
.insert_task("exit")
5391 vim_threads
["deleting"][thread_id
] = thread
5392 return "datacenter {} detached. {}".format(datacenter_id
, warning
)
5395 def datacenter_action(mydb
, tenant_id
, datacenter
, action_dict
):
5397 #get datacenter info
5398 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5400 if 'check-connectivity' in action_dict
:
5402 myvim
.check_vim_connectivity()
5403 except vimconn
.vimconnException
as e
:
5404 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
5405 raise NfvoException(str(e
), e
.http_code
)
5406 elif 'net-update' in action_dict
:
5408 nets
= myvim
.get_network_list(filter_dict
={'shared': True, 'admin_state_up': True, 'status': 'ACTIVE'})
5410 except vimconn
.vimconnException
as e
:
5411 #logger.error("nfvo.datacenter_action() Not possible to get_network_list from VIM: %s ", str(e))
5412 raise NfvoException(str(e
), httperrors
.Internal_Server_Error
)
5413 #update nets Change from VIM format to NFVO format
5416 net_nfvo
={'datacenter_id': datacenter_id
}
5417 net_nfvo
['name'] = net
['name']
5418 #net_nfvo['description']= net['name']
5419 net_nfvo
['vim_net_id'] = net
['id']
5420 net_nfvo
['type'] = net
['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5421 net_nfvo
['shared'] = net
['shared']
5422 net_nfvo
['multipoint'] = False if net
['type']=='ptp' else True
5423 net_list
.append(net_nfvo
)
5424 inserted
, deleted
= mydb
.update_datacenter_nets(datacenter_id
, net_list
)
5425 logger
.info("Inserted %d nets, deleted %d old nets", inserted
, deleted
)
5427 elif 'net-edit' in action_dict
:
5428 net
= action_dict
['net-edit'].pop('net')
5429 what
= 'vim_net_id' if utils
.check_valid_uuid(net
) else 'name'
5430 result
= mydb
.update_rows('datacenter_nets', action_dict
['net-edit'],
5431 WHERE
={'datacenter_id':datacenter_id
, what
: net
})
5433 elif 'net-delete' in action_dict
:
5434 net
= action_dict
['net-deelte'].get('net')
5435 what
= 'vim_net_id' if utils
.check_valid_uuid(net
) else 'name'
5436 result
= mydb
.delete_row(FROM
='datacenter_nets',
5437 WHERE
={'datacenter_id':datacenter_id
, what
: net
})
5441 raise NfvoException("Unknown action " + str(action_dict
), httperrors
.Bad_Request
)
5444 def datacenter_edit_netmap(mydb
, tenant_id
, datacenter
, netmap
, action_dict
):
5445 #get datacenter info
5446 datacenter_id
, _
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5448 what
= 'uuid' if utils
.check_valid_uuid(netmap
) else 'name'
5449 result
= mydb
.update_rows('datacenter_nets', action_dict
['netmap'],
5450 WHERE
={'datacenter_id':datacenter_id
, what
: netmap
})
5454 def datacenter_new_netmap(mydb
, tenant_id
, datacenter
, action_dict
=None):
5455 #get datacenter info
5456 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5459 action_dict
= action_dict
["netmap"]
5460 if 'vim_id' in action_dict
:
5461 filter_dict
["id"] = action_dict
['vim_id']
5462 if 'vim_name' in action_dict
:
5463 filter_dict
["name"] = action_dict
['vim_name']
5465 filter_dict
["shared"] = True
5468 vim_nets
= myvim
.get_network_list(filter_dict
=filter_dict
)
5469 except vimconn
.vimconnException
as e
:
5470 #logger.error("nfvo.datacenter_new_netmap() Not possible to get_network_list from VIM: %s ", str(e))
5471 raise NfvoException(str(e
), httperrors
.Internal_Server_Error
)
5472 if len(vim_nets
)>1 and action_dict
:
5473 raise NfvoException("more than two networks found, specify with vim_id", httperrors
.Conflict
)
5474 elif len(vim_nets
)==0: # and action_dict:
5475 raise NfvoException("Not found a network at VIM with " + str(filter_dict
), httperrors
.Not_Found
)
5477 for net
in vim_nets
:
5478 net_nfvo
={'datacenter_id': datacenter_id
}
5479 if action_dict
and "name" in action_dict
:
5480 net_nfvo
['name'] = action_dict
['name']
5482 net_nfvo
['name'] = net
['name']
5483 #net_nfvo['description']= net['name']
5484 net_nfvo
['vim_net_id'] = net
['id']
5485 net_nfvo
['type'] = net
['type'][0:6] #change from ('ptp','data','bridge_data','bridge_man') to ('bridge','data','ptp')
5486 net_nfvo
['shared'] = net
['shared']
5487 net_nfvo
['multipoint'] = False if net
['type']=='ptp' else True
5489 net_id
= mydb
.new_row("datacenter_nets", net_nfvo
, add_uuid
=True)
5490 net_nfvo
["status"] = "OK"
5491 net_nfvo
["uuid"] = net_id
5492 except db_base_Exception
as e
:
5496 net_nfvo
["status"] = "FAIL: " + str(e
)
5497 net_list
.append(net_nfvo
)
5500 def get_sdn_net_id(mydb
, tenant_id
, datacenter
, network_id
):
5501 # obtain all network data
5503 if utils
.check_valid_uuid(network_id
):
5504 filter_dict
= {"id": network_id
}
5506 filter_dict
= {"name": network_id
}
5508 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5509 network
= myvim
.get_network_list(filter_dict
=filter_dict
)
5510 except vimconn
.vimconnException
as e
:
5511 raise NfvoException("Not possible to get_sdn_net_id from VIM: {}".format(str(e
)), e
.http_code
)
5513 # ensure the network is defined
5514 if len(network
) == 0:
5515 raise NfvoException("Network {} is not present in the system".format(network_id
),
5516 httperrors
.Bad_Request
)
5518 # ensure there is only one network with the provided name
5519 if len(network
) > 1:
5520 raise NfvoException("Multiple networks present in vim identified by {}".format(network_id
), httperrors
.Bad_Request
)
5522 # ensure it is a dataplane network
5523 if network
[0]['type'] != 'data':
5526 # ensure we use the id
5527 network_id
= network
[0]['id']
5529 # search in dabase mano_db in table instance nets for the sdn_net_id that corresponds to the vim_net_id==network_id
5530 # and with instance_scenario_id==NULL
5531 #search_dict = {'vim_net_id': network_id, 'instance_scenario_id': None}
5532 search_dict
= {'vim_net_id': network_id
}
5535 #sdn_network_id = mydb.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', WHERE=search_dict)[0]['sdn_net_id']
5536 result
= mydb
.get_rows(SELECT
=('sdn_net_id',), FROM
='instance_nets', WHERE
=search_dict
)
5537 except db_base_Exception
as e
:
5538 raise NfvoException("db_base_Exception obtaining SDN network to associated to vim network {}".format(
5539 network_id
) + str(e
), e
.http_code
)
5543 if net
['sdn_net_id'] != None:
5545 sdn_net_id
= net
['sdn_net_id']
5547 if sdn_net_counter
== 0:
5549 elif sdn_net_counter
== 1:
5552 raise NfvoException("More than one SDN network is associated to vim network {}".format(
5553 network_id
), httperrors
.Internal_Server_Error
)
5555 def get_sdn_controller_id(mydb
, datacenter
):
5556 # Obtain sdn controller id
5557 config
= mydb
.get_rows(SELECT
=('config',), FROM
='datacenters', WHERE
={'uuid': datacenter
})[0].get('config', '{}')
5561 return yaml
.load(config
, Loader
=yaml
.Loader
).get('sdn-controller')
5563 def vim_net_sdn_attach(mydb
, tenant_id
, datacenter
, network_id
, descriptor
):
5565 sdn_network_id
= get_sdn_net_id(mydb
, tenant_id
, datacenter
, network_id
)
5566 if not sdn_network_id
:
5567 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id
), httperrors
.Internal_Server_Error
)
5569 #Obtain sdn controller id
5570 controller_id
= get_sdn_controller_id(mydb
, datacenter
)
5571 if not controller_id
:
5572 raise NfvoException("No SDN controller is set for datacenter {}".format(datacenter
), httperrors
.Internal_Server_Error
)
5574 #Obtain sdn controller info
5575 sdn_controller
= ovim
.show_of_controller(controller_id
)
5578 'name': 'external_port',
5579 'net_id': sdn_network_id
,
5580 'ofc_id': controller_id
,
5581 'switch_dpid': sdn_controller
['dpid'],
5582 'switch_port': descriptor
['port']
5585 if 'vlan' in descriptor
:
5586 port_data
['vlan'] = descriptor
['vlan']
5587 if 'mac' in descriptor
:
5588 port_data
['mac'] = descriptor
['mac']
5590 result
= ovim
.new_port(port_data
)
5591 except ovimException
as e
:
5592 raise NfvoException("ovimException attaching SDN network {} to vim network {}".format(
5593 sdn_network_id
, network_id
) + str(e
), httperrors
.Internal_Server_Error
)
5594 except db_base_Exception
as e
:
5595 raise NfvoException("db_base_Exception attaching SDN network to vim network {}".format(
5596 network_id
) + str(e
), e
.http_code
)
5598 return 'Port uuid: '+ result
5600 def vim_net_sdn_detach(mydb
, tenant_id
, datacenter
, network_id
, port_id
=None):
5602 filter = {'uuid': port_id
}
5604 sdn_network_id
= get_sdn_net_id(mydb
, tenant_id
, datacenter
, network_id
)
5605 if not sdn_network_id
:
5606 raise NfvoException("No SDN network is associated to vim-network {}".format(network_id
),
5607 httperrors
.Internal_Server_Error
)
5608 #in case no port_id is specified only ports marked as 'external_port' will be detached
5609 filter = {'name': 'external_port', 'net_id': sdn_network_id
}
5612 port_list
= ovim
.get_ports(columns
={'uuid'}, filter=filter)
5613 except ovimException
as e
:
5614 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id
) + str(e
),
5615 httperrors
.Internal_Server_Error
)
5617 if len(port_list
) == 0:
5618 raise NfvoException("No ports attached to the network {} were found with the requested criteria".format(network_id
),
5619 httperrors
.Bad_Request
)
5622 for port
in port_list
:
5624 port_uuid_list
.append(port
['uuid'])
5625 ovim
.delete_port(port
['uuid'])
5626 except ovimException
as e
:
5627 raise NfvoException("ovimException deleting port {} for net {}. ".format(port
['uuid'], network_id
) + str(e
), httperrors
.Internal_Server_Error
)
5629 return 'Detached ports uuid: {}'.format(','.join(port_uuid_list
))
5631 def vim_action_get(mydb
, tenant_id
, datacenter
, item
, name
):
5632 #get datacenter info
5633 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5636 if utils
.check_valid_uuid(name
):
5637 filter_dict
["id"] = name
5639 filter_dict
["name"] = name
5641 if item
=="networks":
5642 #filter_dict['tenant_id'] = myvim['tenant_id']
5643 content
= myvim
.get_network_list(filter_dict
=filter_dict
)
5645 if len(content
) == 0:
5646 raise NfvoException("Network {} is not present in the system. ".format(name
),
5647 httperrors
.Bad_Request
)
5649 #Update the networks with the attached ports
5651 sdn_network_id
= get_sdn_net_id(mydb
, tenant_id
, datacenter
, net
['id'])
5652 if sdn_network_id
!= None:
5654 #port_list = ovim.get_ports(columns={'uuid', 'switch_port', 'vlan'}, filter={'name': 'external_port', 'net_id': sdn_network_id})
5655 port_list
= ovim
.get_ports(columns
={'uuid', 'switch_port', 'vlan','name'}, filter={'net_id': sdn_network_id
})
5656 except ovimException
as e
:
5657 raise NfvoException("ovimException obtaining external ports for net {}. ".format(network_id
) + str(e
), httperrors
.Internal_Server_Error
)
5658 #Remove field name and if port name is external_port save it as 'type'
5659 for port
in port_list
:
5660 if port
['name'] == 'external_port':
5661 port
['type'] = "External"
5663 net
['sdn_network_id'] = sdn_network_id
5664 net
['sdn_attached_ports'] = port_list
5666 elif item
=="tenants":
5667 content
= myvim
.get_tenant_list(filter_dict
=filter_dict
)
5668 elif item
== "images":
5670 content
= myvim
.get_image_list(filter_dict
=filter_dict
)
5672 raise NfvoException(item
+ "?", httperrors
.Method_Not_Allowed
)
5673 logger
.debug("vim_action response %s", content
) #update nets Change from VIM format to NFVO format
5674 if name
and len(content
)==1:
5675 return {item
[:-1]: content
[0]}
5676 elif name
and len(content
)==0:
5677 raise NfvoException("No {} found with ".format(item
[:-1]) + " and ".join(map(lambda x
: str(x
[0])+": "+str(x
[1]), filter_dict
.items())),
5680 return {item
: content
}
5681 except vimconn
.vimconnException
as e
:
5682 print("vim_action Not possible to get_{}_list from VIM: {} ".format(item
, str(e
)))
5683 raise NfvoException("Not possible to get_{}_list from VIM: {}".format(item
, str(e
)), e
.http_code
)
5686 def vim_action_delete(mydb
, tenant_id
, datacenter
, item
, name
):
5687 #get datacenter info
5688 if tenant_id
== "any":
5691 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5693 content
= vim_action_get(mydb
, tenant_id
, datacenter
, item
, name
)
5694 logger
.debug("vim_action_delete vim response: " + str(content
))
5695 items
= next(iter(content
.values()))
5696 if type(items
)==list and len(items
)==0:
5697 raise NfvoException("Not found " + item
, httperrors
.Not_Found
)
5698 elif type(items
)==list and len(items
)>1:
5699 raise NfvoException("Found more than one {} with this name. Use uuid.".format(item
), httperrors
.Not_Found
)
5700 else: # it is a dict
5701 item_id
= items
["id"]
5702 item_name
= str(items
.get("name"))
5705 if item
=="networks":
5706 # If there is a SDN network associated to the vim-network, proceed to clear the relationship and delete it
5707 sdn_network_id
= get_sdn_net_id(mydb
, tenant_id
, datacenter
, item_id
)
5708 if sdn_network_id
!= None:
5709 #Delete any port attachment to this network
5711 port_list
= ovim
.get_ports(columns
={'uuid'}, filter={'net_id': sdn_network_id
})
5712 except ovimException
as e
:
5713 raise NfvoException(
5714 "ovimException obtaining external ports for net {}. ".format(sdn_network_id
) + str(e
),
5715 httperrors
.Internal_Server_Error
)
5717 # By calling one by one all ports to be detached we ensure that not only the external_ports get detached
5718 for port
in port_list
:
5719 vim_net_sdn_detach(mydb
, tenant_id
, datacenter
, item_id
, port
['uuid'])
5721 #Delete from 'instance_nets' the correspondence between the vim-net-id and the sdn-net-id
5723 mydb
.delete_row(FROM
='instance_nets', WHERE
={'instance_scenario_id': None,
5724 'sdn_net_id': sdn_network_id
,
5725 'vim_net_id': item_id
})
5726 except db_base_Exception
as e
:
5727 raise NfvoException("Error deleting correspondence for VIM/SDN dataplane networks{}: {}".format(
5728 item_id
, e
), e
.http_code
)
5730 #Delete the SDN network
5732 ovim
.delete_network(sdn_network_id
)
5733 except ovimException
as e
:
5734 logger
.error("ovimException deleting SDN network={} ".format(sdn_network_id
) + str(e
), exc_info
=True)
5735 raise NfvoException("ovimException deleting SDN network={} ".format(sdn_network_id
) + str(e
),
5736 httperrors
.Internal_Server_Error
)
5738 content
= myvim
.delete_network(item_id
)
5739 elif item
=="tenants":
5740 content
= myvim
.delete_tenant(item_id
)
5741 elif item
== "images":
5742 content
= myvim
.delete_image(item_id
)
5744 raise NfvoException(item
+ "?", httperrors
.Method_Not_Allowed
)
5745 except vimconn
.vimconnException
as e
:
5746 #logger.error( "vim_action Not possible to delete_{} {}from VIM: {} ".format(item, name, str(e)))
5747 raise NfvoException("Not possible to delete_{} {} from VIM: {}".format(item
, name
, str(e
)), e
.http_code
)
5749 return "{} {} {} deleted".format(item
[:-1], item_id
,item_name
)
5752 def vim_action_create(mydb
, tenant_id
, datacenter
, item
, descriptor
):
5753 #get datacenter info
5754 logger
.debug("vim_action_create descriptor %s", str(descriptor
))
5755 if tenant_id
== "any":
5757 datacenter_id
, myvim
= get_datacenter_by_name_uuid(mydb
, tenant_id
, datacenter
)
5759 if item
=="networks":
5760 net
= descriptor
["network"]
5761 net_name
= net
.pop("name")
5762 net_type
= net
.pop("type", "bridge")
5763 net_public
= net
.pop("shared", False)
5764 net_ipprofile
= net
.pop("ip_profile", None)
5765 net_vlan
= net
.pop("vlan", None)
5766 net_provider_network_profile
= None
5768 net_provider_network_profile
= {"segmentation-id": net_vlan
}
5769 content
, _
= myvim
.new_network(net_name
, net_type
, net_ipprofile
, shared
=net_public
, provider_network_profile
=net_provider_network_profile
) #, **net)
5771 #If the datacenter has a SDN controller defined and the network is of dataplane type, then create the sdn network
5772 if get_sdn_controller_id(mydb
, datacenter
) != None and (net_type
== 'data' or net_type
== 'ptp'):
5773 #obtain datacenter_tenant_id
5774 datacenter_tenant_id
= mydb
.get_rows(SELECT
=('uuid',),
5775 FROM
='datacenter_tenants',
5776 WHERE
={'datacenter_id': datacenter
})[0]['uuid']
5779 sdn_network
['vlan'] = net_vlan
5780 sdn_network
['type'] = net_type
5781 sdn_network
['name'] = net_name
5782 sdn_network
['region'] = datacenter_tenant_id
5783 ovim_content
= ovim
.new_network(sdn_network
)
5784 except ovimException
as e
:
5785 logger
.error("ovimException creating SDN network={} ".format(
5786 sdn_network
) + str(e
), exc_info
=True)
5787 raise NfvoException("ovimException creating SDN network={} ".format(sdn_network
) + str(e
),
5788 httperrors
.Internal_Server_Error
)
5790 # Save entry in in dabase mano_db in table instance_nets to stablish a dictionary vim_net_id <->sdn_net_id
5791 # use instance_scenario_id=None to distinguish from real instaces of nets
5792 correspondence
= {'instance_scenario_id': None,
5793 'sdn_net_id': ovim_content
,
5794 'vim_net_id': content
,
5795 'datacenter_tenant_id': datacenter_tenant_id
5798 mydb
.new_row('instance_nets', correspondence
, add_uuid
=True)
5799 except db_base_Exception
as e
:
5800 raise NfvoException("Error saving correspondence for VIM/SDN dataplane networks{}: {}".format(
5801 correspondence
, e
), e
.http_code
)
5802 elif item
=="tenants":
5803 tenant
= descriptor
["tenant"]
5804 content
= myvim
.new_tenant(tenant
["name"], tenant
.get("description"))
5806 raise NfvoException(item
+ "?", httperrors
.Method_Not_Allowed
)
5807 except vimconn
.vimconnException
as e
:
5808 raise NfvoException("Not possible to create {} at VIM: {}".format(item
, str(e
)), e
.http_code
)
5810 return vim_action_get(mydb
, tenant_id
, datacenter
, item
, content
)
5812 def sdn_controller_create(mydb
, tenant_id
, sdn_controller
):
5814 wim_id
= ovim
.new_of_controller(sdn_controller
)
5816 # Load plugin if not previously loaded
5817 controller_type
= sdn_controller
.get("type")
5818 plugin_name
= "rosdn_" + controller_type
5819 if plugin_name
not in plugins
:
5820 _load_plugin(plugin_name
, type="sdn")
5822 thread_name
= get_non_used_vim_name(sdn_controller
['name'], wim_id
)
5823 new_thread
= vim_thread(task_lock
, plugins
, thread_name
, wim_id
, None, db
=db
)
5826 vim_threads
["running"][thread_id
] = new_thread
5827 logger
.debug('New SDN controller created with uuid {}'.format(wim_id
))
5829 except ovimException
as e
:
5830 raise NfvoException(e
) from e
5832 def sdn_controller_update(mydb
, tenant_id
, controller_id
, sdn_controller
):
5833 data
= ovim
.edit_of_controller(controller_id
, sdn_controller
)
5834 msg
= 'SDN controller {} updated'.format(data
)
5835 vim_threads
["running"][controller_id
].insert_task("reload")
5839 def sdn_controller_list(mydb
, tenant_id
, controller_id
=None):
5840 if controller_id
== None:
5841 data
= ovim
.get_of_controllers()
5843 data
= ovim
.show_of_controller(controller_id
)
5845 msg
= 'SDN controller list:\n {}'.format(data
)
5849 def sdn_controller_delete(mydb
, tenant_id
, controller_id
):
5850 select_
= ('uuid', 'config')
5851 datacenters
= mydb
.get_rows(FROM
='datacenters', SELECT
=select_
)
5852 for datacenter
in datacenters
:
5853 if datacenter
['config']:
5854 config
= yaml
.load(datacenter
['config'], Loader
=yaml
.Loader
)
5855 if 'sdn-controller' in config
and config
['sdn-controller'] == controller_id
:
5856 raise NfvoException("SDN controller {} is in use by datacenter {}".format(controller_id
, datacenter
['uuid']), httperrors
.Conflict
)
5858 data
= ovim
.delete_of_controller(controller_id
)
5859 msg
= 'SDN controller {} deleted'.format(data
)
5863 def datacenter_sdn_port_mapping_set(mydb
, tenant_id
, datacenter_id
, sdn_port_mapping
):
5864 controller
= mydb
.get_rows(FROM
="datacenters", SELECT
=("config",), WHERE
={"uuid":datacenter_id
})
5865 if len(controller
) < 1:
5866 raise NfvoException("Datacenter {} not present in the database".format(datacenter_id
), httperrors
.Not_Found
)
5869 sdn_controller_id
= yaml
.load(controller
[0]["config"], Loader
=yaml
.Loader
)["sdn-controller"]
5871 raise NfvoException("The datacenter {} has not an SDN controller associated".format(datacenter_id
), httperrors
.Bad_Request
)
5873 sdn_controller
= ovim
.show_of_controller(sdn_controller_id
)
5874 switch_dpid
= sdn_controller
["dpid"]
5877 for compute_node
in sdn_port_mapping
:
5878 #element = {"ofc_id": sdn_controller_id, "region": datacenter_id, "switch_dpid": switch_dpid}
5880 element
["compute_node"] = compute_node
["compute_node"]
5881 if compute_node
["ports"]:
5882 for port
in compute_node
["ports"]:
5883 pci
= port
.get("pci")
5884 element
["switch_port"] = port
.get("switch_port")
5885 element
["switch_mac"] = port
.get("switch_mac")
5886 element
["switch_dpid"] = port
.get("switch_dpid")
5887 element
["switch_id"] = port
.get("switch_id")
5888 if not element
["switch_port"] and not element
["switch_mac"]:
5889 raise NfvoException ("The mapping must contain 'switch_port' or 'switch_mac'", httperrors
.Bad_Request
)
5890 for pci_expanded
in utils
.expand_brackets(pci
):
5891 element
["pci"] = pci_expanded
5892 maps
.append(dict(element
))
5894 out
= ovim
.set_of_port_mapping(maps
, sdn_id
=sdn_controller_id
, switch_dpid
=switch_dpid
, vim_id
=datacenter_id
)
5895 vim_threads
["running"][sdn_controller_id
].insert_task("reload")
5898 def datacenter_sdn_port_mapping_list(mydb
, tenant_id
, datacenter_id
):
5899 maps
= ovim
.get_of_port_mappings(db_filter
={"datacenter_id": datacenter_id
})
5902 "sdn-controller": None,
5903 "datacenter-id": datacenter_id
,
5905 "ports_mapping": list()
5908 datacenter
= mydb
.get_table_by_uuid_name('datacenters', datacenter_id
)
5909 if datacenter
['config']:
5910 config
= yaml
.load(datacenter
['config'], Loader
=yaml
.Loader
)
5911 if 'sdn-controller' in config
:
5912 controller_id
= config
['sdn-controller']
5913 sdn_controller
= sdn_controller_list(mydb
, tenant_id
, controller_id
)
5914 result
["sdn-controller"] = controller_id
5915 result
["dpid"] = sdn_controller
["dpid"]
5917 if result
["sdn-controller"] == None:
5918 raise NfvoException("SDN controller is not defined for datacenter {}".format(datacenter_id
), httperrors
.Bad_Request
)
5919 if result
["dpid"] == None:
5920 raise NfvoException("It was not possible to determine DPID for SDN controller {}".format(result
["sdn-controller"]),
5921 httperrors
.Internal_Server_Error
)
5926 ports_correspondence_dict
= dict()
5928 if result
["sdn-controller"] != link
["wim_id"]:
5929 raise NfvoException("The sdn-controller specified for different port mappings differ", httperrors
.Internal_Server_Error
)
5930 if result
["dpid"] != link
["switch_dpid"]:
5931 raise NfvoException("The dpid specified for different port mappings differ", httperrors
.Internal_Server_Error
)
5932 link_config
= link
["service_mapping_info"]
5934 element
["pci"] = link
.get("device_interface_id")
5935 if link
["switch_port"]:
5936 element
["switch_port"] = link
["switch_port"]
5937 if link_config
["switch_mac"]:
5938 element
["switch_mac"] = link_config
.get("switch_mac")
5940 if not link
.get("interface_id") in ports_correspondence_dict
:
5942 content
["compute_node"] = link
.get("interface_id")
5943 content
["ports"] = list()
5944 ports_correspondence_dict
[link
.get("interface_id")] = content
5946 ports_correspondence_dict
[link
["interface_id"]]["ports"].append(element
)
5948 for key
in sorted(ports_correspondence_dict
):
5949 result
["ports_mapping"].append(ports_correspondence_dict
[key
])
5953 def datacenter_sdn_port_mapping_delete(mydb
, tenant_id
, datacenter_id
):
5954 return ovim
.clear_of_port_mapping(db_filter
={"datacenter_id":datacenter_id
})
5956 def create_RO_keypair(tenant_id
):
5958 Creates a public / private keys for a RO tenant and returns their values
5960 tenant_id: ID of the tenant
5962 public_key: Public key for the RO tenant
5963 private_key: Encrypted private key for RO tenant
5967 key
= RSA
.generate(bits
)
5969 public_key
= key
.publickey().exportKey('OpenSSH')
5970 if isinstance(public_key
, ValueError):
5971 raise NfvoException("Unable to create public key: {}".format(public_key
), httperrors
.Internal_Server_Error
)
5972 private_key
= key
.exportKey(passphrase
=tenant_id
, pkcs
=8)
5973 except (ValueError, NameError) as e
:
5974 raise NfvoException("Unable to create private key: {}".format(e
), httperrors
.Internal_Server_Error
)
5975 if isinstance(public_key
, bytes
):
5976 public_key
= public_key
.decode(encoding
='UTF-8')
5977 if isinstance(private_key
, bytes
):
5978 private_key
= private_key
.decode(encoding
='UTF-8')
5979 return public_key
, private_key
5981 def decrypt_key (key
, tenant_id
):
5983 Decrypts an encrypted RSA key
5985 key: Private key to be decrypted
5986 tenant_id: ID of the tenant
5988 unencrypted_key: Unencrypted private key for RO tenant
5991 key
= RSA
.importKey(key
,tenant_id
)
5992 unencrypted_key
= key
.exportKey('PEM')
5993 if isinstance(unencrypted_key
, ValueError):
5994 raise NfvoException("Unable to decrypt the private key: {}".format(unencrypted_key
), httperrors
.Internal_Server_Error
)
5995 if isinstance(unencrypted_key
, bytes
):
5996 unencrypted_key
= unencrypted_key
.decode(encoding
='UTF-8')
5997 except ValueError as e
:
5998 raise NfvoException("Unable to decrypt the private key: {}".format(e
), httperrors
.Internal_Server_Error
)
5999 return unencrypted_key