# For those usages not covered by the Apache License, Version 2.0 please
# contact with: nfvlabs@tid.es
##
-
+
'''
NFVO engine, implementing all the methods for the creation, deletion and management of vnfs, scenarios and instances
'''
if vnfd["mgmt-interface"].get("ip-address"):
mgmt_access["ip-address"] = str(vnfd["mgmt-interface"].get("ip-address"))
- if vnfd["mgmt-interface"].get("cp"):
+ if vnfd["mgmt-interface"].get("cp") and vnfd.get("vdu"):
if vnfd["mgmt-interface"]["cp"] not in cp_name2iface_uuid:
raise NfvoException("Error. Invalid VNF descriptor at 'vnfd[{vnf}]':'mgmt-interface':'cp'['{cp}']. "
"Reference to a non-existing connection-point".format(
elif vld.get("vim-network-name"):
db_sce_net["vim_network_name"] = get_str(vld, "vim-network-name", 255)
+
# table sce_interfaces (vld:vnfd-connection-point-ref)
for iface in vld.get("vnfd-connection-point-ref").itervalues():
+ # Check if there are VDUs in the descriptor
vnf_index = str(iface['member-vnf-index-ref'])
- # check correct parameters
- if vnf_index not in vnf_index2vnf_uuid:
- raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
- "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
- "'nsd':'constituent-vnfd'".format(
- str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
- httperrors.Bad_Request)
-
- existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
- FROM="interfaces as i join vms on i.vm_id=vms.uuid",
- WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
- 'external_name': get_str(iface, "vnfd-connection-point-ref",
- 255)})
- if not existing_ifaces:
- raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
- "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
- "connection-point name at VNFD '{}'".format(
- str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
- str(iface.get("vnfd-id-ref"))[:255]),
- httperrors.Bad_Request)
- interface_uuid = existing_ifaces[0]["uuid"]
- if existing_ifaces[0]["iface_type"] == "data":
- db_sce_net["type"] = "data"
- sce_interface_uuid = str(uuid4())
- uuid_list.append(sce_net_uuid)
- iface_ip_address = None
- if iface.get("ip-address"):
- iface_ip_address = str(iface.get("ip-address"))
- db_sce_interface = {
- "uuid": sce_interface_uuid,
- "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
- "sce_net_id": sce_net_uuid,
- "interface_id": interface_uuid,
- "ip_address": iface_ip_address,
- }
- db_sce_interfaces.append(db_sce_interface)
- if not db_sce_net["type"]:
- db_sce_net["type"] = "bridge"
+ existing_vdus = mydb.get_rows(SELECT=('vms.uuid'), FROM="vms", WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index]})
+ if existing_vdus:
+ # check correct parameters
+ if vnf_index not in vnf_index2vnf_uuid:
+ raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
+ "-ref':'member-vnf-index-ref':'{}'. Reference to a non-existing index at "
+ "'nsd':'constituent-vnfd'".format(
+ str(nsd["id"]), str(vld["id"]), str(iface["member-vnf-index-ref"])),
+ httperrors.Bad_Request)
+
+ existing_ifaces = mydb.get_rows(SELECT=('i.uuid as uuid', 'i.type as iface_type'),
+ FROM="interfaces as i join vms on i.vm_id=vms.uuid",
+ WHERE={'vnf_id': vnf_index2vnf_uuid[vnf_index],
+ 'external_name': get_str(iface, "vnfd-connection-point-ref",
+ 255)})
+ if not existing_ifaces:
+ raise NfvoException("Error. Invalid NS descriptor at 'nsd[{}]':'vld[{}]':'vnfd-connection-point"
+ "-ref':'vnfd-connection-point-ref':'{}'. Reference to a non-existing "
+ "connection-point name at VNFD '{}'".format(
+ str(nsd["id"]), str(vld["id"]), str(iface["vnfd-connection-point-ref"]),
+ str(iface.get("vnfd-id-ref"))[:255]),
+ httperrors.Bad_Request)
+ interface_uuid = existing_ifaces[0]["uuid"]
+ if existing_ifaces[0]["iface_type"] == "data":
+ db_sce_net["type"] = "data"
+ sce_interface_uuid = str(uuid4())
+ uuid_list.append(sce_net_uuid)
+ iface_ip_address = None
+ if iface.get("ip-address"):
+ iface_ip_address = str(iface.get("ip-address"))
+ db_sce_interface = {
+ "uuid": sce_interface_uuid,
+ "sce_vnf_id": vnf_index2scevnf_uuid[vnf_index],
+ "sce_net_id": sce_net_uuid,
+ "interface_id": interface_uuid,
+ "ip_address": iface_ip_address,
+ }
+ db_sce_interfaces.append(db_sce_interface)
+ if not db_sce_net["type"]:
+ db_sce_net["type"] = "bridge"
# table sce_vnffgs (vnffgd)
for vnffg in nsd.get("vnffgd").itervalues():
cloud_config_vm = unify_cloud_config({"key-pairs": vm["instance_parameters"]["mgmt_keys"]},
cloud_config_vm)
if RO_pub_key:
- cloud_config_vm = unify_cloud_config(cloud_config_vm, {"key-pairs": RO_pub_key})
+ cloud_config_vm = unify_cloud_config(cloud_config_vm, {"key-pairs": [RO_pub_key]})
if vm.get("boot_data"):
cloud_config_vm = unify_cloud_config(vm["boot_data"], cloud_config_vm)
if 'ip_address' in vm:
mgmt_ip = vm['ip_address'].split(';')
priv_RO_key = decrypt_key(tenant[0]['encrypted_RO_priv_key'], tenant[0]['uuid'])
- myvim.inject_user_key(mgmt_ip[0], action_dict.get('user', default_user),
+ data = myvim.inject_user_key(mgmt_ip[0], action_dict.get('user', default_user),
action_dict['add_public_key'],
password=password, ro_key=priv_RO_key)
+ vm_result[ vm['uuid'] ] = {"vim_result": 200,
+ "description": "Public key injected",
+ "name":vm['name']
+ }
+
except KeyError:
raise NfvoException("Unable to inject ssh key in vm: {} - Aborting".format(vm['uuid']),
httperrors.Internal_Server_Error)
# -*- coding: utf-8 -*-
-import base64
-
-
+##
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+##
+import base64
import vimconn
import logging
import netaddr
from msrest.exceptions import AuthenticationError
from requests.exceptions import ConnectionError
-__author__ = 'Sergio Gonzalez'
-__date__ = '$18-apr-2019 23:59:59$'
+__author__ = 'Isabel Lloret, Sergio Gonzalez, Alfonso Tierno'
+__date__ = '$18-apr-2019 23:59:59$'
if getenv('OSMRO_PDB_DEBUG'):
self.tenant = (tenant_id or tenant_name)
# Store config to create azure subscription later
- self._config = {}
- self._config["user"] = user
- self._config["passwd"] = passwd
- self._config["tenant"] = (tenant_id or tenant_name)
+ self._config = {
+ "user": user,
+ "passwd": passwd,
+ "tenant": tenant_id or tenant_name
+ }
# SUBSCRIPTION
if 'subscription_id' in config:
self._config["subscription_id"] = config.get('subscription_id')
- #self.logger.debug('Setting subscription to: %s', self.config["subscription_id"])
+ # self.logger.debug('Setting subscription to: %s', self.config["subscription_id"])
else:
raise vimconn.vimconnException('Subscription not specified')
resource = str(resource_id.split('/')[-1])
return resource
except Exception as e:
- raise vimconn.vimconnException("Unable to get resource name from invalid resource_id format: '{}'".format(resource_id))
+ raise vimconn.vimconnException("Unable to get resource name from resource_id '{}' Error: '{}'".
+ format(resource_id, e))
def _get_location_from_resource_group(self, resource_group_name):
try:
ip_profile = {"subnet_address": ip_profile['subnet_address']}
try:
- #subnet_name = "{}-{}".format(net_name[:24], uuid4())
+ # subnet_name = "{}-{}".format(net_name[:24], uuid4())
subnet_params = {
'address_prefix': ip_profile['subnet_address']
}
# get the name with the first not used suffix
name_suffix = 0
- #name = subnet_name + "-" + str(name_suffix)
- name = subnet_name # first subnet created will have no prefix
+ # name = subnet_name + "-" + str(name_suffix)
+ name = subnet_name # first subnet created will have no prefix
while name in net_names:
name_suffix += 1
name = subnet_name + "-" + str(name_suffix)
subnet_id = net['net_id']
location = self._get_location_from_resource_group(self.resource_group)
try:
- net_ifz = {'location':location}
+ net_ifz = {'location': location}
net_ip_config = {'name': nic_name + '-ipconfiguration', 'subnet': {'id': subnet_id}}
if static_ip:
net_ip_config['privateIPAddress'] = static_ip
if mac_address:
net_ifz['mac_address'] = mac_address
- async_nic_creation = self.conn_vnet.network_interfaces.create_or_update(
- self.resource_group,
- nic_name,
- net_ifz
- )
+ async_nic_creation = self.conn_vnet.network_interfaces.create_or_update(self.resource_group, nic_name,
+ net_ifz)
async_nic_creation.wait()
self.logger.debug('created nic name %s', nic_name)
)
self.logger.debug('created public IP: {}'.format(public_ip.result()))
- # Asociate NIC to Public IP
+ # Associate NIC to Public IP
nic_data = self.conn_vnet.network_interfaces.get(
self.resource_group,
nic_name)
return [offer.name for offer in result_offers]
except CloudError as e:
# azure raises CloudError when not found
- self.logger.info("error listing offers for publisher {}, message: {}".format(publisher, e.message))
+ self.logger.info("error listing offers for publisher {}, Error: {}".format(publisher, e))
return []
def _get_sku_list(self, params, publisher, offer):
return [sku.name for sku in result_skus]
except CloudError as e:
# azure raises CloudError when not found
- self.logger.info("error listing skus for publisher {}, offer {}, message: {}".format(publisher, offer, e.message))
+ self.logger.info("error listing skus for publisher {}, offer {}, Error: {}".format(publisher, offer, e))
return []
def _get_sku_image_list(self, publisher, offer, sku):
})
except CloudError as e:
self.logger.info(
- "error listing skus for publisher {}, offer {}, message: {}".format(publisher, offer, e.message))
+ "error listing skus for publisher {}, offer {}, Error: {}".format(publisher, offer, e))
image_list = []
return image_list
})
except CloudError as e:
# azure gives CloudError when not found
- self.logger.info(
- "error listing images for publisher {}, offer {}, sku {}, vesion {} message: {}".format(publisher,
- offer,
- sku,
- version,
- e.message))
+ self.logger.info("error listing images for publisher {}, offer {}, sku {}, version {} Error: {}".
+ format(publisher, offer, sku, version, e))
image_list = []
return image_list
status: 'ACTIVE', not implemented in Azure #
Returns the network list of dictionaries
"""
- #self.logger.debug('getting network list for vim, filter %s', filter_dict)
+ # self.logger.debug('getting network list for vim, filter %s', filter_dict)
try:
self._reload_connection()
subnet_list.append({
'id': str(subnet.id),
- 'name': self._get_resource_name_from_resource_id(subnet.id),
+ 'name': name,
'status': self.provision_state2osm[subnet.provisioning_state],
'cidr_block': str(subnet.address_prefix),
'type': 'bridge',
'shared': False
- }
- )
+ })
return subnet_list
except Exception as e:
self._format_vimconn_exception(e)
- def new_vminstance(self, vm_name, description, start, image_id, flavor_id, net_list, cloud_config=None,
- disk_list=None, availability_zone_index=None, availability_zone_list=None):
-
- return self._new_vminstance(vm_name, image_id, flavor_id, net_list)
-
def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None,
- disk_list=None, availability_zone_index=None, availability_zone_list=None):
+ disk_list=None, availability_zone_index=None, availability_zone_list=None):
- self.logger.debug("new vm instance name: %s, image_id: %s, flavor_id: %s, net_list: %s, cloud_config: %s"
- + "disk_list: %s, availability_zone_index: %s, availability_zone_list: %s",
+ self.logger.debug("new vm instance name: %s, image_id: %s, flavor_id: %s, net_list: %s, cloud_config: %s, "
+ "disk_list: %s, availability_zone_index: %s, availability_zone_list: %s",
name, image_id, flavor_id, net_list, cloud_config, disk_list,
availability_zone_index, availability_zone_list)
if cloud_config.get("users"):
user_name = cloud_config.get("users")[0].get("name", "osm")
else:
- user_name = "osm" # DEFAULT USER IS OSM
+ user_name = "osm" # DEFAULT USER IS OSM
os_profile = {
'computer_name': vm_name,
}
else:
os_profile = {
- 'computer_name': vm_name
- ,'admin_username': 'osm'
- ,'admin_password': 'Osm4u!',
+ 'computer_name': vm_name,
+ 'admin_username': 'osm',
+ 'admin_password': 'Osm4u!',
}
vm_parameters = {
'disk_size_gb': disk.get("size")
})
else:
- #self.logger.debug("currently not able to create data disks from image for azure, ignoring")
+ # self.logger.debug("currently not able to create data disks from image for azure, ignoring")
data_disks.append({
'lun': lun_name, # You choose the value, depending of what is available for you
'name': vm_name + "_data_disk-" + str(lun_name),
vm_name,
vm_parameters
)
- #creation_result.wait()
+ # creation_result.wait()
result = creation_result.result()
self.logger.debug("created vm name: %s", vm_name)
if start:
- start_result = self.conn_compute.virtual_machines.start(
+ self.conn_compute.virtual_machines.start(
self.resource_group,
vm_name)
- #start_result.wait()
+ # start_result.wait()
return result.id, None
- #run_command_parameters = {
- # 'command_id': 'RunShellScript', # For linux, don't change it
- # 'script': [
- # 'date > /tmp/test.txt'
- # ]
- #}
+ # run_command_parameters = {
+ # 'command_id': 'RunShellScript', # For linux, don't change it
+ # 'script': [
+ # 'date > /tmp/test.txt'
+ # ]
+ # }
except Exception as e:
self.logger.debug('Exception creating new vminstance: %s', e, exc_info=True)
self._format_vimconn_exception(e)
name = vm_name + "-" + str(name_suffix)
return name
-
# It is necesary extract from image_id data to create the VM with this format
# 'image_reference': {
# 'publisher': vm_reference['publisher'],
version = str(image_id.split('/')[16])
return {
- 'publisher': publisher,
- 'offer': offer,
- 'sku': sku,
- 'version': version
+ 'publisher': publisher,
+ 'offer': offer,
+ 'sku': sku,
+ 'version': version
}
except Exception as e:
raise vimconn.vimconnException(
Checks vm name, in case the vm has not allowed characters they are removed, not error raised
"""
- #chars_not_allowed_list = ['~','!','@','#','$','%','^','&','*','(',')','=','+','_','[',']','{','}','|',';',':','<','>','/','?','.']
chars_not_allowed_list = "~!@#$%^&*()=+_[]{}|;:<>/?."
# First: the VM name max length is 64 characters
for elem in chars_not_allowed_list:
# Check if string is in the main string
if elem in vm_name_aux:
- #self.logger.debug('Dentro del IF')
+ # self.logger.debug('Dentro del IF')
# Replace the string
vm_name_aux = vm_name_aux.replace(elem, '-')
filter_dict = flavor_dict or {}
try:
self._reload_connection()
- vm_sizes_list = [vm_size.serialize() for vm_size in self.conn_compute.virtual_machine_sizes.list(self.region)]
+ vm_sizes_list = [vm_size.serialize() for vm_size in
+ self.conn_compute.virtual_machine_sizes.list(self.region)]
cpus = filter_dict.get('vcpus') or 0
memMB = filter_dict.get('ram') or 0
# Filter
if self._config.get("flavors_pattern"):
- filtered_sizes = [size for size in vm_sizes_list if size['numberOfCores'] >= cpus
- and size['memoryInMB'] >= memMB
- and re.search(self._config.get("flavors_pattern"), size["name"])]
+ filtered_sizes = [size for size in vm_sizes_list if size['numberOfCores'] >= cpus and
+ size['memoryInMB'] >= memMB and
+ re.search(self._config.get("flavors_pattern"), size["name"])]
else:
- filtered_sizes = [size for size in vm_sizes_list if size['numberOfCores'] >= cpus
- and size['memoryInMB'] >= memMB]
-
-
+ filtered_sizes = [size for size in vm_sizes_list if size['numberOfCores'] >= cpus and
+ size['memoryInMB'] >= memMB]
# Sort
- listedFilteredSizes = sorted(filtered_sizes, key=lambda k: (k['numberOfCores'], k['memoryInMB'], k['resourceDiskSizeInMB']))
+ listedFilteredSizes = sorted(filtered_sizes, key=lambda k: (k['numberOfCores'], k['memoryInMB'],
+ k['resourceDiskSizeInMB']))
if listedFilteredSizes:
return listedFilteredSizes[0]['name']
def _get_flavor_id_from_flavor_name(self, flavor_name):
- #self.logger.debug("getting flavor id from flavor name {}".format(flavor_name))
+ # self.logger.debug("getting flavor id from flavor name {}".format(flavor_name))
try:
self._reload_connection()
- vm_sizes_list = [vm_size.serialize() for vm_size in self.conn_compute.virtual_machine_sizes.list(self.region)]
+ vm_sizes_list = [vm_size.serialize() for vm_size in
+ self.conn_compute.virtual_machine_sizes.list(self.region)]
output_flavor = None
for size in vm_sizes_list:
if size['name'] == flavor_name:
output_flavor = size
- # Si no se encuentra ninguno, este metodo devuelve None
+ # None is returned if not found anything
return output_flavor
except Exception as e:
def get_network(self, net_id):
- #self.logger.debug('get network id: {}'.format(net_id))
- res_name = self._get_resource_name_from_resource_id(net_id)
+ # self.logger.debug('get network id: {}'.format(net_id))
+ # res_name = self._get_resource_name_from_resource_id(net_id)
self._reload_connection()
filter_dict = {'name': net_id}
vm = self.conn_compute.virtual_machines.get(self.resource_group, res_name)
# Shuts down the virtual machine and releases the compute resources
- #vm_stop = self.conn_compute.virtual_machines.power_off(self.resource_group, resName)
- #vm_stop.wait()
+ # vm_stop = self.conn_compute.virtual_machines.power_off(self.resource_group, resName)
+ # vm_stop.wait()
vm_delete = self.conn_compute.virtual_machines.delete(self.resource_group, res_name)
vm_delete.wait()
# Delete list of public ips
if public_ip_name:
self.logger.debug('delete PUBLIC IP - ' + public_ip_name)
- public_ip = self.conn_vnet.public_ip_addresses.delete(self.resource_group, public_ip_name)
+ self.conn_vnet.public_ip_addresses.delete(self.resource_group, public_ip_name)
except CloudError as e:
if e.error.error and "notfound" in e.error.error.lower():
except Exception as e:
self._format_vimconn_exception(e)
- def action_vminstance(self, vm_id, action_dict, created_items = {}):
+ def action_vminstance(self, vm_id, action_dict, created_items={}):
"""Send and action over a VM instance from VIM
Returns the vm_id if the action was successfully sent to the VIM
"""
self._reload_connection()
try:
resName = self._get_resource_name_from_resource_id(vm_id)
- vm=self.conn_compute.virtual_machines.get(self.resource_group, resName)
+ vm = self.conn_compute.virtual_machines.get(self.resource_group, resName)
except CloudError as e:
if e.error.error and "notfound" in e.error.error.lower():
raise vimconn.vimconnNotFoundException("No vminstance found '{}'".format(vm_id))
For the azure connector only the azure tenant will be returned if it is compatible
with filter_dict
"""
- tenants_azure=[{'name': self.tenant, 'id': self.tenant}]
- tenant_list=[]
+ tenants_azure = [{'name': self.tenant, 'id': self.tenant}]
+ tenant_list = []
self.logger.debug("get tenant list: %s", filter_dict)
for tenant_azure in tenants_azure:
ips = []
if nic_data.ip_configurations[0].public_ip_address:
self.logger.debug("Obtain public ip address")
- public_ip_name = self._get_resource_name_from_resource_id(nic_data.ip_configurations[0].public_ip_address.id)
+ public_ip_name = self._get_resource_name_from_resource_id(
+ nic_data.ip_configurations[0].public_ip_address.id)
public_ip = self.conn_vnet.public_ip_addresses.get(self.resource_group, public_ip_name)
self.logger.debug("Public ip address is: %s", public_ip.ip_address)
ips.append(public_ip.ip_address)
test_params[param] = value
config = {
- 'region_name': getenv("AZURE_REGION_NAME", 'westeurope'),
- 'resource_group': getenv("AZURE_RESOURCE_GROUP"),
- 'subscription_id': getenv("AZURE_SUBSCRIPTION_ID"),
- 'pub_key': getenv("AZURE_PUB_KEY", None),
- 'vnet_name': getenv("AZURE_VNET_NAME", 'myNetwork'),
+ 'region_name': getenv("AZURE_REGION_NAME", 'westeurope'),
+ 'resource_group': getenv("AZURE_RESOURCE_GROUP"),
+ 'subscription_id': getenv("AZURE_SUBSCRIPTION_ID"),
+ 'pub_key': getenv("AZURE_PUB_KEY", None),
+ 'vnet_name': getenv("AZURE_VNET_NAME", 'myNetwork'),
}
virtualMachine = {
vnet_config = {
'subnet_address': '10.1.2.0/24',
- #'subnet_name': 'subnet-oam'
+ # 'subnet_name': 'subnet-oam'
}
###########################