Fix flake8 errors in vCD connector
[osm/RO.git] / RO-VIM-openstack / osm_rovim_openstack / vimconn_openstack.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
5 # This file is part of openmano
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
18 # under the License.
19 ##
20
21 """
22 osconnector implements all the methods to interact with openstack using the python-neutronclient.
23
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)
31 """
32
33 import copy
34 from http.client import HTTPException
35 import logging
36 from pprint import pformat
37 import random
38 import re
39 import time
40
41 from cinderclient import client as cClient
42 from glanceclient import client as glClient
43 import glanceclient.exc as gl1Exceptions
44 from keystoneauth1 import session
45 from keystoneauth1.identity import v2, v3
46 import keystoneclient.exceptions as ksExceptions
47 import keystoneclient.v2_0.client as ksClient_v2
48 import keystoneclient.v3.client as ksClient_v3
49 import netaddr
50 from neutronclient.common import exceptions as neExceptions
51 from neutronclient.neutron import client as neClient
52 from novaclient import client as nClient, exceptions as nvExceptions
53 from osm_ro_plugin import vimconn
54 from requests.exceptions import ConnectionError
55 import yaml
56
57 __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes, xFlow Research, Igor D.C., Eduardo Sousa"
58 __date__ = "$22-sep-2017 23:59:59$"
59
60 """contain the openstack virtual machine status to openmano status"""
61 vmStatus2manoFormat = {
62 "ACTIVE": "ACTIVE",
63 "PAUSED": "PAUSED",
64 "SUSPENDED": "SUSPENDED",
65 "SHUTOFF": "INACTIVE",
66 "BUILD": "BUILD",
67 "ERROR": "ERROR",
68 "DELETED": "DELETED",
69 }
70 netStatus2manoFormat = {
71 "ACTIVE": "ACTIVE",
72 "PAUSED": "PAUSED",
73 "INACTIVE": "INACTIVE",
74 "BUILD": "BUILD",
75 "ERROR": "ERROR",
76 "DELETED": "DELETED",
77 }
78
79 supportedClassificationTypes = ["legacy_flow_classifier"]
80
81 # global var to have a timeout creating and deleting volumes
82 volume_timeout = 1800
83 server_timeout = 1800
84
85
86 class SafeDumper(yaml.SafeDumper):
87 def represent_data(self, data):
88 # Openstack APIs use custom subclasses of dict and YAML safe dumper
89 # is designed to not handle that (reference issue 142 of pyyaml)
90 if isinstance(data, dict) and data.__class__ != dict:
91 # A simple solution is to convert those items back to dicts
92 data = dict(data.items())
93
94 return super(SafeDumper, self).represent_data(data)
95
96
97 class vimconnector(vimconn.VimConnector):
98 def __init__(
99 self,
100 uuid,
101 name,
102 tenant_id,
103 tenant_name,
104 url,
105 url_admin=None,
106 user=None,
107 passwd=None,
108 log_level=None,
109 config={},
110 persistent_info={},
111 ):
112 """using common constructor parameters. In this case
113 'url' is the keystone authorization url,
114 'url_admin' is not use
115 """
116 api_version = config.get("APIversion")
117
118 if api_version and api_version not in ("v3.3", "v2.0", "2", "3"):
119 raise vimconn.VimConnException(
120 "Invalid value '{}' for config:APIversion. "
121 "Allowed values are 'v3.3', 'v2.0', '2' or '3'".format(api_version)
122 )
123
124 vim_type = config.get("vim_type")
125
126 if vim_type and vim_type not in ("vio", "VIO"):
127 raise vimconn.VimConnException(
128 "Invalid value '{}' for config:vim_type."
129 "Allowed values are 'vio' or 'VIO'".format(vim_type)
130 )
131
132 if config.get("dataplane_net_vlan_range") is not None:
133 # validate vlan ranges provided by user
134 self._validate_vlan_ranges(
135 config.get("dataplane_net_vlan_range"), "dataplane_net_vlan_range"
136 )
137
138 if config.get("multisegment_vlan_range") is not None:
139 # validate vlan ranges provided by user
140 self._validate_vlan_ranges(
141 config.get("multisegment_vlan_range"), "multisegment_vlan_range"
142 )
143
144 vimconn.VimConnector.__init__(
145 self,
146 uuid,
147 name,
148 tenant_id,
149 tenant_name,
150 url,
151 url_admin,
152 user,
153 passwd,
154 log_level,
155 config,
156 )
157
158 if self.config.get("insecure") and self.config.get("ca_cert"):
159 raise vimconn.VimConnException(
160 "options insecure and ca_cert are mutually exclusive"
161 )
162
163 self.verify = True
164
165 if self.config.get("insecure"):
166 self.verify = False
167
168 if self.config.get("ca_cert"):
169 self.verify = self.config.get("ca_cert")
170
171 if not url:
172 raise TypeError("url param can not be NoneType")
173
174 self.persistent_info = persistent_info
175 self.availability_zone = persistent_info.get("availability_zone", None)
176 self.session = persistent_info.get("session", {"reload_client": True})
177 self.my_tenant_id = self.session.get("my_tenant_id")
178 self.nova = self.session.get("nova")
179 self.neutron = self.session.get("neutron")
180 self.cinder = self.session.get("cinder")
181 self.glance = self.session.get("glance")
182 # self.glancev1 = self.session.get("glancev1")
183 self.keystone = self.session.get("keystone")
184 self.api_version3 = self.session.get("api_version3")
185 self.vim_type = self.config.get("vim_type")
186
187 if self.vim_type:
188 self.vim_type = self.vim_type.upper()
189
190 if self.config.get("use_internal_endpoint"):
191 self.endpoint_type = "internalURL"
192 else:
193 self.endpoint_type = None
194
195 logging.getLogger("urllib3").setLevel(logging.WARNING)
196 logging.getLogger("keystoneauth").setLevel(logging.WARNING)
197 logging.getLogger("novaclient").setLevel(logging.WARNING)
198 self.logger = logging.getLogger("ro.vim.openstack")
199
200 # allow security_groups to be a list or a single string
201 if isinstance(self.config.get("security_groups"), str):
202 self.config["security_groups"] = [self.config["security_groups"]]
203
204 self.security_groups_id = None
205
206 # ###### VIO Specific Changes #########
207 if self.vim_type == "VIO":
208 self.logger = logging.getLogger("ro.vim.vio")
209
210 if log_level:
211 self.logger.setLevel(getattr(logging, log_level))
212
213 def __getitem__(self, index):
214 """Get individuals parameters.
215 Throw KeyError"""
216 if index == "project_domain_id":
217 return self.config.get("project_domain_id")
218 elif index == "user_domain_id":
219 return self.config.get("user_domain_id")
220 else:
221 return vimconn.VimConnector.__getitem__(self, index)
222
223 def __setitem__(self, index, value):
224 """Set individuals parameters and it is marked as dirty so to force connection reload.
225 Throw KeyError"""
226 if index == "project_domain_id":
227 self.config["project_domain_id"] = value
228 elif index == "user_domain_id":
229 self.config["user_domain_id"] = value
230 else:
231 vimconn.VimConnector.__setitem__(self, index, value)
232
233 self.session["reload_client"] = True
234
235 def serialize(self, value):
236 """Serialization of python basic types.
237
238 In the case value is not serializable a message will be logged and a
239 simple representation of the data that cannot be converted back to
240 python is returned.
241 """
242 if isinstance(value, str):
243 return value
244
245 try:
246 return yaml.dump(
247 value, Dumper=SafeDumper, default_flow_style=True, width=256
248 )
249 except yaml.representer.RepresenterError:
250 self.logger.debug(
251 "The following entity cannot be serialized in YAML:\n\n%s\n\n",
252 pformat(value),
253 exc_info=True,
254 )
255
256 return str(value)
257
258 def _reload_connection(self):
259 """Called before any operation, it check if credentials has changed
260 Throw keystoneclient.apiclient.exceptions.AuthorizationFailure
261 """
262 # TODO control the timing and possible token timeout, but it seams that python client does this task for us :-)
263 if self.session["reload_client"]:
264 if self.config.get("APIversion"):
265 self.api_version3 = (
266 self.config["APIversion"] == "v3.3"
267 or self.config["APIversion"] == "3"
268 )
269 else: # get from ending auth_url that end with v3 or with v2.0
270 self.api_version3 = self.url.endswith("/v3") or self.url.endswith(
271 "/v3/"
272 )
273
274 self.session["api_version3"] = self.api_version3
275
276 if self.api_version3:
277 if self.config.get("project_domain_id") or self.config.get(
278 "project_domain_name"
279 ):
280 project_domain_id_default = None
281 else:
282 project_domain_id_default = "default"
283
284 if self.config.get("user_domain_id") or self.config.get(
285 "user_domain_name"
286 ):
287 user_domain_id_default = None
288 else:
289 user_domain_id_default = "default"
290 auth = v3.Password(
291 auth_url=self.url,
292 username=self.user,
293 password=self.passwd,
294 project_name=self.tenant_name,
295 project_id=self.tenant_id,
296 project_domain_id=self.config.get(
297 "project_domain_id", project_domain_id_default
298 ),
299 user_domain_id=self.config.get(
300 "user_domain_id", user_domain_id_default
301 ),
302 project_domain_name=self.config.get("project_domain_name"),
303 user_domain_name=self.config.get("user_domain_name"),
304 )
305 else:
306 auth = v2.Password(
307 auth_url=self.url,
308 username=self.user,
309 password=self.passwd,
310 tenant_name=self.tenant_name,
311 tenant_id=self.tenant_id,
312 )
313
314 sess = session.Session(auth=auth, verify=self.verify)
315 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
316 # Titanium cloud and StarlingX
317 region_name = self.config.get("region_name")
318
319 if self.api_version3:
320 self.keystone = ksClient_v3.Client(
321 session=sess,
322 endpoint_type=self.endpoint_type,
323 region_name=region_name,
324 )
325 else:
326 self.keystone = ksClient_v2.Client(
327 session=sess, endpoint_type=self.endpoint_type
328 )
329
330 self.session["keystone"] = self.keystone
331 # In order to enable microversion functionality an explicit microversion must be specified in "config".
332 # This implementation approach is due to the warning message in
333 # https://developer.openstack.org/api-guide/compute/microversions.html
334 # where it is stated that microversion backwards compatibility is not guaranteed and clients should
335 # always require an specific microversion.
336 # To be able to use "device role tagging" functionality define "microversion: 2.32" in datacenter config
337 version = self.config.get("microversion")
338
339 if not version:
340 version = "2.1"
341
342 # addedd region_name to keystone, nova, neutron and cinder to support distributed cloud for Wind River
343 # Titanium cloud and StarlingX
344 self.nova = self.session["nova"] = nClient.Client(
345 str(version),
346 session=sess,
347 endpoint_type=self.endpoint_type,
348 region_name=region_name,
349 )
350 self.neutron = self.session["neutron"] = neClient.Client(
351 "2.0",
352 session=sess,
353 endpoint_type=self.endpoint_type,
354 region_name=region_name,
355 )
356 self.cinder = self.session["cinder"] = cClient.Client(
357 2,
358 session=sess,
359 endpoint_type=self.endpoint_type,
360 region_name=region_name,
361 )
362
363 try:
364 self.my_tenant_id = self.session["my_tenant_id"] = sess.get_project_id()
365 except Exception:
366 self.logger.error("Cannot get project_id from session", exc_info=True)
367
368 if self.endpoint_type == "internalURL":
369 glance_service_id = self.keystone.services.list(name="glance")[0].id
370 glance_endpoint = self.keystone.endpoints.list(
371 glance_service_id, interface="internal"
372 )[0].url
373 else:
374 glance_endpoint = None
375
376 self.glance = self.session["glance"] = glClient.Client(
377 2, session=sess, endpoint=glance_endpoint
378 )
379 # using version 1 of glance client in new_image()
380 # self.glancev1 = self.session["glancev1"] = glClient.Client("1", session=sess,
381 # endpoint=glance_endpoint)
382 self.session["reload_client"] = False
383 self.persistent_info["session"] = self.session
384 # add availablity zone info inside self.persistent_info
385 self._set_availablity_zones()
386 self.persistent_info["availability_zone"] = self.availability_zone
387 # force to get again security_groups_ids next time they are needed
388 self.security_groups_id = None
389
390 def __net_os2mano(self, net_list_dict):
391 """Transform the net openstack format to mano format
392 net_list_dict can be a list of dict or a single dict"""
393 if type(net_list_dict) is dict:
394 net_list_ = (net_list_dict,)
395 elif type(net_list_dict) is list:
396 net_list_ = net_list_dict
397 else:
398 raise TypeError("param net_list_dict must be a list or a dictionary")
399 for net in net_list_:
400 if net.get("provider:network_type") == "vlan":
401 net["type"] = "data"
402 else:
403 net["type"] = "bridge"
404
405 def __classification_os2mano(self, class_list_dict):
406 """Transform the openstack format (Flow Classifier) to mano format
407 (Classification) class_list_dict can be a list of dict or a single dict
408 """
409 if isinstance(class_list_dict, dict):
410 class_list_ = [class_list_dict]
411 elif isinstance(class_list_dict, list):
412 class_list_ = class_list_dict
413 else:
414 raise TypeError("param class_list_dict must be a list or a dictionary")
415 for classification in class_list_:
416 id = classification.pop("id")
417 name = classification.pop("name")
418 description = classification.pop("description")
419 project_id = classification.pop("project_id")
420 tenant_id = classification.pop("tenant_id")
421 original_classification = copy.deepcopy(classification)
422 classification.clear()
423 classification["ctype"] = "legacy_flow_classifier"
424 classification["definition"] = original_classification
425 classification["id"] = id
426 classification["name"] = name
427 classification["description"] = description
428 classification["project_id"] = project_id
429 classification["tenant_id"] = tenant_id
430
431 def __sfi_os2mano(self, sfi_list_dict):
432 """Transform the openstack format (Port Pair) to mano format (SFI)
433 sfi_list_dict can be a list of dict or a single dict
434 """
435 if isinstance(sfi_list_dict, dict):
436 sfi_list_ = [sfi_list_dict]
437 elif isinstance(sfi_list_dict, list):
438 sfi_list_ = sfi_list_dict
439 else:
440 raise TypeError("param sfi_list_dict must be a list or a dictionary")
441
442 for sfi in sfi_list_:
443 sfi["ingress_ports"] = []
444 sfi["egress_ports"] = []
445
446 if sfi.get("ingress"):
447 sfi["ingress_ports"].append(sfi["ingress"])
448
449 if sfi.get("egress"):
450 sfi["egress_ports"].append(sfi["egress"])
451
452 del sfi["ingress"]
453 del sfi["egress"]
454 params = sfi.get("service_function_parameters")
455 sfc_encap = False
456
457 if params:
458 correlation = params.get("correlation")
459
460 if correlation:
461 sfc_encap = True
462
463 sfi["sfc_encap"] = sfc_encap
464 del sfi["service_function_parameters"]
465
466 def __sf_os2mano(self, sf_list_dict):
467 """Transform the openstack format (Port Pair Group) to mano format (SF)
468 sf_list_dict can be a list of dict or a single dict
469 """
470 if isinstance(sf_list_dict, dict):
471 sf_list_ = [sf_list_dict]
472 elif isinstance(sf_list_dict, list):
473 sf_list_ = sf_list_dict
474 else:
475 raise TypeError("param sf_list_dict must be a list or a dictionary")
476
477 for sf in sf_list_:
478 del sf["port_pair_group_parameters"]
479 sf["sfis"] = sf["port_pairs"]
480 del sf["port_pairs"]
481
482 def __sfp_os2mano(self, sfp_list_dict):
483 """Transform the openstack format (Port Chain) to mano format (SFP)
484 sfp_list_dict can be a list of dict or a single dict
485 """
486 if isinstance(sfp_list_dict, dict):
487 sfp_list_ = [sfp_list_dict]
488 elif isinstance(sfp_list_dict, list):
489 sfp_list_ = sfp_list_dict
490 else:
491 raise TypeError("param sfp_list_dict must be a list or a dictionary")
492
493 for sfp in sfp_list_:
494 params = sfp.pop("chain_parameters")
495 sfc_encap = False
496
497 if params:
498 correlation = params.get("correlation")
499
500 if correlation:
501 sfc_encap = True
502
503 sfp["sfc_encap"] = sfc_encap
504 sfp["spi"] = sfp.pop("chain_id")
505 sfp["classifications"] = sfp.pop("flow_classifiers")
506 sfp["service_functions"] = sfp.pop("port_pair_groups")
507
508 # placeholder for now; read TODO note below
509 def _validate_classification(self, type, definition):
510 # only legacy_flow_classifier Type is supported at this point
511 return True
512 # TODO(igordcard): this method should be an abstract method of an
513 # abstract Classification class to be implemented by the specific
514 # Types. Also, abstract vimconnector should call the validation
515 # method before the implemented VIM connectors are called.
516
517 def _format_exception(self, exception):
518 """Transform a keystone, nova, neutron exception into a vimconn exception discovering the cause"""
519 message_error = str(exception)
520 tip = ""
521
522 if isinstance(
523 exception,
524 (
525 neExceptions.NetworkNotFoundClient,
526 nvExceptions.NotFound,
527 ksExceptions.NotFound,
528 gl1Exceptions.HTTPNotFound,
529 ),
530 ):
531 raise vimconn.VimConnNotFoundException(
532 type(exception).__name__ + ": " + message_error
533 )
534 elif isinstance(
535 exception,
536 (
537 HTTPException,
538 gl1Exceptions.HTTPException,
539 gl1Exceptions.CommunicationError,
540 ConnectionError,
541 ksExceptions.ConnectionError,
542 neExceptions.ConnectionFailed,
543 ),
544 ):
545 if type(exception).__name__ == "SSLError":
546 tip = " (maybe option 'insecure' must be added to the VIM)"
547
548 raise vimconn.VimConnConnectionException(
549 "Invalid URL or credentials{}: {}".format(tip, message_error)
550 )
551 elif isinstance(
552 exception,
553 (
554 KeyError,
555 nvExceptions.BadRequest,
556 ksExceptions.BadRequest,
557 ),
558 ):
559 raise vimconn.VimConnException(
560 type(exception).__name__ + ": " + message_error
561 )
562 elif isinstance(
563 exception,
564 (
565 nvExceptions.ClientException,
566 ksExceptions.ClientException,
567 neExceptions.NeutronException,
568 ),
569 ):
570 raise vimconn.VimConnUnexpectedResponse(
571 type(exception).__name__ + ": " + message_error
572 )
573 elif isinstance(exception, nvExceptions.Conflict):
574 raise vimconn.VimConnConflictException(
575 type(exception).__name__ + ": " + message_error
576 )
577 elif isinstance(exception, vimconn.VimConnException):
578 raise exception
579 else: # ()
580 self.logger.error("General Exception " + message_error, exc_info=True)
581
582 raise vimconn.VimConnConnectionException(
583 type(exception).__name__ + ": " + message_error
584 )
585
586 def _get_ids_from_name(self):
587 """
588 Obtain ids from name of tenant and security_groups. Store at self .security_groups_id"
589 :return: None
590 """
591 # get tenant_id if only tenant_name is supplied
592 self._reload_connection()
593
594 if not self.my_tenant_id:
595 raise vimconn.VimConnConnectionException(
596 "Error getting tenant information from name={} id={}".format(
597 self.tenant_name, self.tenant_id
598 )
599 )
600
601 if self.config.get("security_groups") and not self.security_groups_id:
602 # convert from name to id
603 neutron_sg_list = self.neutron.list_security_groups(
604 tenant_id=self.my_tenant_id
605 )["security_groups"]
606
607 self.security_groups_id = []
608 for sg in self.config.get("security_groups"):
609 for neutron_sg in neutron_sg_list:
610 if sg in (neutron_sg["id"], neutron_sg["name"]):
611 self.security_groups_id.append(neutron_sg["id"])
612 break
613 else:
614 self.security_groups_id = None
615
616 raise vimconn.VimConnConnectionException(
617 "Not found security group {} for this tenant".format(sg)
618 )
619
620 def check_vim_connectivity(self):
621 # just get network list to check connectivity and credentials
622 self.get_network_list(filter_dict={})
623
624 def get_tenant_list(self, filter_dict={}):
625 """Obtain tenants of VIM
626 filter_dict can contain the following keys:
627 name: filter by tenant name
628 id: filter by tenant uuid/id
629 <other VIM specific>
630 Returns the tenant list of dictionaries: [{'name':'<name>, 'id':'<id>, ...}, ...]
631 """
632 self.logger.debug("Getting tenants from VIM filter: '%s'", str(filter_dict))
633
634 try:
635 self._reload_connection()
636
637 if self.api_version3:
638 project_class_list = self.keystone.projects.list(
639 name=filter_dict.get("name")
640 )
641 else:
642 project_class_list = self.keystone.tenants.findall(**filter_dict)
643
644 project_list = []
645
646 for project in project_class_list:
647 if filter_dict.get("id") and filter_dict["id"] != project.id:
648 continue
649
650 project_list.append(project.to_dict())
651
652 return project_list
653 except (
654 ksExceptions.ConnectionError,
655 ksExceptions.ClientException,
656 ConnectionError,
657 ) as e:
658 self._format_exception(e)
659
660 def new_tenant(self, tenant_name, tenant_description):
661 """Adds a new tenant to openstack VIM. Returns the tenant identifier"""
662 self.logger.debug("Adding a new tenant name: %s", tenant_name)
663
664 try:
665 self._reload_connection()
666
667 if self.api_version3:
668 project = self.keystone.projects.create(
669 tenant_name,
670 self.config.get("project_domain_id", "default"),
671 description=tenant_description,
672 is_domain=False,
673 )
674 else:
675 project = self.keystone.tenants.create(tenant_name, tenant_description)
676
677 return project.id
678 except (
679 ksExceptions.ConnectionError,
680 ksExceptions.ClientException,
681 ksExceptions.BadRequest,
682 ConnectionError,
683 ) as e:
684 self._format_exception(e)
685
686 def delete_tenant(self, tenant_id):
687 """Delete a tenant from openstack VIM. Returns the old tenant identifier"""
688 self.logger.debug("Deleting tenant %s from VIM", tenant_id)
689
690 try:
691 self._reload_connection()
692
693 if self.api_version3:
694 self.keystone.projects.delete(tenant_id)
695 else:
696 self.keystone.tenants.delete(tenant_id)
697
698 return tenant_id
699 except (
700 ksExceptions.ConnectionError,
701 ksExceptions.ClientException,
702 ksExceptions.NotFound,
703 ConnectionError,
704 ) as e:
705 self._format_exception(e)
706
707 def new_network(
708 self,
709 net_name,
710 net_type,
711 ip_profile=None,
712 shared=False,
713 provider_network_profile=None,
714 ):
715 """Adds a tenant network to VIM
716 Params:
717 'net_name': name of the network
718 'net_type': one of:
719 'bridge': overlay isolated network
720 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
721 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
722 'ip_profile': is a dict containing the IP parameters of the network
723 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
724 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
725 'gateway_address': (Optional) ip_schema, that is X.X.X.X
726 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
727 'dhcp_enabled': True or False
728 'dhcp_start_address': ip_schema, first IP to grant
729 'dhcp_count': number of IPs to grant.
730 'shared': if this network can be seen/use by other tenants/organization
731 'provider_network_profile': (optional) contains {segmentation-id: vlan, network-type: vlan|vxlan,
732 physical-network: physnet-label}
733 Returns a tuple with the network identifier and created_items, or raises an exception on error
734 created_items can be None or a dictionary where this method can include key-values that will be passed to
735 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
736 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
737 as not present.
738 """
739 self.logger.debug(
740 "Adding a new network to VIM name '%s', type '%s'", net_name, net_type
741 )
742 # self.logger.debug(">>>>>>>>>>>>>>>>>> IP profile %s", str(ip_profile))
743
744 try:
745 vlan = None
746
747 if provider_network_profile:
748 vlan = provider_network_profile.get("segmentation-id")
749
750 new_net = None
751 created_items = {}
752 self._reload_connection()
753 network_dict = {"name": net_name, "admin_state_up": True}
754
755 if net_type in ("data", "ptp"):
756 provider_physical_network = None
757
758 if provider_network_profile and provider_network_profile.get(
759 "physical-network"
760 ):
761 provider_physical_network = provider_network_profile.get(
762 "physical-network"
763 )
764
765 # provider-network must be one of the dataplane_physcial_netowrk if this is a list. If it is string
766 # or not declared, just ignore the checking
767 if (
768 isinstance(
769 self.config.get("dataplane_physical_net"), (tuple, list)
770 )
771 and provider_physical_network
772 not in self.config["dataplane_physical_net"]
773 ):
774 raise vimconn.VimConnConflictException(
775 "Invalid parameter 'provider-network:physical-network' "
776 "for network creation. '{}' is not one of the declared "
777 "list at VIM_config:dataplane_physical_net".format(
778 provider_physical_network
779 )
780 )
781
782 # use the default dataplane_physical_net
783 if not provider_physical_network:
784 provider_physical_network = self.config.get(
785 "dataplane_physical_net"
786 )
787
788 # if it is non empty list, use the first value. If it is a string use the value directly
789 if (
790 isinstance(provider_physical_network, (tuple, list))
791 and provider_physical_network
792 ):
793 provider_physical_network = provider_physical_network[0]
794
795 if not provider_physical_network:
796 raise vimconn.VimConnConflictException(
797 "missing information needed for underlay networks. Provide "
798 "'dataplane_physical_net' configuration at VIM or use the NS "
799 "instantiation parameter 'provider-network.physical-network'"
800 " for the VLD"
801 )
802
803 if not self.config.get("multisegment_support"):
804 network_dict[
805 "provider:physical_network"
806 ] = provider_physical_network
807
808 if (
809 provider_network_profile
810 and "network-type" in provider_network_profile
811 ):
812 network_dict[
813 "provider:network_type"
814 ] = provider_network_profile["network-type"]
815 else:
816 network_dict["provider:network_type"] = self.config.get(
817 "dataplane_network_type", "vlan"
818 )
819
820 if vlan:
821 network_dict["provider:segmentation_id"] = vlan
822 else:
823 # Multi-segment case
824 segment_list = []
825 segment1_dict = {
826 "provider:physical_network": "",
827 "provider:network_type": "vxlan",
828 }
829 segment_list.append(segment1_dict)
830 segment2_dict = {
831 "provider:physical_network": provider_physical_network,
832 "provider:network_type": "vlan",
833 }
834
835 if vlan:
836 segment2_dict["provider:segmentation_id"] = vlan
837 elif self.config.get("multisegment_vlan_range"):
838 vlanID = self._generate_multisegment_vlanID()
839 segment2_dict["provider:segmentation_id"] = vlanID
840
841 # else
842 # raise vimconn.VimConnConflictException(
843 # "You must provide "multisegment_vlan_range" at config dict before creating a multisegment
844 # network")
845 segment_list.append(segment2_dict)
846 network_dict["segments"] = segment_list
847
848 # VIO Specific Changes. It needs a concrete VLAN
849 if self.vim_type == "VIO" and vlan is None:
850 if self.config.get("dataplane_net_vlan_range") is None:
851 raise vimconn.VimConnConflictException(
852 "You must provide 'dataplane_net_vlan_range' in format "
853 "[start_ID - end_ID] at VIM_config for creating underlay "
854 "networks"
855 )
856
857 network_dict["provider:segmentation_id"] = self._generate_vlanID()
858
859 network_dict["shared"] = shared
860
861 if self.config.get("disable_network_port_security"):
862 network_dict["port_security_enabled"] = False
863
864 if self.config.get("neutron_availability_zone_hints"):
865 hints = self.config.get("neutron_availability_zone_hints")
866
867 if isinstance(hints, str):
868 hints = [hints]
869
870 network_dict["availability_zone_hints"] = hints
871
872 new_net = self.neutron.create_network({"network": network_dict})
873 # print new_net
874 # create subnetwork, even if there is no profile
875
876 if not ip_profile:
877 ip_profile = {}
878
879 if not ip_profile.get("subnet_address"):
880 # Fake subnet is required
881 subnet_rand = random.randint(0, 255)
882 ip_profile["subnet_address"] = "192.168.{}.0/24".format(subnet_rand)
883
884 if "ip_version" not in ip_profile:
885 ip_profile["ip_version"] = "IPv4"
886
887 subnet = {
888 "name": net_name + "-subnet",
889 "network_id": new_net["network"]["id"],
890 "ip_version": 4 if ip_profile["ip_version"] == "IPv4" else 6,
891 "cidr": ip_profile["subnet_address"],
892 }
893
894 # Gateway should be set to None if not needed. Otherwise openstack assigns one by default
895 if ip_profile.get("gateway_address"):
896 subnet["gateway_ip"] = ip_profile["gateway_address"]
897 else:
898 subnet["gateway_ip"] = None
899
900 if ip_profile.get("dns_address"):
901 subnet["dns_nameservers"] = ip_profile["dns_address"].split(";")
902
903 if "dhcp_enabled" in ip_profile:
904 subnet["enable_dhcp"] = (
905 False
906 if ip_profile["dhcp_enabled"] == "false"
907 or ip_profile["dhcp_enabled"] is False
908 else True
909 )
910
911 if ip_profile.get("dhcp_start_address"):
912 subnet["allocation_pools"] = []
913 subnet["allocation_pools"].append(dict())
914 subnet["allocation_pools"][0]["start"] = ip_profile[
915 "dhcp_start_address"
916 ]
917
918 if ip_profile.get("dhcp_count"):
919 # parts = ip_profile["dhcp_start_address"].split(".")
920 # ip_int = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
921 ip_int = int(netaddr.IPAddress(ip_profile["dhcp_start_address"]))
922 ip_int += ip_profile["dhcp_count"] - 1
923 ip_str = str(netaddr.IPAddress(ip_int))
924 subnet["allocation_pools"][0]["end"] = ip_str
925
926 # self.logger.debug(">>>>>>>>>>>>>>>>>> Subnet: %s", str(subnet))
927 self.neutron.create_subnet({"subnet": subnet})
928
929 if net_type == "data" and self.config.get("multisegment_support"):
930 if self.config.get("l2gw_support"):
931 l2gw_list = self.neutron.list_l2_gateways().get("l2_gateways", ())
932 for l2gw in l2gw_list:
933 l2gw_conn = {
934 "l2_gateway_id": l2gw["id"],
935 "network_id": new_net["network"]["id"],
936 "segmentation_id": str(vlanID),
937 }
938 new_l2gw_conn = self.neutron.create_l2_gateway_connection(
939 {"l2_gateway_connection": l2gw_conn}
940 )
941 created_items[
942 "l2gwconn:"
943 + str(new_l2gw_conn["l2_gateway_connection"]["id"])
944 ] = True
945
946 return new_net["network"]["id"], created_items
947 except Exception as e:
948 # delete l2gw connections (if any) before deleting the network
949 for k, v in created_items.items():
950 if not v: # skip already deleted
951 continue
952
953 try:
954 k_item, _, k_id = k.partition(":")
955
956 if k_item == "l2gwconn":
957 self.neutron.delete_l2_gateway_connection(k_id)
958 except Exception as e2:
959 self.logger.error(
960 "Error deleting l2 gateway connection: {}: {}".format(
961 type(e2).__name__, e2
962 )
963 )
964
965 if new_net:
966 self.neutron.delete_network(new_net["network"]["id"])
967
968 self._format_exception(e)
969
970 def get_network_list(self, filter_dict={}):
971 """Obtain tenant networks of VIM
972 Filter_dict can be:
973 name: network name
974 id: network uuid
975 shared: boolean
976 tenant_id: tenant
977 admin_state_up: boolean
978 status: 'ACTIVE'
979 Returns the network list of dictionaries
980 """
981 self.logger.debug("Getting network from VIM filter: '%s'", str(filter_dict))
982
983 try:
984 self._reload_connection()
985 filter_dict_os = filter_dict.copy()
986
987 if self.api_version3 and "tenant_id" in filter_dict_os:
988 # TODO check
989 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
990
991 net_dict = self.neutron.list_networks(**filter_dict_os)
992 net_list = net_dict["networks"]
993 self.__net_os2mano(net_list)
994
995 return net_list
996 except (
997 neExceptions.ConnectionFailed,
998 ksExceptions.ClientException,
999 neExceptions.NeutronException,
1000 ConnectionError,
1001 ) as e:
1002 self._format_exception(e)
1003
1004 def get_network(self, net_id):
1005 """Obtain details of network from VIM
1006 Returns the network information from a network id"""
1007 self.logger.debug(" Getting tenant network %s from VIM", net_id)
1008 filter_dict = {"id": net_id}
1009 net_list = self.get_network_list(filter_dict)
1010
1011 if len(net_list) == 0:
1012 raise vimconn.VimConnNotFoundException(
1013 "Network '{}' not found".format(net_id)
1014 )
1015 elif len(net_list) > 1:
1016 raise vimconn.VimConnConflictException(
1017 "Found more than one network with this criteria"
1018 )
1019
1020 net = net_list[0]
1021 subnets = []
1022 for subnet_id in net.get("subnets", ()):
1023 try:
1024 subnet = self.neutron.show_subnet(subnet_id)
1025 except Exception as e:
1026 self.logger.error(
1027 "osconnector.get_network(): Error getting subnet %s %s"
1028 % (net_id, str(e))
1029 )
1030 subnet = {"id": subnet_id, "fault": str(e)}
1031
1032 subnets.append(subnet)
1033
1034 net["subnets"] = subnets
1035 net["encapsulation"] = net.get("provider:network_type")
1036 net["encapsulation_type"] = net.get("provider:network_type")
1037 net["segmentation_id"] = net.get("provider:segmentation_id")
1038 net["encapsulation_id"] = net.get("provider:segmentation_id")
1039
1040 return net
1041
1042 def delete_network(self, net_id, created_items=None):
1043 """
1044 Removes a tenant network from VIM and its associated elements
1045 :param net_id: VIM identifier of the network, provided by method new_network
1046 :param created_items: dictionary with extra items to be deleted. provided by method new_network
1047 Returns the network identifier or raises an exception upon error or when network is not found
1048 """
1049 self.logger.debug("Deleting network '%s' from VIM", net_id)
1050
1051 if created_items is None:
1052 created_items = {}
1053
1054 try:
1055 self._reload_connection()
1056 # delete l2gw connections (if any) before deleting the network
1057 for k, v in created_items.items():
1058 if not v: # skip already deleted
1059 continue
1060
1061 try:
1062 k_item, _, k_id = k.partition(":")
1063 if k_item == "l2gwconn":
1064 self.neutron.delete_l2_gateway_connection(k_id)
1065 except Exception as e:
1066 self.logger.error(
1067 "Error deleting l2 gateway connection: {}: {}".format(
1068 type(e).__name__, e
1069 )
1070 )
1071
1072 # delete VM ports attached to this networks before the network
1073 ports = self.neutron.list_ports(network_id=net_id)
1074 for p in ports["ports"]:
1075 try:
1076 self.neutron.delete_port(p["id"])
1077 except Exception as e:
1078 self.logger.error("Error deleting port %s: %s", p["id"], str(e))
1079
1080 self.neutron.delete_network(net_id)
1081
1082 return net_id
1083 except (
1084 neExceptions.ConnectionFailed,
1085 neExceptions.NetworkNotFoundClient,
1086 neExceptions.NeutronException,
1087 ksExceptions.ClientException,
1088 neExceptions.NeutronException,
1089 ConnectionError,
1090 ) as e:
1091 self._format_exception(e)
1092
1093 def refresh_nets_status(self, net_list):
1094 """Get the status of the networks
1095 Params: the list of network identifiers
1096 Returns a dictionary with:
1097 net_id: #VIM id of this network
1098 status: #Mandatory. Text with one of:
1099 # DELETED (not found at vim)
1100 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
1101 # OTHER (Vim reported other status not understood)
1102 # ERROR (VIM indicates an ERROR status)
1103 # ACTIVE, INACTIVE, DOWN (admin down),
1104 # BUILD (on building process)
1105 #
1106 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
1107 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
1108 """
1109 net_dict = {}
1110
1111 for net_id in net_list:
1112 net = {}
1113
1114 try:
1115 net_vim = self.get_network(net_id)
1116
1117 if net_vim["status"] in netStatus2manoFormat:
1118 net["status"] = netStatus2manoFormat[net_vim["status"]]
1119 else:
1120 net["status"] = "OTHER"
1121 net["error_msg"] = "VIM status reported " + net_vim["status"]
1122
1123 if net["status"] == "ACTIVE" and not net_vim["admin_state_up"]:
1124 net["status"] = "DOWN"
1125
1126 net["vim_info"] = self.serialize(net_vim)
1127
1128 if net_vim.get("fault"): # TODO
1129 net["error_msg"] = str(net_vim["fault"])
1130 except vimconn.VimConnNotFoundException as e:
1131 self.logger.error("Exception getting net status: %s", str(e))
1132 net["status"] = "DELETED"
1133 net["error_msg"] = str(e)
1134 except vimconn.VimConnException as e:
1135 self.logger.error("Exception getting net status: %s", str(e))
1136 net["status"] = "VIM_ERROR"
1137 net["error_msg"] = str(e)
1138 net_dict[net_id] = net
1139 return net_dict
1140
1141 def get_flavor(self, flavor_id):
1142 """Obtain flavor details from the VIM. Returns the flavor dict details"""
1143 self.logger.debug("Getting flavor '%s'", flavor_id)
1144
1145 try:
1146 self._reload_connection()
1147 flavor = self.nova.flavors.find(id=flavor_id)
1148 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
1149
1150 return flavor.to_dict()
1151 except (
1152 nvExceptions.NotFound,
1153 nvExceptions.ClientException,
1154 ksExceptions.ClientException,
1155 ConnectionError,
1156 ) as e:
1157 self._format_exception(e)
1158
1159 def get_flavor_id_from_data(self, flavor_dict):
1160 """Obtain flavor id that match the flavor description
1161 Returns the flavor_id or raises a vimconnNotFoundException
1162 flavor_dict: contains the required ram, vcpus, disk
1163 If 'use_existing_flavors' is set to True at config, the closer flavor that provides same or more ram, vcpus
1164 and disk is returned. Otherwise a flavor with exactly same ram, vcpus and disk is returned or a
1165 vimconnNotFoundException is raised
1166 """
1167 exact_match = False if self.config.get("use_existing_flavors") else True
1168
1169 try:
1170 self._reload_connection()
1171 flavor_candidate_id = None
1172 flavor_candidate_data = (10000, 10000, 10000)
1173 flavor_target = (
1174 flavor_dict["ram"],
1175 flavor_dict["vcpus"],
1176 flavor_dict["disk"],
1177 flavor_dict.get("ephemeral", 0),
1178 flavor_dict.get("swap", 0),
1179 )
1180 # numa=None
1181 extended = flavor_dict.get("extended", {})
1182 if extended:
1183 # TODO
1184 raise vimconn.VimConnNotFoundException(
1185 "Flavor with EPA still not implemented"
1186 )
1187 # if len(numas) > 1:
1188 # raise vimconn.VimConnNotFoundException("Cannot find any flavor with more than one numa")
1189 # numa=numas[0]
1190 # numas = extended.get("numas")
1191 for flavor in self.nova.flavors.list():
1192 epa = flavor.get_keys()
1193
1194 if epa:
1195 continue
1196 # TODO
1197
1198 flavor_data = (
1199 flavor.ram,
1200 flavor.vcpus,
1201 flavor.disk,
1202 flavor.ephemeral,
1203 flavor.swap if isinstance(flavor.swap, int) else 0,
1204 )
1205 if flavor_data == flavor_target:
1206 return flavor.id
1207 elif (
1208 not exact_match
1209 and flavor_target < flavor_data < flavor_candidate_data
1210 ):
1211 flavor_candidate_id = flavor.id
1212 flavor_candidate_data = flavor_data
1213
1214 if not exact_match and flavor_candidate_id:
1215 return flavor_candidate_id
1216
1217 raise vimconn.VimConnNotFoundException(
1218 "Cannot find any flavor matching '{}'".format(flavor_dict)
1219 )
1220 except (
1221 nvExceptions.NotFound,
1222 nvExceptions.ClientException,
1223 ksExceptions.ClientException,
1224 ConnectionError,
1225 ) as e:
1226 self._format_exception(e)
1227
1228 def process_resource_quota(self, quota, prefix, extra_specs):
1229 """
1230 :param prefix:
1231 :param extra_specs:
1232 :return:
1233 """
1234 if "limit" in quota:
1235 extra_specs["quota:" + prefix + "_limit"] = quota["limit"]
1236
1237 if "reserve" in quota:
1238 extra_specs["quota:" + prefix + "_reservation"] = quota["reserve"]
1239
1240 if "shares" in quota:
1241 extra_specs["quota:" + prefix + "_shares_level"] = "custom"
1242 extra_specs["quota:" + prefix + "_shares_share"] = quota["shares"]
1243
1244 def new_flavor(self, flavor_data, change_name_if_used=True):
1245 """Adds a tenant flavor to openstack VIM
1246 if change_name_if_used is True, it will change name in case of conflict, because it is not supported name
1247 repetition
1248 Returns the flavor identifier
1249 """
1250 self.logger.debug("Adding flavor '%s'", str(flavor_data))
1251 retry = 0
1252 max_retries = 3
1253 name_suffix = 0
1254
1255 try:
1256 name = flavor_data["name"]
1257 while retry < max_retries:
1258 retry += 1
1259 try:
1260 self._reload_connection()
1261
1262 if change_name_if_used:
1263 # get used names
1264 fl_names = []
1265 fl = self.nova.flavors.list()
1266
1267 for f in fl:
1268 fl_names.append(f.name)
1269
1270 while name in fl_names:
1271 name_suffix += 1
1272 name = flavor_data["name"] + "-" + str(name_suffix)
1273
1274 ram = flavor_data.get("ram", 64)
1275 vcpus = flavor_data.get("vcpus", 1)
1276 extra_specs = {}
1277
1278 extended = flavor_data.get("extended")
1279 if extended:
1280 numas = extended.get("numas")
1281
1282 if numas:
1283 numa_nodes = len(numas)
1284
1285 if numa_nodes > 1:
1286 return -1, "Can not add flavor with more than one numa"
1287
1288 extra_specs["hw:numa_nodes"] = str(numa_nodes)
1289 extra_specs["hw:mem_page_size"] = "large"
1290 extra_specs["hw:cpu_policy"] = "dedicated"
1291 extra_specs["hw:numa_mempolicy"] = "strict"
1292
1293 if self.vim_type == "VIO":
1294 extra_specs[
1295 "vmware:extra_config"
1296 ] = '{"numa.nodeAffinity":"0"}'
1297 extra_specs["vmware:latency_sensitivity_level"] = "high"
1298
1299 for numa in numas:
1300 # overwrite ram and vcpus
1301 # check if key "memory" is present in numa else use ram value at flavor
1302 if "memory" in numa:
1303 ram = numa["memory"] * 1024
1304 # See for reference: https://specs.openstack.org/openstack/nova-specs/specs/mitaka/
1305 # implemented/virt-driver-cpu-thread-pinning.html
1306 extra_specs["hw:cpu_sockets"] = 1
1307
1308 if "paired-threads" in numa:
1309 vcpus = numa["paired-threads"] * 2
1310 # cpu_thread_policy "require" implies that the compute node must have an
1311 # STM architecture
1312 extra_specs["hw:cpu_thread_policy"] = "require"
1313 extra_specs["hw:cpu_policy"] = "dedicated"
1314 elif "cores" in numa:
1315 vcpus = numa["cores"]
1316 # cpu_thread_policy "prefer" implies that the host must not have an SMT
1317 # architecture, or a non-SMT architecture will be emulated
1318 extra_specs["hw:cpu_thread_policy"] = "isolate"
1319 extra_specs["hw:cpu_policy"] = "dedicated"
1320 elif "threads" in numa:
1321 vcpus = numa["threads"]
1322 # cpu_thread_policy "prefer" implies that the host may or may not have an SMT
1323 # architecture
1324 extra_specs["hw:cpu_thread_policy"] = "prefer"
1325 extra_specs["hw:cpu_policy"] = "dedicated"
1326 # for interface in numa.get("interfaces",() ):
1327 # if interface["dedicated"]=="yes":
1328 # raise vimconn.VimConnException("Passthrough interfaces are not supported
1329 # for the openstack connector", http_code=vimconn.HTTP_Service_Unavailable)
1330 # #TODO, add the key 'pci_passthrough:alias"="<label at config>:<number ifaces>"'
1331 # when a way to connect it is available
1332 elif extended.get("cpu-quota"):
1333 self.process_resource_quota(
1334 extended.get("cpu-quota"), "cpu", extra_specs
1335 )
1336
1337 if extended.get("mem-quota"):
1338 self.process_resource_quota(
1339 extended.get("mem-quota"), "memory", extra_specs
1340 )
1341
1342 if extended.get("vif-quota"):
1343 self.process_resource_quota(
1344 extended.get("vif-quota"), "vif", extra_specs
1345 )
1346
1347 if extended.get("disk-io-quota"):
1348 self.process_resource_quota(
1349 extended.get("disk-io-quota"), "disk_io", extra_specs
1350 )
1351
1352 # Set the mempage size as specified in the descriptor
1353 if extended.get("mempage-size"):
1354 if extended.get("mempage-size") == "LARGE":
1355 extra_specs["hw:mem_page_size"] = "large"
1356 elif extended.get("mempage-size") == "SMALL":
1357 extra_specs["hw:mem_page_size"] = "small"
1358 elif extended.get("mempage-size") == "SIZE_2MB":
1359 extra_specs["hw:mem_page_size"] = "2MB"
1360 elif extended.get("mempage-size") == "SIZE_1GB":
1361 extra_specs["hw:mem_page_size"] = "1GB"
1362 elif extended.get("mempage-size") == "PREFER_LARGE":
1363 extra_specs["hw:mem_page_size"] = "any"
1364 else:
1365 # The validations in NBI should make reaching here not possible.
1366 # If this message is shown, check validations
1367 self.logger.debug(
1368 "Invalid mempage-size %s. Will be ignored",
1369 extended.get("mempage-size"),
1370 )
1371
1372 # create flavor
1373 new_flavor = self.nova.flavors.create(
1374 name=name,
1375 ram=ram,
1376 vcpus=vcpus,
1377 disk=flavor_data.get("disk", 0),
1378 ephemeral=flavor_data.get("ephemeral", 0),
1379 swap=flavor_data.get("swap", 0),
1380 is_public=flavor_data.get("is_public", True),
1381 )
1382 # add metadata
1383 if extra_specs:
1384 new_flavor.set_keys(extra_specs)
1385
1386 return new_flavor.id
1387 except nvExceptions.Conflict as e:
1388 if change_name_if_used and retry < max_retries:
1389 continue
1390
1391 self._format_exception(e)
1392 # except nvExceptions.BadRequest as e:
1393 except (
1394 ksExceptions.ClientException,
1395 nvExceptions.ClientException,
1396 ConnectionError,
1397 KeyError,
1398 ) as e:
1399 self._format_exception(e)
1400
1401 def delete_flavor(self, flavor_id):
1402 """Deletes a tenant flavor from openstack VIM. Returns the old flavor_id"""
1403 try:
1404 self._reload_connection()
1405 self.nova.flavors.delete(flavor_id)
1406
1407 return flavor_id
1408 # except nvExceptions.BadRequest as e:
1409 except (
1410 nvExceptions.NotFound,
1411 ksExceptions.ClientException,
1412 nvExceptions.ClientException,
1413 ConnectionError,
1414 ) as e:
1415 self._format_exception(e)
1416
1417 def new_image(self, image_dict):
1418 """
1419 Adds a tenant image to VIM. imge_dict is a dictionary with:
1420 name: name
1421 disk_format: qcow2, vhd, vmdk, raw (by default), ...
1422 location: path or URI
1423 public: "yes" or "no"
1424 metadata: metadata of the image
1425 Returns the image_id
1426 """
1427 retry = 0
1428 max_retries = 3
1429
1430 while retry < max_retries:
1431 retry += 1
1432 try:
1433 self._reload_connection()
1434
1435 # determine format http://docs.openstack.org/developer/glance/formats.html
1436 if "disk_format" in image_dict:
1437 disk_format = image_dict["disk_format"]
1438 else: # autodiscover based on extension
1439 if image_dict["location"].endswith(".qcow2"):
1440 disk_format = "qcow2"
1441 elif image_dict["location"].endswith(".vhd"):
1442 disk_format = "vhd"
1443 elif image_dict["location"].endswith(".vmdk"):
1444 disk_format = "vmdk"
1445 elif image_dict["location"].endswith(".vdi"):
1446 disk_format = "vdi"
1447 elif image_dict["location"].endswith(".iso"):
1448 disk_format = "iso"
1449 elif image_dict["location"].endswith(".aki"):
1450 disk_format = "aki"
1451 elif image_dict["location"].endswith(".ari"):
1452 disk_format = "ari"
1453 elif image_dict["location"].endswith(".ami"):
1454 disk_format = "ami"
1455 else:
1456 disk_format = "raw"
1457
1458 self.logger.debug(
1459 "new_image: '%s' loading from '%s'",
1460 image_dict["name"],
1461 image_dict["location"],
1462 )
1463 if self.vim_type == "VIO":
1464 container_format = "bare"
1465 if "container_format" in image_dict:
1466 container_format = image_dict["container_format"]
1467
1468 new_image = self.glance.images.create(
1469 name=image_dict["name"],
1470 container_format=container_format,
1471 disk_format=disk_format,
1472 )
1473 else:
1474 new_image = self.glance.images.create(name=image_dict["name"])
1475
1476 if image_dict["location"].startswith("http"):
1477 # TODO there is not a method to direct download. It must be downloaded locally with requests
1478 raise vimconn.VimConnNotImplemented("Cannot create image from URL")
1479 else: # local path
1480 with open(image_dict["location"]) as fimage:
1481 self.glance.images.upload(new_image.id, fimage)
1482 # new_image = self.glancev1.images.create(name=image_dict["name"], is_public=
1483 # image_dict.get("public","yes")=="yes",
1484 # container_format="bare", data=fimage, disk_format=disk_format)
1485
1486 metadata_to_load = image_dict.get("metadata")
1487
1488 # TODO location is a reserved word for current openstack versions. fixed for VIO please check
1489 # for openstack
1490 if self.vim_type == "VIO":
1491 metadata_to_load["upload_location"] = image_dict["location"]
1492 else:
1493 metadata_to_load["location"] = image_dict["location"]
1494
1495 self.glance.images.update(new_image.id, **metadata_to_load)
1496
1497 return new_image.id
1498 except (
1499 nvExceptions.Conflict,
1500 ksExceptions.ClientException,
1501 nvExceptions.ClientException,
1502 ) as e:
1503 self._format_exception(e)
1504 except (
1505 HTTPException,
1506 gl1Exceptions.HTTPException,
1507 gl1Exceptions.CommunicationError,
1508 ConnectionError,
1509 ) as e:
1510 if retry == max_retries:
1511 continue
1512
1513 self._format_exception(e)
1514 except IOError as e: # can not open the file
1515 raise vimconn.VimConnConnectionException(
1516 "{}: {} for {}".format(type(e).__name__, e, image_dict["location"]),
1517 http_code=vimconn.HTTP_Bad_Request,
1518 )
1519
1520 def delete_image(self, image_id):
1521 """Deletes a tenant image from openstack VIM. Returns the old id"""
1522 try:
1523 self._reload_connection()
1524 self.glance.images.delete(image_id)
1525
1526 return image_id
1527 except (
1528 nvExceptions.NotFound,
1529 ksExceptions.ClientException,
1530 nvExceptions.ClientException,
1531 gl1Exceptions.CommunicationError,
1532 gl1Exceptions.HTTPNotFound,
1533 ConnectionError,
1534 ) as e: # TODO remove
1535 self._format_exception(e)
1536
1537 def get_image_id_from_path(self, path):
1538 """Get the image id from image path in the VIM database. Returns the image_id"""
1539 try:
1540 self._reload_connection()
1541 images = self.glance.images.list()
1542
1543 for image in images:
1544 if image.metadata.get("location") == path:
1545 return image.id
1546
1547 raise vimconn.VimConnNotFoundException(
1548 "image with location '{}' not found".format(path)
1549 )
1550 except (
1551 ksExceptions.ClientException,
1552 nvExceptions.ClientException,
1553 gl1Exceptions.CommunicationError,
1554 ConnectionError,
1555 ) as e:
1556 self._format_exception(e)
1557
1558 def get_image_list(self, filter_dict={}):
1559 """Obtain tenant images from VIM
1560 Filter_dict can be:
1561 id: image id
1562 name: image name
1563 checksum: image checksum
1564 Returns the image list of dictionaries:
1565 [{<the fields at Filter_dict plus some VIM specific>}, ...]
1566 List can be empty
1567 """
1568 self.logger.debug("Getting image list from VIM filter: '%s'", str(filter_dict))
1569
1570 try:
1571 self._reload_connection()
1572 # filter_dict_os = filter_dict.copy()
1573 # First we filter by the available filter fields: name, id. The others are removed.
1574 image_list = self.glance.images.list()
1575 filtered_list = []
1576
1577 for image in image_list:
1578 try:
1579 if filter_dict.get("name") and image["name"] != filter_dict["name"]:
1580 continue
1581
1582 if filter_dict.get("id") and image["id"] != filter_dict["id"]:
1583 continue
1584
1585 if (
1586 filter_dict.get("checksum")
1587 and image["checksum"] != filter_dict["checksum"]
1588 ):
1589 continue
1590
1591 filtered_list.append(image.copy())
1592 except gl1Exceptions.HTTPNotFound:
1593 pass
1594
1595 return filtered_list
1596 except (
1597 ksExceptions.ClientException,
1598 nvExceptions.ClientException,
1599 gl1Exceptions.CommunicationError,
1600 ConnectionError,
1601 ) as e:
1602 self._format_exception(e)
1603
1604 def __wait_for_vm(self, vm_id, status):
1605 """wait until vm is in the desired status and return True.
1606 If the VM gets in ERROR status, return false.
1607 If the timeout is reached generate an exception"""
1608 elapsed_time = 0
1609 while elapsed_time < server_timeout:
1610 vm_status = self.nova.servers.get(vm_id).status
1611
1612 if vm_status == status:
1613 return True
1614
1615 if vm_status == "ERROR":
1616 return False
1617
1618 time.sleep(5)
1619 elapsed_time += 5
1620
1621 # if we exceeded the timeout rollback
1622 if elapsed_time >= server_timeout:
1623 raise vimconn.VimConnException(
1624 "Timeout waiting for instance " + vm_id + " to get " + status,
1625 http_code=vimconn.HTTP_Request_Timeout,
1626 )
1627
1628 def _get_openstack_availablity_zones(self):
1629 """
1630 Get from openstack availability zones available
1631 :return:
1632 """
1633 try:
1634 openstack_availability_zone = self.nova.availability_zones.list()
1635 openstack_availability_zone = [
1636 str(zone.zoneName)
1637 for zone in openstack_availability_zone
1638 if zone.zoneName != "internal"
1639 ]
1640
1641 return openstack_availability_zone
1642 except Exception:
1643 return None
1644
1645 def _set_availablity_zones(self):
1646 """
1647 Set vim availablity zone
1648 :return:
1649 """
1650 if "availability_zone" in self.config:
1651 vim_availability_zones = self.config.get("availability_zone")
1652
1653 if isinstance(vim_availability_zones, str):
1654 self.availability_zone = [vim_availability_zones]
1655 elif isinstance(vim_availability_zones, list):
1656 self.availability_zone = vim_availability_zones
1657 else:
1658 self.availability_zone = self._get_openstack_availablity_zones()
1659
1660 def _get_vm_availability_zone(
1661 self, availability_zone_index, availability_zone_list
1662 ):
1663 """
1664 Return thge availability zone to be used by the created VM.
1665 :return: The VIM availability zone to be used or None
1666 """
1667 if availability_zone_index is None:
1668 if not self.config.get("availability_zone"):
1669 return None
1670 elif isinstance(self.config.get("availability_zone"), str):
1671 return self.config["availability_zone"]
1672 else:
1673 # TODO consider using a different parameter at config for default AV and AV list match
1674 return self.config["availability_zone"][0]
1675
1676 vim_availability_zones = self.availability_zone
1677 # check if VIM offer enough availability zones describe in the VNFD
1678 if vim_availability_zones and len(availability_zone_list) <= len(
1679 vim_availability_zones
1680 ):
1681 # check if all the names of NFV AV match VIM AV names
1682 match_by_index = False
1683 for av in availability_zone_list:
1684 if av not in vim_availability_zones:
1685 match_by_index = True
1686 break
1687
1688 if match_by_index:
1689 return vim_availability_zones[availability_zone_index]
1690 else:
1691 return availability_zone_list[availability_zone_index]
1692 else:
1693 raise vimconn.VimConnConflictException(
1694 "No enough availability zones at VIM for this deployment"
1695 )
1696
1697 def new_vminstance(
1698 self,
1699 name,
1700 description,
1701 start,
1702 image_id,
1703 flavor_id,
1704 affinity_group_list,
1705 net_list,
1706 cloud_config=None,
1707 disk_list=None,
1708 availability_zone_index=None,
1709 availability_zone_list=None,
1710 ):
1711 """Adds a VM instance to VIM
1712 Params:
1713 start: indicates if VM must start or boot in pause mode. Ignored
1714 image_id,flavor_id: image and flavor uuid
1715 affinity_group_list: list of affinity groups, each one is a dictionary.
1716 Ignore if empty.
1717 net_list: list of interfaces, each one is a dictionary with:
1718 name:
1719 net_id: network uuid to connect
1720 vpci: virtual vcpi to assign, ignored because openstack lack #TODO
1721 model: interface model, ignored #TODO
1722 mac_address: used for SR-IOV ifaces #TODO for other types
1723 use: 'data', 'bridge', 'mgmt'
1724 type: 'virtual', 'PCI-PASSTHROUGH'('PF'), 'SR-IOV'('VF'), 'VFnotShared'
1725 vim_id: filled/added by this function
1726 floating_ip: True/False (or it can be None)
1727 port_security: True/False
1728 'cloud_config': (optional) dictionary with:
1729 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
1730 'users': (optional) list of users to be inserted, each item is a dict with:
1731 'name': (mandatory) user name,
1732 'key-pairs': (optional) list of strings with the public key to be inserted to the user
1733 'user-data': (optional) string is a text script to be passed directly to cloud-init
1734 'config-files': (optional). List of files to be transferred. Each item is a dict with:
1735 'dest': (mandatory) string with the destination absolute path
1736 'encoding': (optional, by default text). Can be one of:
1737 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
1738 'content' (mandatory): string with the content of the file
1739 'permissions': (optional) string with file permissions, typically octal notation '0644'
1740 'owner': (optional) file owner, string with the format 'owner:group'
1741 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
1742 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
1743 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
1744 'size': (mandatory) string with the size of the disk in GB
1745 'vim_id' (optional) should use this existing volume id
1746 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
1747 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
1748 availability_zone_index is None
1749 #TODO ip, security groups
1750 Returns a tuple with the instance identifier and created_items or raises an exception on error
1751 created_items can be None or a dictionary where this method can include key-values that will be passed to
1752 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
1753 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
1754 as not present.
1755 """
1756 self.logger.debug(
1757 "new_vminstance input: image='%s' flavor='%s' nics='%s'",
1758 image_id,
1759 flavor_id,
1760 str(net_list),
1761 )
1762
1763 try:
1764 server = None
1765 created_items = {}
1766 # metadata = {}
1767 net_list_vim = []
1768 external_network = []
1769 # ^list of external networks to be connected to instance, later on used to create floating_ip
1770 no_secured_ports = [] # List of port-is with port-security disabled
1771 self._reload_connection()
1772 # metadata_vpci = {} # For a specific neutron plugin
1773 block_device_mapping = None
1774
1775 for net in net_list:
1776 if not net.get("net_id"): # skip non connected iface
1777 continue
1778
1779 port_dict = {
1780 "network_id": net["net_id"],
1781 "name": net.get("name"),
1782 "admin_state_up": True,
1783 }
1784
1785 if (
1786 self.config.get("security_groups")
1787 and net.get("port_security") is not False
1788 and not self.config.get("no_port_security_extension")
1789 ):
1790 if not self.security_groups_id:
1791 self._get_ids_from_name()
1792
1793 port_dict["security_groups"] = self.security_groups_id
1794
1795 if net["type"] == "virtual":
1796 pass
1797 # if "vpci" in net:
1798 # metadata_vpci[ net["net_id"] ] = [[ net["vpci"], "" ]]
1799 elif net["type"] == "VF" or net["type"] == "SR-IOV": # for VF
1800 # if "vpci" in net:
1801 # if "VF" not in metadata_vpci:
1802 # metadata_vpci["VF"]=[]
1803 # metadata_vpci["VF"].append([ net["vpci"], "" ])
1804 port_dict["binding:vnic_type"] = "direct"
1805
1806 # VIO specific Changes
1807 if self.vim_type == "VIO":
1808 # Need to create port with port_security_enabled = False and no-security-groups
1809 port_dict["port_security_enabled"] = False
1810 port_dict["provider_security_groups"] = []
1811 port_dict["security_groups"] = []
1812 else: # For PT PCI-PASSTHROUGH
1813 # if "vpci" in net:
1814 # if "PF" not in metadata_vpci:
1815 # metadata_vpci["PF"]=[]
1816 # metadata_vpci["PF"].append([ net["vpci"], "" ])
1817 port_dict["binding:vnic_type"] = "direct-physical"
1818
1819 if not port_dict["name"]:
1820 port_dict["name"] = name
1821
1822 if net.get("mac_address"):
1823 port_dict["mac_address"] = net["mac_address"]
1824
1825 if net.get("ip_address"):
1826 port_dict["fixed_ips"] = [{"ip_address": net["ip_address"]}]
1827 # TODO add "subnet_id": <subnet_id>
1828
1829 new_port = self.neutron.create_port({"port": port_dict})
1830 created_items["port:" + str(new_port["port"]["id"])] = True
1831 net["mac_adress"] = new_port["port"]["mac_address"]
1832 net["vim_id"] = new_port["port"]["id"]
1833 # if try to use a network without subnetwork, it will return a emtpy list
1834 fixed_ips = new_port["port"].get("fixed_ips")
1835
1836 if fixed_ips:
1837 net["ip"] = fixed_ips[0].get("ip_address")
1838 else:
1839 net["ip"] = None
1840
1841 port = {"port-id": new_port["port"]["id"]}
1842 if float(self.nova.api_version.get_string()) >= 2.32:
1843 port["tag"] = new_port["port"]["name"]
1844
1845 net_list_vim.append(port)
1846
1847 if net.get("floating_ip", False):
1848 net["exit_on_floating_ip_error"] = True
1849 external_network.append(net)
1850 elif net["use"] == "mgmt" and self.config.get("use_floating_ip"):
1851 net["exit_on_floating_ip_error"] = False
1852 external_network.append(net)
1853 net["floating_ip"] = self.config.get("use_floating_ip")
1854
1855 # If port security is disabled when the port has not yet been attached to the VM, then all vm traffic
1856 # is dropped.
1857 # As a workaround we wait until the VM is active and then disable the port-security
1858 if net.get("port_security") is False and not self.config.get(
1859 "no_port_security_extension"
1860 ):
1861 no_secured_ports.append(
1862 (
1863 new_port["port"]["id"],
1864 net.get("port_security_disable_strategy"),
1865 )
1866 )
1867
1868 # if metadata_vpci:
1869 # metadata = {"pci_assignement": json.dumps(metadata_vpci)}
1870 # if len(metadata["pci_assignement"]) >255:
1871 # #limit the metadata size
1872 # #metadata["pci_assignement"] = metadata["pci_assignement"][0:255]
1873 # self.logger.warn("Metadata deleted since it exceeds the expected length (255) ")
1874 # metadata = {}
1875
1876 self.logger.debug(
1877 "name '%s' image_id '%s'flavor_id '%s' net_list_vim '%s' description '%s'",
1878 name,
1879 image_id,
1880 flavor_id,
1881 str(net_list_vim),
1882 description,
1883 )
1884
1885 # cloud config
1886 config_drive, userdata = self._create_user_data(cloud_config)
1887
1888 # get availability Zone
1889 vm_av_zone = self._get_vm_availability_zone(
1890 availability_zone_index, availability_zone_list
1891 )
1892
1893 # Create additional volumes in case these are present in disk_list
1894 base_disk_index = ord("b")
1895 boot_volume_id = None
1896 if disk_list:
1897 block_device_mapping = {}
1898 for disk in disk_list:
1899 if disk.get("vim_id"):
1900 block_device_mapping["_vd" + chr(base_disk_index)] = disk[
1901 "vim_id"
1902 ]
1903 else:
1904 if "image_id" in disk:
1905 base_disk_index = ord("a")
1906 volume = self.cinder.volumes.create(
1907 size=disk["size"],
1908 name=name + "_vd" + chr(base_disk_index),
1909 imageRef=disk["image_id"],
1910 # Make sure volume is in the same AZ as the VM to be attached to
1911 availability_zone=vm_av_zone,
1912 )
1913 boot_volume_id = volume.id
1914 else:
1915 volume = self.cinder.volumes.create(
1916 size=disk["size"],
1917 name=name + "_vd" + chr(base_disk_index),
1918 # Make sure volume is in the same AZ as the VM to be attached to
1919 availability_zone=vm_av_zone,
1920 )
1921
1922 created_items["volume:" + str(volume.id)] = True
1923 block_device_mapping["_vd" + chr(base_disk_index)] = volume.id
1924
1925 base_disk_index += 1
1926
1927 # Wait until created volumes are with status available
1928 elapsed_time = 0
1929 while elapsed_time < volume_timeout:
1930 for created_item in created_items:
1931 v, _, volume_id = created_item.partition(":")
1932 if v == "volume":
1933 if self.cinder.volumes.get(volume_id).status != "available":
1934 break
1935 else: # all ready: break from while
1936 break
1937
1938 time.sleep(5)
1939 elapsed_time += 5
1940
1941 # If we exceeded the timeout rollback
1942 if elapsed_time >= volume_timeout:
1943 raise vimconn.VimConnException(
1944 "Timeout creating volumes for instance " + name,
1945 http_code=vimconn.HTTP_Request_Timeout,
1946 )
1947 if boot_volume_id:
1948 self.cinder.volumes.set_bootable(boot_volume_id, True)
1949
1950 # Manage affinity groups/server groups
1951 server_group_id = None
1952 scheduller_hints = {}
1953
1954 if affinity_group_list:
1955 # Only first id on the list will be used. Openstack restriction
1956 server_group_id = affinity_group_list[0]["affinity_group_id"]
1957 scheduller_hints["group"] = server_group_id
1958
1959 self.logger.debug(
1960 "nova.servers.create({}, {}, {}, nics={}, security_groups={}, "
1961 "availability_zone={}, key_name={}, userdata={}, config_drive={}, "
1962 "block_device_mapping={}, server_group={})".format(
1963 name,
1964 image_id,
1965 flavor_id,
1966 net_list_vim,
1967 self.config.get("security_groups"),
1968 vm_av_zone,
1969 self.config.get("keypair"),
1970 userdata,
1971 config_drive,
1972 block_device_mapping,
1973 server_group_id,
1974 )
1975 )
1976 server = self.nova.servers.create(
1977 name,
1978 image_id,
1979 flavor_id,
1980 nics=net_list_vim,
1981 security_groups=self.config.get("security_groups"),
1982 # TODO remove security_groups in future versions. Already at neutron port
1983 availability_zone=vm_av_zone,
1984 key_name=self.config.get("keypair"),
1985 userdata=userdata,
1986 config_drive=config_drive,
1987 block_device_mapping=block_device_mapping,
1988 scheduler_hints=scheduller_hints,
1989 ) # , description=description)
1990
1991 vm_start_time = time.time()
1992 # Previously mentioned workaround to wait until the VM is active and then disable the port-security
1993 if no_secured_ports:
1994 self.__wait_for_vm(server.id, "ACTIVE")
1995
1996 for port in no_secured_ports:
1997 port_update = {
1998 "port": {"port_security_enabled": False, "security_groups": None}
1999 }
2000
2001 if port[1] == "allow-address-pairs":
2002 port_update = {
2003 "port": {"allowed_address_pairs": [{"ip_address": "0.0.0.0/0"}]}
2004 }
2005
2006 try:
2007 self.neutron.update_port(port[0], port_update)
2008 except Exception:
2009 raise vimconn.VimConnException(
2010 "It was not possible to disable port security for port {}".format(
2011 port[0]
2012 )
2013 )
2014
2015 # print "DONE :-)", server
2016
2017 # pool_id = None
2018 for floating_network in external_network:
2019 try:
2020 assigned = False
2021 floating_ip_retries = 3
2022 # In case of RO in HA there can be conflicts, two RO trying to assign same floating IP, so retry
2023 # several times
2024 while not assigned:
2025 floating_ips = self.neutron.list_floatingips().get(
2026 "floatingips", ()
2027 )
2028 random.shuffle(floating_ips) # randomize
2029 for fip in floating_ips:
2030 if (
2031 fip.get("port_id")
2032 or fip.get("tenant_id") != server.tenant_id
2033 ):
2034 continue
2035
2036 if isinstance(floating_network["floating_ip"], str):
2037 if (
2038 fip.get("floating_network_id")
2039 != floating_network["floating_ip"]
2040 ):
2041 continue
2042
2043 free_floating_ip = fip["id"]
2044 break
2045 else:
2046 if (
2047 isinstance(floating_network["floating_ip"], str)
2048 and floating_network["floating_ip"].lower() != "true"
2049 ):
2050 pool_id = floating_network["floating_ip"]
2051 else:
2052 # Find the external network
2053 external_nets = list()
2054
2055 for net in self.neutron.list_networks()["networks"]:
2056 if net["router:external"]:
2057 external_nets.append(net)
2058
2059 if len(external_nets) == 0:
2060 raise vimconn.VimConnException(
2061 "Cannot create floating_ip automatically since "
2062 "no external network is present",
2063 http_code=vimconn.HTTP_Conflict,
2064 )
2065
2066 if len(external_nets) > 1:
2067 raise vimconn.VimConnException(
2068 "Cannot create floating_ip automatically since "
2069 "multiple external networks are present",
2070 http_code=vimconn.HTTP_Conflict,
2071 )
2072
2073 pool_id = external_nets[0].get("id")
2074
2075 param = {
2076 "floatingip": {
2077 "floating_network_id": pool_id,
2078 "tenant_id": server.tenant_id,
2079 }
2080 }
2081
2082 try:
2083 # self.logger.debug("Creating floating IP")
2084 new_floating_ip = self.neutron.create_floatingip(param)
2085 free_floating_ip = new_floating_ip["floatingip"]["id"]
2086 created_items[
2087 "floating_ip:" + str(free_floating_ip)
2088 ] = True
2089 except Exception as e:
2090 raise vimconn.VimConnException(
2091 type(e).__name__
2092 + ": Cannot create new floating_ip "
2093 + str(e),
2094 http_code=vimconn.HTTP_Conflict,
2095 )
2096
2097 try:
2098 # for race condition ensure not already assigned
2099 fip = self.neutron.show_floatingip(free_floating_ip)
2100
2101 if fip["floatingip"]["port_id"]:
2102 continue
2103
2104 # the vim_id key contains the neutron.port_id
2105 self.neutron.update_floatingip(
2106 free_floating_ip,
2107 {"floatingip": {"port_id": floating_network["vim_id"]}},
2108 )
2109 # for race condition ensure not re-assigned to other VM after 5 seconds
2110 time.sleep(5)
2111 fip = self.neutron.show_floatingip(free_floating_ip)
2112
2113 if (
2114 fip["floatingip"]["port_id"]
2115 != floating_network["vim_id"]
2116 ):
2117 self.logger.error(
2118 "floating_ip {} re-assigned to other port".format(
2119 free_floating_ip
2120 )
2121 )
2122 continue
2123
2124 self.logger.debug(
2125 "Assigned floating_ip {} to VM {}".format(
2126 free_floating_ip, server.id
2127 )
2128 )
2129 assigned = True
2130 except Exception as e:
2131 # openstack need some time after VM creation to assign an IP. So retry if fails
2132 vm_status = self.nova.servers.get(server.id).status
2133
2134 if vm_status not in ("ACTIVE", "ERROR"):
2135 if time.time() - vm_start_time < server_timeout:
2136 time.sleep(5)
2137 continue
2138 elif floating_ip_retries > 0:
2139 floating_ip_retries -= 1
2140 continue
2141
2142 raise vimconn.VimConnException(
2143 "Cannot create floating_ip: {} {}".format(
2144 type(e).__name__, e
2145 ),
2146 http_code=vimconn.HTTP_Conflict,
2147 )
2148
2149 except Exception as e:
2150 if not floating_network["exit_on_floating_ip_error"]:
2151 self.logger.error("Cannot create floating_ip. %s", str(e))
2152 continue
2153
2154 raise
2155
2156 return server.id, created_items
2157 # except nvExceptions.NotFound as e:
2158 # error_value=-vimconn.HTTP_Not_Found
2159 # error_text= "vm instance %s not found" % vm_id
2160 # except TypeError as e:
2161 # raise vimconn.VimConnException(type(e).__name__ + ": "+ str(e), http_code=vimconn.HTTP_Bad_Request)
2162
2163 except Exception as e:
2164 server_id = None
2165 if server:
2166 server_id = server.id
2167
2168 try:
2169 self.delete_vminstance(server_id, created_items)
2170 except Exception as e2:
2171 self.logger.error("new_vminstance rollback fail {}".format(e2))
2172
2173 self._format_exception(e)
2174
2175 def get_vminstance(self, vm_id):
2176 """Returns the VM instance information from VIM"""
2177 # self.logger.debug("Getting VM from VIM")
2178 try:
2179 self._reload_connection()
2180 server = self.nova.servers.find(id=vm_id)
2181 # TODO parse input and translate to VIM format (openmano_schemas.new_vminstance_response_schema)
2182
2183 return server.to_dict()
2184 except (
2185 ksExceptions.ClientException,
2186 nvExceptions.ClientException,
2187 nvExceptions.NotFound,
2188 ConnectionError,
2189 ) as e:
2190 self._format_exception(e)
2191
2192 def get_vminstance_console(self, vm_id, console_type="vnc"):
2193 """
2194 Get a console for the virtual machine
2195 Params:
2196 vm_id: uuid of the VM
2197 console_type, can be:
2198 "novnc" (by default), "xvpvnc" for VNC types,
2199 "rdp-html5" for RDP types, "spice-html5" for SPICE types
2200 Returns dict with the console parameters:
2201 protocol: ssh, ftp, http, https, ...
2202 server: usually ip address
2203 port: the http, ssh, ... port
2204 suffix: extra text, e.g. the http path and query string
2205 """
2206 self.logger.debug("Getting VM CONSOLE from VIM")
2207
2208 try:
2209 self._reload_connection()
2210 server = self.nova.servers.find(id=vm_id)
2211
2212 if console_type is None or console_type == "novnc":
2213 console_dict = server.get_vnc_console("novnc")
2214 elif console_type == "xvpvnc":
2215 console_dict = server.get_vnc_console(console_type)
2216 elif console_type == "rdp-html5":
2217 console_dict = server.get_rdp_console(console_type)
2218 elif console_type == "spice-html5":
2219 console_dict = server.get_spice_console(console_type)
2220 else:
2221 raise vimconn.VimConnException(
2222 "console type '{}' not allowed".format(console_type),
2223 http_code=vimconn.HTTP_Bad_Request,
2224 )
2225
2226 console_dict1 = console_dict.get("console")
2227
2228 if console_dict1:
2229 console_url = console_dict1.get("url")
2230
2231 if console_url:
2232 # parse console_url
2233 protocol_index = console_url.find("//")
2234 suffix_index = (
2235 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2236 )
2237 port_index = (
2238 console_url[protocol_index + 2 : suffix_index].find(":")
2239 + protocol_index
2240 + 2
2241 )
2242
2243 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
2244 return (
2245 -vimconn.HTTP_Internal_Server_Error,
2246 "Unexpected response from VIM",
2247 )
2248
2249 console_dict = {
2250 "protocol": console_url[0:protocol_index],
2251 "server": console_url[protocol_index + 2 : port_index],
2252 "port": console_url[port_index:suffix_index],
2253 "suffix": console_url[suffix_index + 1 :],
2254 }
2255 protocol_index += 2
2256
2257 return console_dict
2258 raise vimconn.VimConnUnexpectedResponse("Unexpected response from VIM")
2259 except (
2260 nvExceptions.NotFound,
2261 ksExceptions.ClientException,
2262 nvExceptions.ClientException,
2263 nvExceptions.BadRequest,
2264 ConnectionError,
2265 ) as e:
2266 self._format_exception(e)
2267
2268 def delete_vminstance(self, vm_id, created_items=None):
2269 """Removes a VM instance from VIM. Returns the old identifier"""
2270 # print "osconnector: Getting VM from VIM"
2271 if created_items is None:
2272 created_items = {}
2273
2274 try:
2275 self._reload_connection()
2276 # delete VM ports attached to this networks before the virtual machine
2277 for k, v in created_items.items():
2278 if not v: # skip already deleted
2279 continue
2280
2281 try:
2282 k_item, _, k_id = k.partition(":")
2283 if k_item == "port":
2284 port_dict = self.neutron.list_ports()
2285 existing_ports = [
2286 port["id"] for port in port_dict["ports"] if port_dict
2287 ]
2288 if k_id in existing_ports:
2289 self.neutron.delete_port(k_id)
2290 except Exception as e:
2291 self.logger.error(
2292 "Error deleting port: {}: {}".format(type(e).__name__, e)
2293 )
2294
2295 # #commented because detaching the volumes makes the servers.delete not work properly ?!?
2296 # #dettach volumes attached
2297 # server = self.nova.servers.get(vm_id)
2298 # volumes_attached_dict = server._info["os-extended-volumes:volumes_attached"] #volume["id"]
2299 # #for volume in volumes_attached_dict:
2300 # # self.cinder.volumes.detach(volume["id"])
2301
2302 if vm_id:
2303 self.nova.servers.delete(vm_id)
2304
2305 # delete volumes. Although having detached, they should have in active status before deleting
2306 # we ensure in this loop
2307 keep_waiting = True
2308 elapsed_time = 0
2309
2310 while keep_waiting and elapsed_time < volume_timeout:
2311 keep_waiting = False
2312
2313 for k, v in created_items.items():
2314 if not v: # skip already deleted
2315 continue
2316
2317 try:
2318 k_item, _, k_id = k.partition(":")
2319 if k_item == "volume":
2320 if self.cinder.volumes.get(k_id).status != "available":
2321 keep_waiting = True
2322 else:
2323 self.cinder.volumes.delete(k_id)
2324 created_items[k] = None
2325 elif k_item == "floating_ip": # floating ip
2326 self.neutron.delete_floatingip(k_id)
2327 created_items[k] = None
2328
2329 except Exception as e:
2330 self.logger.error("Error deleting {}: {}".format(k, e))
2331
2332 if keep_waiting:
2333 time.sleep(1)
2334 elapsed_time += 1
2335
2336 return None
2337 except (
2338 nvExceptions.NotFound,
2339 ksExceptions.ClientException,
2340 nvExceptions.ClientException,
2341 ConnectionError,
2342 ) as e:
2343 self._format_exception(e)
2344
2345 def refresh_vms_status(self, vm_list):
2346 """Get the status of the virtual machines and their interfaces/ports
2347 Params: the list of VM identifiers
2348 Returns a dictionary with:
2349 vm_id: #VIM id of this Virtual Machine
2350 status: #Mandatory. Text with one of:
2351 # DELETED (not found at vim)
2352 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
2353 # OTHER (Vim reported other status not understood)
2354 # ERROR (VIM indicates an ERROR status)
2355 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
2356 # CREATING (on building process), ERROR
2357 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
2358 #
2359 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
2360 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2361 interfaces:
2362 - vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
2363 mac_address: #Text format XX:XX:XX:XX:XX:XX
2364 vim_net_id: #network id where this interface is connected
2365 vim_interface_id: #interface/port VIM id
2366 ip_address: #null, or text with IPv4, IPv6 address
2367 compute_node: #identification of compute node where PF,VF interface is allocated
2368 pci: #PCI address of the NIC that hosts the PF,VF
2369 vlan: #physical VLAN used for VF
2370 """
2371 vm_dict = {}
2372 self.logger.debug(
2373 "refresh_vms status: Getting tenant VM instance information from VIM"
2374 )
2375
2376 for vm_id in vm_list:
2377 vm = {}
2378
2379 try:
2380 vm_vim = self.get_vminstance(vm_id)
2381
2382 if vm_vim["status"] in vmStatus2manoFormat:
2383 vm["status"] = vmStatus2manoFormat[vm_vim["status"]]
2384 else:
2385 vm["status"] = "OTHER"
2386 vm["error_msg"] = "VIM status reported " + vm_vim["status"]
2387
2388 vm_vim.pop("OS-EXT-SRV-ATTR:user_data", None)
2389 vm_vim.pop("user_data", None)
2390 vm["vim_info"] = self.serialize(vm_vim)
2391
2392 vm["interfaces"] = []
2393 if vm_vim.get("fault"):
2394 vm["error_msg"] = str(vm_vim["fault"])
2395
2396 # get interfaces
2397 try:
2398 self._reload_connection()
2399 port_dict = self.neutron.list_ports(device_id=vm_id)
2400
2401 for port in port_dict["ports"]:
2402 interface = {}
2403 interface["vim_info"] = self.serialize(port)
2404 interface["mac_address"] = port.get("mac_address")
2405 interface["vim_net_id"] = port["network_id"]
2406 interface["vim_interface_id"] = port["id"]
2407 # check if OS-EXT-SRV-ATTR:host is there,
2408 # in case of non-admin credentials, it will be missing
2409
2410 if vm_vim.get("OS-EXT-SRV-ATTR:host"):
2411 interface["compute_node"] = vm_vim["OS-EXT-SRV-ATTR:host"]
2412
2413 interface["pci"] = None
2414
2415 # check if binding:profile is there,
2416 # in case of non-admin credentials, it will be missing
2417 if port.get("binding:profile"):
2418 if port["binding:profile"].get("pci_slot"):
2419 # TODO: At the moment sr-iov pci addresses are converted to PF pci addresses by setting
2420 # the slot to 0x00
2421 # TODO: This is just a workaround valid for niantinc. Find a better way to do so
2422 # CHANGE DDDD:BB:SS.F to DDDD:BB:00.(F%2) assuming there are 2 ports per nic
2423 pci = port["binding:profile"]["pci_slot"]
2424 # interface["pci"] = pci[:-4] + "00." + str(int(pci[-1]) % 2)
2425 interface["pci"] = pci
2426
2427 interface["vlan"] = None
2428
2429 if port.get("binding:vif_details"):
2430 interface["vlan"] = port["binding:vif_details"].get("vlan")
2431
2432 # Get vlan from network in case not present in port for those old openstacks and cases where
2433 # it is needed vlan at PT
2434 if not interface["vlan"]:
2435 # if network is of type vlan and port is of type direct (sr-iov) then set vlan id
2436 network = self.neutron.show_network(port["network_id"])
2437
2438 if (
2439 network["network"].get("provider:network_type")
2440 == "vlan"
2441 ):
2442 # and port.get("binding:vnic_type") in ("direct", "direct-physical"):
2443 interface["vlan"] = network["network"].get(
2444 "provider:segmentation_id"
2445 )
2446
2447 ips = []
2448 # look for floating ip address
2449 try:
2450 floating_ip_dict = self.neutron.list_floatingips(
2451 port_id=port["id"]
2452 )
2453
2454 if floating_ip_dict.get("floatingips"):
2455 ips.append(
2456 floating_ip_dict["floatingips"][0].get(
2457 "floating_ip_address"
2458 )
2459 )
2460 except Exception:
2461 pass
2462
2463 for subnet in port["fixed_ips"]:
2464 ips.append(subnet["ip_address"])
2465
2466 interface["ip_address"] = ";".join(ips)
2467 vm["interfaces"].append(interface)
2468 except Exception as e:
2469 self.logger.error(
2470 "Error getting vm interface information {}: {}".format(
2471 type(e).__name__, e
2472 ),
2473 exc_info=True,
2474 )
2475 except vimconn.VimConnNotFoundException as e:
2476 self.logger.error("Exception getting vm status: %s", str(e))
2477 vm["status"] = "DELETED"
2478 vm["error_msg"] = str(e)
2479 except vimconn.VimConnException as e:
2480 self.logger.error("Exception getting vm status: %s", str(e))
2481 vm["status"] = "VIM_ERROR"
2482 vm["error_msg"] = str(e)
2483
2484 vm_dict[vm_id] = vm
2485
2486 return vm_dict
2487
2488 def action_vminstance(self, vm_id, action_dict, created_items={}):
2489 """Send and action over a VM instance from VIM
2490 Returns None or the console dict if the action was successfully sent to the VIM"""
2491 self.logger.debug("Action over VM '%s': %s", vm_id, str(action_dict))
2492
2493 try:
2494 self._reload_connection()
2495 server = self.nova.servers.find(id=vm_id)
2496
2497 if "start" in action_dict:
2498 if action_dict["start"] == "rebuild":
2499 server.rebuild()
2500 else:
2501 if server.status == "PAUSED":
2502 server.unpause()
2503 elif server.status == "SUSPENDED":
2504 server.resume()
2505 elif server.status == "SHUTOFF":
2506 server.start()
2507 elif "pause" in action_dict:
2508 server.pause()
2509 elif "resume" in action_dict:
2510 server.resume()
2511 elif "shutoff" in action_dict or "shutdown" in action_dict:
2512 server.stop()
2513 elif "forceOff" in action_dict:
2514 server.stop() # TODO
2515 elif "terminate" in action_dict:
2516 server.delete()
2517 elif "createImage" in action_dict:
2518 server.create_image()
2519 # "path":path_schema,
2520 # "description":description_schema,
2521 # "name":name_schema,
2522 # "metadata":metadata_schema,
2523 # "imageRef": id_schema,
2524 # "disk": {"oneOf":[{"type": "null"}, {"type":"string"}] },
2525 elif "rebuild" in action_dict:
2526 server.rebuild(server.image["id"])
2527 elif "reboot" in action_dict:
2528 server.reboot() # reboot_type="SOFT"
2529 elif "console" in action_dict:
2530 console_type = action_dict["console"]
2531
2532 if console_type is None or console_type == "novnc":
2533 console_dict = server.get_vnc_console("novnc")
2534 elif console_type == "xvpvnc":
2535 console_dict = server.get_vnc_console(console_type)
2536 elif console_type == "rdp-html5":
2537 console_dict = server.get_rdp_console(console_type)
2538 elif console_type == "spice-html5":
2539 console_dict = server.get_spice_console(console_type)
2540 else:
2541 raise vimconn.VimConnException(
2542 "console type '{}' not allowed".format(console_type),
2543 http_code=vimconn.HTTP_Bad_Request,
2544 )
2545
2546 try:
2547 console_url = console_dict["console"]["url"]
2548 # parse console_url
2549 protocol_index = console_url.find("//")
2550 suffix_index = (
2551 console_url[protocol_index + 2 :].find("/") + protocol_index + 2
2552 )
2553 port_index = (
2554 console_url[protocol_index + 2 : suffix_index].find(":")
2555 + protocol_index
2556 + 2
2557 )
2558
2559 if protocol_index < 0 or port_index < 0 or suffix_index < 0:
2560 raise vimconn.VimConnException(
2561 "Unexpected response from VIM " + str(console_dict)
2562 )
2563
2564 console_dict2 = {
2565 "protocol": console_url[0:protocol_index],
2566 "server": console_url[protocol_index + 2 : port_index],
2567 "port": int(console_url[port_index + 1 : suffix_index]),
2568 "suffix": console_url[suffix_index + 1 :],
2569 }
2570
2571 return console_dict2
2572 except Exception:
2573 raise vimconn.VimConnException(
2574 "Unexpected response from VIM " + str(console_dict)
2575 )
2576
2577 return None
2578 except (
2579 ksExceptions.ClientException,
2580 nvExceptions.ClientException,
2581 nvExceptions.NotFound,
2582 ConnectionError,
2583 ) as e:
2584 self._format_exception(e)
2585 # TODO insert exception vimconn.HTTP_Unauthorized
2586
2587 # ###### VIO Specific Changes #########
2588 def _generate_vlanID(self):
2589 """
2590 Method to get unused vlanID
2591 Args:
2592 None
2593 Returns:
2594 vlanID
2595 """
2596 # Get used VLAN IDs
2597 usedVlanIDs = []
2598 networks = self.get_network_list()
2599
2600 for net in networks:
2601 if net.get("provider:segmentation_id"):
2602 usedVlanIDs.append(net.get("provider:segmentation_id"))
2603
2604 used_vlanIDs = set(usedVlanIDs)
2605
2606 # find unused VLAN ID
2607 for vlanID_range in self.config.get("dataplane_net_vlan_range"):
2608 try:
2609 start_vlanid, end_vlanid = map(
2610 int, vlanID_range.replace(" ", "").split("-")
2611 )
2612
2613 for vlanID in range(start_vlanid, end_vlanid + 1):
2614 if vlanID not in used_vlanIDs:
2615 return vlanID
2616 except Exception as exp:
2617 raise vimconn.VimConnException(
2618 "Exception {} occurred while generating VLAN ID.".format(exp)
2619 )
2620 else:
2621 raise vimconn.VimConnConflictException(
2622 "Unable to create the SRIOV VLAN network. All given Vlan IDs {} are in use.".format(
2623 self.config.get("dataplane_net_vlan_range")
2624 )
2625 )
2626
2627 def _generate_multisegment_vlanID(self):
2628 """
2629 Method to get unused vlanID
2630 Args:
2631 None
2632 Returns:
2633 vlanID
2634 """
2635 # Get used VLAN IDs
2636 usedVlanIDs = []
2637 networks = self.get_network_list()
2638 for net in networks:
2639 if net.get("provider:network_type") == "vlan" and net.get(
2640 "provider:segmentation_id"
2641 ):
2642 usedVlanIDs.append(net.get("provider:segmentation_id"))
2643 elif net.get("segments"):
2644 for segment in net.get("segments"):
2645 if segment.get("provider:network_type") == "vlan" and segment.get(
2646 "provider:segmentation_id"
2647 ):
2648 usedVlanIDs.append(segment.get("provider:segmentation_id"))
2649
2650 used_vlanIDs = set(usedVlanIDs)
2651
2652 # find unused VLAN ID
2653 for vlanID_range in self.config.get("multisegment_vlan_range"):
2654 try:
2655 start_vlanid, end_vlanid = map(
2656 int, vlanID_range.replace(" ", "").split("-")
2657 )
2658
2659 for vlanID in range(start_vlanid, end_vlanid + 1):
2660 if vlanID not in used_vlanIDs:
2661 return vlanID
2662 except Exception as exp:
2663 raise vimconn.VimConnException(
2664 "Exception {} occurred while generating VLAN ID.".format(exp)
2665 )
2666 else:
2667 raise vimconn.VimConnConflictException(
2668 "Unable to create the VLAN segment. All VLAN IDs {} are in use.".format(
2669 self.config.get("multisegment_vlan_range")
2670 )
2671 )
2672
2673 def _validate_vlan_ranges(self, input_vlan_range, text_vlan_range):
2674 """
2675 Method to validate user given vlanID ranges
2676 Args: None
2677 Returns: None
2678 """
2679 for vlanID_range in input_vlan_range:
2680 vlan_range = vlanID_range.replace(" ", "")
2681 # validate format
2682 vlanID_pattern = r"(\d)*-(\d)*$"
2683 match_obj = re.match(vlanID_pattern, vlan_range)
2684 if not match_obj:
2685 raise vimconn.VimConnConflictException(
2686 "Invalid VLAN range for {}: {}.You must provide "
2687 "'{}' in format [start_ID - end_ID].".format(
2688 text_vlan_range, vlanID_range, text_vlan_range
2689 )
2690 )
2691
2692 start_vlanid, end_vlanid = map(int, vlan_range.split("-"))
2693 if start_vlanid <= 0:
2694 raise vimconn.VimConnConflictException(
2695 "Invalid VLAN range for {}: {}. Start ID can not be zero. For VLAN "
2696 "networks valid IDs are 1 to 4094 ".format(
2697 text_vlan_range, vlanID_range
2698 )
2699 )
2700
2701 if end_vlanid > 4094:
2702 raise vimconn.VimConnConflictException(
2703 "Invalid VLAN range for {}: {}. End VLAN ID can not be "
2704 "greater than 4094. For VLAN networks valid IDs are 1 to 4094 ".format(
2705 text_vlan_range, vlanID_range
2706 )
2707 )
2708
2709 if start_vlanid > end_vlanid:
2710 raise vimconn.VimConnConflictException(
2711 "Invalid VLAN range for {}: {}. You must provide '{}'"
2712 " in format start_ID - end_ID and start_ID < end_ID ".format(
2713 text_vlan_range, vlanID_range, text_vlan_range
2714 )
2715 )
2716
2717 # NOT USED FUNCTIONS
2718
2719 def new_external_port(self, port_data):
2720 """Adds a external port to VIM
2721 Returns the port identifier"""
2722 # TODO openstack if needed
2723 return (
2724 -vimconn.HTTP_Internal_Server_Error,
2725 "osconnector.new_external_port() not implemented",
2726 )
2727
2728 def connect_port_network(self, port_id, network_id, admin=False):
2729 """Connects a external port to a network
2730 Returns status code of the VIM response"""
2731 # TODO openstack if needed
2732 return (
2733 -vimconn.HTTP_Internal_Server_Error,
2734 "osconnector.connect_port_network() not implemented",
2735 )
2736
2737 def new_user(self, user_name, user_passwd, tenant_id=None):
2738 """Adds a new user to openstack VIM
2739 Returns the user identifier"""
2740 self.logger.debug("osconnector: Adding a new user to VIM")
2741
2742 try:
2743 self._reload_connection()
2744 user = self.keystone.users.create(
2745 user_name, password=user_passwd, default_project=tenant_id
2746 )
2747 # self.keystone.tenants.add_user(self.k_creds["username"], #role)
2748
2749 return user.id
2750 except ksExceptions.ConnectionError as e:
2751 error_value = -vimconn.HTTP_Bad_Request
2752 error_text = (
2753 type(e).__name__
2754 + ": "
2755 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2756 )
2757 except ksExceptions.ClientException as e: # TODO remove
2758 error_value = -vimconn.HTTP_Bad_Request
2759 error_text = (
2760 type(e).__name__
2761 + ": "
2762 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2763 )
2764
2765 # TODO insert exception vimconn.HTTP_Unauthorized
2766 # if reaching here is because an exception
2767 self.logger.debug("new_user " + error_text)
2768
2769 return error_value, error_text
2770
2771 def delete_user(self, user_id):
2772 """Delete a user from openstack VIM
2773 Returns the user identifier"""
2774 if self.debug:
2775 print("osconnector: Deleting a user from VIM")
2776
2777 try:
2778 self._reload_connection()
2779 self.keystone.users.delete(user_id)
2780
2781 return 1, user_id
2782 except ksExceptions.ConnectionError as e:
2783 error_value = -vimconn.HTTP_Bad_Request
2784 error_text = (
2785 type(e).__name__
2786 + ": "
2787 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2788 )
2789 except ksExceptions.NotFound as e:
2790 error_value = -vimconn.HTTP_Not_Found
2791 error_text = (
2792 type(e).__name__
2793 + ": "
2794 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2795 )
2796 except ksExceptions.ClientException as e: # TODO remove
2797 error_value = -vimconn.HTTP_Bad_Request
2798 error_text = (
2799 type(e).__name__
2800 + ": "
2801 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2802 )
2803
2804 # TODO insert exception vimconn.HTTP_Unauthorized
2805 # if reaching here is because an exception
2806 self.logger.debug("delete_tenant " + error_text)
2807
2808 return error_value, error_text
2809
2810 def get_hosts_info(self):
2811 """Get the information of deployed hosts
2812 Returns the hosts content"""
2813 if self.debug:
2814 print("osconnector: Getting Host info from VIM")
2815
2816 try:
2817 h_list = []
2818 self._reload_connection()
2819 hypervisors = self.nova.hypervisors.list()
2820
2821 for hype in hypervisors:
2822 h_list.append(hype.to_dict())
2823
2824 return 1, {"hosts": h_list}
2825 except nvExceptions.NotFound as e:
2826 error_value = -vimconn.HTTP_Not_Found
2827 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
2828 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
2829 error_value = -vimconn.HTTP_Bad_Request
2830 error_text = (
2831 type(e).__name__
2832 + ": "
2833 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2834 )
2835
2836 # TODO insert exception vimconn.HTTP_Unauthorized
2837 # if reaching here is because an exception
2838 self.logger.debug("get_hosts_info " + error_text)
2839
2840 return error_value, error_text
2841
2842 def get_hosts(self, vim_tenant):
2843 """Get the hosts and deployed instances
2844 Returns the hosts content"""
2845 r, hype_dict = self.get_hosts_info()
2846
2847 if r < 0:
2848 return r, hype_dict
2849
2850 hypervisors = hype_dict["hosts"]
2851
2852 try:
2853 servers = self.nova.servers.list()
2854 for hype in hypervisors:
2855 for server in servers:
2856 if (
2857 server.to_dict()["OS-EXT-SRV-ATTR:hypervisor_hostname"]
2858 == hype["hypervisor_hostname"]
2859 ):
2860 if "vm" in hype:
2861 hype["vm"].append(server.id)
2862 else:
2863 hype["vm"] = [server.id]
2864
2865 return 1, hype_dict
2866 except nvExceptions.NotFound as e:
2867 error_value = -vimconn.HTTP_Not_Found
2868 error_text = str(e) if len(e.args) == 0 else str(e.args[0])
2869 except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
2870 error_value = -vimconn.HTTP_Bad_Request
2871 error_text = (
2872 type(e).__name__
2873 + ": "
2874 + (str(e) if len(e.args) == 0 else str(e.args[0]))
2875 )
2876
2877 # TODO insert exception vimconn.HTTP_Unauthorized
2878 # if reaching here is because an exception
2879 self.logger.debug("get_hosts " + error_text)
2880
2881 return error_value, error_text
2882
2883 def new_classification(self, name, ctype, definition):
2884 self.logger.debug(
2885 "Adding a new (Traffic) Classification to VIM, named %s", name
2886 )
2887
2888 try:
2889 new_class = None
2890 self._reload_connection()
2891
2892 if ctype not in supportedClassificationTypes:
2893 raise vimconn.VimConnNotSupportedException(
2894 "OpenStack VIM connector does not support provided "
2895 "Classification Type {}, supported ones are: {}".format(
2896 ctype, supportedClassificationTypes
2897 )
2898 )
2899
2900 if not self._validate_classification(ctype, definition):
2901 raise vimconn.VimConnException(
2902 "Incorrect Classification definition for the type specified."
2903 )
2904
2905 classification_dict = definition
2906 classification_dict["name"] = name
2907 new_class = self.neutron.create_sfc_flow_classifier(
2908 {"flow_classifier": classification_dict}
2909 )
2910
2911 return new_class["flow_classifier"]["id"]
2912 except (
2913 neExceptions.ConnectionFailed,
2914 ksExceptions.ClientException,
2915 neExceptions.NeutronException,
2916 ConnectionError,
2917 ) as e:
2918 self.logger.error("Creation of Classification failed.")
2919 self._format_exception(e)
2920
2921 def get_classification(self, class_id):
2922 self.logger.debug(" Getting Classification %s from VIM", class_id)
2923 filter_dict = {"id": class_id}
2924 class_list = self.get_classification_list(filter_dict)
2925
2926 if len(class_list) == 0:
2927 raise vimconn.VimConnNotFoundException(
2928 "Classification '{}' not found".format(class_id)
2929 )
2930 elif len(class_list) > 1:
2931 raise vimconn.VimConnConflictException(
2932 "Found more than one Classification with this criteria"
2933 )
2934
2935 classification = class_list[0]
2936
2937 return classification
2938
2939 def get_classification_list(self, filter_dict={}):
2940 self.logger.debug(
2941 "Getting Classifications from VIM filter: '%s'", str(filter_dict)
2942 )
2943
2944 try:
2945 filter_dict_os = filter_dict.copy()
2946 self._reload_connection()
2947
2948 if self.api_version3 and "tenant_id" in filter_dict_os:
2949 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
2950
2951 classification_dict = self.neutron.list_sfc_flow_classifiers(
2952 **filter_dict_os
2953 )
2954 classification_list = classification_dict["flow_classifiers"]
2955 self.__classification_os2mano(classification_list)
2956
2957 return classification_list
2958 except (
2959 neExceptions.ConnectionFailed,
2960 ksExceptions.ClientException,
2961 neExceptions.NeutronException,
2962 ConnectionError,
2963 ) as e:
2964 self._format_exception(e)
2965
2966 def delete_classification(self, class_id):
2967 self.logger.debug("Deleting Classification '%s' from VIM", class_id)
2968
2969 try:
2970 self._reload_connection()
2971 self.neutron.delete_sfc_flow_classifier(class_id)
2972
2973 return class_id
2974 except (
2975 neExceptions.ConnectionFailed,
2976 neExceptions.NeutronException,
2977 ksExceptions.ClientException,
2978 neExceptions.NeutronException,
2979 ConnectionError,
2980 ) as e:
2981 self._format_exception(e)
2982
2983 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
2984 self.logger.debug(
2985 "Adding a new Service Function Instance to VIM, named '%s'", name
2986 )
2987
2988 try:
2989 new_sfi = None
2990 self._reload_connection()
2991 correlation = None
2992
2993 if sfc_encap:
2994 correlation = "nsh"
2995
2996 if len(ingress_ports) != 1:
2997 raise vimconn.VimConnNotSupportedException(
2998 "OpenStack VIM connector can only have 1 ingress port per SFI"
2999 )
3000
3001 if len(egress_ports) != 1:
3002 raise vimconn.VimConnNotSupportedException(
3003 "OpenStack VIM connector can only have 1 egress port per SFI"
3004 )
3005
3006 sfi_dict = {
3007 "name": name,
3008 "ingress": ingress_ports[0],
3009 "egress": egress_ports[0],
3010 "service_function_parameters": {"correlation": correlation},
3011 }
3012 new_sfi = self.neutron.create_sfc_port_pair({"port_pair": sfi_dict})
3013
3014 return new_sfi["port_pair"]["id"]
3015 except (
3016 neExceptions.ConnectionFailed,
3017 ksExceptions.ClientException,
3018 neExceptions.NeutronException,
3019 ConnectionError,
3020 ) as e:
3021 if new_sfi:
3022 try:
3023 self.neutron.delete_sfc_port_pair(new_sfi["port_pair"]["id"])
3024 except Exception:
3025 self.logger.error(
3026 "Creation of Service Function Instance failed, with "
3027 "subsequent deletion failure as well."
3028 )
3029
3030 self._format_exception(e)
3031
3032 def get_sfi(self, sfi_id):
3033 self.logger.debug("Getting Service Function Instance %s from VIM", sfi_id)
3034 filter_dict = {"id": sfi_id}
3035 sfi_list = self.get_sfi_list(filter_dict)
3036
3037 if len(sfi_list) == 0:
3038 raise vimconn.VimConnNotFoundException(
3039 "Service Function Instance '{}' not found".format(sfi_id)
3040 )
3041 elif len(sfi_list) > 1:
3042 raise vimconn.VimConnConflictException(
3043 "Found more than one Service Function Instance with this criteria"
3044 )
3045
3046 sfi = sfi_list[0]
3047
3048 return sfi
3049
3050 def get_sfi_list(self, filter_dict={}):
3051 self.logger.debug(
3052 "Getting Service Function Instances from VIM filter: '%s'", str(filter_dict)
3053 )
3054
3055 try:
3056 self._reload_connection()
3057 filter_dict_os = filter_dict.copy()
3058
3059 if self.api_version3 and "tenant_id" in filter_dict_os:
3060 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3061
3062 sfi_dict = self.neutron.list_sfc_port_pairs(**filter_dict_os)
3063 sfi_list = sfi_dict["port_pairs"]
3064 self.__sfi_os2mano(sfi_list)
3065
3066 return sfi_list
3067 except (
3068 neExceptions.ConnectionFailed,
3069 ksExceptions.ClientException,
3070 neExceptions.NeutronException,
3071 ConnectionError,
3072 ) as e:
3073 self._format_exception(e)
3074
3075 def delete_sfi(self, sfi_id):
3076 self.logger.debug("Deleting Service Function Instance '%s' from VIM", sfi_id)
3077
3078 try:
3079 self._reload_connection()
3080 self.neutron.delete_sfc_port_pair(sfi_id)
3081
3082 return sfi_id
3083 except (
3084 neExceptions.ConnectionFailed,
3085 neExceptions.NeutronException,
3086 ksExceptions.ClientException,
3087 neExceptions.NeutronException,
3088 ConnectionError,
3089 ) as e:
3090 self._format_exception(e)
3091
3092 def new_sf(self, name, sfis, sfc_encap=True):
3093 self.logger.debug("Adding a new Service Function to VIM, named '%s'", name)
3094
3095 try:
3096 new_sf = None
3097 self._reload_connection()
3098 # correlation = None
3099 # if sfc_encap:
3100 # correlation = "nsh"
3101
3102 for instance in sfis:
3103 sfi = self.get_sfi(instance)
3104
3105 if sfi.get("sfc_encap") != sfc_encap:
3106 raise vimconn.VimConnNotSupportedException(
3107 "OpenStack VIM connector requires all SFIs of the "
3108 "same SF to share the same SFC Encapsulation"
3109 )
3110
3111 sf_dict = {"name": name, "port_pairs": sfis}
3112 new_sf = self.neutron.create_sfc_port_pair_group(
3113 {"port_pair_group": sf_dict}
3114 )
3115
3116 return new_sf["port_pair_group"]["id"]
3117 except (
3118 neExceptions.ConnectionFailed,
3119 ksExceptions.ClientException,
3120 neExceptions.NeutronException,
3121 ConnectionError,
3122 ) as e:
3123 if new_sf:
3124 try:
3125 self.neutron.delete_sfc_port_pair_group(
3126 new_sf["port_pair_group"]["id"]
3127 )
3128 except Exception:
3129 self.logger.error(
3130 "Creation of Service Function failed, with "
3131 "subsequent deletion failure as well."
3132 )
3133
3134 self._format_exception(e)
3135
3136 def get_sf(self, sf_id):
3137 self.logger.debug("Getting Service Function %s from VIM", sf_id)
3138 filter_dict = {"id": sf_id}
3139 sf_list = self.get_sf_list(filter_dict)
3140
3141 if len(sf_list) == 0:
3142 raise vimconn.VimConnNotFoundException(
3143 "Service Function '{}' not found".format(sf_id)
3144 )
3145 elif len(sf_list) > 1:
3146 raise vimconn.VimConnConflictException(
3147 "Found more than one Service Function with this criteria"
3148 )
3149
3150 sf = sf_list[0]
3151
3152 return sf
3153
3154 def get_sf_list(self, filter_dict={}):
3155 self.logger.debug(
3156 "Getting Service Function from VIM filter: '%s'", str(filter_dict)
3157 )
3158
3159 try:
3160 self._reload_connection()
3161 filter_dict_os = filter_dict.copy()
3162
3163 if self.api_version3 and "tenant_id" in filter_dict_os:
3164 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3165
3166 sf_dict = self.neutron.list_sfc_port_pair_groups(**filter_dict_os)
3167 sf_list = sf_dict["port_pair_groups"]
3168 self.__sf_os2mano(sf_list)
3169
3170 return sf_list
3171 except (
3172 neExceptions.ConnectionFailed,
3173 ksExceptions.ClientException,
3174 neExceptions.NeutronException,
3175 ConnectionError,
3176 ) as e:
3177 self._format_exception(e)
3178
3179 def delete_sf(self, sf_id):
3180 self.logger.debug("Deleting Service Function '%s' from VIM", sf_id)
3181
3182 try:
3183 self._reload_connection()
3184 self.neutron.delete_sfc_port_pair_group(sf_id)
3185
3186 return sf_id
3187 except (
3188 neExceptions.ConnectionFailed,
3189 neExceptions.NeutronException,
3190 ksExceptions.ClientException,
3191 neExceptions.NeutronException,
3192 ConnectionError,
3193 ) as e:
3194 self._format_exception(e)
3195
3196 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
3197 self.logger.debug("Adding a new Service Function Path to VIM, named '%s'", name)
3198
3199 try:
3200 new_sfp = None
3201 self._reload_connection()
3202 # In networking-sfc the MPLS encapsulation is legacy
3203 # should be used when no full SFC Encapsulation is intended
3204 correlation = "mpls"
3205
3206 if sfc_encap:
3207 correlation = "nsh"
3208
3209 sfp_dict = {
3210 "name": name,
3211 "flow_classifiers": classifications,
3212 "port_pair_groups": sfs,
3213 "chain_parameters": {"correlation": correlation},
3214 }
3215
3216 if spi:
3217 sfp_dict["chain_id"] = spi
3218
3219 new_sfp = self.neutron.create_sfc_port_chain({"port_chain": sfp_dict})
3220
3221 return new_sfp["port_chain"]["id"]
3222 except (
3223 neExceptions.ConnectionFailed,
3224 ksExceptions.ClientException,
3225 neExceptions.NeutronException,
3226 ConnectionError,
3227 ) as e:
3228 if new_sfp:
3229 try:
3230 self.neutron.delete_sfc_port_chain(new_sfp["port_chain"]["id"])
3231 except Exception:
3232 self.logger.error(
3233 "Creation of Service Function Path failed, with "
3234 "subsequent deletion failure as well."
3235 )
3236
3237 self._format_exception(e)
3238
3239 def get_sfp(self, sfp_id):
3240 self.logger.debug(" Getting Service Function Path %s from VIM", sfp_id)
3241
3242 filter_dict = {"id": sfp_id}
3243 sfp_list = self.get_sfp_list(filter_dict)
3244
3245 if len(sfp_list) == 0:
3246 raise vimconn.VimConnNotFoundException(
3247 "Service Function Path '{}' not found".format(sfp_id)
3248 )
3249 elif len(sfp_list) > 1:
3250 raise vimconn.VimConnConflictException(
3251 "Found more than one Service Function Path with this criteria"
3252 )
3253
3254 sfp = sfp_list[0]
3255
3256 return sfp
3257
3258 def get_sfp_list(self, filter_dict={}):
3259 self.logger.debug(
3260 "Getting Service Function Paths from VIM filter: '%s'", str(filter_dict)
3261 )
3262
3263 try:
3264 self._reload_connection()
3265 filter_dict_os = filter_dict.copy()
3266
3267 if self.api_version3 and "tenant_id" in filter_dict_os:
3268 filter_dict_os["project_id"] = filter_dict_os.pop("tenant_id")
3269
3270 sfp_dict = self.neutron.list_sfc_port_chains(**filter_dict_os)
3271 sfp_list = sfp_dict["port_chains"]
3272 self.__sfp_os2mano(sfp_list)
3273
3274 return sfp_list
3275 except (
3276 neExceptions.ConnectionFailed,
3277 ksExceptions.ClientException,
3278 neExceptions.NeutronException,
3279 ConnectionError,
3280 ) as e:
3281 self._format_exception(e)
3282
3283 def delete_sfp(self, sfp_id):
3284 self.logger.debug("Deleting Service Function Path '%s' from VIM", sfp_id)
3285
3286 try:
3287 self._reload_connection()
3288 self.neutron.delete_sfc_port_chain(sfp_id)
3289
3290 return sfp_id
3291 except (
3292 neExceptions.ConnectionFailed,
3293 neExceptions.NeutronException,
3294 ksExceptions.ClientException,
3295 neExceptions.NeutronException,
3296 ConnectionError,
3297 ) as e:
3298 self._format_exception(e)
3299
3300 def refresh_sfps_status(self, sfp_list):
3301 """Get the status of the service function path
3302 Params: the list of sfp identifiers
3303 Returns a dictionary with:
3304 vm_id: #VIM id of this service function path
3305 status: #Mandatory. Text with one of:
3306 # DELETED (not found at vim)
3307 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3308 # OTHER (Vim reported other status not understood)
3309 # ERROR (VIM indicates an ERROR status)
3310 # ACTIVE,
3311 # CREATING (on building process)
3312 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3313 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
3314 """
3315 sfp_dict = {}
3316 self.logger.debug(
3317 "refresh_sfps status: Getting tenant SFP information from VIM"
3318 )
3319
3320 for sfp_id in sfp_list:
3321 sfp = {}
3322
3323 try:
3324 sfp_vim = self.get_sfp(sfp_id)
3325
3326 if sfp_vim["spi"]:
3327 sfp["status"] = vmStatus2manoFormat["ACTIVE"]
3328 else:
3329 sfp["status"] = "OTHER"
3330 sfp["error_msg"] = "VIM status reported " + sfp["status"]
3331
3332 sfp["vim_info"] = self.serialize(sfp_vim)
3333
3334 if sfp_vim.get("fault"):
3335 sfp["error_msg"] = str(sfp_vim["fault"])
3336 except vimconn.VimConnNotFoundException as e:
3337 self.logger.error("Exception getting sfp status: %s", str(e))
3338 sfp["status"] = "DELETED"
3339 sfp["error_msg"] = str(e)
3340 except vimconn.VimConnException as e:
3341 self.logger.error("Exception getting sfp status: %s", str(e))
3342 sfp["status"] = "VIM_ERROR"
3343 sfp["error_msg"] = str(e)
3344
3345 sfp_dict[sfp_id] = sfp
3346
3347 return sfp_dict
3348
3349 def refresh_sfis_status(self, sfi_list):
3350 """Get the status of the service function instances
3351 Params: the list of sfi identifiers
3352 Returns a dictionary with:
3353 vm_id: #VIM id of this service function instance
3354 status: #Mandatory. Text with one of:
3355 # DELETED (not found at vim)
3356 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3357 # OTHER (Vim reported other status not understood)
3358 # ERROR (VIM indicates an ERROR status)
3359 # ACTIVE,
3360 # CREATING (on building process)
3361 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3362 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3363 """
3364 sfi_dict = {}
3365 self.logger.debug(
3366 "refresh_sfis status: Getting tenant sfi information from VIM"
3367 )
3368
3369 for sfi_id in sfi_list:
3370 sfi = {}
3371
3372 try:
3373 sfi_vim = self.get_sfi(sfi_id)
3374
3375 if sfi_vim:
3376 sfi["status"] = vmStatus2manoFormat["ACTIVE"]
3377 else:
3378 sfi["status"] = "OTHER"
3379 sfi["error_msg"] = "VIM status reported " + sfi["status"]
3380
3381 sfi["vim_info"] = self.serialize(sfi_vim)
3382
3383 if sfi_vim.get("fault"):
3384 sfi["error_msg"] = str(sfi_vim["fault"])
3385 except vimconn.VimConnNotFoundException as e:
3386 self.logger.error("Exception getting sfi status: %s", str(e))
3387 sfi["status"] = "DELETED"
3388 sfi["error_msg"] = str(e)
3389 except vimconn.VimConnException as e:
3390 self.logger.error("Exception getting sfi status: %s", str(e))
3391 sfi["status"] = "VIM_ERROR"
3392 sfi["error_msg"] = str(e)
3393
3394 sfi_dict[sfi_id] = sfi
3395
3396 return sfi_dict
3397
3398 def refresh_sfs_status(self, sf_list):
3399 """Get the status of the service functions
3400 Params: the list of sf identifiers
3401 Returns a dictionary with:
3402 vm_id: #VIM id of this service function
3403 status: #Mandatory. Text with one of:
3404 # DELETED (not found at vim)
3405 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3406 # OTHER (Vim reported other status not understood)
3407 # ERROR (VIM indicates an ERROR status)
3408 # ACTIVE,
3409 # CREATING (on building process)
3410 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3411 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3412 """
3413 sf_dict = {}
3414 self.logger.debug("refresh_sfs status: Getting tenant sf information from VIM")
3415
3416 for sf_id in sf_list:
3417 sf = {}
3418
3419 try:
3420 sf_vim = self.get_sf(sf_id)
3421
3422 if sf_vim:
3423 sf["status"] = vmStatus2manoFormat["ACTIVE"]
3424 else:
3425 sf["status"] = "OTHER"
3426 sf["error_msg"] = "VIM status reported " + sf_vim["status"]
3427
3428 sf["vim_info"] = self.serialize(sf_vim)
3429
3430 if sf_vim.get("fault"):
3431 sf["error_msg"] = str(sf_vim["fault"])
3432 except vimconn.VimConnNotFoundException as e:
3433 self.logger.error("Exception getting sf status: %s", str(e))
3434 sf["status"] = "DELETED"
3435 sf["error_msg"] = str(e)
3436 except vimconn.VimConnException as e:
3437 self.logger.error("Exception getting sf status: %s", str(e))
3438 sf["status"] = "VIM_ERROR"
3439 sf["error_msg"] = str(e)
3440
3441 sf_dict[sf_id] = sf
3442
3443 return sf_dict
3444
3445 def refresh_classifications_status(self, classification_list):
3446 """Get the status of the classifications
3447 Params: the list of classification identifiers
3448 Returns a dictionary with:
3449 vm_id: #VIM id of this classifier
3450 status: #Mandatory. Text with one of:
3451 # DELETED (not found at vim)
3452 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
3453 # OTHER (Vim reported other status not understood)
3454 # ERROR (VIM indicates an ERROR status)
3455 # ACTIVE,
3456 # CREATING (on building process)
3457 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
3458 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
3459 """
3460 classification_dict = {}
3461 self.logger.debug(
3462 "refresh_classifications status: Getting tenant classification information from VIM"
3463 )
3464
3465 for classification_id in classification_list:
3466 classification = {}
3467
3468 try:
3469 classification_vim = self.get_classification(classification_id)
3470
3471 if classification_vim:
3472 classification["status"] = vmStatus2manoFormat["ACTIVE"]
3473 else:
3474 classification["status"] = "OTHER"
3475 classification["error_msg"] = (
3476 "VIM status reported " + classification["status"]
3477 )
3478
3479 classification["vim_info"] = self.serialize(classification_vim)
3480
3481 if classification_vim.get("fault"):
3482 classification["error_msg"] = str(classification_vim["fault"])
3483 except vimconn.VimConnNotFoundException as e:
3484 self.logger.error("Exception getting classification status: %s", str(e))
3485 classification["status"] = "DELETED"
3486 classification["error_msg"] = str(e)
3487 except vimconn.VimConnException as e:
3488 self.logger.error("Exception getting classification status: %s", str(e))
3489 classification["status"] = "VIM_ERROR"
3490 classification["error_msg"] = str(e)
3491
3492 classification_dict[classification_id] = classification
3493
3494 return classification_dict
3495
3496 def new_affinity_group(self, affinity_group_data):
3497 """Adds a server group to VIM
3498 affinity_group_data contains a dictionary with information, keys:
3499 name: name in VIM for the server group
3500 type: affinity or anti-affinity
3501 scope: Only nfvi-node allowed
3502 Returns the server group identifier"""
3503 self.logger.debug("Adding Server Group '%s'", str(affinity_group_data))
3504
3505 try:
3506 name = affinity_group_data["name"]
3507 policy = affinity_group_data["type"]
3508
3509 self._reload_connection()
3510 new_server_group = self.nova.server_groups.create(name, policy)
3511
3512 return new_server_group.id
3513 except (
3514 ksExceptions.ClientException,
3515 nvExceptions.ClientException,
3516 ConnectionError,
3517 KeyError,
3518 ) as e:
3519 self._format_exception(e)
3520
3521 def get_affinity_group(self, affinity_group_id):
3522 """Obtain server group details from the VIM. Returns the server group detais as a dict"""
3523 self.logger.debug("Getting flavor '%s'", affinity_group_id)
3524 try:
3525 self._reload_connection()
3526 server_group = self.nova.server_groups.find(id=affinity_group_id)
3527
3528 return server_group.to_dict()
3529 except (
3530 nvExceptions.NotFound,
3531 nvExceptions.ClientException,
3532 ksExceptions.ClientException,
3533 ConnectionError,
3534 ) as e:
3535 self._format_exception(e)
3536
3537 def delete_affinity_group(self, affinity_group_id):
3538 """Deletes a server group from the VIM. Returns the old affinity_group_id"""
3539 self.logger.debug("Getting server group '%s'", affinity_group_id)
3540 try:
3541 self._reload_connection()
3542 self.nova.server_groups.delete(affinity_group_id)
3543
3544 return affinity_group_id
3545 except (
3546 nvExceptions.NotFound,
3547 ksExceptions.ClientException,
3548 nvExceptions.ClientException,
3549 ConnectionError,
3550 ) as e:
3551 self._format_exception(e)