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
22 osconnector implements all the methods to interact with openstack using the python-neutronclient.
24 For the VNF forwarding graph, The OpenStack VIM connector calls the
25 networking-sfc Neutron extension methods, whose resources are mapped
26 to the VIM connector's SFC resources as follows:
27 - Classification (OSM) -> Flow Classifier (Neutron)
28 - Service Function Instance (OSM) -> Port Pair (Neutron)
29 - Service Function (OSM) -> Port Pair Group (Neutron)
30 - Service Function Path (OSM) -> Port Chain (Neutron)
33 from osm_ro_plugin
import vimconn
43 from pprint
import pformat
44 from novaclient
import client
as nClient
, exceptions
as nvExceptions
45 from keystoneauth1
.identity
import v2
, v3
46 from keystoneauth1
import session
47 import keystoneclient
.exceptions
as ksExceptions
48 import keystoneclient
.v3
.client
as ksClient_v3
49 import keystoneclient
.v2_0
.client
as ksClient_v2
50 from glanceclient
import client
as glClient
51 import glanceclient
.exc
as gl1Exceptions
52 from cinderclient
import client
as cClient
54 # TODO py3 check that this base exception matches python2 httplib.HTTPException
55 from http
.client
import HTTPException
56 from neutronclient
.neutron
import client
as neClient
57 from neutronclient
.common
import exceptions
as neExceptions
58 from requests
.exceptions
import ConnectionError
60 __author__
= "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
61 __date__
= "$22-sep-2017 23:59:59$"
63 """contain the openstack virtual machine status to openmano status"""
64 vmStatus2manoFormat
= {
67 "SUSPENDED": "SUSPENDED",
68 "SHUTOFF": "INACTIVE",
73 netStatus2manoFormat
= {
76 "INACTIVE": "INACTIVE",
82 supportedClassificationTypes
= ["legacy_flow_classifier"]
84 # global var to have a timeout creating and deleting volumes
89 class SafeDumper(yaml
.SafeDumper
):
90 def represent_data(self
, data
):
91 # Openstack APIs use custom subclasses of dict and YAML safe dumper
92 # is designed to not handle that (reference issue 142 of pyyaml)
93 if isinstance(data
, dict) and data
.__class
__ != dict:
94 # A simple solution is to convert those items back to dicts
95 data
= dict(data
.items())
97 return super(SafeDumper
, self
).represent_data(data
)
100 class vimconnector(vimconn
.VimConnector
):
115 """using common constructor parameters. In this case
116 'url' is the keystone authorization url,
117 'url_admin' is not use
119 api_version
= config
.get("APIversion")
121 if api_version
and api_version
not in ("v3.3", "v2.0", "2", "3"):
122 raise vimconn
.VimConnException(
123 "Invalid value '{}' for config:APIversion. "
124 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version
)
127 vim_type
= config
.get("vim_type")
129 if vim_type
and vim_type
not in ("vio", "VIO"):
130 raise vimconn
.VimConnException(
131 "Invalid value '{}' for config:vim_type."
132 "Allowed values are 'vio' or 'VIO'".format(vim_type
)
135 if config
.get("dataplane_net_vlan_range") is not None:
136 # validate vlan ranges provided by user
137 self
._validate
_vlan
_ranges
(
138 config
.get("dataplane_net_vlan_range"), "dataplane_net_vlan_range"
141 if config
.get("multisegment_vlan_range") is not None:
142 # validate vlan ranges provided by user
143 self
._validate
_vlan
_ranges
(
144 config
.get("multisegment_vlan_range"), "multisegment_vlan_range"
147 vimconn
.VimConnector
.__init
__(
161 if self
.config
.get("insecure") and self
.config
.get("ca_cert"):
162 raise vimconn
.VimConnException(
163 "options insecure and ca_cert are mutually exclusive"
168 if self
.config
.get("insecure"):
171 if self
.config
.get("ca_cert"):
172 self
.verify
= self
.config
.get("ca_cert")
175 raise TypeError("url param can not be NoneType")
177 self
.persistent_info
= persistent_info
178 self
.availability_zone
= persistent_info
.get("availability_zone", None)
179 self
.session
= persistent_info
.get("session", {"reload_client": True})
180 self
.my_tenant_id
= self
.session
.get("my_tenant_id")
181 self
.nova
= self
.session
.get("nova")
182 self
.neutron
= self
.session
.get("neutron")
183 self
.cinder
= self
.session
.get("cinder")
184 self
.glance
= self
.session
.get("glance")
185 # self.glancev1 = self.session.get("glancev1")
186 self
.keystone
= self
.session
.get("keystone")
187 self
.api_version3
= self
.session
.get("api_version3")
188 self
.vim_type
= self
.config
.get("vim_type")
191 self
.vim_type
= self
.vim_type
.upper()
193 if self
.config
.get("use_internal_endpoint"):
194 self
.endpoint_type
= "internalURL"
196 self
.endpoint_type
= None
198 logging
.getLogger("urllib3").setLevel(logging
.WARNING
)
199 logging
.getLogger("keystoneauth").setLevel(logging
.WARNING
)
200 logging
.getLogger("novaclient").setLevel(logging
.WARNING
)
201 self
.logger
= logging
.getLogger("ro.vim.openstack")
203 # allow security_groups to be a list or a single string
204 if isinstance(self
.config
.get("security_groups"), str):
205 self
.config
["security_groups"] = [self
.config
["security_groups"]]
207 self
.security_groups_id
= None
209 # ###### VIO Specific Changes #########
210 if self
.vim_type
== "VIO":
211 self
.logger
= logging
.getLogger("ro.vim.vio")
214 self
.logger
.setLevel(getattr(logging
, log_level
))
216 def __getitem__(self
, index
):
217 """Get individuals parameters.
219 if index
== "project_domain_id":
220 return self
.config
.get("project_domain_id")
221 elif index
== "user_domain_id":
222 return self
.config
.get("user_domain_id")
224 return vimconn
.VimConnector
.__getitem
__(self
, index
)
226 def __setitem__(self
, index
, value
):
227 """Set individuals parameters and it is marked as dirty so to force connection reload.
229 if index
== "project_domain_id":
230 self
.config
["project_domain_id"] = value
231 elif index
== "user_domain_id":
232 self
.config
["user_domain_id"] = value
234 vimconn
.VimConnector
.__setitem
__(self
, index
, value
)
236 self
.session
["reload_client"] = True
238 def serialize(self
, value
):
239 """Serialization of python basic types.
241 In the case value is not serializable a message will be logged and a
242 simple representation of the data that cannot be converted back to
245 if isinstance(value
, str):
250 value
, Dumper
=SafeDumper
, default_flow_style
=True, width
=256
252 except yaml
.representer
.RepresenterError
:
254 "The following entity cannot be serialized in YAML:\n\n%s\n\n",
261 def _reload_connection(self
):
262 """Called before any operation, it check if credentials has changed
263 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
265 # TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
266 if self
.session
["reload_client"]:
267 if self
.config
.get("APIversion"):
268 self
.api_version3
= (
269 self
.config
["APIversion"] == "v3.3"
270 or self
.config
["APIversion"] == "3"
272 else: # get from ending auth_url that end with v3 or with v2.0
273 self
.api_version3
= self
.url
.endswith("/v3") or self
.url
.endswith(
277 self
.session
["api_version3"] = self
.api_version3
279 if self
.api_version3
:
280 if self
.config
.get("project_domain_id") or self
.config
.get(
281 "project_domain_name"
283 project_domain_id_default
= None
285 project_domain_id_default
= "default"
287 if self
.config
.get("user_domain_id") or self
.config
.get(
290 user_domain_id_default
= None
292 user_domain_id_default
= "default"
296 password
=self
.passwd
,
297 project_name
=self
.tenant_name
,
298 project_id
=self
.tenant_id
,
299 project_domain_id
=self
.config
.get(
300 "project_domain_id", project_domain_id_default
302 user_domain_id
=self
.config
.get(
303 "user_domain_id", user_domain_id_default
305 project_domain_name
=self
.config
.get("project_domain_name"),
306 user_domain_name
=self
.config
.get("user_domain_name"),
312 password
=self
.passwd
,
313 tenant_name
=self
.tenant_name
,
314 tenant_id
=self
.tenant_id
,
317 sess
= session
.Session(auth
=auth
, verify
=self
.verify
)
318 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
319 # Titanium cloud and StarlingX
320 region_name
= self
.config
.get("region_name")
322 if self
.api_version3
:
323 self
.keystone
= ksClient_v3
.Client(
325 endpoint_type
=self
.endpoint_type
,
326 region_name
=region_name
,
329 self
.keystone
= ksClient_v2
.Client(
330 session
=sess
, endpoint_type
=self
.endpoint_type
333 self
.session
["keystone"] = self
.keystone
334 # In order to enable microversion functionality an explicit microversion must be specified in "config".
335 # This implementation approach is due to the warning message in
336 # https://developer.openstack.org/api-guide/compute/microversions.html
337 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
338 # always require an specific microversion.
339 # To be able to use "device role tagging" functionality define "microversion: 2.32" in datacenter config
340 version
= self
.config
.get("microversion")
345 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
346 # Titanium cloud and StarlingX
347 self
.nova
= self
.session
["nova"] = nClient
.Client(
350 endpoint_type
=self
.endpoint_type
,
351 region_name
=region_name
,
353 self
.neutron
= self
.session
["neutron"] = neClient
.Client(
356 endpoint_type
=self
.endpoint_type
,
357 region_name
=region_name
,
359 self
.cinder
= self
.session
["cinder"] = cClient
.Client(
362 endpoint_type
=self
.endpoint_type
,
363 region_name
=region_name
,
367 self
.my_tenant_id
= self
.session
["my_tenant_id"] = sess
.get_project_id()
369 self
.logger
.error("Cannot get project_id from session", exc_info
=True)
371 if self
.endpoint_type
== "internalURL":
372 glance_service_id
= self
.keystone
.services
.list(name
="glance")[0].id
373 glance_endpoint
= self
.keystone
.endpoints
.list(
374 glance_service_id
, interface
="internal"
377 glance_endpoint
= None
379 self
.glance
= self
.session
["glance"] = glClient
.Client(
380 2, session
=sess
, endpoint
=glance_endpoint
382 # using version 1 of glance client in new_image()
383 # self.glancev1 = self.session["glancev1"] = glClient.Client("1", session=sess,
384 # endpoint=glance_endpoint)
385 self
.session
["reload_client"] = False
386 self
.persistent_info
["session"] = self
.session
387 # add availablity zone info inside self.persistent_info
388 self
._set
_availablity
_zones
()
389 self
.persistent_info
["availability_zone"] = self
.availability_zone
390 # force to get again security_groups_ids next time they are needed
391 self
.security_groups_id
= None
393 def __net_os2mano(self
, net_list_dict
):
394 """Transform the net openstack format to mano format
395 net_list_dict can be a list of dict or a single dict"""
396 if type(net_list_dict
) is dict:
397 net_list_
= (net_list_dict
,)
398 elif type(net_list_dict
) is list:
399 net_list_
= net_list_dict
401 raise TypeError("param net_list_dict must be a list or a dictionary")
402 for net
in net_list_
:
403 if net
.get("provider:network_type") == "vlan":
406 net
["type"] = "bridge"
408 def __classification_os2mano(self
, class_list_dict
):
409 """Transform the openstack format (Flow Classifier) to mano format
410 (Classification) class_list_dict can be a list of dict or a single dict
412 if isinstance(class_list_dict
, dict):
413 class_list_
= [class_list_dict
]
414 elif isinstance(class_list_dict
, list):
415 class_list_
= class_list_dict
417 raise TypeError("param class_list_dict must be a list or a dictionary")
418 for classification
in class_list_
:
419 id = classification
.pop("id")
420 name
= classification
.pop("name")
421 description
= classification
.pop("description")
422 project_id
= classification
.pop("project_id")
423 tenant_id
= classification
.pop("tenant_id")
424 original_classification
= copy
.deepcopy(classification
)
425 classification
.clear()
426 classification
["ctype"] = "legacy_flow_classifier"
427 classification
["definition"] = original_classification
428 classification
["id"] = id
429 classification
["name"] = name
430 classification
["description"] = description
431 classification
["project_id"] = project_id
432 classification
["tenant_id"] = tenant_id
434 def __sfi_os2mano(self
, sfi_list_dict
):
435 """Transform the openstack format (Port Pair) to mano format (SFI)
436 sfi_list_dict can be a list of dict or a single dict
438 if isinstance(sfi_list_dict
, dict):
439 sfi_list_
= [sfi_list_dict
]
440 elif isinstance(sfi_list_dict
, list):
441 sfi_list_
= sfi_list_dict
443 raise TypeError("param sfi_list_dict must be a list or a dictionary")
445 for sfi
in sfi_list_
:
446 sfi
["ingress_ports"] = []
447 sfi
["egress_ports"] = []
449 if sfi
.get("ingress"):
450 sfi
["ingress_ports"].append(sfi
["ingress"])
452 if sfi
.get("egress"):
453 sfi
["egress_ports"].append(sfi
["egress"])
457 params
= sfi
.get("service_function_parameters")
461 correlation
= params
.get("correlation")
466 sfi
["sfc_encap"] = sfc_encap
467 del sfi
["service_function_parameters"]
469 def __sf_os2mano(self
, sf_list_dict
):
470 """Transform the openstack format (Port Pair Group) to mano format (SF)
471 sf_list_dict can be a list of dict or a single dict
473 if isinstance(sf_list_dict
, dict):
474 sf_list_
= [sf_list_dict
]
475 elif isinstance(sf_list_dict
, list):
476 sf_list_
= sf_list_dict
478 raise TypeError("param sf_list_dict must be a list or a dictionary")
481 del sf
["port_pair_group_parameters"]
482 sf
["sfis"] = sf
["port_pairs"]
485 def __sfp_os2mano(self
, sfp_list_dict
):
486 """Transform the openstack format (Port Chain) to mano format (SFP)
487 sfp_list_dict can be a list of dict or a single dict
489 if isinstance(sfp_list_dict
, dict):
490 sfp_list_
= [sfp_list_dict
]
491 elif isinstance(sfp_list_dict
, list):
492 sfp_list_
= sfp_list_dict
494 raise TypeError("param sfp_list_dict must be a list or a dictionary")
496 for sfp
in sfp_list_
:
497 params
= sfp
.pop("chain_parameters")
501 correlation
= params
.get("correlation")
506 sfp
["sfc_encap"] = sfc_encap
507 sfp
["spi"] = sfp
.pop("chain_id")
508 sfp
["classifications"] = sfp
.pop("flow_classifiers")
509 sfp
["service_functions"] = sfp
.pop("port_pair_groups")
511 # placeholder for now; read TODO note below
512 def _validate_classification(self
, type, definition
):
513 # only legacy_flow_classifier Type is supported at this point
515 # TODO(igordcard): this method should be an abstract method of an
516 # abstract Classification class to be implemented by the specific
517 # Types. Also, abstract vimconnector should call the validation
518 # method before the implemented VIM connectors are called.
520 def _format_exception(self
, exception
):
521 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
522 message_error
= str(exception
)
528 neExceptions
.NetworkNotFoundClient
,
529 nvExceptions
.NotFound
,
530 ksExceptions
.NotFound
,
531 gl1Exceptions
.HTTPNotFound
,
534 raise vimconn
.VimConnNotFoundException(
535 type(exception
).__name
__ + ": " + message_error
541 gl1Exceptions
.HTTPException
,
542 gl1Exceptions
.CommunicationError
,
544 ksExceptions
.ConnectionError
,
545 neExceptions
.ConnectionFailed
,
548 if type(exception
).__name
__ == "SSLError":
549 tip
= " (maybe option 'insecure' must be added to the VIM)"
551 raise vimconn
.VimConnConnectionException(
552 "Invalid URL or credentials{}: {}".format(tip
, message_error
)
558 nvExceptions
.BadRequest
,
559 ksExceptions
.BadRequest
,
562 raise vimconn
.VimConnException(
563 type(exception
).__name
__ + ": " + message_error
568 nvExceptions
.ClientException
,
569 ksExceptions
.ClientException
,
570 neExceptions
.NeutronException
,
573 raise vimconn
.VimConnUnexpectedResponse(
574 type(exception
).__name
__ + ": " + message_error
576 elif isinstance(exception
, nvExceptions
.Conflict
):
577 raise vimconn
.VimConnConflictException(
578 type(exception
).__name
__ + ": " + message_error
580 elif isinstance(exception
, vimconn
.VimConnException
):
583 self
.logger
.error("General Exception " + message_error
, exc_info
=True)
585 raise vimconn
.VimConnConnectionException(
586 type(exception
).__name
__ + ": " + message_error
589 def _get_ids_from_name(self
):
591 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
594 # get tenant_id if only tenant_name is supplied
595 self
._reload
_connection
()
597 if not self
.my_tenant_id
:
598 raise vimconn
.VimConnConnectionException(
599 "Error getting tenant information from name={} id={}".format(
600 self
.tenant_name
, self
.tenant_id
604 if self
.config
.get("security_groups") and not self
.security_groups_id
:
605 # convert from name to id
606 neutron_sg_list
= self
.neutron
.list_security_groups(
607 tenant_id
=self
.my_tenant_id
610 self
.security_groups_id
= []
611 for sg
in self
.config
.get("security_groups"):
612 for neutron_sg
in neutron_sg_list
:
613 if sg
in (neutron_sg
["id"], neutron_sg
["name"]):
614 self
.security_groups_id
.append(neutron_sg
["id"])
617 self
.security_groups_id
= None
619 raise vimconn
.VimConnConnectionException(
620 "Not found security group {} for this tenant".format(sg
)
623 def check_vim_connectivity(self
):
624 # just get network list to check connectivity and credentials
625 self
.get_network_list(filter_dict
={})
627 def get_tenant_list(self
, filter_dict
={}):
628 """Obtain tenants of VIM
629 filter_dict can contain the following keys:
630 name: filter by tenant name
631 id: filter by tenant uuid/id
633 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
635 self
.logger
.debug("Getting tenants from VIM filter: '%s'", str(filter_dict
))
638 self
._reload
_connection
()
640 if self
.api_version3
:
641 project_class_list
= self
.keystone
.projects
.list(
642 name
=filter_dict
.get("name")
645 project_class_list
= self
.keystone
.tenants
.findall(**filter_dict
)
649 for project
in project_class_list
:
650 if filter_dict
.get("id") and filter_dict
["id"] != project
.id:
653 project_list
.append(project
.to_dict())
657 ksExceptions
.ConnectionError
,
658 ksExceptions
.ClientException
,
661 self
._format
_exception
(e
)
663 def new_tenant(self
, tenant_name
, tenant_description
):
664 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
665 self
.logger
.debug("Adding a new tenant name: %s", tenant_name
)
668 self
._reload
_connection
()
670 if self
.api_version3
:
671 project
= self
.keystone
.projects
.create(
673 self
.config
.get("project_domain_id", "default"),
674 description
=tenant_description
,
678 project
= self
.keystone
.tenants
.create(tenant_name
, tenant_description
)
682 ksExceptions
.ConnectionError
,
683 ksExceptions
.ClientException
,
684 ksExceptions
.BadRequest
,
687 self
._format
_exception
(e
)
689 def delete_tenant(self
, tenant_id
):
690 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
691 self
.logger
.debug("Deleting tenant %s from VIM", tenant_id
)
694 self
._reload
_connection
()
696 if self
.api_version3
:
697 self
.keystone
.projects
.delete(tenant_id
)
699 self
.keystone
.tenants
.delete(tenant_id
)
703 ksExceptions
.ConnectionError
,
704 ksExceptions
.ClientException
,
705 ksExceptions
.NotFound
,
708 self
._format
_exception
(e
)
716 provider_network_profile
=None,
718 """Adds a tenant network to VIM
720 'net_name': name of the network
722 'bridge': overlay isolated network
723 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
724 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
725 'ip_profile': is a dict containing the IP parameters of the network
726 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
727 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
728 'gateway_address': (Optional) ip_schema, that is X.X.X.X
729 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
730 'dhcp_enabled': True or False
731 'dhcp_start_address': ip_schema, first IP to grant
732 'dhcp_count': number of IPs to grant.
733 'shared': if this network can be seen/use by other tenants/organization
734 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
735 physical-network: physnet-label}
736 Returns a tuple with the network identifier and created_items, or raises an exception on error
737 created_items can be None or a dictionary where this method can include key-values that will be passed to
738 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
739 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
743 "Adding a new network to VIM name '%s', type '%s'", net_name
, net_type
745 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
750 if provider_network_profile
:
751 vlan
= provider_network_profile
.get("segmentation-id")
755 self
._reload
_connection
()
756 network_dict
= {"name": net_name
, "admin_state_up": True}
758 if net_type
in ("data", "ptp"):
759 provider_physical_network
= None
761 if provider_network_profile
and provider_network_profile
.get(
764 provider_physical_network
= provider_network_profile
.get(
768 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
769 # or not declared, just ignore the checking
772 self
.config
.get("dataplane_physical_net"), (tuple, list)
774 and provider_physical_network
775 not in self
.config
["dataplane_physical_net"]
777 raise vimconn
.VimConnConflictException(
778 "Invalid parameter 'provider-network:physical-network' "
779 "for network creation. '{}' is not one of the declared "
780 "list at VIM_config:dataplane_physical_net".format(
781 provider_physical_network
785 # use the default dataplane_physical_net
786 if not provider_physical_network
:
787 provider_physical_network
= self
.config
.get(
788 "dataplane_physical_net"
791 # if it is non empty list, use the first value. If it is a string use the value directly
793 isinstance(provider_physical_network
, (tuple, list))
794 and provider_physical_network
796 provider_physical_network
= provider_physical_network
[0]
798 if not provider_physical_network
:
799 raise vimconn
.VimConnConflictException(
800 "missing information needed for underlay networks. Provide "
801 "'dataplane_physical_net' configuration at VIM or use the NS "
802 "instantiation parameter 'provider-network.physical-network'"
806 if not self
.config
.get("multisegment_support"):
808 "provider:physical_network"
809 ] = provider_physical_network
812 provider_network_profile
813 and "network-type" in provider_network_profile
816 "provider:network_type"
817 ] = provider_network_profile
["network-type"]
819 network_dict
["provider:network_type"] = self
.config
.get(
820 "dataplane_network_type", "vlan"
824 network_dict
["provider:segmentation_id"] = vlan
829 "provider:physical_network": "",
830 "provider:network_type": "vxlan",
832 segment_list
.append(segment1_dict
)
834 "provider:physical_network": provider_physical_network
,
835 "provider:network_type": "vlan",
839 segment2_dict
["provider:segmentation_id"] = vlan
840 elif self
.config
.get("multisegment_vlan_range"):
841 vlanID
= self
._generate
_multisegment
_vlanID
()
842 segment2_dict
["provider:segmentation_id"] = vlanID
845 # raise vimconn.VimConnConflictException(
846 # "You must provide "multisegment_vlan_range" at config dict before creating a multisegment
848 segment_list
.append(segment2_dict
)
849 network_dict
["segments"] = segment_list
851 # VIO Specific Changes. It needs a concrete VLAN
852 if self
.vim_type
== "VIO" and vlan
is None:
853 if self
.config
.get("dataplane_net_vlan_range") is None:
854 raise vimconn
.VimConnConflictException(
855 "You must provide 'dataplane_net_vlan_range' in format "
856 "[start_ID - end_ID] at VIM_config for creating underlay "
860 network_dict
["provider:segmentation_id"] = self
._generate
_vlanID
()
862 network_dict
["shared"] = shared
864 if self
.config
.get("disable_network_port_security"):
865 network_dict
["port_security_enabled"] = False
867 if self
.config
.get("neutron_availability_zone_hints"):
868 hints
= self
.config
.get("neutron_availability_zone_hints")
870 if isinstance(hints
, str):
873 network_dict
["availability_zone_hints"] = hints
875 new_net
= self
.neutron
.create_network({"network": network_dict
})
877 # create subnetwork, even if there is no profile
882 if not ip_profile
.get("subnet_address"):
883 # Fake subnet is required
884 subnet_rand
= random
.randint(0, 255)
885 ip_profile
["subnet_address"] = "192.168.{}.0/24".format(subnet_rand
)
887 if "ip_version" not in ip_profile
:
888 ip_profile
["ip_version"] = "IPv4"
891 "name": net_name
+ "-subnet",
892 "network_id": new_net
["network"]["id"],
893 "ip_version": 4 if ip_profile
["ip_version"] == "IPv4" else 6,
894 "cidr": ip_profile
["subnet_address"],
897 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
898 if ip_profile
.get("gateway_address"):
899 subnet
["gateway_ip"] = ip_profile
["gateway_address"]
901 subnet
["gateway_ip"] = None
903 if ip_profile
.get("dns_address"):
904 subnet
["dns_nameservers"] = ip_profile
["dns_address"].split(";")
906 if "dhcp_enabled" in ip_profile
:
907 subnet
["enable_dhcp"] = (
909 if ip_profile
["dhcp_enabled"] == "false"
910 or ip_profile
["dhcp_enabled"] is False
914 if ip_profile
.get("dhcp_start_address"):
915 subnet
["allocation_pools"] = []
916 subnet
["allocation_pools"].append(dict())
917 subnet
["allocation_pools"][0]["start"] = ip_profile
[
921 if ip_profile
.get("dhcp_count"):
922 # parts = ip_profile["dhcp_start_address"].split(".")
923 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
924 ip_int
= int(netaddr
.IPAddress(ip_profile
["dhcp_start_address"]))
925 ip_int
+= ip_profile
["dhcp_count"] - 1
926 ip_str
= str(netaddr
.IPAddress(ip_int
))
927 subnet
["allocation_pools"][0]["end"] = ip_str
929 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
930 self
.neutron
.create_subnet({"subnet": subnet
})
932 if net_type
== "data" and self
.config
.get("multisegment_support"):
933 if self
.config
.get("l2gw_support"):
934 l2gw_list
= self
.neutron
.list_l2_gateways().get("l2_gateways", ())
935 for l2gw
in l2gw_list
:
937 "l2_gateway_id": l2gw
["id"],
938 "network_id": new_net
["network"]["id"],
939 "segmentation_id": str(vlanID
),
941 new_l2gw_conn
= self
.neutron
.create_l2_gateway_connection(
942 {"l2_gateway_connection": l2gw_conn
}
946 + str(new_l2gw_conn
["l2_gateway_connection"]["id"])
949 return new_net
["network"]["id"], created_items
950 except Exception as e
:
951 # delete l2gw connections (if any) before deleting the network
952 for k
, v
in created_items
.items():
953 if not v
: # skip already deleted
957 k_item
, _
, k_id
= k
.partition(":")
959 if k_item
== "l2gwconn":
960 self
.neutron
.delete_l2_gateway_connection(k_id
)
961 except Exception as e2
:
963 "Error deleting l2 gateway connection: {}: {}".format(
964 type(e2
).__name
__, e2
969 self
.neutron
.delete_network(new_net
["network"]["id"])
971 self
._format
_exception
(e
)
973 def get_network_list(self
, filter_dict
={}):
974 """Obtain tenant networks of VIM
980 admin_state_up: boolean
982 Returns the network list of dictionaries
984 self
.logger
.debug("Getting network from VIM filter: '%s'", str(filter_dict
))
987 self
._reload
_connection
()
988 filter_dict_os
= filter_dict
.copy()
990 if self
.api_version3
and "tenant_id" in filter_dict_os
:
992 filter_dict_os
["project_id"] = filter_dict_os
.pop("tenant_id")
994 net_dict
= self
.neutron
.list_networks(**filter_dict_os
)
995 net_list
= net_dict
["networks"]
996 self
.__net
_os
2mano
(net_list
)
1000 neExceptions
.ConnectionFailed
,
1001 ksExceptions
.ClientException
,
1002 neExceptions
.NeutronException
,
1005 self
._format
_exception
(e
)
1007 def get_network(self
, net_id
):
1008 """Obtain details of network from VIM
1009 Returns the network information from a network id"""
1010 self
.logger
.debug(" Getting tenant network %s from VIM", net_id
)
1011 filter_dict
= {"id": net_id
}
1012 net_list
= self
.get_network_list(filter_dict
)
1014 if len(net_list
) == 0:
1015 raise vimconn
.VimConnNotFoundException(
1016 "Network '{}' not found".format(net_id
)
1018 elif len(net_list
) > 1:
1019 raise vimconn
.VimConnConflictException(
1020 "Found more than one network with this criteria"
1025 for subnet_id
in net
.get("subnets", ()):
1027 subnet
= self
.neutron
.show_subnet(subnet_id
)
1028 except Exception as e
:
1030 "osconnector.get_network(): Error getting subnet %s %s"
1033 subnet
= {"id": subnet_id
, "fault": str(e
)}
1035 subnets
.append(subnet
)
1037 net
["subnets"] = subnets
1038 net
["encapsulation"] = net
.get("provider:network_type")
1039 net
["encapsulation_type"] = net
.get("provider:network_type")
1040 net
["segmentation_id"] = net
.get("provider:segmentation_id")
1041 net
["encapsulation_id"] = net
.get("provider:segmentation_id")
1045 def delete_network(self
, net_id
, created_items
=None):
1047 Removes a tenant network from VIM and its associated elements
1048 :param net_id: VIM identifier of the network, provided by method new_network
1049 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1050 Returns the network identifier or raises an exception upon error or when network is not found
1052 self
.logger
.debug("Deleting network '%s' from VIM", net_id
)
1054 if created_items
is None:
1058 self
._reload
_connection
()
1059 # delete l2gw connections (if any) before deleting the network
1060 for k
, v
in created_items
.items():
1061 if not v
: # skip already deleted
1065 k_item
, _
, k_id
= k
.partition(":")
1066 if k_item
== "l2gwconn":
1067 self
.neutron
.delete_l2_gateway_connection(k_id
)
1068 except Exception as e
:
1070 "Error deleting l2 gateway connection: {}: {}".format(
1075 # delete VM ports attached to this networks before the network
1076 ports
= self
.neutron
.list_ports(network_id
=net_id
)
1077 for p
in ports
["ports"]:
1079 self
.neutron
.delete_port(p
["id"])
1080 except Exception as e
:
1081 self
.logger
.error("Error deleting port %s: %s", p
["id"], str(e
))
1083 self
.neutron
.delete_network(net_id
)
1087 neExceptions
.ConnectionFailed
,
1088 neExceptions
.NetworkNotFoundClient
,
1089 neExceptions
.NeutronException
,
1090 ksExceptions
.ClientException
,
1091 neExceptions
.NeutronException
,
1094 self
._format
_exception
(e
)
1096 def refresh_nets_status(self
, net_list
):
1097 """Get the status of the networks
1098 Params: the list of network identifiers
1099 Returns a dictionary with:
1100 net_id: #VIM id of this network
1101 status: #Mandatory. Text with one of:
1102 # DELETED (not found at vim)
1103 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1104 # OTHER (Vim reported other status not understood)
1105 # ERROR (VIM indicates an ERROR status)
1106 # ACTIVE, INACTIVE, DOWN (admin down),
1107 # BUILD (on building process)
1109 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1110 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1114 for net_id
in net_list
:
1118 net_vim
= self
.get_network(net_id
)
1120 if net_vim
["status"] in netStatus2manoFormat
:
1121 net
["status"] = netStatus2manoFormat
[net_vim
["status"]]
1123 net
["status"] = "OTHER"
1124 net
["error_msg"] = "VIM status reported " + net_vim
["status"]
1126 if net
["status"] == "ACTIVE" and not net_vim
["admin_state_up"]:
1127 net
["status"] = "DOWN"
1129 net
["vim_info"] = self
.serialize(net_vim
)
1131 if net_vim
.get("fault"): # TODO
1132 net
["error_msg"] = str(net_vim
["fault"])
1133 except vimconn
.VimConnNotFoundException
as e
:
1134 self
.logger
.error("Exception getting net status: %s", str(e
))
1135 net
["status"] = "DELETED"
1136 net
["error_msg"] = str(e
)
1137 except vimconn
.VimConnException
as e
:
1138 self
.logger
.error("Exception getting net status: %s", str(e
))
1139 net
["status"] = "VIM_ERROR"
1140 net
["error_msg"] = str(e
)
1141 net_dict
[net_id
] = net
1144 def get_flavor(self
, flavor_id
):
1145 """Obtain flavor details from the VIM. Returns the flavor dict details"""
1146 self
.logger
.debug("Getting flavor '%s'", flavor_id
)
1149 self
._reload
_connection
()
1150 flavor
= self
.nova
.flavors
.find(id=flavor_id
)
1151 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
1153 return flavor
.to_dict()
1155 nvExceptions
.NotFound
,
1156 nvExceptions
.ClientException
,
1157 ksExceptions
.ClientException
,
1160 self
._format
_exception
(e
)
1162 def get_flavor_id_from_data(self
, flavor_dict
):
1163 """Obtain flavor id that match the flavor description
1164 Returns the flavor_id or raises a vimconnNotFoundException
1165 flavor_dict: contains the required ram, vcpus, disk
1166 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
1167 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
1168 vimconnNotFoundException is raised
1170 exact_match
= False if self
.config
.get("use_existing_flavors") else True
1173 self
._reload
_connection
()
1174 flavor_candidate_id
= None
1175 flavor_candidate_data
= (10000, 10000, 10000)
1178 flavor_dict
["vcpus"],
1179 flavor_dict
["disk"],
1180 flavor_dict
.get("ephemeral", 0),
1181 flavor_dict
.get("swap", 0),
1184 extended
= flavor_dict
.get("extended", {})
1187 raise vimconn
.VimConnNotFoundException(
1188 "Flavor with EPA still not implemented"
1190 # if len(numas) > 1:
1191 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
1193 # numas = extended.get("numas")
1194 for flavor
in self
.nova
.flavors
.list():
1195 epa
= flavor
.get_keys()
1208 if flavor_data
== flavor_target
:
1212 and flavor_target
< flavor_data
< flavor_candidate_data
1214 flavor_candidate_id
= flavor
.id
1215 flavor_candidate_data
= flavor_data
1217 if not exact_match
and flavor_candidate_id
:
1218 return flavor_candidate_id
1220 raise vimconn
.VimConnNotFoundException(
1221 "Cannot find any flavor matching '{}'".format(flavor_dict
)
1224 nvExceptions
.NotFound
,
1225 nvExceptions
.ClientException
,
1226 ksExceptions
.ClientException
,
1229 self
._format
_exception
(e
)
1231 def process_resource_quota(self
, quota
, prefix
, extra_specs
):
1237 if "limit" in quota
:
1238 extra_specs
["quota:" + prefix
+ "_limit"] = quota
["limit"]
1240 if "reserve" in quota
:
1241 extra_specs
["quota:" + prefix
+ "_reservation"] = quota
["reserve"]
1243 if "shares" in quota
:
1244 extra_specs
["quota:" + prefix
+ "_shares_level"] = "custom"
1245 extra_specs
["quota:" + prefix
+ "_shares_share"] = quota
["shares"]
1247 def new_flavor(self
, flavor_data
, change_name_if_used
=True):
1248 """Adds a tenant flavor to openstack VIM
1249 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name
1251 Returns the flavor identifier
1253 self
.logger
.debug("Adding flavor '%s'", str(flavor_data
))
1259 name
= flavor_data
["name"]
1260 while retry
< max_retries
:
1263 self
._reload
_connection
()
1265 if change_name_if_used
:
1268 fl
= self
.nova
.flavors
.list()
1271 fl_names
.append(f
.name
)
1273 while name
in fl_names
:
1275 name
= flavor_data
["name"] + "-" + str(name_suffix
)
1277 ram
= flavor_data
.get("ram", 64)
1278 vcpus
= flavor_data
.get("vcpus", 1)
1281 extended
= flavor_data
.get("extended")
1283 numas
= extended
.get("numas")
1286 numa_nodes
= len(numas
)
1289 return -1, "Can not add flavor with more than one numa"
1291 extra_specs
["hw:numa_nodes"] = str(numa_nodes
)
1292 extra_specs
["hw:mem_page_size"] = "large"
1293 extra_specs
["hw:cpu_policy"] = "dedicated"
1294 extra_specs
["hw:numa_mempolicy"] = "strict"
1296 if self
.vim_type
== "VIO":
1298 "vmware:extra_config"
1299 ] = '{"numa.nodeAffinity":"0"}'
1300 extra_specs
["vmware:latency_sensitivity_level"] = "high"
1303 # overwrite ram and vcpus
1304 # check if key "memory" is present in numa else use ram value at flavor
1305 if "memory" in numa
:
1306 ram
= numa
["memory"] * 1024
1307 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/
1308 # implemented/virt-driver-cpu-thread-pinning.html
1309 extra_specs
["hw:cpu_sockets"] = 1
1311 if "paired-threads" in numa
:
1312 vcpus
= numa
["paired-threads"] * 2
1313 # cpu_thread_policy "require" implies that the compute node must have an
1315 extra_specs
["hw:cpu_thread_policy"] = "require"
1316 extra_specs
["hw:cpu_policy"] = "dedicated"
1317 elif "cores" in numa
:
1318 vcpus
= numa
["cores"]
1319 # cpu_thread_policy "prefer" implies that the host must not have an SMT
1320 # architecture, or a non-SMT architecture will be emulated
1321 extra_specs
["hw:cpu_thread_policy"] = "isolate"
1322 extra_specs
["hw:cpu_policy"] = "dedicated"
1323 elif "threads" in numa
:
1324 vcpus
= numa
["threads"]
1325 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT
1327 extra_specs
["hw:cpu_thread_policy"] = "prefer"
1328 extra_specs
["hw:cpu_policy"] = "dedicated"
1329 # for interface in numa.get("interfaces",() ):
1330 # if interface["dedicated"]=="yes":
1331 # raise vimconn.VimConnException("Passthrough interfaces are not supported
1332 # for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
1333 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"'
1334 # when a way to connect it is available
1335 elif extended
.get("cpu-quota"):
1336 self
.process_resource_quota(
1337 extended
.get("cpu-quota"), "cpu", extra_specs
1340 if extended
.get("mem-quota"):
1341 self
.process_resource_quota(
1342 extended
.get("mem-quota"), "memory", extra_specs
1345 if extended
.get("vif-quota"):
1346 self
.process_resource_quota(
1347 extended
.get("vif-quota"), "vif", extra_specs
1350 if extended
.get("disk-io-quota"):
1351 self
.process_resource_quota(
1352 extended
.get("disk-io-quota"), "disk_io", extra_specs
1356 new_flavor
= self
.nova
.flavors
.create(
1360 disk
=flavor_data
.get("disk", 0),
1361 ephemeral
=flavor_data
.get("ephemeral", 0),
1362 swap
=flavor_data
.get("swap", 0),
1363 is_public
=flavor_data
.get("is_public", True),
1367 new_flavor
.set_keys(extra_specs
)
1369 return new_flavor
.id
1370 except nvExceptions
.Conflict
as e
:
1371 if change_name_if_used
and retry
< max_retries
:
1374 self
._format
_exception
(e
)
1375 # except nvExceptions.BadRequest as e:
1377 ksExceptions
.ClientException
,
1378 nvExceptions
.ClientException
,
1382 self
._format
_exception
(e
)
1384 def delete_flavor(self
, flavor_id
):
1385 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id"""
1387 self
._reload
_connection
()
1388 self
.nova
.flavors
.delete(flavor_id
)
1391 # except nvExceptions.BadRequest as e:
1393 nvExceptions
.NotFound
,
1394 ksExceptions
.ClientException
,
1395 nvExceptions
.ClientException
,
1398 self
._format
_exception
(e
)
1400 def new_image(self
, image_dict
):
1402 Adds a tenant image to VIM. imge_dict is a dictionary with:
1404 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1405 location: path or URI
1406 public: "yes" or "no"
1407 metadata: metadata of the image
1408 Returns the image_id
1413 while retry
< max_retries
:
1416 self
._reload
_connection
()
1418 # determine format http://docs.openstack.org/developer/glance/formats.html
1419 if "disk_format" in image_dict
:
1420 disk_format
= image_dict
["disk_format"]
1421 else: # autodiscover based on extension
1422 if image_dict
["location"].endswith(".qcow2"):
1423 disk_format
= "qcow2"
1424 elif image_dict
["location"].endswith(".vhd"):
1426 elif image_dict
["location"].endswith(".vmdk"):
1427 disk_format
= "vmdk"
1428 elif image_dict
["location"].endswith(".vdi"):
1430 elif image_dict
["location"].endswith(".iso"):
1432 elif image_dict
["location"].endswith(".aki"):
1434 elif image_dict
["location"].endswith(".ari"):
1436 elif image_dict
["location"].endswith(".ami"):
1442 "new_image: '%s' loading from '%s'",
1444 image_dict
["location"],
1446 if self
.vim_type
== "VIO":
1447 container_format
= "bare"
1448 if "container_format" in image_dict
:
1449 container_format
= image_dict
["container_format"]
1451 new_image
= self
.glance
.images
.create(
1452 name
=image_dict
["name"],
1453 container_format
=container_format
,
1454 disk_format
=disk_format
,
1457 new_image
= self
.glance
.images
.create(name
=image_dict
["name"])
1459 if image_dict
["location"].startswith("http"):
1460 # TODO there is not a method to direct download. It must be downloaded locally with requests
1461 raise vimconn
.VimConnNotImplemented("Cannot create image from URL")
1463 with
open(image_dict
["location"]) as fimage
:
1464 self
.glance
.images
.upload(new_image
.id, fimage
)
1465 # new_image = self.glancev1.images.create(name=image_dict["name"], is_public=
1466 # image_dict.get("public","yes")=="yes",
1467 # container_format="bare", data=fimage, disk_format=disk_format)
1469 metadata_to_load
= image_dict
.get("metadata")
1471 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
1473 if self
.vim_type
== "VIO":
1474 metadata_to_load
["upload_location"] = image_dict
["location"]
1476 metadata_to_load
["location"] = image_dict
["location"]
1478 self
.glance
.images
.update(new_image
.id, **metadata_to_load
)
1482 nvExceptions
.Conflict
,
1483 ksExceptions
.ClientException
,
1484 nvExceptions
.ClientException
,
1486 self
._format
_exception
(e
)
1489 gl1Exceptions
.HTTPException
,
1490 gl1Exceptions
.CommunicationError
,
1493 if retry
== max_retries
:
1496 self
._format
_exception
(e
)
1497 except IOError as e
: # can not open the file
1498 raise vimconn
.VimConnConnectionException(
1499 "{}: {} for {}".format(type(e
).__name
__, e
, image_dict
["location"]),
1500 http_code
=vimconn
.HTTP_Bad_Request
,
1503 def delete_image(self
, image_id
):
1504 """Deletes a tenant image from openstack VIM. Returns the old id"""
1506 self
._reload
_connection
()
1507 self
.glance
.images
.delete(image_id
)
1511 nvExceptions
.NotFound
,
1512 ksExceptions
.ClientException
,
1513 nvExceptions
.ClientException
,
1514 gl1Exceptions
.CommunicationError
,
1515 gl1Exceptions
.HTTPNotFound
,
1517 ) as e
: # TODO remove
1518 self
._format
_exception
(e
)
1520 def get_image_id_from_path(self
, path
):
1521 """Get the image id from image path in the VIM database. Returns the image_id"""
1523 self
._reload
_connection
()
1524 images
= self
.glance
.images
.list()
1526 for image
in images
:
1527 if image
.metadata
.get("location") == path
:
1530 raise vimconn
.VimConnNotFoundException(
1531 "image with location '{}' not found".format(path
)
1534 ksExceptions
.ClientException
,
1535 nvExceptions
.ClientException
,
1536 gl1Exceptions
.CommunicationError
,
1539 self
._format
_exception
(e
)
1541 def get_image_list(self
, filter_dict
={}):
1542 """Obtain tenant images from VIM
1546 checksum: image checksum
1547 Returns the image list of dictionaries:
1548 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1551 self
.logger
.debug("Getting image list from VIM filter: '%s'", str(filter_dict
))
1554 self
._reload
_connection
()
1555 # filter_dict_os = filter_dict.copy()
1556 # First we filter by the available filter fields: name, id. The others are removed.
1557 image_list
= self
.glance
.images
.list()
1560 for image
in image_list
:
1562 if filter_dict
.get("name") and image
["name"] != filter_dict
["name"]:
1565 if filter_dict
.get("id") and image
["id"] != filter_dict
["id"]:
1569 filter_dict
.get("checksum")
1570 and image
["checksum"] != filter_dict
["checksum"]
1574 filtered_list
.append(image
.copy())
1575 except gl1Exceptions
.HTTPNotFound
:
1578 return filtered_list
1580 ksExceptions
.ClientException
,
1581 nvExceptions
.ClientException
,
1582 gl1Exceptions
.CommunicationError
,
1585 self
._format
_exception
(e
)
1587 def __wait_for_vm(self
, vm_id
, status
):
1588 """wait until vm is in the desired status and return True.
1589 If the VM gets in ERROR status, return false.
1590 If the timeout is reached generate an exception"""
1592 while elapsed_time
< server_timeout
:
1593 vm_status
= self
.nova
.servers
.get(vm_id
).status
1595 if vm_status
== status
:
1598 if vm_status
== "ERROR":
1604 # if we exceeded the timeout rollback
1605 if elapsed_time
>= server_timeout
:
1606 raise vimconn
.VimConnException(
1607 "Timeout waiting for instance " + vm_id
+ " to get " + status
,
1608 http_code
=vimconn
.HTTP_Request_Timeout
,
1611 def _get_openstack_availablity_zones(self
):
1613 Get from openstack availability zones available
1617 openstack_availability_zone
= self
.nova
.availability_zones
.list()
1618 openstack_availability_zone
= [
1620 for zone
in openstack_availability_zone
1621 if zone
.zoneName
!= "internal"
1624 return openstack_availability_zone
1628 def _set_availablity_zones(self
):
1630 Set vim availablity zone
1633 if "availability_zone" in self
.config
:
1634 vim_availability_zones
= self
.config
.get("availability_zone")
1636 if isinstance(vim_availability_zones
, str):
1637 self
.availability_zone
= [vim_availability_zones
]
1638 elif isinstance(vim_availability_zones
, list):
1639 self
.availability_zone
= vim_availability_zones
1641 self
.availability_zone
= self
._get
_openstack
_availablity
_zones
()
1643 def _get_vm_availability_zone(
1644 self
, availability_zone_index
, availability_zone_list
1647 Return thge availability zone to be used by the created VM.
1648 :return: The VIM availability zone to be used or None
1650 if availability_zone_index
is None:
1651 if not self
.config
.get("availability_zone"):
1653 elif isinstance(self
.config
.get("availability_zone"), str):
1654 return self
.config
["availability_zone"]
1656 # TODO consider using a different parameter at config for default AV and AV list match
1657 return self
.config
["availability_zone"][0]
1659 vim_availability_zones
= self
.availability_zone
1660 # check if VIM offer enough availability zones describe in the VNFD
1661 if vim_availability_zones
and len(availability_zone_list
) <= len(
1662 vim_availability_zones
1664 # check if all the names of NFV AV match VIM AV names
1665 match_by_index
= False
1666 for av
in availability_zone_list
:
1667 if av
not in vim_availability_zones
:
1668 match_by_index
= True
1672 return vim_availability_zones
[availability_zone_index
]
1674 return availability_zone_list
[availability_zone_index
]
1676 raise vimconn
.VimConnConflictException(
1677 "No enough availability zones at VIM for this deployment"
1690 availability_zone_index
=None,
1691 availability_zone_list
=None,
1693 """Adds a VM instance to VIM
1695 start: indicates if VM must start or boot in pause mode. Ignored
1696 image_id,flavor_id: iamge and flavor uuid
1697 net_list: list of interfaces, each one is a dictionary with:
1699 net_id: network uuid to connect
1700 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1701 model: interface model, ignored #TODO
1702 mac_address: used for SR-IOV ifaces #TODO for other types
1703 use: 'data', 'bridge', 'mgmt'
1704 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
1705 vim_id: filled/added by this function
1706 floating_ip: True/False (or it can be None)
1707 port_security: True/False
1708 'cloud_config': (optional) dictionary with:
1709 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1710 'users': (optional) list of users to be inserted, each item is a dict with:
1711 'name': (mandatory) user name,
1712 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1713 'user-data': (optional) string is a text script to be passed directly to cloud-init
1714 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1715 'dest': (mandatory) string with the destination absolute path
1716 'encoding': (optional, by default text). Can be one of:
1717 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1718 'content' (mandatory): string with the content of the file
1719 'permissions': (optional) string with file permissions, typically octal notation '0644'
1720 'owner': (optional) file owner, string with the format 'owner:group'
1721 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1722 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1723 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1724 'size': (mandatory) string with the size of the disk in GB
1725 'vim_id' (optional) should use this existing volume id
1726 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1727 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1728 availability_zone_index is None
1729 #TODO ip, security groups
1730 Returns a tuple with the instance identifier and created_items or raises an exception on error
1731 created_items can be None or a dictionary where this method can include key-values that will be passed to
1732 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1733 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1737 "new_vminstance input: image='%s' flavor='%s' nics='%s'",
1748 external_network
= []
1749 # ^list of external networks to be connected to instance, later on used to create floating_ip
1750 no_secured_ports
= [] # List of port-is with port-security disabled
1751 self
._reload
_connection
()
1752 # metadata_vpci = {} # For a specific neutron plugin
1753 block_device_mapping
= None
1755 for net
in net_list
:
1756 if not net
.get("net_id"): # skip non connected iface
1760 "network_id": net
["net_id"],
1761 "name": net
.get("name"),
1762 "admin_state_up": True,
1766 self
.config
.get("security_groups")
1767 and net
.get("port_security") is not False
1768 and not self
.config
.get("no_port_security_extension")
1770 if not self
.security_groups_id
:
1771 self
._get
_ids
_from
_name
()
1773 port_dict
["security_groups"] = self
.security_groups_id
1775 if net
["type"] == "virtual":
1778 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
1779 elif net
["type"] == "VF" or net
["type"] == "SR-IOV": # for VF
1781 # if "VF" not in metadata_vpci:
1782 # metadata_vpci["VF"]=[]
1783 # metadata_vpci["VF"].append([ net["vpci"], "" ])
1784 port_dict
["binding:vnic_type"] = "direct"
1786 # VIO specific Changes
1787 if self
.vim_type
== "VIO":
1788 # Need to create port with port_security_enabled = False and no-security-groups
1789 port_dict
["port_security_enabled"] = False
1790 port_dict
["provider_security_groups"] = []
1791 port_dict
["security_groups"] = []
1792 else: # For PT PCI-PASSTHROUGH
1794 # if "PF" not in metadata_vpci:
1795 # metadata_vpci["PF"]=[]
1796 # metadata_vpci["PF"].append([ net["vpci"], "" ])
1797 port_dict
["binding:vnic_type"] = "direct-physical"
1799 if not port_dict
["name"]:
1800 port_dict
["name"] = name
1802 if net
.get("mac_address"):
1803 port_dict
["mac_address"] = net
["mac_address"]
1805 if net
.get("ip_address"):
1806 port_dict
["fixed_ips"] = [{"ip_address": net
["ip_address"]}]
1807 # TODO add "subnet_id": <subnet_id>
1809 new_port
= self
.neutron
.create_port({"port": port_dict
})
1810 created_items
["port:" + str(new_port
["port"]["id"])] = True
1811 net
["mac_adress"] = new_port
["port"]["mac_address"]
1812 net
["vim_id"] = new_port
["port"]["id"]
1813 # if try to use a network without subnetwork, it will return a emtpy list
1814 fixed_ips
= new_port
["port"].get("fixed_ips")
1817 net
["ip"] = fixed_ips
[0].get("ip_address")
1821 port
= {"port-id": new_port
["port"]["id"]}
1822 if float(self
.nova
.api_version
.get_string()) >= 2.32:
1823 port
["tag"] = new_port
["port"]["name"]
1825 net_list_vim
.append(port
)
1827 if net
.get("floating_ip", False):
1828 net
["exit_on_floating_ip_error"] = True
1829 external_network
.append(net
)
1830 elif net
["use"] == "mgmt" and self
.config
.get("use_floating_ip"):
1831 net
["exit_on_floating_ip_error"] = False
1832 external_network
.append(net
)
1833 net
["floating_ip"] = self
.config
.get("use_floating_ip")
1835 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
1837 # As a workaround we wait until the VM is active and then disable the port-security
1838 if net
.get("port_security") is False and not self
.config
.get(
1839 "no_port_security_extension"
1841 no_secured_ports
.append(
1843 new_port
["port"]["id"],
1844 net
.get("port_security_disable_strategy"),
1849 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1850 # if len(metadata["pci_assignement"]) >255:
1851 # #limit the metadata size
1852 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1853 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1857 "name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1866 config_drive
, userdata
= self
._create
_user
_data
(cloud_config
)
1868 # Create additional volumes in case these are present in disk_list
1869 base_disk_index
= ord("b")
1871 block_device_mapping
= {}
1872 for disk
in disk_list
:
1873 if disk
.get("vim_id"):
1874 block_device_mapping
["_vd" + chr(base_disk_index
)] = disk
[
1878 if "image_id" in disk
:
1879 volume
= self
.cinder
.volumes
.create(
1881 name
=name
+ "_vd" + chr(base_disk_index
),
1882 imageRef
=disk
["image_id"],
1885 volume
= self
.cinder
.volumes
.create(
1887 name
=name
+ "_vd" + chr(base_disk_index
),
1890 created_items
["volume:" + str(volume
.id)] = True
1891 block_device_mapping
["_vd" + chr(base_disk_index
)] = volume
.id
1893 base_disk_index
+= 1
1895 # Wait until created volumes are with status available
1897 while elapsed_time
< volume_timeout
:
1898 for created_item
in created_items
:
1899 v
, _
, volume_id
= created_item
.partition(":")
1901 if self
.cinder
.volumes
.get(volume_id
).status
!= "available":
1903 else: # all ready: break from while
1909 # If we exceeded the timeout rollback
1910 if elapsed_time
>= volume_timeout
:
1911 raise vimconn
.VimConnException(
1912 "Timeout creating volumes for instance " + name
,
1913 http_code
=vimconn
.HTTP_Request_Timeout
,
1916 # get availability Zone
1917 vm_av_zone
= self
._get
_vm
_availability
_zone
(
1918 availability_zone_index
, availability_zone_list
1922 "nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
1923 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
1924 "block_device_mapping={})".format(
1929 self
.config
.get("security_groups"),
1931 self
.config
.get("keypair"),
1934 block_device_mapping
,
1937 server
= self
.nova
.servers
.create(
1942 security_groups
=self
.config
.get("security_groups"),
1943 # TODO remove security_groups in future versions. Already at neutron port
1944 availability_zone
=vm_av_zone
,
1945 key_name
=self
.config
.get("keypair"),
1947 config_drive
=config_drive
,
1948 block_device_mapping
=block_device_mapping
,
1949 ) # , description=description)
1951 vm_start_time
= time
.time()
1952 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1953 if no_secured_ports
:
1954 self
.__wait
_for
_vm
(server
.id, "ACTIVE")
1956 for port
in no_secured_ports
:
1958 "port": {"port_security_enabled": False, "security_groups": None}
1961 if port
[1] == "allow-address-pairs":
1963 "port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}
1967 self
.neutron
.update_port(port
[0], port_update
)
1969 raise vimconn
.VimConnException(
1970 "It was not possible to disable port security for port {}".format(
1975 # print "DONE :-)", server
1978 for floating_network
in external_network
:
1981 floating_ip_retries
= 3
1982 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
1985 floating_ips
= self
.neutron
.list_floatingips().get(
1988 random
.shuffle(floating_ips
) # randomize
1989 for fip
in floating_ips
:
1992 or fip
.get("tenant_id") != server
.tenant_id
1996 if isinstance(floating_network
["floating_ip"], str):
1998 fip
.get("floating_network_id")
1999 != floating_network
["floating_ip"]
2003 free_floating_ip
= fip
["id"]
2007 isinstance(floating_network
["floating_ip"], str)
2008 and floating_network
["floating_ip"].lower() != "true"
2010 pool_id
= floating_network
["floating_ip"]
2012 # Find the external network
2013 external_nets
= list()
2015 for net
in self
.neutron
.list_networks()["networks"]:
2016 if net
["router:external"]:
2017 external_nets
.append(net
)
2019 if len(external_nets
) == 0:
2020 raise vimconn
.VimConnException(
2021 "Cannot create floating_ip automatically since "
2022 "no external network is present",
2023 http_code
=vimconn
.HTTP_Conflict
,
2026 if len(external_nets
) > 1:
2027 raise vimconn
.VimConnException(
2028 "Cannot create floating_ip automatically since "
2029 "multiple external networks are present",
2030 http_code
=vimconn
.HTTP_Conflict
,
2033 pool_id
= external_nets
[0].get("id")
2037 "floating_network_id": pool_id
,
2038 "tenant_id": server
.tenant_id
,
2043 # self.logger.debug("Creating floating IP")
2044 new_floating_ip
= self
.neutron
.create_floatingip(param
)
2045 free_floating_ip
= new_floating_ip
["floatingip"]["id"]
2047 "floating_ip:" + str(free_floating_ip
)
2049 except Exception as e
:
2050 raise vimconn
.VimConnException(
2052 + ": Cannot create new floating_ip "
2054 http_code
=vimconn
.HTTP_Conflict
,
2058 # for race condition ensure not already assigned
2059 fip
= self
.neutron
.show_floatingip(free_floating_ip
)
2061 if fip
["floatingip"]["port_id"]:
2064 # the vim_id key contains the neutron.port_id
2065 self
.neutron
.update_floatingip(
2067 {"floatingip": {"port_id": floating_network
["vim_id"]}},
2069 # for race condition ensure not re-assigned to other VM after 5 seconds
2071 fip
= self
.neutron
.show_floatingip(free_floating_ip
)
2074 fip
["floatingip"]["port_id"]
2075 != floating_network
["vim_id"]
2078 "floating_ip {} re-assigned to other port".format(
2085 "Assigned floating_ip {} to VM {}".format(
2086 free_floating_ip
, server
.id
2090 except Exception as e
:
2091 # openstack need some time after VM creation to assign an IP. So retry if fails
2092 vm_status
= self
.nova
.servers
.get(server
.id).status
2094 if vm_status
not in ("ACTIVE", "ERROR"):
2095 if time
.time() - vm_start_time
< server_timeout
:
2098 elif floating_ip_retries
> 0:
2099 floating_ip_retries
-= 1
2102 raise vimconn
.VimConnException(
2103 "Cannot create floating_ip: {} {}".format(
2106 http_code
=vimconn
.HTTP_Conflict
,
2109 except Exception as e
:
2110 if not floating_network
["exit_on_floating_ip_error"]:
2111 self
.logger
.error("Cannot create floating_ip. %s", str(e
))
2116 return server
.id, created_items
2117 # except nvExceptions.NotFound as e:
2118 # error_value=-vimconn.HTTP_Not_Found
2119 # error_text= "vm instance %s not found" % vm_id
2120 # except TypeError as e:
2121 # raise vimconn.VimConnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
2123 except Exception as e
:
2126 server_id
= server
.id
2129 self
.delete_vminstance(server_id
, created_items
)
2130 except Exception as e2
:
2131 self
.logger
.error("new_vminstance rollback fail {}".format(e2
))
2133 self
._format
_exception
(e
)
2135 def get_vminstance(self
, vm_id
):
2136 """Returns the VM instance information from VIM"""
2137 # self.logger.debug("Getting VM from VIM")
2139 self
._reload
_connection
()
2140 server
= self
.nova
.servers
.find(id=vm_id
)
2141 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
2143 return server
.to_dict()
2145 ksExceptions
.ClientException
,
2146 nvExceptions
.ClientException
,
2147 nvExceptions
.NotFound
,
2150 self
._format
_exception
(e
)
2152 def get_vminstance_console(self
, vm_id
, console_type
="vnc"):
2154 Get a console for the virtual machine
2156 vm_id: uuid of the VM
2157 console_type, can be:
2158 "novnc" (by default), "xvpvnc" for VNC types,
2159 "rdp-html5" for RDP types, "spice-html5" for SPICE types
2160 Returns dict with the console parameters:
2161 protocol: ssh, ftp, http, https, ...
2162 server: usually ip address
2163 port: the http, ssh, ... port
2164 suffix: extra text, e.g. the http path and query string
2166 self
.logger
.debug("Getting VM CONSOLE from VIM")
2169 self
._reload
_connection
()
2170 server
= self
.nova
.servers
.find(id=vm_id
)
2172 if console_type
is None or console_type
== "novnc":
2173 console_dict
= server
.get_vnc_console("novnc")
2174 elif console_type
== "xvpvnc":
2175 console_dict
= server
.get_vnc_console(console_type
)
2176 elif console_type
== "rdp-html5":
2177 console_dict
= server
.get_rdp_console(console_type
)
2178 elif console_type
== "spice-html5":
2179 console_dict
= server
.get_spice_console(console_type
)
2181 raise vimconn
.VimConnException(
2182 "console type '{}' not allowed".format(console_type
),
2183 http_code
=vimconn
.HTTP_Bad_Request
,
2186 console_dict1
= console_dict
.get("console")
2189 console_url
= console_dict1
.get("url")
2193 protocol_index
= console_url
.find("//")
2195 console_url
[protocol_index
+ 2 :].find("/") + protocol_index
+ 2
2198 console_url
[protocol_index
+ 2 : suffix_index
].find(":")
2203 if protocol_index
< 0 or port_index
< 0 or suffix_index
< 0:
2205 -vimconn
.HTTP_Internal_Server_Error
,
2206 "Unexpected response from VIM",
2210 "protocol": console_url
[0:protocol_index
],
2211 "server": console_url
[protocol_index
+ 2 : port_index
],
2212 "port": console_url
[port_index
:suffix_index
],
2213 "suffix": console_url
[suffix_index
+ 1 :],
2218 raise vimconn
.VimConnUnexpectedResponse("Unexpected response from VIM")
2220 nvExceptions
.NotFound
,
2221 ksExceptions
.ClientException
,
2222 nvExceptions
.ClientException
,
2223 nvExceptions
.BadRequest
,
2226 self
._format
_exception
(e
)
2228 def delete_vminstance(self
, vm_id
, created_items
=None):
2229 """Removes a VM instance from VIM. Returns the old identifier"""
2230 # print "osconnector: Getting VM from VIM"
2231 if created_items
is None:
2235 self
._reload
_connection
()
2236 # delete VM ports attached to this networks before the virtual machine
2237 for k
, v
in created_items
.items():
2238 if not v
: # skip already deleted
2242 k_item
, _
, k_id
= k
.partition(":")
2243 if k_item
== "port":
2244 self
.neutron
.delete_port(k_id
)
2245 except Exception as e
:
2247 "Error deleting port: {}: {}".format(type(e
).__name
__, e
)
2250 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
2251 # #dettach volumes attached
2252 # server = self.nova.servers.get(vm_id)
2253 # volumes_attached_dict = server._info["os-extended-volumes:volumes_attached"] #volume["id"]
2254 # #for volume in volumes_attached_dict:
2255 # # self.cinder.volumes.detach(volume["id"])
2258 self
.nova
.servers
.delete(vm_id
)
2260 # delete volumes. Although having detached, they should have in active status before deleting
2261 # we ensure in this loop
2265 while keep_waiting
and elapsed_time
< volume_timeout
:
2266 keep_waiting
= False
2268 for k
, v
in created_items
.items():
2269 if not v
: # skip already deleted
2273 k_item
, _
, k_id
= k
.partition(":")
2274 if k_item
== "volume":
2275 if self
.cinder
.volumes
.get(k_id
).status
!= "available":
2278 self
.cinder
.volumes
.delete(k_id
)
2279 created_items
[k
] = None
2280 elif k_item
== "floating_ip": # floating ip
2281 self
.neutron
.delete_floatingip(k_id
)
2282 created_items
[k
] = None
2284 except Exception as e
:
2285 self
.logger
.error("Error deleting {}: {}".format(k
, e
))
2293 nvExceptions
.NotFound
,
2294 ksExceptions
.ClientException
,
2295 nvExceptions
.ClientException
,
2298 self
._format
_exception
(e
)
2300 def refresh_vms_status(self
, vm_list
):
2301 """Get the status of the virtual machines and their interfaces/ports
2302 Params: the list of VM identifiers
2303 Returns a dictionary with:
2304 vm_id: #VIM id of this Virtual Machine
2305 status: #Mandatory. Text with one of:
2306 # DELETED (not found at vim)
2307 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2308 # OTHER (Vim reported other status not understood)
2309 # ERROR (VIM indicates an ERROR status)
2310 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2311 # CREATING (on building process), ERROR
2312 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2314 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2315 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2317 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2318 mac_address: #Text format XX:XX:XX:XX:XX:XX
2319 vim_net_id: #network id where this interface is connected
2320 vim_interface_id: #interface/port VIM id
2321 ip_address: #null, or text with IPv4, IPv6 address
2322 compute_node: #identification of compute node where PF,VF interface is allocated
2323 pci: #PCI address of the NIC that hosts the PF,VF
2324 vlan: #physical VLAN used for VF
2328 "refresh_vms status: Getting tenant VM instance information from VIM"
2331 for vm_id
in vm_list
:
2335 vm_vim
= self
.get_vminstance(vm_id
)
2337 if vm_vim
["status"] in vmStatus2manoFormat
:
2338 vm
["status"] = vmStatus2manoFormat
[vm_vim
["status"]]
2340 vm
["status"] = "OTHER"
2341 vm
["error_msg"] = "VIM status reported " + vm_vim
["status"]
2343 vm_vim
.pop("OS-EXT-SRV-ATTR:user_data", None)
2344 vm_vim
.pop("user_data", None)
2345 vm
["vim_info"] = self
.serialize(vm_vim
)
2347 vm
["interfaces"] = []
2348 if vm_vim
.get("fault"):
2349 vm
["error_msg"] = str(vm_vim
["fault"])
2353 self
._reload
_connection
()
2354 port_dict
= self
.neutron
.list_ports(device_id
=vm_id
)
2356 for port
in port_dict
["ports"]:
2358 interface
["vim_info"] = self
.serialize(port
)
2359 interface
["mac_address"] = port
.get("mac_address")
2360 interface
["vim_net_id"] = port
["network_id"]
2361 interface
["vim_interface_id"] = port
["id"]
2362 # check if OS-EXT-SRV-ATTR:host is there,
2363 # in case of non-admin credentials, it will be missing
2365 if vm_vim
.get("OS-EXT-SRV-ATTR:host"):
2366 interface
["compute_node"] = vm_vim
["OS-EXT-SRV-ATTR:host"]
2368 interface
["pci"] = None
2370 # check if binding:profile is there,
2371 # in case of non-admin credentials, it will be missing
2372 if port
.get("binding:profile"):
2373 if port
["binding:profile"].get("pci_slot"):
2374 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
2376 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
2377 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
2378 pci
= port
["binding:profile"]["pci_slot"]
2379 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
2380 interface
["pci"] = pci
2382 interface
["vlan"] = None
2384 if port
.get("binding:vif_details"):
2385 interface
["vlan"] = port
["binding:vif_details"].get("vlan")
2387 # Get vlan from network in case not present in port for those old openstacks and cases where
2388 # it is needed vlan at PT
2389 if not interface
["vlan"]:
2390 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
2391 network
= self
.neutron
.show_network(port
["network_id"])
2394 network
["network"].get("provider:network_type")
2397 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
2398 interface
["vlan"] = network
["network"].get(
2399 "provider:segmentation_id"
2403 # look for floating ip address
2405 floating_ip_dict
= self
.neutron
.list_floatingips(
2409 if floating_ip_dict
.get("floatingips"):
2411 floating_ip_dict
["floatingips"][0].get(
2412 "floating_ip_address"
2418 for subnet
in port
["fixed_ips"]:
2419 ips
.append(subnet
["ip_address"])
2421 interface
["ip_address"] = ";".join(ips
)
2422 vm
["interfaces"].append(interface
)
2423 except Exception as e
:
2425 "Error getting vm interface information {}: {}".format(
2430 except vimconn
.VimConnNotFoundException
as e
:
2431 self
.logger
.error("Exception getting vm status: %s", str(e
))
2432 vm
["status"] = "DELETED"
2433 vm
["error_msg"] = str(e
)
2434 except vimconn
.VimConnException
as e
:
2435 self
.logger
.error("Exception getting vm status: %s", str(e
))
2436 vm
["status"] = "VIM_ERROR"
2437 vm
["error_msg"] = str(e
)
2443 def action_vminstance(self
, vm_id
, action_dict
, created_items
={}):
2444 """Send and action over a VM instance from VIM
2445 Returns None or the console dict if the action was successfully sent to the VIM"""
2446 self
.logger
.debug("Action over VM '%s': %s", vm_id
, str(action_dict
))
2449 self
._reload
_connection
()
2450 server
= self
.nova
.servers
.find(id=vm_id
)
2452 if "start" in action_dict
:
2453 if action_dict
["start"] == "rebuild":
2456 if server
.status
== "PAUSED":
2458 elif server
.status
== "SUSPENDED":
2460 elif server
.status
== "SHUTOFF":
2462 elif "pause" in action_dict
:
2464 elif "resume" in action_dict
:
2466 elif "shutoff" in action_dict
or "shutdown" in action_dict
:
2468 elif "forceOff" in action_dict
:
2469 server
.stop() # TODO
2470 elif "terminate" in action_dict
:
2472 elif "createImage" in action_dict
:
2473 server
.create_image()
2474 # "path":path_schema,
2475 # "description":description_schema,
2476 # "name":name_schema,
2477 # "metadata":metadata_schema,
2478 # "imageRef": id_schema,
2479 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
2480 elif "rebuild" in action_dict
:
2481 server
.rebuild(server
.image
["id"])
2482 elif "reboot" in action_dict
:
2483 server
.reboot() # reboot_type="SOFT"
2484 elif "console" in action_dict
:
2485 console_type
= action_dict
["console"]
2487 if console_type
is None or console_type
== "novnc":
2488 console_dict
= server
.get_vnc_console("novnc")
2489 elif console_type
== "xvpvnc":
2490 console_dict
= server
.get_vnc_console(console_type
)
2491 elif console_type
== "rdp-html5":
2492 console_dict
= server
.get_rdp_console(console_type
)
2493 elif console_type
== "spice-html5":
2494 console_dict
= server
.get_spice_console(console_type
)
2496 raise vimconn
.VimConnException(
2497 "console type '{}' not allowed".format(console_type
),
2498 http_code
=vimconn
.HTTP_Bad_Request
,
2502 console_url
= console_dict
["console"]["url"]
2504 protocol_index
= console_url
.find("//")
2506 console_url
[protocol_index
+ 2 :].find("/") + protocol_index
+ 2
2509 console_url
[protocol_index
+ 2 : suffix_index
].find(":")
2514 if protocol_index
< 0 or port_index
< 0 or suffix_index
< 0:
2515 raise vimconn
.VimConnException(
2516 "Unexpected response from VIM " + str(console_dict
)
2520 "protocol": console_url
[0:protocol_index
],
2521 "server": console_url
[protocol_index
+ 2 : port_index
],
2522 "port": int(console_url
[port_index
+ 1 : suffix_index
]),
2523 "suffix": console_url
[suffix_index
+ 1 :],
2526 return console_dict2
2528 raise vimconn
.VimConnException(
2529 "Unexpected response from VIM " + str(console_dict
)
2534 ksExceptions
.ClientException
,
2535 nvExceptions
.ClientException
,
2536 nvExceptions
.NotFound
,
2539 self
._format
_exception
(e
)
2540 # TODO insert exception vimconn.HTTP_Unauthorized
2542 # ###### VIO Specific Changes #########
2543 def _generate_vlanID(self
):
2545 Method to get unused vlanID
2553 networks
= self
.get_network_list()
2555 for net
in networks
:
2556 if net
.get("provider:segmentation_id"):
2557 usedVlanIDs
.append(net
.get("provider:segmentation_id"))
2559 used_vlanIDs
= set(usedVlanIDs
)
2561 # find unused VLAN ID
2562 for vlanID_range
in self
.config
.get("dataplane_net_vlan_range"):
2564 start_vlanid
, end_vlanid
= map(
2565 int, vlanID_range
.replace(" ", "").split("-")
2568 for vlanID
in range(start_vlanid
, end_vlanid
+ 1):
2569 if vlanID
not in used_vlanIDs
:
2571 except Exception as exp
:
2572 raise vimconn
.VimConnException(
2573 "Exception {} occurred while generating VLAN ID.".format(exp
)
2576 raise vimconn
.VimConnConflictException(
2577 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
2578 self
.config
.get("dataplane_net_vlan_range")
2582 def _generate_multisegment_vlanID(self
):
2584 Method to get unused vlanID
2592 networks
= self
.get_network_list()
2593 for net
in networks
:
2594 if net
.get("provider:network_type") == "vlan" and net
.get(
2595 "provider:segmentation_id"
2597 usedVlanIDs
.append(net
.get("provider:segmentation_id"))
2598 elif net
.get("segments"):
2599 for segment
in net
.get("segments"):
2600 if segment
.get("provider:network_type") == "vlan" and segment
.get(
2601 "provider:segmentation_id"
2603 usedVlanIDs
.append(segment
.get("provider:segmentation_id"))
2605 used_vlanIDs
= set(usedVlanIDs
)
2607 # find unused VLAN ID
2608 for vlanID_range
in self
.config
.get("multisegment_vlan_range"):
2610 start_vlanid
, end_vlanid
= map(
2611 int, vlanID_range
.replace(" ", "").split("-")
2614 for vlanID
in range(start_vlanid
, end_vlanid
+ 1):
2615 if vlanID
not in used_vlanIDs
:
2617 except Exception as exp
:
2618 raise vimconn
.VimConnException(
2619 "Exception {} occurred while generating VLAN ID.".format(exp
)
2622 raise vimconn
.VimConnConflictException(
2623 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
2624 self
.config
.get("multisegment_vlan_range")
2628 def _validate_vlan_ranges(self
, input_vlan_range
, text_vlan_range
):
2630 Method to validate user given vlanID ranges
2634 for vlanID_range
in input_vlan_range
:
2635 vlan_range
= vlanID_range
.replace(" ", "")
2637 vlanID_pattern
= r
"(\d)*-(\d)*$"
2638 match_obj
= re
.match(vlanID_pattern
, vlan_range
)
2640 raise vimconn
.VimConnConflictException(
2641 "Invalid VLAN range for {}: {}.You must provide "
2642 "'{}' in format [start_ID - end_ID].".format(
2643 text_vlan_range
, vlanID_range
, text_vlan_range
2647 start_vlanid
, end_vlanid
= map(int, vlan_range
.split("-"))
2648 if start_vlanid
<= 0:
2649 raise vimconn
.VimConnConflictException(
2650 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
2651 "networks valid IDs are 1 to 4094 ".format(
2652 text_vlan_range
, vlanID_range
2656 if end_vlanid
> 4094:
2657 raise vimconn
.VimConnConflictException(
2658 "Invalid VLAN range for {}: {}. End VLAN ID can not be "
2659 "greater than 4094. For VLAN networks valid IDs are 1 to 4094 ".format(
2660 text_vlan_range
, vlanID_range
2664 if start_vlanid
> end_vlanid
:
2665 raise vimconn
.VimConnConflictException(
2666 "Invalid VLAN range for {}: {}. You must provide '{}'"
2667 " in format start_ID - end_ID and start_ID < end_ID ".format(
2668 text_vlan_range
, vlanID_range
, text_vlan_range
2672 # NOT USED FUNCTIONS
2674 def new_external_port(self
, port_data
):
2675 """Adds a external port to VIM
2676 Returns the port identifier"""
2677 # TODO openstack if needed
2679 -vimconn
.HTTP_Internal_Server_Error
,
2680 "osconnector.new_external_port() not implemented",
2683 def connect_port_network(self
, port_id
, network_id
, admin
=False):
2684 """Connects a external port to a network
2685 Returns status code of the VIM response"""
2686 # TODO openstack if needed
2688 -vimconn
.HTTP_Internal_Server_Error
,
2689 "osconnector.connect_port_network() not implemented",
2692 def new_user(self
, user_name
, user_passwd
, tenant_id
=None):
2693 """Adds a new user to openstack VIM
2694 Returns the user identifier"""
2695 self
.logger
.debug("osconnector: Adding a new user to VIM")
2698 self
._reload
_connection
()
2699 user
= self
.keystone
.users
.create(
2700 user_name
, password
=user_passwd
, default_project
=tenant_id
2702 # self.keystone.tenants.add_user(self.k_creds["username"], #role)
2705 except ksExceptions
.ConnectionError
as e
:
2706 error_value
= -vimconn
.HTTP_Bad_Request
2710 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2712 except ksExceptions
.ClientException
as e
: # TODO remove
2713 error_value
= -vimconn
.HTTP_Bad_Request
2717 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2720 # TODO insert exception vimconn.HTTP_Unauthorized
2721 # if reaching here is because an exception
2722 self
.logger
.debug("new_user " + error_text
)
2724 return error_value
, error_text
2726 def delete_user(self
, user_id
):
2727 """Delete a user from openstack VIM
2728 Returns the user identifier"""
2730 print("osconnector: Deleting a user from VIM")
2733 self
._reload
_connection
()
2734 self
.keystone
.users
.delete(user_id
)
2737 except ksExceptions
.ConnectionError
as e
:
2738 error_value
= -vimconn
.HTTP_Bad_Request
2742 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2744 except ksExceptions
.NotFound
as e
:
2745 error_value
= -vimconn
.HTTP_Not_Found
2749 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2751 except ksExceptions
.ClientException
as e
: # TODO remove
2752 error_value
= -vimconn
.HTTP_Bad_Request
2756 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2759 # TODO insert exception vimconn.HTTP_Unauthorized
2760 # if reaching here is because an exception
2761 self
.logger
.debug("delete_tenant " + error_text
)
2763 return error_value
, error_text
2765 def get_hosts_info(self
):
2766 """Get the information of deployed hosts
2767 Returns the hosts content"""
2769 print("osconnector: Getting Host info from VIM")
2773 self
._reload
_connection
()
2774 hypervisors
= self
.nova
.hypervisors
.list()
2776 for hype
in hypervisors
:
2777 h_list
.append(hype
.to_dict())
2779 return 1, {"hosts": h_list
}
2780 except nvExceptions
.NotFound
as e
:
2781 error_value
= -vimconn
.HTTP_Not_Found
2782 error_text
= str(e
) if len(e
.args
) == 0 else str(e
.args
[0])
2783 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
2784 error_value
= -vimconn
.HTTP_Bad_Request
2788 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2791 # TODO insert exception vimconn.HTTP_Unauthorized
2792 # if reaching here is because an exception
2793 self
.logger
.debug("get_hosts_info " + error_text
)
2795 return error_value
, error_text
2797 def get_hosts(self
, vim_tenant
):
2798 """Get the hosts and deployed instances
2799 Returns the hosts content"""
2800 r
, hype_dict
= self
.get_hosts_info()
2805 hypervisors
= hype_dict
["hosts"]
2808 servers
= self
.nova
.servers
.list()
2809 for hype
in hypervisors
:
2810 for server
in servers
:
2812 server
.to_dict()["OS-EXT-SRV-ATTR:hypervisor_hostname"]
2813 == hype
["hypervisor_hostname"]
2816 hype
["vm"].append(server
.id)
2818 hype
["vm"] = [server
.id]
2821 except nvExceptions
.NotFound
as e
:
2822 error_value
= -vimconn
.HTTP_Not_Found
2823 error_text
= str(e
) if len(e
.args
) == 0 else str(e
.args
[0])
2824 except (ksExceptions
.ClientException
, nvExceptions
.ClientException
) as e
:
2825 error_value
= -vimconn
.HTTP_Bad_Request
2829 + (str(e
) if len(e
.args
) == 0 else str(e
.args
[0]))
2832 # TODO insert exception vimconn.HTTP_Unauthorized
2833 # if reaching here is because an exception
2834 self
.logger
.debug("get_hosts " + error_text
)
2836 return error_value
, error_text
2838 def new_classification(self
, name
, ctype
, definition
):
2840 "Adding a new (Traffic) Classification to VIM, named %s", name
2845 self
._reload
_connection
()
2847 if ctype
not in supportedClassificationTypes
:
2848 raise vimconn
.VimConnNotSupportedException(
2849 "OpenStack VIM connector does not support provided "
2850 "Classification Type {}, supported ones are: {}".format(
2851 ctype
, supportedClassificationTypes
2855 if not self
._validate
_classification
(ctype
, definition
):
2856 raise vimconn
.VimConnException(
2857 "Incorrect Classification definition for the type specified."
2860 classification_dict
= definition
2861 classification_dict
["name"] = name
2862 new_class
= self
.neutron
.create_sfc_flow_classifier(
2863 {"flow_classifier": classification_dict
}
2866 return new_class
["flow_classifier"]["id"]
2868 neExceptions
.ConnectionFailed
,
2869 ksExceptions
.ClientException
,
2870 neExceptions
.NeutronException
,
2873 self
.logger
.error("Creation of Classification failed.")
2874 self
._format
_exception
(e
)
2876 def get_classification(self
, class_id
):
2877 self
.logger
.debug(" Getting Classification %s from VIM", class_id
)
2878 filter_dict
= {"id": class_id
}
2879 class_list
= self
.get_classification_list(filter_dict
)
2881 if len(class_list
) == 0:
2882 raise vimconn
.VimConnNotFoundException(
2883 "Classification '{}' not found".format(class_id
)
2885 elif len(class_list
) > 1:
2886 raise vimconn
.VimConnConflictException(
2887 "Found more than one Classification with this criteria"
2890 classification
= class_list
[0]
2892 return classification
2894 def get_classification_list(self
, filter_dict
={}):
2896 "Getting Classifications from VIM filter: '%s'", str(filter_dict
)
2900 filter_dict_os
= filter_dict
.copy()
2901 self
._reload
_connection
()
2903 if self
.api_version3
and "tenant_id" in filter_dict_os
:
2904 filter_dict_os
["project_id"] = filter_dict_os
.pop("tenant_id")
2906 classification_dict
= self
.neutron
.list_sfc_flow_classifiers(
2909 classification_list
= classification_dict
["flow_classifiers"]
2910 self
.__classification
_os
2mano
(classification_list
)
2912 return classification_list
2914 neExceptions
.ConnectionFailed
,
2915 ksExceptions
.ClientException
,
2916 neExceptions
.NeutronException
,
2919 self
._format
_exception
(e
)
2921 def delete_classification(self
, class_id
):
2922 self
.logger
.debug("Deleting Classification '%s' from VIM", class_id
)
2925 self
._reload
_connection
()
2926 self
.neutron
.delete_sfc_flow_classifier(class_id
)
2930 neExceptions
.ConnectionFailed
,
2931 neExceptions
.NeutronException
,
2932 ksExceptions
.ClientException
,
2933 neExceptions
.NeutronException
,
2936 self
._format
_exception
(e
)
2938 def new_sfi(self
, name
, ingress_ports
, egress_ports
, sfc_encap
=True):
2940 "Adding a new Service Function Instance to VIM, named '%s'", name
2945 self
._reload
_connection
()
2951 if len(ingress_ports
) != 1:
2952 raise vimconn
.VimConnNotSupportedException(
2953 "OpenStack VIM connector can only have 1 ingress port per SFI"
2956 if len(egress_ports
) != 1:
2957 raise vimconn
.VimConnNotSupportedException(
2958 "OpenStack VIM connector can only have 1 egress port per SFI"
2963 "ingress": ingress_ports
[0],
2964 "egress": egress_ports
[0],
2965 "service_function_parameters": {"correlation": correlation
},
2967 new_sfi
= self
.neutron
.create_sfc_port_pair({"port_pair": sfi_dict
})
2969 return new_sfi
["port_pair"]["id"]
2971 neExceptions
.ConnectionFailed
,
2972 ksExceptions
.ClientException
,
2973 neExceptions
.NeutronException
,
2978 self
.neutron
.delete_sfc_port_pair(new_sfi
["port_pair"]["id"])
2981 "Creation of Service Function Instance failed, with "
2982 "subsequent deletion failure as well."
2985 self
._format
_exception
(e
)
2987 def get_sfi(self
, sfi_id
):
2988 self
.logger
.debug("Getting Service Function Instance %s from VIM", sfi_id
)
2989 filter_dict
= {"id": sfi_id
}
2990 sfi_list
= self
.get_sfi_list(filter_dict
)
2992 if len(sfi_list
) == 0:
2993 raise vimconn
.VimConnNotFoundException(
2994 "Service Function Instance '{}' not found".format(sfi_id
)
2996 elif len(sfi_list
) > 1:
2997 raise vimconn
.VimConnConflictException(
2998 "Found more than one Service Function Instance with this criteria"
3005 def get_sfi_list(self
, filter_dict
={}):
3007 "Getting Service Function Instances from VIM filter: '%s'", str(filter_dict
)
3011 self
._reload
_connection
()
3012 filter_dict_os
= filter_dict
.copy()
3014 if self
.api_version3
and "tenant_id" in filter_dict_os
:
3015 filter_dict_os
["project_id"] = filter_dict_os
.pop("tenant_id")
3017 sfi_dict
= self
.neutron
.list_sfc_port_pairs(**filter_dict_os
)
3018 sfi_list
= sfi_dict
["port_pairs"]
3019 self
.__sfi
_os
2mano
(sfi_list
)
3023 neExceptions
.ConnectionFailed
,
3024 ksExceptions
.ClientException
,
3025 neExceptions
.NeutronException
,
3028 self
._format
_exception
(e
)
3030 def delete_sfi(self
, sfi_id
):
3031 self
.logger
.debug("Deleting Service Function Instance '%s' from VIM", sfi_id
)
3034 self
._reload
_connection
()
3035 self
.neutron
.delete_sfc_port_pair(sfi_id
)
3039 neExceptions
.ConnectionFailed
,
3040 neExceptions
.NeutronException
,
3041 ksExceptions
.ClientException
,
3042 neExceptions
.NeutronException
,
3045 self
._format
_exception
(e
)
3047 def new_sf(self
, name
, sfis
, sfc_encap
=True):
3048 self
.logger
.debug("Adding a new Service Function to VIM, named '%s'", name
)
3052 self
._reload
_connection
()
3053 # correlation = None
3055 # correlation = "nsh"
3057 for instance
in sfis
:
3058 sfi
= self
.get_sfi(instance
)
3060 if sfi
.get("sfc_encap") != sfc_encap
:
3061 raise vimconn
.VimConnNotSupportedException(
3062 "OpenStack VIM connector requires all SFIs of the "
3063 "same SF to share the same SFC Encapsulation"
3066 sf_dict
= {"name": name
, "port_pairs": sfis
}
3067 new_sf
= self
.neutron
.create_sfc_port_pair_group(
3068 {"port_pair_group": sf_dict
}
3071 return new_sf
["port_pair_group"]["id"]
3073 neExceptions
.ConnectionFailed
,
3074 ksExceptions
.ClientException
,
3075 neExceptions
.NeutronException
,
3080 self
.neutron
.delete_sfc_port_pair_group(
3081 new_sf
["port_pair_group"]["id"]
3085 "Creation of Service Function failed, with "
3086 "subsequent deletion failure as well."
3089 self
._format
_exception
(e
)
3091 def get_sf(self
, sf_id
):
3092 self
.logger
.debug("Getting Service Function %s from VIM", sf_id
)
3093 filter_dict
= {"id": sf_id
}
3094 sf_list
= self
.get_sf_list(filter_dict
)
3096 if len(sf_list
) == 0:
3097 raise vimconn
.VimConnNotFoundException(
3098 "Service Function '{}' not found".format(sf_id
)
3100 elif len(sf_list
) > 1:
3101 raise vimconn
.VimConnConflictException(
3102 "Found more than one Service Function with this criteria"
3109 def get_sf_list(self
, filter_dict
={}):
3111 "Getting Service Function from VIM filter: '%s'", str(filter_dict
)
3115 self
._reload
_connection
()
3116 filter_dict_os
= filter_dict
.copy()
3118 if self
.api_version3
and "tenant_id" in filter_dict_os
:
3119 filter_dict_os
["project_id"] = filter_dict_os
.pop("tenant_id")
3121 sf_dict
= self
.neutron
.list_sfc_port_pair_groups(**filter_dict_os
)
3122 sf_list
= sf_dict
["port_pair_groups"]
3123 self
.__sf
_os
2mano
(sf_list
)
3127 neExceptions
.ConnectionFailed
,
3128 ksExceptions
.ClientException
,
3129 neExceptions
.NeutronException
,
3132 self
._format
_exception
(e
)
3134 def delete_sf(self
, sf_id
):
3135 self
.logger
.debug("Deleting Service Function '%s' from VIM", sf_id
)
3138 self
._reload
_connection
()
3139 self
.neutron
.delete_sfc_port_pair_group(sf_id
)
3143 neExceptions
.ConnectionFailed
,
3144 neExceptions
.NeutronException
,
3145 ksExceptions
.ClientException
,
3146 neExceptions
.NeutronException
,
3149 self
._format
_exception
(e
)
3151 def new_sfp(self
, name
, classifications
, sfs
, sfc_encap
=True, spi
=None):
3152 self
.logger
.debug("Adding a new Service Function Path to VIM, named '%s'", name
)
3156 self
._reload
_connection
()
3157 # In networking-sfc the MPLS encapsulation is legacy
3158 # should be used when no full SFC Encapsulation is intended
3159 correlation
= "mpls"
3166 "flow_classifiers": classifications
,
3167 "port_pair_groups": sfs
,
3168 "chain_parameters": {"correlation": correlation
},
3172 sfp_dict
["chain_id"] = spi
3174 new_sfp
= self
.neutron
.create_sfc_port_chain({"port_chain": sfp_dict
})
3176 return new_sfp
["port_chain"]["id"]
3178 neExceptions
.ConnectionFailed
,
3179 ksExceptions
.ClientException
,
3180 neExceptions
.NeutronException
,
3185 self
.neutron
.delete_sfc_port_chain(new_sfp
["port_chain"]["id"])
3188 "Creation of Service Function Path failed, with "
3189 "subsequent deletion failure as well."
3192 self
._format
_exception
(e
)
3194 def get_sfp(self
, sfp_id
):
3195 self
.logger
.debug(" Getting Service Function Path %s from VIM", sfp_id
)
3197 filter_dict
= {"id": sfp_id
}
3198 sfp_list
= self
.get_sfp_list(filter_dict
)
3200 if len(sfp_list
) == 0:
3201 raise vimconn
.VimConnNotFoundException(
3202 "Service Function Path '{}' not found".format(sfp_id
)
3204 elif len(sfp_list
) > 1:
3205 raise vimconn
.VimConnConflictException(
3206 "Found more than one Service Function Path with this criteria"
3213 def get_sfp_list(self
, filter_dict
={}):
3215 "Getting Service Function Paths from VIM filter: '%s'", str(filter_dict
)
3219 self
._reload
_connection
()
3220 filter_dict_os
= filter_dict
.copy()
3222 if self
.api_version3
and "tenant_id" in filter_dict_os
:
3223 filter_dict_os
["project_id"] = filter_dict_os
.pop("tenant_id")
3225 sfp_dict
= self
.neutron
.list_sfc_port_chains(**filter_dict_os
)
3226 sfp_list
= sfp_dict
["port_chains"]
3227 self
.__sfp
_os
2mano
(sfp_list
)
3231 neExceptions
.ConnectionFailed
,
3232 ksExceptions
.ClientException
,
3233 neExceptions
.NeutronException
,
3236 self
._format
_exception
(e
)
3238 def delete_sfp(self
, sfp_id
):
3239 self
.logger
.debug("Deleting Service Function Path '%s' from VIM", sfp_id
)
3242 self
._reload
_connection
()
3243 self
.neutron
.delete_sfc_port_chain(sfp_id
)
3247 neExceptions
.ConnectionFailed
,
3248 neExceptions
.NeutronException
,
3249 ksExceptions
.ClientException
,
3250 neExceptions
.NeutronException
,
3253 self
._format
_exception
(e
)
3255 def refresh_sfps_status(self
, sfp_list
):
3256 """Get the status of the service function path
3257 Params: the list of sfp identifiers
3258 Returns a dictionary with:
3259 vm_id: #VIM id of this service function path
3260 status: #Mandatory. Text with one of:
3261 # DELETED (not found at vim)
3262 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3263 # OTHER (Vim reported other status not understood)
3264 # ERROR (VIM indicates an ERROR status)
3266 # CREATING (on building process)
3267 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3268 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
3272 "refresh_sfps status: Getting tenant SFP information from VIM"
3275 for sfp_id
in sfp_list
:
3279 sfp_vim
= self
.get_sfp(sfp_id
)
3282 sfp
["status"] = vmStatus2manoFormat
["ACTIVE"]
3284 sfp
["status"] = "OTHER"
3285 sfp
["error_msg"] = "VIM status reported " + sfp
["status"]
3287 sfp
["vim_info"] = self
.serialize(sfp_vim
)
3289 if sfp_vim
.get("fault"):
3290 sfp
["error_msg"] = str(sfp_vim
["fault"])
3291 except vimconn
.VimConnNotFoundException
as e
:
3292 self
.logger
.error("Exception getting sfp status: %s", str(e
))
3293 sfp
["status"] = "DELETED"
3294 sfp
["error_msg"] = str(e
)
3295 except vimconn
.VimConnException
as e
:
3296 self
.logger
.error("Exception getting sfp status: %s", str(e
))
3297 sfp
["status"] = "VIM_ERROR"
3298 sfp
["error_msg"] = str(e
)
3300 sfp_dict
[sfp_id
] = sfp
3304 def refresh_sfis_status(self
, sfi_list
):
3305 """Get the status of the service function instances
3306 Params: the list of sfi identifiers
3307 Returns a dictionary with:
3308 vm_id: #VIM id of this service function instance
3309 status: #Mandatory. Text with one of:
3310 # DELETED (not found at vim)
3311 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3312 # OTHER (Vim reported other status not understood)
3313 # ERROR (VIM indicates an ERROR status)
3315 # CREATING (on building process)
3316 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3317 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3321 "refresh_sfis status: Getting tenant sfi information from VIM"
3324 for sfi_id
in sfi_list
:
3328 sfi_vim
= self
.get_sfi(sfi_id
)
3331 sfi
["status"] = vmStatus2manoFormat
["ACTIVE"]
3333 sfi
["status"] = "OTHER"
3334 sfi
["error_msg"] = "VIM status reported " + sfi
["status"]
3336 sfi
["vim_info"] = self
.serialize(sfi_vim
)
3338 if sfi_vim
.get("fault"):
3339 sfi
["error_msg"] = str(sfi_vim
["fault"])
3340 except vimconn
.VimConnNotFoundException
as e
:
3341 self
.logger
.error("Exception getting sfi status: %s", str(e
))
3342 sfi
["status"] = "DELETED"
3343 sfi
["error_msg"] = str(e
)
3344 except vimconn
.VimConnException
as e
:
3345 self
.logger
.error("Exception getting sfi status: %s", str(e
))
3346 sfi
["status"] = "VIM_ERROR"
3347 sfi
["error_msg"] = str(e
)
3349 sfi_dict
[sfi_id
] = sfi
3353 def refresh_sfs_status(self
, sf_list
):
3354 """Get the status of the service functions
3355 Params: the list of sf identifiers
3356 Returns a dictionary with:
3357 vm_id: #VIM id of this service function
3358 status: #Mandatory. Text with one of:
3359 # DELETED (not found at vim)
3360 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3361 # OTHER (Vim reported other status not understood)
3362 # ERROR (VIM indicates an ERROR status)
3364 # CREATING (on building process)
3365 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3366 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3369 self
.logger
.debug("refresh_sfs status: Getting tenant sf information from VIM")
3371 for sf_id
in sf_list
:
3375 sf_vim
= self
.get_sf(sf_id
)
3378 sf
["status"] = vmStatus2manoFormat
["ACTIVE"]
3380 sf
["status"] = "OTHER"
3381 sf
["error_msg"] = "VIM status reported " + sf_vim
["status"]
3383 sf
["vim_info"] = self
.serialize(sf_vim
)
3385 if sf_vim
.get("fault"):
3386 sf
["error_msg"] = str(sf_vim
["fault"])
3387 except vimconn
.VimConnNotFoundException
as e
:
3388 self
.logger
.error("Exception getting sf status: %s", str(e
))
3389 sf
["status"] = "DELETED"
3390 sf
["error_msg"] = str(e
)
3391 except vimconn
.VimConnException
as e
:
3392 self
.logger
.error("Exception getting sf status: %s", str(e
))
3393 sf
["status"] = "VIM_ERROR"
3394 sf
["error_msg"] = str(e
)
3400 def refresh_classifications_status(self
, classification_list
):
3401 """Get the status of the classifications
3402 Params: the list of classification identifiers
3403 Returns a dictionary with:
3404 vm_id: #VIM id of this classifier
3405 status: #Mandatory. Text with one of:
3406 # DELETED (not found at vim)
3407 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3408 # OTHER (Vim reported other status not understood)
3409 # ERROR (VIM indicates an ERROR status)
3411 # CREATING (on building process)
3412 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3413 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3415 classification_dict
= {}
3417 "refresh_classifications status: Getting tenant classification information from VIM"
3420 for classification_id
in classification_list
:
3424 classification_vim
= self
.get_classification(classification_id
)
3426 if classification_vim
:
3427 classification
["status"] = vmStatus2manoFormat
["ACTIVE"]
3429 classification
["status"] = "OTHER"
3430 classification
["error_msg"] = (
3431 "VIM status reported " + classification
["status"]
3434 classification
["vim_info"] = self
.serialize(classification_vim
)
3436 if classification_vim
.get("fault"):
3437 classification
["error_msg"] = str(classification_vim
["fault"])
3438 except vimconn
.VimConnNotFoundException
as e
:
3439 self
.logger
.error("Exception getting classification status: %s", str(e
))
3440 classification
["status"] = "DELETED"
3441 classification
["error_msg"] = str(e
)
3442 except vimconn
.VimConnException
as e
:
3443 self
.logger
.error("Exception getting classification status: %s", str(e
))
3444 classification
["status"] = "VIM_ERROR"
3445 classification
["error_msg"] = str(e
)
3447 classification_dict
[classification_id
] = classification
3449 return classification_dict