def login(self): """Get session based login""" login_obj = {"username": self.username, "password": self.password} msg = "NetScaler driver login:"******"login", NITRO_LOGIN_URI, "login", login_obj) LOG.info(_LI("Response: status : %(status)s %result(result)s"), { "status": resp_status, "result": result['body']}) result_body = jsonutils.loads(result['body']) session_id = None if result_body and "login" in result_body: logins = result_body["login"] if isinstance(logins, list): login = logins[0] else: login = logins if login and "sessionid" in login: session_id = login["sessionid"] if session_id: LOG.info(_LI("Response: %(result)s"), {"result": result['body']}) LOG.info( _LI("Session_id = %(session_id)s") % {"session_id": session_id}) # Update sessin_id in auth self.auth = "SessId=%s" % session_id else: raise NCCException(NCCException.RESPONSE_ERROR)
def stop(self, graceful=False): if self.server: LOG.info(_LI('Stopping consumer...')) self.server.stop() if graceful: LOG.info( _LI('Consumer successfully stopped. Waiting for final ' 'messages to be processed...')) self.server.wait() super(OctaviaConsumer, self).stop(graceful=graceful)
def agent_updated(self, context, payload): """Handle the agent_updated notification event.""" if payload['admin_state_up'] != self.admin_state_up: self.admin_state_up = payload['admin_state_up'] if self.admin_state_up: self.needs_resync = True else: for pool_id in self.instance_mapping.keys(): LOG.info(_LI("Destroying pool %s due to agent disabling"), pool_id) self._destroy_pool(pool_id) LOG.info(_LI("Agent_updated by server side %s!"), payload)
def agent_updated(self, context, payload): """Handle the agent_updated notification event.""" if payload["admin_state_up"] != self.admin_state_up: self.admin_state_up = payload["admin_state_up"] if self.admin_state_up: self.needs_resync = True else: # Copy keys since the dictionary is modified in the loop body for loadbalancer_id in list(self.instance_mapping.keys()): LOG.info(_LI("Destroying loadbalancer %s due to agent " "disabling"), loadbalancer_id) self._destroy_loadbalancer(loadbalancer_id) LOG.info(_LI("Agent_updated by server side %s!"), payload)
def agent_updated(self, context, payload): """Handle the agent_updated notification event.""" if payload['admin_state_up'] != self.admin_state_up: self.admin_state_up = payload['admin_state_up'] if self.admin_state_up: self.needs_resync = True else: for loadbalancer_id in self.instance_mapping.keys(): LOG.info(_LI("Destroying loadbalancer %s due to agent " "disabling"), loadbalancer_id) self._destroy_loadbalancer(loadbalancer_id) LOG.info(_LI("Agent_updated by server side %s!"), payload)
def _create_snatport_for_subnet_if_not_exists(self, context, tenant_id, subnet_id, network_info): port = self._get_snatport_for_subnet(context, tenant_id, subnet_id) if not port: LOG.info(_LI("No SNAT port found for subnet %s. Creating one..."), subnet_id) port = self._create_snatport_for_subnet(context, tenant_id, subnet_id, ip_address=None) network_info['port_id'] = port['id'] network_info['snat_ip'] = port['fixed_ips'][0]['ip_address'] LOG.info(_LI("SNAT port: %r"), port)
def agent_updated(self, context, payload): """Handle the agent_updated notification event.""" if payload['admin_state_up'] != self.admin_state_up: self.admin_state_up = payload['admin_state_up'] if self.admin_state_up: self.needs_resync = True else: # Copy keys because the dict is modified in the loop body for pool_id in list(self.instance_mapping.keys()): LOG.info(_LI("Destroying pool %s due to agent disabling"), pool_id) self._destroy_pool(pool_id) LOG.info(_LI("Agent_updated by server side %s!"), payload)
def agent_updated(self, context, payload): """Handle the agent_updated notification event.""" if payload['admin_state_up'] != self.admin_state_up: self.admin_state_up = payload['admin_state_up'] if self.admin_state_up: self.needs_resync = True else: # Copy keys since the dictionary is modified in the loop body for loadbalancer_id in list(self.instance_mapping.keys()): LOG.info( _LI("Destroying loadbalancer %s due to agent " "disabling"), loadbalancer_id) self._destroy_loadbalancer(loadbalancer_id) LOG.info(_LI("Agent_updated by server side %s!"), payload)
def get_cert(self, project_id, cert_ref, resource_ref, check_only=False, service_name='lbaas'): """Retrieves the specified cert and registers as a consumer. :param cert_ref: the UUID of the cert to retrieve :param resource_ref: Full HATEOAS reference to the consuming resource :param check_only: Read Certificate data without registering :param service_name: Friendly name for the consuming service :returns: octavia.certificates.common.Cert representation of the certificate data :raises Exception: if certificate retrieval fails """ connection = self.auth.get_barbican_client(project_id) LOG.info(_LI( "Loading certificate container {0} from Barbican." ).format(cert_ref)) try: if check_only: cert_container = connection.containers.get( container_ref=cert_ref ) else: cert_container = connection.containers.register_consumer( container_ref=cert_ref, name=service_name, url=resource_ref ) return Cert(cert_container) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Error getting {0}").format(cert_ref))
def start(self): super(OctaviaConsumer, self).start() LOG.info(_LI("Starting octavia consumer...")) self.server = messaging.get_rpc_server(self.transport, self.target, self.endpoints, executor='eventlet') self.server.start()
def delete_cert(self, project_id, cert_ref, resource_ref, service_name='lbaas'): """Deregister as a consumer for the specified cert. :param cert_ref: the UUID of the cert to retrieve :param service_name: Friendly name for the consuming service :param lb_id: Loadbalancer id for building resource consumer URL :raises Exception: if deregistration fails """ connection = self.auth.get_barbican_client(project_id) LOG.info( _LI("Deregistering as a consumer of {0} in Barbican.").format( cert_ref)) try: connection.containers.remove_consumer(container_ref=cert_ref, name=service_name, url=resource_ref) except Exception: with excutils.save_and_reraise_exception(): LOG.exception( _LE("Error deregistering as a consumer of {0}").format( cert_ref))
def get_cert(self, project_id, cert_ref, resource_ref, check_only=False, service_name='lbaas'): """Retrieves the specified cert and registers as a consumer. :param cert_ref: the UUID of the cert to retrieve :param resource_ref: Full HATEOAS reference to the consuming resource :param check_only: Read Certificate data without registering :param service_name: Friendly name for the consuming service :returns: octavia.certificates.common.Cert representation of the certificate data :raises Exception: if certificate retrieval fails """ connection = self.auth.get_barbican_client(project_id) LOG.info( _LI("Loading certificate container {0} from Barbican.").format( cert_ref)) try: if check_only: cert_container = connection.containers.get( container_ref=cert_ref) else: cert_container = connection.containers.register_consumer( container_ref=cert_ref, name=service_name, url=resource_ref) return Cert(cert_container) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Error getting {0}").format(cert_ref))
def delete_cert(self, project_id, cert_ref, resource_ref, **kwargs): """Deletes the specified cert. :param project_id: Project ID for the owner of the certificate :param cert_ref: the UUID of the cert to delete :param resource_ref: Full HATEOAS reference to the consuming resource :raises CertificateStorageException: if certificate deletion fails """ LOG.info( _LI("Deleting certificate {0} from the local filesystem.").format( cert_ref)) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) filename_certificate = "{0}.crt".format(filename_base) filename_private_key = "{0}.key".format(filename_base) filename_intermediates = "{0}.int".format(filename_base) filename_pkp = "{0}.pass".format(filename_base) try: os.remove(filename_certificate) os.remove(filename_private_key) os.remove(filename_intermediates) os.remove(filename_pkp) except IOError as ioe: LOG.error( _LE("Failed to delete certificate {0}.").format(cert_ref)) raise exceptions.CertificateStorageException(message=ioe.message)
def delete_cert(cert_ref, lb_id, service_name='lbaas', **kwargs): """Deregister as a consumer for the specified cert. :param cert_ref: the UUID of the cert to retrieve :param service_name: Friendly name for the consuming service :param lb_id: Loadbalancer id for building resource consumer URL :raises Exception: if deregistration fails """ connection = BarbicanKeystoneAuth.get_barbican_client() LOG.info(_LI( "Deregistering as a consumer of {0} in Barbican." ).format(cert_ref)) try: connection.containers.remove_consumer( container_ref=cert_ref, name=service_name, url=CertManager._get_service_url(lb_id) ) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE( "Error deregistering as a consumer of {0}" ).format(cert_ref))
def delete_cert(self, project_id, cert_ref, resource_ref, **kwargs): """Deletes the specified cert. :param project_id: Project ID for the owner of the certificate :param cert_ref: the UUID of the cert to delete :param resource_ref: Full HATEOAS reference to the consuming resource :raises CertificateStorageException: if certificate deletion fails """ LOG.info(_LI( "Deleting certificate {0} from the local filesystem." ).format(cert_ref)) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) filename_certificate = "{0}.crt".format(filename_base) filename_private_key = "{0}.key".format(filename_base) filename_intermediates = "{0}.int".format(filename_base) filename_pkp = "{0}.pass".format(filename_base) try: os.remove(filename_certificate) os.remove(filename_private_key) os.remove(filename_intermediates) os.remove(filename_pkp) except IOError as ioe: LOG.error(_LE( "Failed to delete certificate {0}." ).format(cert_ref)) raise exceptions.CertificateStorageException(message=ioe.message)
def _actually_delete_cert(cert_ref): """Deletes the specified cert. Very dangerous. Do not recommend. :param cert_ref: the UUID of the cert to delete :raises Exception: if certificate deletion fails """ connection = BarbicanKeystoneAuth.get_barbican_client() LOG.info(_LI( "Recursively deleting certificate container {0} from Barbican." ).format(cert_ref)) try: certificate_container = connection.containers.get(cert_ref) certificate_container.certificate.delete() if certificate_container.intermediates: certificate_container.intermediates.delete() if certificate_container.private_key_passphrase: certificate_container.private_key_passphrase.delete() certificate_container.private_key.delete() certificate_container.delete() except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE( "Error recursively deleting certificate container {0}" ).format(cert_ref))
def get_cert(cert_ref, service_name='lbaas', lb_id=None, check_only=False, **kwargs): """Retrieves the specified cert and registers as a consumer. :param cert_ref: the UUID of the cert to retrieve :param service_name: Friendly name for the consuming service :param lb_id: Loadbalancer id for building resource consumer URL :param check_only: Read Certificate data without registering :returns: octavia.certificates.common.Cert representation of the certificate data :raises Exception: if certificate retrieval fails """ connection = BarbicanKeystoneAuth.get_barbican_client() LOG.info(_LI( "Loading certificate container {0} from Barbican." ).format(cert_ref)) try: if check_only: cert_container = connection.containers.get( container_ref=cert_ref ) else: cert_container = connection.containers.register_consumer( container_ref=cert_ref, name=service_name, url=CertManager._get_service_url(lb_id) ) return Cert(cert_container) except Exception: with excutils.save_and_reraise_exception(): LOG.exception(_LE("Error getting {0}").format(cert_ref))
def get_cert(self, project_id, cert_ref, resource_ref, **kwargs): """Retrieves the specified cert. :param project_id: Project ID for the owner of the certificate :param cert_ref: the UUID of the cert to retrieve :param resource_ref: Full HATEOAS reference to the consuming resource :returns: neutron_lbaas.common.cert_manager.cert_manager.Cert representation of the certificate data :raises CertificateStorageException: if certificate retrieval fails """ LOG.info(_LI( "Loading certificate {0} from the local filesystem." ).format(cert_ref)) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) filename_certificate = "{0}.crt".format(filename_base) filename_private_key = "{0}.key".format(filename_base) filename_intermediates = "{0}.int".format(filename_base) filename_pkp = "{0}.pass".format(filename_base) cert_data = dict() try: with open(filename_certificate, 'r') as cert_file: cert_data['certificate'] = cert_file.read() except IOError: LOG.error(_LE( "Failed to read certificate for {0}." ).format(cert_ref)) raise exceptions.CertificateStorageException( msg="Certificate could not be read." ) try: with open(filename_private_key, 'r') as key_file: cert_data['private_key'] = key_file.read() except IOError: LOG.error(_LE( "Failed to read private key for {0}." ).format(cert_ref)) raise exceptions.CertificateStorageException( msg="Private Key could not be read." ) try: with open(filename_intermediates, 'r') as int_file: cert_data['intermediates'] = int_file.read() except IOError: pass try: with open(filename_pkp, 'r') as pass_file: cert_data['private_key_passphrase'] = pass_file.read() except IOError: pass return Cert(**cert_data)
def _create_proxy_port(self, ctx, lb, proxy_port_subnet_id): """Check if proxy port was created earlier. If not, create a new port on proxy subnet and return its ip address. Returns port IP address """ proxy_port = self._get_proxy_port(ctx, lb) if proxy_port: LOG.info( _LI('LB %(lb_id)s proxy port exists on subnet \ %(subnet_id)s with ip address %(ip_address)s') % { 'lb_id': lb.id, 'subnet_id': proxy_port['subnet_id'], 'ip_address': proxy_port['ip_address'] }) return proxy_port proxy_port_name = 'proxy_' + lb.id proxy_port_subnet = self.plugin.db._core_plugin.get_subnet( ctx, proxy_port_subnet_id) proxy_port_data = { 'tenant_id': lb.tenant_id, 'name': proxy_port_name, 'network_id': proxy_port_subnet['network_id'], 'mac_address': n_constants.ATTR_NOT_SPECIFIED, 'admin_state_up': False, 'device_id': '', 'device_owner': 'neutron:' + constants.LOADBALANCERV2, 'fixed_ips': [{ 'subnet_id': proxy_port_subnet_id }] } proxy_port = self.plugin.db._core_plugin.create_port( ctx, {'port': proxy_port_data}) proxy_port_ip_data = proxy_port['fixed_ips'][0] LOG.info( _LI('LB %(lb_id)s proxy port created on subnet %(subnet_id)s \ with ip address %(ip_address)s') % { 'lb_id': lb.id, 'subnet_id': proxy_port_ip_data['subnet_id'], 'ip_address': proxy_port_ip_data['ip_address'] }) return proxy_port_ip_data
def _remove_snatport_for_subnet_if_not_used(self, context, tenant_id, subnet_id): pools = self._get_pools_on_subnet(context, tenant_id, subnet_id) if not pools: #No pools left on the old subnet. #We can remove the SNAT port/ipaddress self._remove_snatport_for_subnet(context, tenant_id, subnet_id) LOG.info(_LI("Removing SNAT port for subnet %s " "as this is the last pool using it..."), subnet_id)
def start(self): super(OctaviaConsumer, self).start() LOG.info(_LI("Starting octavia consumer...")) access_policy = dispatcher.DefaultRPCAccessPolicy self.server = messaging.get_rpc_server(self.transport, self.target, self.endpoints, executor='eventlet', access_policy=access_policy) self.server.start()
def get_cert(self, project_id, cert_ref, resource_ref, **kwargs): """Retrieves the specified cert. :param project_id: Project ID for the owner of the certificate :param cert_ref: the UUID of the cert to retrieve :param resource_ref: Full HATEOAS reference to the consuming resource :returns: neutron_lbaas.common.cert_manager.cert_manager.Cert representation of the certificate data :raises CertificateStorageException: if certificate retrieval fails """ LOG.info( _LI("Loading certificate {0} from the local filesystem.").format( cert_ref)) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) filename_certificate = "{0}.crt".format(filename_base) filename_private_key = "{0}.key".format(filename_base) filename_intermediates = "{0}.int".format(filename_base) filename_pkp = "{0}.pass".format(filename_base) cert_data = dict() try: with open(filename_certificate, 'r') as cert_file: cert_data['certificate'] = cert_file.read() except IOError: LOG.error( _LE("Failed to read certificate for {0}.").format(cert_ref)) raise exceptions.CertificateStorageException( msg="Certificate could not be read.") try: with open(filename_private_key, 'r') as key_file: cert_data['private_key'] = key_file.read() except IOError: LOG.error( _LE("Failed to read private key for {0}.").format(cert_ref)) raise exceptions.CertificateStorageException( msg="Private Key could not be read.") try: with open(filename_intermediates, 'r') as int_file: cert_data['intermediates'] = int_file.read() except IOError: pass try: with open(filename_pkp, 'r') as pass_file: cert_data['private_key_passphrase'] = pass_file.read() except IOError: pass return Cert(**cert_data)
def _get_snatport_for_subnet(self, context, tenant_id, subnet_id): device_id = '_lb-snatport-' + subnet_id subnet = self.plugin._core_plugin.get_subnet(context, subnet_id) network_id = subnet['network_id'] LOG.debug("Filtering ports based on network_id=%(network_id)s, " "tenant_id=%(tenant_id)s, device_id=%(device_id)s", {'network_id': network_id, 'tenant_id': tenant_id, 'device_id': device_id}) filter_dict = { 'network_id': [network_id], 'tenant_id': [tenant_id], 'device_id': [device_id], 'device-owner': [DRIVER_NAME] } ports = self.plugin._core_plugin.get_ports(context, filters=filter_dict) if ports: LOG.info(_LI("Found an existing SNAT port for subnet %s"), subnet_id) return ports[0] LOG.info(_LI("Found no SNAT ports for subnet %s"), subnet_id)
def create_member(self, context, member): """Create a pool member on a NetScaler device.""" ncc_member = self._prepare_member_for_creation(member) LOG.info(_LI("NetScaler driver poolmember creation: %r"), ncc_member) status = constants.ACTIVE try: self.client.create_resource(context.tenant_id, POOLMEMBERS_RESOURCE, POOLMEMBER_RESOURCE, ncc_member) except ncc_client.NCCException: status = constants.ERROR self.plugin.update_status(context, loadbalancer_db.Member, member["id"], status)
def deploy_instance(self, loadbalancer): """Deploys loadbalancer if necessary :returns: True if loadbalancer was deployed, False otherwise """ if not self.deployable(loadbalancer): LOG.info(_LI("Loadbalancer %s is not deployable.") % loadbalancer.id) return False if self.exists(loadbalancer.id): self.update(loadbalancer) else: self.create(loadbalancer) return True
def _create_proxy_port(self, ctx, lb, proxy_port_subnet_id): """Check if proxy port was created earlier. If not, create a new port on proxy subnet and return its ip address. Returns port IP address """ proxy_port = self._get_proxy_port(ctx, lb) if proxy_port: LOG.info(_LI('LB %(lb_id)s proxy port exists on subnet \ %(subnet_id)s with ip address %(ip_address)s') % {'lb_id': lb.id, 'subnet_id': proxy_port['subnet_id'], 'ip_address': proxy_port['ip_address']}) return proxy_port proxy_port_name = 'proxy_' + lb.id proxy_port_subnet = self.plugin.db._core_plugin.get_subnet( ctx, proxy_port_subnet_id) proxy_port_data = { 'tenant_id': lb.tenant_id, 'name': proxy_port_name, 'network_id': proxy_port_subnet['network_id'], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': False, 'device_id': '', 'device_owner': 'neutron:' + constants.LOADBALANCERV2, 'fixed_ips': [{'subnet_id': proxy_port_subnet_id}] } proxy_port = self.plugin.db._core_plugin.create_port( ctx, {'port': proxy_port_data}) proxy_port_ip_data = proxy_port['fixed_ips'][0] LOG.info(_LI('LB %(lb_id)s proxy port created on subnet %(subnet_id)s \ with ip address %(ip_address)s') % {'lb_id': lb.id, 'subnet_id': proxy_port_ip_data['subnet_id'], 'ip_address': proxy_port_ip_data['ip_address']}) return proxy_port_ip_data
def deploy_instance(self, loadbalancer): """Deploys loadbalancer if necessary :returns: True if loadbalancer was deployed, False otherwise """ if not self.deployable(loadbalancer): LOG.info( _LI("Loadbalancer %s is not deployable.") % loadbalancer.id) return False if self.exists(loadbalancer.id): self.update(loadbalancer) else: self.create(loadbalancer) return True
def store_cert(self, project_id, certificate, private_key, intermediates=None, private_key_passphrase=None, **kwargs): """Stores (i.e., registers) a cert with the cert manager. This method stores the specified cert to the filesystem and returns a UUID that can be used to retrieve it. :param project_id: Project ID for the owner of the certificate :param certificate: PEM encoded TLS certificate :param private_key: private key for the supplied certificate :param intermediates: ordered and concatenated intermediate certs :param private_key_passphrase: optional passphrase for the supplied key :returns: the UUID of the stored cert :raises CertificateStorageException: if certificate storage fails """ cert_ref = str(uuid.uuid4()) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) LOG.info(_LI("Storing certificate data on the local filesystem.")) try: filename_certificate = "{0}.crt".format(filename_base) with open(filename_certificate, 'w') as cert_file: cert_file.write(certificate) filename_private_key = "{0}.key".format(filename_base) with open(filename_private_key, 'w') as key_file: key_file.write(private_key) if intermediates: filename_intermediates = "{0}.int".format(filename_base) with open(filename_intermediates, 'w') as int_file: int_file.write(intermediates) if private_key_passphrase: filename_pkp = "{0}.pass".format(filename_base) with open(filename_pkp, 'w') as pass_file: pass_file.write(private_key_passphrase) except IOError as ioe: LOG.error(_LE("Failed to store certificate.")) raise exceptions.CertificateStorageException(message=ioe.message) return cert_ref
def store_cert(self, project_id, certificate, private_key, intermediates=None, private_key_passphrase=None, **kwargs): """Stores (i.e., registers) a cert with the cert manager. This method stores the specified cert to the filesystem and returns a UUID that can be used to retrieve it. :param project_id: Project ID for the owner of the certificate :param certificate: PEM encoded TLS certificate :param private_key: private key for the supplied certificate :param intermediates: ordered and concatenated intermediate certs :param private_key_passphrase: optional passphrase for the supplied key :returns: the UUID of the stored cert :raises CertificateStorageException: if certificate storage fails """ cert_ref = str(uuid.uuid4()) filename_base = os.path.join(CONF.certificates.storage_path, cert_ref) LOG.info(_LI( "Storing certificate data on the local filesystem." )) try: filename_certificate = "{0}.crt".format(filename_base) with open(filename_certificate, 'w') as cert_file: cert_file.write(certificate) filename_private_key = "{0}.key".format(filename_base) with open(filename_private_key, 'w') as key_file: key_file.write(private_key) if intermediates: filename_intermediates = "{0}.int".format(filename_base) with open(filename_intermediates, 'w') as int_file: int_file.write(intermediates) if private_key_passphrase: filename_pkp = "{0}.pass".format(filename_base) with open(filename_pkp, 'w') as pass_file: pass_file.write(private_key_passphrase) except IOError as ioe: LOG.error(_LE("Failed to store certificate.")) raise exceptions.CertificateStorageException(message=ioe.message) return cert_ref
def _call_driver_operation(self, context, driver_method, db_entity, old_db_entity=None): manager_method = "%s.%s" % (driver_method.__self__.__class__.__name__, driver_method.__name__) LOG.info(_LI("Calling driver operation %s") % manager_method) try: if old_db_entity: driver_method(context, old_db_entity, db_entity) else: driver_method(context, db_entity) # catching and reraising agent issues except (lbaas_agentschedulerv2.NoEligibleLbaasAgent, lbaas_agentschedulerv2.NoActiveLbaasAgent) as no_agent: raise no_agent except Exception: LOG.exception(_LE("There was an error in the driver")) self._handle_driver_error(context, db_entity) raise loadbalancerv2.DriverError()
def _create_snatport_for_subnet(self, context, tenant_id, subnet_id, ip_address): subnet = self.plugin._core_plugin.get_subnet(context, subnet_id) fixed_ip = {'subnet_id': subnet['id']} if ip_address and ip_address != attributes.ATTR_NOT_SPECIFIED: fixed_ip['ip_address'] = ip_address port_data = { 'tenant_id': tenant_id, 'name': '_lb-snatport-' + subnet_id, 'network_id': subnet['network_id'], 'mac_address': attributes.ATTR_NOT_SPECIFIED, 'admin_state_up': False, 'device_id': '_lb-snatport-' + subnet_id, 'device_owner': DRIVER_NAME, 'fixed_ips': [fixed_ip], } port = self.plugin._core_plugin.create_port(context, {'port': port_data}) LOG.info(_LI("Created SNAT port: %r"), port) return port
def _delete_proxy_port(self, ctx, lb): port_filter = { 'name': ['proxy_' + lb.id], } ports = self.plugin.db._core_plugin.get_ports(ctx, filters=port_filter) if ports: proxy_port = ports[0] proxy_port_ip_data = proxy_port['fixed_ips'][0] try: LOG.info( _LI('Deleting LB %(lb_id)s proxy port on subnet \ %(subnet_id)s with ip address %(ip_address)s') % { 'lb_id': lb.id, 'subnet_id': proxy_port_ip_data['subnet_id'], 'ip_address': proxy_port_ip_data['ip_address'] }) self.plugin.db._core_plugin.delete_port(ctx, proxy_port['id']) except Exception as exception: # stop exception propagation, nport may have # been deleted by other means LOG.warning(_LW('Proxy port deletion failed: %r'), exception)
def _delete_proxy_port(self, ctx, lb): port_filter = { 'name': ['proxy_' + lb.id], } ports = self.plugin.db._core_plugin.get_ports( ctx, filters=port_filter) if ports: proxy_port = ports[0] proxy_port_ip_data = proxy_port['fixed_ips'][0] try: LOG.info(_LI('Deleting LB %(lb_id)s proxy port on subnet \ %(subnet_id)s with ip address %(ip_address)s') % {'lb_id': lb.id, 'subnet_id': proxy_port_ip_data['subnet_id'], 'ip_address': proxy_port_ip_data['ip_address']}) self.plugin.db._core_plugin.delete_port( ctx, proxy_port['id']) except Exception as exception: # stop exception propagation, nport may have # been deleted by other means LOG.warning(_LW('Proxy port deletion failed: %r'), exception)
def _execute_request(self, method, resource_uri, headers, body=None): service_uri_dict = {"service_uri": self.service_uri} try: response = requests.request(method, url=resource_uri, headers=headers, data=body) except requests.exceptions.SSLError: LOG.exception(_LE("SSL error occurred while connecting " "to %(service_uri)s"), service_uri_dict) raise NCCException(NCCException.CONNECTION_ERROR) except requests.exceptions.ConnectionError: LOG.exception(_LE("Connection error occurred while connecting" "to %(service_uri)s"), service_uri_dict) raise NCCException(NCCException.CONNECTION_ERROR) except requests.exceptions.Timeout: LOG.exception( _LE("Request to %(service_uri)s timed out"), service_uri_dict) raise NCCException(NCCException.CONNECTION_ERROR) except (requests.exceptions.URLRequired, requests.exceptions.InvalidURL, requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema): LOG.exception(_LE("Request did not specify a valid URL")) raise NCCException(NCCException.REQUEST_ERROR) except requests.exceptions.TooManyRedirects: LOG.exception(_LE("Too many redirects occurred for request ")) raise NCCException(NCCException.REQUEST_ERROR) except requests.exceptions.RequestException: LOG.exception( _LE("A request error while connecting to %(service_uri)s"), service_uri_dict) raise NCCException(NCCException.REQUEST_ERROR) except Exception: LOG.exception( _LE("A unknown error occurred during request to" " %(service_uri)s"), service_uri_dict) raise NCCException(NCCException.UNKNOWN_ERROR) resp_dict = self._get_response_dict(response) resp_body = resp_dict['body'] LOG.info(_LI("Response: %(resp_body)s"), {"resp_body": resp_body}) response_status = resp_dict['status'] if response_status == requests.codes.unauthorized: LOG.exception(_LE("Unable to login. Invalid credentials passed." "for: %s"), self.service_uri) if not self.is_login(resource_uri): # Session expired, relogin and retry.... self.login() # Retry the operation headers.update({AUTH_HEADER: self.auth}) self._execute_request(method, resource_uri, headers, body) else: raise NCCException(NCCException.RESPONSE_ERROR) if not self._is_valid_response(response_status): response_msg = resp_body response_dict = {"method": method, "url": resource_uri, "response_status": response_status, "response_msg": response_msg} LOG.exception(_LE("Failed %(method)s operation on %(url)s " "status code: %(response_status)s " "message: %(response_msg)s"), response_dict) raise NCCException(NCCException.RESPONSE_ERROR, response_status) return response_status, resp_dict
def store_cert(self, project_id, certificate, private_key, intermediates=None, private_key_passphrase=None, expiration=None, name='LBaaS TLS Cert'): """Stores a certificate in the certificate manager. :param certificate: PEM encoded TLS certificate :param private_key: private key for the supplied certificate :param intermediates: ordered and concatenated intermediate certs :param private_key_passphrase: optional passphrase for the supplied key :param expiration: the expiration time of the cert in ISO 8601 format :param name: a friendly name for the cert :returns: the container_ref of the stored cert :raises Exception: if certificate storage fails """ connection = self.auth.get_barbican_client(project_id) LOG.info( _LI("Storing certificate container '{0}' in Barbican.").format( name)) certificate_secret = None private_key_secret = None intermediates_secret = None pkp_secret = None try: certificate_secret = connection.secrets.create( payload=certificate, expiration=expiration, name="Certificate") private_key_secret = connection.secrets.create( payload=private_key, expiration=expiration, name="Private Key") certificate_container = connection.containers.create_certificate( name=name, certificate=certificate_secret, private_key=private_key_secret) if intermediates: intermediates_secret = connection.secrets.create( payload=intermediates, expiration=expiration, name="Intermediates") certificate_container.intermediates = intermediates_secret if private_key_passphrase: pkp_secret = connection.secrets.create( payload=private_key_passphrase, expiration=expiration, name="Private Key Passphrase") certificate_container.private_key_passphrase = pkp_secret certificate_container.store() return certificate_container.container_ref # Barbican (because of Keystone-middleware) sometimes masks # exceptions strangely -- this will catch anything that it raises and # reraise the original exception, while also providing useful # feedback in the logs for debugging except Exception: for secret in [ certificate_secret, private_key_secret, intermediates_secret, pkp_secret ]: if secret and secret.secret_ref: old_ref = secret.secret_ref try: secret.delete() LOG.info( _LI("Deleted secret {0} ({1}) during rollback."). format(secret.name, old_ref)) except Exception: LOG.warning( _LW("Failed to delete {0} ({1}) during rollback. This " "is probably not a problem.").format( secret.name, old_ref)) with excutils.save_and_reraise_exception(): LOG.exception(_LE("Error storing certificate data"))
def _remove_snatport_for_subnet(self, context, tenant_id, subnet_id): port = self._get_snatport_for_subnet(context, tenant_id, subnet_id) if port: self.plugin._core_plugin.delete_port(context, port['id']) LOG.info(_LI("Removed SNAT port: %r"), port)
def store_cert(certificate, private_key, intermediates=None, private_key_passphrase=None, expiration=None, name='Octavia TLS Cert', **kwargs): """Stores a certificate in the certificate manager. :param certificate: PEM encoded TLS certificate :param private_key: private key for the supplied certificate :param intermediates: ordered and concatenated intermediate certs :param private_key_passphrase: optional passphrase for the supplied key :param expiration: the expiration time of the cert in ISO 8601 format :param name: a friendly name for the cert :returns: the container_ref of the stored cert :raises Exception: if certificate storage fails """ connection = BarbicanKeystoneAuth.get_barbican_client() LOG.info(_LI( "Storing certificate container '{0}' in Barbican." ).format(name)) certificate_secret = None private_key_secret = None intermediates_secret = None pkp_secret = None try: certificate_secret = connection.secrets.create( payload=certificate, expiration=expiration, name="Certificate" ) private_key_secret = connection.secrets.create( payload=private_key, expiration=expiration, name="Private Key" ) certificate_container = connection.containers.create_certificate( name=name, certificate=certificate_secret, private_key=private_key_secret ) if intermediates: intermediates_secret = connection.secrets.create( payload=intermediates, expiration=expiration, name="Intermediates" ) certificate_container.intermediates = intermediates_secret if private_key_passphrase: pkp_secret = connection.secrets.create( payload=private_key_passphrase, expiration=expiration, name="Private Key Passphrase" ) certificate_container.private_key_passphrase = pkp_secret certificate_container.store() return certificate_container.container_ref # Barbican (because of Keystone-middleware) sometimes masks # exceptions strangely -- this will catch anything that it raises and # reraise the original exception, while also providing useful # feedback in the logs for debugging except Exception: for secret in [certificate_secret, private_key_secret, intermediates_secret, pkp_secret]: if secret and secret.secret_ref: old_ref = secret.secret_ref try: secret.delete() LOG.info(_LI( "Deleted secret {0} ({1}) during rollback." ).format(secret.name, old_ref)) except Exception: LOG.warning(_LW( "Failed to delete {0} ({1}) during rollback. This " "is probably not a problem." ).format(secret.name, old_ref)) with excutils.save_and_reraise_exception(): LOG.exception(_LE("Error storing certificate data"))
def tearDown(cls): super(BaseTestCase, cls).tearDown() cls.LOG.info(_LI('Finished: {0}\n').format(cls._testMethodName))
def _start_completion_handling_thread(self): if not self.completion_handler_started: LOG.info(_LI('Starting operation completion handling thread')) self.completion_handler.start() self.completion_handler_started = True
def setUp(cls): cls.LOG.info(_LI("Starting: {0}").format(cls._testMethodName)) super(BaseTestCase, cls).setUp()
def setUp(cls): cls.LOG.info(_LI('Starting: {0}').format(cls._testMethodName)) super(BaseTestCase, cls).setUp()
def tearDown(cls): super(BaseTestCase, cls).tearDown() cls.LOG.info(_LI("Finished: {0}\n").format(cls._testMethodName))