octavia-lib-2.0.0/0000775000175000017500000000000013641343053013727 5ustar zuulzuul00000000000000octavia-lib-2.0.0/.coveragerc0000664000175000017500000000014313641342731016050 0ustar zuulzuul00000000000000[run] branch = True source = octavia_lib omit = octavia_lib/tests/* [report] ignore_errors = True octavia-lib-2.0.0/AUTHORS0000664000175000017500000000116313641343052014777 0ustar zuulzuul00000000000000Adam Harwell Ajay Kumar Andreas Jaeger Brian Haley Carlos Goncalves Corey Bryant Maciej Józefczyk Michael Johnson Noah Mickus OpenStack Release Bot Sam Morrison Steven Glasford Thomas Bechtold caoyuan melissaml pengyuesheng zhangboye octavia-lib-2.0.0/ChangeLog0000664000175000017500000000402713641343052015503 0ustar zuulzuul00000000000000CHANGES ======= 2.0.0 ----- * Add TLS protocols for listener and pool model * Update hacking for Python3 * Adding cipher list Support for provider drivers * Remove the dependency on the "mock" package * Re-home constants here from octavia * Remove all usage of six library * Complete dropping py27 support goal * Fix flake8 tox.ini directive * Missed some flavor references in the AZ methods * Stop testing python 2 * Return tips jobs to voting 1.5.0 ----- * Add availability\_zone to the LoadBalancer model * Availability zone / metadata validation * Switch to Ussuri jobs * Batch member update needs pool\_id explicitly * Generate PDF documentation * Update master for stable/train 1.4.0 ----- * Add Octavia tox tips job template as voting * Clean up octavia-lib docs and remove oslo.log 1.3.1 ----- * Update for storyboard * Fix docstring and avoid such errors 1.3.0 ----- * Blacklist sphinx 2.1.0 (autodoc bug) * Add constants to octavia-lib * Add get methods to the driver-lib * Bump the openstackdocstheme extension to 1.20 * Add new LB Algorithm - SOURCE\_IP\_PORT * Add Python 3 Train unit tests * Update tox.ini for new upper constraints strategy * Add tox "requirements" env * Additional VIPs is also relevant in provider\_base * Add allowed\_cidrs to Listener data model 1.2.0 ----- * Add 'additional\_vips' field to driver datamodel * Replace git.openstack.org URLs with opendev.org URLs * Add project\_id to all of the data model objects * Cap sphinx for py2 to match global requirements * Add python 3.7 testing * OpenDev Migration Patch * Remove python3.5 jobs for Train * Remove testtools from test-requirements.txt * Do not install README.rst and LICENSE * Update master for stable/stein 1.1.1 ----- * Sync data models and import new constants from Octavia 1.1.0 ----- * Fix some driver library bugs * Add FLAVOR as a constant * Add missing libraries to requirement files 1.0.0 ----- * Change openstack-dev to openstack-discuss * Initial provider driver library checkin * Initial cookie-cutter commit for octavia-lib * Added .gitreview octavia-lib-2.0.0/test-requirements.txt0000664000175000017500000000073713641342731020201 0ustar zuulzuul00000000000000# The order of packages is significant, because pip processes them in the order # of appearance. Changing the order has an impact on the overall integration # process, which may cause wedges in the gate later. hacking>=3.0,<3.1.0 # Apache-2.0 bandit>=1.1.0 # Apache-2.0 coverage>=4.0,!=4.4 # Apache-2.0 doc8>=0.6.0 # Apache-2.0 pylint==1.9.2 # GPLv2 python-subunit>=1.0.0 # Apache-2.0/BSD oslo.utils>=3.33.0 # Apache-2.0 oslotest>=3.2.0 # Apache-2.0 stestr>=2.0.0 # Apache-2.0 octavia-lib-2.0.0/octavia_lib/0000775000175000017500000000000013641343053016203 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/api/0000775000175000017500000000000013641343053016754 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/api/drivers/0000775000175000017500000000000013641343053020432 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/api/drivers/provider_base.py0000664000175000017500000006016613641342731023643 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from octavia_lib.api.drivers import exceptions # This class describes the abstraction of a provider driver interface. # Load balancing provider drivers will implement this interface. class ProviderDriver(object): # name is for internal Octavia use and should not be used by drivers name = None # Load Balancer def create_vip_port(self, loadbalancer_id, project_id, vip_dictionary, additional_vip_dicts): """Creates a port for a load balancer VIP. If the driver supports creating VIP ports, the driver will create a VIP port with the primary VIP and all additional VIPs added to the port, and return the vip_dictionary populated with the vip_port_id and a list of vip_dictionaries populated with data from the additional VIPs (which are guaranteed to be in the same Network). This might look like: {'port_id': port_id, 'subnet_id': subnet_id_1, 'ip_address': ip1}, [{'subnet_id': subnet_id_2, 'ip_address': ip2}, {...}, {...}] If the driver does not support port creation, the driver will raise a NotImplementedError. :param loadbalancer_id: ID of loadbalancer. :type loadbalancer_id: string :param project_id: The project ID to create the VIP under. :type project_id: string :param: vip_dictionary: The VIP dictionary. :type vip_dictionary: dict :param: additional_vip_dicts: A list of additional VIP dictionaries, with subnets guaranteed to be in the same network as the primary vip_dictionary. :type additional_vip_dicts: list(dict) :returns: VIP dictionary with vip_port_id + a list of additional VIP dictionaries (vip_dict, additional_vip_dicts). :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support creating VIP ports. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating VIP ' 'ports.', operator_fault_string='This provider does not support creating ' 'VIP ports. Octavia will create it.') def loadbalancer_create(self, loadbalancer): """Creates a new load balancer. :param loadbalancer: The load balancer object. :type loadbalancer: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support create. :raises UnsupportedOptionError: The driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'load balancers.', operator_fault_string='This provider does not support creating ' 'load balancers. What?') def loadbalancer_delete(self, loadbalancer, cascade=False): """Deletes a load balancer. :param loadbalancer: The load balancer to delete. :type loadbalancer: object :param cascade: If True, deletes all child objects (listeners, pools, etc.) in addition to the load balancer. :type cascade: bool :return: Nothing if the delete request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'load balancers.', operator_fault_string='This provider does not support deleting ' 'load balancers.') def loadbalancer_failover(self, loadbalancer_id): """Performs a fail over of a load balancer. :param loadbalancer_id: ID of the load balancer to failover. :type loadbalancer_id: string :return: Nothing if the failover request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises: NotImplementedError if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support failing over ' 'load balancers.', operator_fault_string='This provider does not support failing ' 'over load balancers.') def loadbalancer_update(self, old_loadbalancer, new_loadbalncer): """Updates a load balancer. :param old_loadbalancer: The baseline load balancer object. :type old_loadbalancer: object :param new_loadbalancer: The updated load balancer object. :type new_loadbalancer: object :return: Nothing if the update request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support request. :raises UnsupportedOptionError: The driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'load balancers.', operator_fault_string='This provider does not support updating ' 'load balancers.') # Listener def listener_create(self, listener): """Creates a new listener. :param listener: The listener object. :type listener: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'listeners.', operator_fault_string='This provider does not support creating ' 'listeners.') def listener_delete(self, listener): """Deletes a listener. :param listener: The listener to delete. :type listener: object :return: Nothing if the delete request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'listeners.', operator_fault_string='This provider does not support deleting ' 'listeners.') def listener_update(self, old_listener, new_listener): """Updates a listener. :param old_listener: The baseline listener object. :type old_listener: object :param new_listener: The updated listener object. :type new_listener: object :return: Nothing if the update request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'listeners.', operator_fault_string='This provider does not support updating ' 'listeners.') # Pool def pool_create(self, pool): """Creates a new pool. :param pool: The pool object. :type pool: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'pools.', operator_fault_string='This provider does not support creating ' 'pools.') def pool_delete(self, pool): """Deletes a pool and its members. :param pool: The pool to delete. :type pool: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'pools.', operator_fault_string='This provider does not support deleting ' 'pools.') def pool_update(self, old_pool, new_pool): """Updates a pool. :param pool: The baseline pool object. :type pool: object :param pool: The updated pool object. :type pool: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'pools.', operator_fault_string='This provider does not support updating ' 'pools.') # Member def member_create(self, member): """Creates a new member for a pool. :param member: The member object. :type member: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'members.', operator_fault_string='This provider does not support creating ' 'members.') def member_delete(self, member): """Deletes a pool member. :param member: The member to delete. :type member: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'members.', operator_fault_string='This provider does not support deleting ' 'members.') def member_update(self, old_member, new_member): """Updates a pool member. :param old_member: The baseline member object. :type old_member: object :param new_member: The updated member object. :type new_member: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'members.', operator_fault_string='This provider does not support updating ' 'members.') def member_batch_update(self, pool_id, members): """Creates, updates, or deletes a set of pool members. :param pool_id: The id of the pool to update. :type pool_id: string :param members: List of member objects. :type members: list :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support batch ' 'updating members.', operator_fault_string='This provider does not support batch ' 'updating members.') # Health Monitor def health_monitor_create(self, healthmonitor): """Creates a new health monitor. :param healthmonitor: The health monitor object. :type healthmonitor: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'health monitors.', operator_fault_string='This provider does not support creating ' 'health monitors.') def health_monitor_delete(self, healthmonitor): """Deletes a healthmonitor_id. :param healthmonitor: The monitor to delete. :type healthmonitor: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'health monitors.', operator_fault_string='This provider does not support deleting ' 'health monitors.') def health_monitor_update(self, old_healthmonitor, new_healthmonitor): """Updates a health monitor. :param old_healthmonitor: The baseline health monitor object. :type old_healthmonitor: object :param new_healthmonitor: The updated health monitor object. :type new_healthmonitor: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'health monitors.', operator_fault_string='This provider does not support updating ' 'health monitors.') # L7 Policy def l7policy_create(self, l7policy): """Creates a new L7 policy. :param l7policy: The L7 policy object. :type l7policy: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'l7policies.', operator_fault_string='This provider does not support creating ' 'l7policies.') def l7policy_delete(self, l7policy): """Deletes an L7 policy. :param l7policy: The L7 policy to delete. :type l7policy: object :return: Nothing if the delete request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'l7policies.', operator_fault_string='This provider does not support deleting ' 'l7policies.') def l7policy_update(self, old_l7policy, new_l7policy): """Updates an L7 policy. :param old_l7policy: The baseline L7 policy object. :type old_l7policy: object :param new_l7policy: The updated L7 policy object. :type new_l7policy: object :return: Nothing if the update request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'l7policies.', operator_fault_string='This provider does not support updating ' 'l7policies.') # L7 Rule def l7rule_create(self, l7rule): """Creates a new L7 rule. :param l7rule: The L7 rule object. :type l7rule: object :return: Nothing if the create request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support creating ' 'l7rules.', operator_fault_string='This provider does not support creating ' 'l7rules.') def l7rule_delete(self, l7rule): """Deletes an L7 rule. :param l7rule: The L7 rule to delete. :type l7rule: object :return: Nothing if the delete request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support deleting ' 'l7rules.', operator_fault_string='This provider does not support deleting ' 'l7rules.') def l7rule_update(self, old_l7rule, new_l7rule): """Updates an L7 rule. :param old_l7rule: The baseline L7 rule object. :type old_l7rule: object :param new_l7rule: The updated L7 rule object. :type new_l7rule: object :return: Nothing if the update request was accepted. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: if driver does not support request. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support updating ' 'l7rules.', operator_fault_string='This provider does not support updating ' 'l7rules.') # Flavor def get_supported_flavor_metadata(self): """Returns a dict of flavor metadata keys supported by this driver. The returned dictionary will include key/value pairs, 'name' and 'description.' :returns: The flavor metadata dictionary :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support flavors. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support getting the ' 'supported flavor metadata.', operator_fault_string='This provider does not support getting ' 'the supported flavor metadata.') def validate_flavor(self, flavor_metadata): """Validates if driver can support the flavor. :param flavor_metadata: Dictionary with flavor metadata. :type flavor_metadata: dict :return: Nothing if the flavor is valid and supported. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support flavors. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support validating ' 'flavors.', operator_fault_string='This provider does not support validating ' 'the supported flavor metadata.') # Availability Zone def get_supported_availability_zone_metadata(self): """Returns a dict of supported availability zone metadata keys. The returned dictionary will include key/value pairs, 'name' and 'description.' :returns: The availability zone metadata dictionary :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support AZs. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support getting the ' 'supported availability zone metadata.', operator_fault_string='This provider does not support getting ' 'the supported availability zone metadata.') def validate_availability_zone(self, availability_zone_metadata): """Validates if driver can support the availability zone. :param availability_zone_metadata: Dictionary with az metadata. :type availability_zone_metadata: dict :return: Nothing if the availability zone is valid and supported. :raises DriverError: An unexpected error occurred in the driver. :raises NotImplementedError: The driver does not support availability zones. :raises UnsupportedOptionError: if driver does not support one of the configuration options. """ raise exceptions.NotImplementedError( user_fault_string='This provider does not support validating ' 'availability zones.', operator_fault_string='This provider does not support validating ' 'the supported availability zone metadata.') octavia-lib-2.0.0/octavia_lib/api/drivers/driver_lib.py0000664000175000017500000002475513641342731023144 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import socket import time from oslo_serialization import jsonutils import tenacity from octavia_lib.api.drivers import data_models from octavia_lib.api.drivers import exceptions as driver_exceptions from octavia_lib.common import constants DEFAULT_STATUS_SOCKET = '/var/run/octavia/status.sock' DEFAULT_STATS_SOCKET = '/var/run/octavia/stats.sock' DEFAULT_GET_SOCKET = '/var/run/octavia/get.sock' SOCKET_TIMEOUT = 5 DRIVER_AGENT_TIMEOUT = 30 class DriverLibrary(object): @tenacity.retry( stop=tenacity.stop_after_attempt(30), reraise=True, wait=tenacity.wait_exponential(multiplier=1, min=1, max=5), retry=tenacity.retry_if_exception_type( driver_exceptions.DriverAgentNotFound)) def _check_for_socket_ready(self, socket): if not os.path.exists(socket): raise driver_exceptions.DriverAgentNotFound( fault_string=('Unable to open the driver agent ' 'socket: {}'.format(socket))) def __init__(self, status_socket=DEFAULT_STATUS_SOCKET, stats_socket=DEFAULT_STATS_SOCKET, get_socket=DEFAULT_GET_SOCKET, **kwargs): self.status_socket = status_socket self.stats_socket = stats_socket self.get_socket = get_socket self._check_for_socket_ready(status_socket) self._check_for_socket_ready(stats_socket) self._check_for_socket_ready(get_socket) super(DriverLibrary, self).__init__(**kwargs) def _recv(self, sock): size_str = b'' char = sock.recv(1) begin = time.time() while char != b'\n': size_str += char char = sock.recv(1) if time.time() - begin > DRIVER_AGENT_TIMEOUT: raise driver_exceptions.DriverAgentTimeout( fault_string=('The driver agent did not respond in {} ' 'seconds.'.format(DRIVER_AGENT_TIMEOUT))) # Give the CPU a break from polling time.sleep(0.01) payload_size = int(size_str) mv_buffer = memoryview(bytearray(payload_size)) next_offset = 0 begin = time.time() while payload_size - next_offset > 0: recv_size = sock.recv_into(mv_buffer[next_offset:], payload_size - next_offset) next_offset += recv_size if time.time() - begin > DRIVER_AGENT_TIMEOUT: raise driver_exceptions.DriverAgentTimeout( fault_string=('The driver agent did not respond in {} ' 'seconds.'.format(DRIVER_AGENT_TIMEOUT))) # Give the CPU a break from polling time.sleep(0.01) return jsonutils.loads(mv_buffer.tobytes()) def _send(self, socket_path, data): sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(SOCKET_TIMEOUT) sock.connect(socket_path) try: json_data = jsonutils.dump_as_bytes(data) len_str = '{}\n'.format(len(json_data)).encode('utf-8') sock.send(len_str) sock.sendall(json_data) response = self._recv(sock) finally: sock.close() return response def update_loadbalancer_status(self, status): """Update load balancer status. :param status: dictionary defining the provisioning status and operating status for load balancer objects, including pools, members, listeners, L7 policies, and L7 rules. iod (string): ID for the object. provisioning_status (string): Provisioning status for the object. operating_status (string): Operating status for the object. :type status: dict :raises: UpdateStatusError :returns: None """ try: response = self._send(self.status_socket, status) except Exception as e: raise driver_exceptions.UpdateStatusError(fault_string=str(e)) if response[constants.STATUS_CODE] != constants.DRVR_STATUS_CODE_OK: raise driver_exceptions.UpdateStatusError( fault_string=response.pop(constants.FAULT_STRING, None), status_object=response.pop(constants.STATUS_OBJECT, None), status_object_id=response.pop(constants.STATUS_OBJECT_ID, None), status_record=response.pop(constants.STATUS_RECORD, None)) def update_listener_statistics(self, statistics): """Update listener statistics. :param statistics: Statistics for listeners: id (string): ID for listener. active_connections (int): Number of currently active connections. bytes_in (int): Total bytes received. bytes_out (int): Total bytes sent. request_errors (int): Total requests not fulfilled. total_connections (int): The total connections handled. :type statistics: dict :raises: UpdateStatisticsError :returns: None """ try: response = self._send(self.stats_socket, statistics) except Exception as e: raise driver_exceptions.UpdateStatisticsError( fault_string=str(e), stats_object=constants.LISTENERS) if response[constants.STATUS_CODE] != constants.DRVR_STATUS_CODE_OK: raise driver_exceptions.UpdateStatisticsError( fault_string=response.pop(constants.FAULT_STRING, None), stats_object=response.pop(constants.STATS_OBJECT, None), stats_object_id=response.pop(constants.STATS_OBJECT_ID, None), stats_record=response.pop(constants.STATS_RECORD, None)) def _get_resource(self, resource, id): try: return self._send(self.get_socket, {constants.OBJECT: resource, constants.ID: id}) except driver_exceptions.DriverAgentTimeout: raise except Exception: raise driver_exceptions.DriverError() def get_loadbalancer(self, loadbalancer_id): """Get a load balancer object. :param loadbalancer_id: The load balancer ID to lookup. :type loadbalancer_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A LoadBalancer object or None if not found. """ data = self._get_resource(constants.LOADBALANCERS, loadbalancer_id) if data: return data_models.LoadBalancer.from_dict(data) return None def get_listener(self, listener_id): """Get a listener object. :param listener_id: The listener ID to lookup. :type listener_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A Listener object or None if not found. """ data = self._get_resource(constants.LISTENERS, listener_id) if data: return data_models.Listener.from_dict(data) return None def get_pool(self, pool_id): """Get a pool object. :param pool_id: The pool ID to lookup. :type pool_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A Pool object or None if not found. """ data = self._get_resource(constants.POOLS, pool_id) if data: return data_models.Pool.from_dict(data) return None def get_healthmonitor(self, healthmonitor_id): """Get a health monitor object. :param healthmonitor_id: The health monitor ID to lookup. :type healthmonitor_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A HealthMonitor object or None if not found. """ data = self._get_resource(constants.HEALTHMONITORS, healthmonitor_id) if data: return data_models.HealthMonitor.from_dict(data) return None def get_member(self, member_id): """Get a member object. :param member_id: The member ID to lookup. :type member_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A Member object or None if not found. """ data = self._get_resource(constants.MEMBERS, member_id) if data: return data_models.Member.from_dict(data) return None def get_l7policy(self, l7policy_id): """Get a L7 policy object. :param l7policy_id: The L7 policy ID to lookup. :type l7policy_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A L7Policy object or None if not found. """ data = self._get_resource(constants.L7POLICIES, l7policy_id) if data: return data_models.L7Policy.from_dict(data) return None def get_l7rule(self, l7rule_id): """Get a L7 rule object. :param l7rule_id: The L7 rule ID to lookup. :type l7rule_id: UUID string :raises DriverAgentTimeout: The driver agent did not respond inside the timeout. :raises DriverError: An unexpected error occurred. :returns: A L7Rule object or None if not found. """ data = self._get_resource(constants.L7RULES, l7rule_id) if data: return data_models.L7Rule.from_dict(data) return None octavia-lib-2.0.0/octavia_lib/api/drivers/data_models.py0000664000175000017500000002727013641342731023272 0ustar zuulzuul00000000000000# Copyright (c) 2014 Rackspace # Copyright (c) 2016 Blue Box, an IBM Company # Copyright 2018 Rackspace, US Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class BaseDataModel(object): def to_dict(self, calling_classes=None, recurse=False, render_unsets=False, **kwargs): """Converts a data model to a dictionary.""" calling_classes = calling_classes or [] ret = {} for attr in self.__dict__: if attr.startswith('_') or not kwargs.get(attr, True): continue value = self.__dict__[attr] if recurse: if isinstance(getattr(self, attr), list): ret[attr] = [] for item in value: if isinstance(item, BaseDataModel): if type(self) not in calling_classes: ret[attr].append( item.to_dict(calling_classes=( calling_classes + [type(self)]), recurse=True, render_unsets=render_unsets)) else: ret[attr].append(None) else: ret[attr].append(item) elif isinstance(getattr(self, attr), BaseDataModel): if type(self) not in calling_classes: ret[attr] = value.to_dict( recurse=recurse, render_unsets=render_unsets, calling_classes=calling_classes + [type(self)]) else: ret[attr] = None elif isinstance(value, UnsetType): if render_unsets: ret[attr] = None else: continue else: ret[attr] = value else: if (isinstance(getattr(self, attr), (BaseDataModel, list)) or isinstance(value, UnsetType)): if render_unsets: ret[attr] = None else: continue else: ret[attr] = value return ret def __eq__(self, other): if isinstance(other, self.__class__): return self.to_dict() == other.to_dict() return False def __ne__(self, other): return not self.__eq__(other) @classmethod def from_dict(cls, dict): return cls(**dict) class UnsetType(object): def __bool__(self): return False __nonzero__ = __bool__ def __repr__(self): return 'Unset' Unset = UnsetType() class LoadBalancer(BaseDataModel): def __init__(self, admin_state_up=Unset, description=Unset, flavor=Unset, listeners=Unset, loadbalancer_id=Unset, name=Unset, pools=Unset, project_id=Unset, vip_address=Unset, vip_network_id=Unset, vip_port_id=Unset, vip_subnet_id=Unset, vip_qos_policy_id=Unset, additional_vips=Unset, availability_zone=Unset): self.admin_state_up = admin_state_up self.description = description self.flavor = flavor self.listeners = listeners self.loadbalancer_id = loadbalancer_id self.name = name self.pools = pools self.project_id = project_id self.vip_address = vip_address self.vip_network_id = vip_network_id self.vip_port_id = vip_port_id self.vip_subnet_id = vip_subnet_id self.vip_qos_policy_id = vip_qos_policy_id self.additional_vips = additional_vips self.availability_zone = availability_zone class Listener(BaseDataModel): def __init__(self, admin_state_up=Unset, connection_limit=Unset, default_pool=Unset, default_pool_id=Unset, default_tls_container_ref=Unset, default_tls_container_data=Unset, description=Unset, insert_headers=Unset, l7policies=Unset, listener_id=Unset, loadbalancer_id=Unset, name=Unset, protocol=Unset, protocol_port=Unset, sni_container_refs=Unset, sni_container_data=Unset, timeout_client_data=Unset, timeout_member_connect=Unset, timeout_member_data=Unset, timeout_tcp_inspect=Unset, client_ca_tls_container_ref=Unset, client_ca_tls_container_data=Unset, client_authentication=Unset, client_crl_container_ref=Unset, client_crl_container_data=Unset, project_id=Unset, allowed_cidrs=Unset, tls_versions=Unset, tls_ciphers=Unset): self.admin_state_up = admin_state_up self.connection_limit = connection_limit self.default_pool = default_pool self.default_pool_id = default_pool_id self.default_tls_container_data = default_tls_container_data self.default_tls_container_ref = default_tls_container_ref self.description = description self.insert_headers = insert_headers self.l7policies = l7policies self.listener_id = listener_id self.loadbalancer_id = loadbalancer_id self.name = name self.protocol = protocol self.protocol_port = protocol_port self.sni_container_data = sni_container_data self.sni_container_refs = sni_container_refs self.timeout_client_data = timeout_client_data self.timeout_member_connect = timeout_member_connect self.timeout_member_data = timeout_member_data self.timeout_tcp_inspect = timeout_tcp_inspect self.client_ca_tls_container_ref = client_ca_tls_container_ref self.client_ca_tls_container_data = client_ca_tls_container_data self.client_authentication = client_authentication self.client_crl_container_ref = client_crl_container_ref self.client_crl_container_data = client_crl_container_data self.project_id = project_id self.allowed_cidrs = allowed_cidrs self.tls_versions = tls_versions self.tls_ciphers = tls_ciphers class Pool(BaseDataModel): def __init__(self, admin_state_up=Unset, description=Unset, healthmonitor=Unset, lb_algorithm=Unset, loadbalancer_id=Unset, members=Unset, name=Unset, pool_id=Unset, listener_id=Unset, protocol=Unset, session_persistence=Unset, tls_container_ref=Unset, tls_container_data=Unset, ca_tls_container_ref=Unset, ca_tls_container_data=Unset, crl_container_ref=Unset, crl_container_data=Unset, tls_enabled=Unset, project_id=Unset, tls_versions=Unset, tls_ciphers=Unset): self.admin_state_up = admin_state_up self.description = description self.healthmonitor = healthmonitor self.lb_algorithm = lb_algorithm self.loadbalancer_id = loadbalancer_id self.members = members self.name = name self.pool_id = pool_id self.listener_id = listener_id self.protocol = protocol self.session_persistence = session_persistence self.tls_container_ref = tls_container_ref self.tls_container_data = tls_container_data self.ca_tls_container_ref = ca_tls_container_ref self.ca_tls_container_data = ca_tls_container_data self.crl_container_ref = crl_container_ref self.crl_container_data = crl_container_data self.tls_enabled = tls_enabled self.project_id = project_id self.tls_versions = tls_versions self.tls_ciphers = tls_ciphers class Member(BaseDataModel): def __init__(self, address=Unset, admin_state_up=Unset, member_id=Unset, monitor_address=Unset, monitor_port=Unset, name=Unset, pool_id=Unset, protocol_port=Unset, subnet_id=Unset, weight=Unset, backup=Unset, project_id=Unset): self.address = address self.admin_state_up = admin_state_up self.member_id = member_id self.monitor_address = monitor_address self.monitor_port = monitor_port self.name = name self.pool_id = pool_id self.protocol_port = protocol_port self.subnet_id = subnet_id self.weight = weight self.backup = backup self.project_id = project_id class HealthMonitor(BaseDataModel): def __init__(self, admin_state_up=Unset, delay=Unset, expected_codes=Unset, healthmonitor_id=Unset, http_method=Unset, max_retries=Unset, max_retries_down=Unset, name=Unset, pool_id=Unset, timeout=Unset, type=Unset, url_path=Unset, http_version=Unset, domain_name=Unset, project_id=Unset): self.admin_state_up = admin_state_up self.delay = delay self.expected_codes = expected_codes self.healthmonitor_id = healthmonitor_id self.http_method = http_method self.max_retries = max_retries self.max_retries_down = max_retries_down self.name = name self.pool_id = pool_id self.timeout = timeout self.type = type self.url_path = url_path self.http_version = http_version self.domain_name = domain_name self.project_id = project_id class L7Policy(BaseDataModel): def __init__(self, action=Unset, admin_state_up=Unset, description=Unset, l7policy_id=Unset, listener_id=Unset, name=Unset, position=Unset, redirect_pool_id=Unset, redirect_url=Unset, rules=Unset, redirect_prefix=Unset, redirect_http_code=Unset, project_id=Unset): self.action = action self.admin_state_up = admin_state_up self.description = description self.l7policy_id = l7policy_id self.listener_id = listener_id self.name = name self.position = position self.redirect_pool_id = redirect_pool_id self.redirect_url = redirect_url self.rules = rules self.redirect_prefix = redirect_prefix self.redirect_http_code = redirect_http_code self.project_id = project_id class L7Rule(BaseDataModel): def __init__(self, admin_state_up=Unset, compare_type=Unset, invert=Unset, key=Unset, l7policy_id=Unset, l7rule_id=Unset, type=Unset, value=Unset, project_id=Unset): self.admin_state_up = admin_state_up self.compare_type = compare_type self.invert = invert self.key = key self.l7policy_id = l7policy_id self.l7rule_id = l7rule_id self.type = type self.value = value self.project_id = project_id class VIP(BaseDataModel): def __init__(self, vip_address=Unset, vip_network_id=Unset, vip_port_id=Unset, vip_subnet_id=Unset, vip_qos_policy_id=Unset): self.vip_address = vip_address self.vip_network_id = vip_network_id self.vip_port_id = vip_port_id self.vip_subnet_id = vip_subnet_id self.vip_qos_policy_id = vip_qos_policy_id octavia-lib-2.0.0/octavia_lib/api/drivers/__init__.py0000664000175000017500000000000013641342731022533 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/api/drivers/exceptions.py0000664000175000017500000002001713641342731023167 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from octavia_lib.i18n import _ class DriverError(Exception): """Catch all exception that drivers can raise. This exception includes two strings: The user fault string and the optional operator fault string. The user fault string, "user_fault_string", will be provided to the API requester. The operator fault string, "operator_fault_string", will be logged in the Octavia API log file for the operator to use when debugging. :param user_fault_string: String provided to the API requester. :type user_fault_string: string :param operator_fault_string: Optional string logged by the Octavia API for the operator to use when debugging. :type operator_fault_string: string """ user_fault_string = _("An unknown driver error occurred.") operator_fault_string = _("An unknown driver error occurred.") def __init__(self, *args, **kwargs): self.user_fault_string = kwargs.pop('user_fault_string', self.user_fault_string) self.operator_fault_string = kwargs.pop('operator_fault_string', self.operator_fault_string) super(DriverError, self).__init__(self.user_fault_string, *args, **kwargs) class NotImplementedError(Exception): """Exception raised when a driver does not implement an API function. :param user_fault_string: String provided to the API requester. :type user_fault_string: string :param operator_fault_string: Optional string logged by the Octavia API for the operator to use when debugging. :type operator_fault_string: string """ user_fault_string = _("This feature is not implemented by the provider.") operator_fault_string = _("This feature is not implemented by this " "provider.") def __init__(self, *args, **kwargs): self.user_fault_string = kwargs.pop('user_fault_string', self.user_fault_string) self.operator_fault_string = kwargs.pop('operator_fault_string', self.operator_fault_string) super(NotImplementedError, self).__init__(self.user_fault_string, *args, **kwargs) class UnsupportedOptionError(Exception): """Exception raised when a driver does not support an option. Provider drivers will validate that they can complete the request -- that all options are supported by the driver. If the request fails validation, drivers will raise an UnsupportedOptionError exception. For example, if a driver does not support a flavor passed as an option to load balancer create(), the driver will raise an UnsupportedOptionError and include a message parameter providing an explanation of the failure. :param user_fault_string: String provided to the API requester. :type user_fault_string: string :param operator_fault_string: Optional string logged by the Octavia API for the operator to use when debugging. :type operator_fault_string: string """ user_fault_string = _("A specified option is not supported by this " "provider.") operator_fault_string = _("A specified option is not supported by this " "provider.") def __init__(self, *args, **kwargs): self.user_fault_string = kwargs.pop('user_fault_string', self.user_fault_string) self.operator_fault_string = kwargs.pop('operator_fault_string', self.operator_fault_string) super(UnsupportedOptionError, self).__init__(self.user_fault_string, *args, **kwargs) class UpdateStatusError(Exception): """Exception raised when a status update fails. Each exception will include a message field that describes the error and references to the failed record if available. :param fault_string: String describing the fault. :type fault_string: string :param status_object: The object the fault occurred on. :type status_object: string :param status_object_id: The ID of the object that failed status update. :type status_object_id: string :param status_record: The status update record that caused the fault. :type status_record: string """ fault_string = _("The status update had an unknown error.") status_object = None status_object_id = None status_record = None def __init__(self, *args, **kwargs): self.fault_string = kwargs.pop('fault_string', self.fault_string) self.status_object = kwargs.pop('status_object', None) self.status_object_id = kwargs.pop('status_object_id', None) self.status_record = kwargs.pop('status_record', None) super(UpdateStatusError, self).__init__(self.fault_string, *args, **kwargs) class UpdateStatisticsError(Exception): """Exception raised when a statistics update fails. Each exception will include a message field that describes the error and references to the failed record if available. :param fault_string: String describing the fault. :type fault_string: string :param status_object: The object the fault occurred on. :type status_object: string :param status_object_id: The ID of the object that failed stats update. :type status_object_id: string :param status_record: The stats update record that caused the fault. :type status_record: string """ fault_string = _("The statistics update had an unknown error.") stats_object = None stats_object_id = None stats_record = None def __init__(self, *args, **kwargs): self.fault_string = kwargs.pop('fault_string', self.fault_string) self.stats_object = kwargs.pop('stats_object', None) self.stats_object_id = kwargs.pop('stats_object_id', None) self.stats_record = kwargs.pop('stats_record', None) super(UpdateStatisticsError, self).__init__(self.fault_string, *args, **kwargs) class DriverAgentNotFound(Exception): """Exception raised when the driver agent cannot be reached. Each exception will include a message field that describes the error. :param fault_string: String describing the fault. :type fault_string: string """ fault_string = _("The driver-agent process was not found or not ready.") def __init__(self, *args, **kwargs): self.fault_string = kwargs.pop('fault_string', self.fault_string) super(DriverAgentNotFound, self).__init__(self.fault_string, *args, **kwargs) class DriverAgentTimeout(Exception): """Exception raised when the driver agent does not respond. Raised when communication with the driver agent times out. Each exception will include a message field that describes the error. :param fault_string: String describing the fault. :type fault_string: string """ fault_string = _("The driver-agent timeout.") def __init__(self, *args, **kwargs): self.fault_string = kwargs.pop('fault_string', self.fault_string) super(DriverAgentTimeout, self).__init__(self.fault_string, *args, **kwargs) octavia-lib-2.0.0/octavia_lib/api/__init__.py0000664000175000017500000000000013641342731021055 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/i18n.py0000664000175000017500000000140713641342731017340 0ustar zuulzuul00000000000000# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import oslo_i18n as i18n _translators = i18n.TranslatorFactory(domain='octavia-lib') # The primary translation function using the well-known name "_" _ = _translators.primary octavia-lib-2.0.0/octavia_lib/hacking/0000775000175000017500000000000013641343053017607 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/hacking/checks.py0000664000175000017500000002663613641342731021440 0ustar zuulzuul00000000000000# Copyright (c) 2014 OpenStack Foundation. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Guidelines for writing new hacking checks - Use only for Octavia specific tests. OpenStack general tests should be submitted to the common 'hacking' module. - Pick numbers in the range O3xx. Find the current test with the highest allocated number and then pick the next value. - Keep the test method code in the source file ordered based on the O3xx value. - List the new rule in the top level HACKING.rst file - Add test cases for each new rule to octavia_lib/tests/unit/test_hacking.py """ import re from hacking import core _all_log_levels = {'critical', 'error', 'exception', 'info', 'warning'} _all_hints = {'_LC', '_LE', '_LI', '_', '_LW'} _log_translation_hint = re.compile( r".*LOG\.(%(levels)s)\(\s*(%(hints)s)\(" % { 'levels': '|'.join(_all_log_levels), 'hints': '|'.join(_all_hints), }) assert_trueinst_re = re.compile( r"(.)*assertTrue\(isinstance\((\w|\.|\'|\"|\[|\])+, " r"(\w|\.|\'|\"|\[|\])+\)\)") assert_equal_in_end_with_true_or_false_re = re.compile( r"assertEqual\((\w|[][.'\"])+ in (\w|[][.'\", ])+, (True|False)\)") assert_equal_in_start_with_true_or_false_re = re.compile( r"assertEqual\((True|False), (\w|[][.'\"])+ in (\w|[][.'\", ])+\)") assert_equal_with_true_re = re.compile( r"assertEqual\(True,") assert_equal_with_false_re = re.compile( r"assertEqual\(False,") mutable_default_args = re.compile(r"^\s*def .+\((.+=\{\}|.+=\[\])") assert_equal_end_with_none_re = re.compile(r"(.)*assertEqual\(.+, None\)") assert_equal_start_with_none_re = re.compile(r".*assertEqual\(None, .+\)") assert_not_equal_end_with_none_re = re.compile( r"(.)*assertNotEqual\(.+, None\)") assert_not_equal_start_with_none_re = re.compile( r"(.)*assertNotEqual\(None, .+\)") revert_must_have_kwargs_re = re.compile( r'[ ]*def revert\(.+,[ ](?!\*\*kwargs)\w+\):') untranslated_exception_re = re.compile(r"raise (?:\w*)\((.*)\)") no_basestring_re = re.compile(r"\bbasestring\b") no_eventlet_re = re.compile(r'(import|from)\s+[(]?eventlet') no_line_continuation_backslash_re = re.compile(r'.*(\\)\n') no_logging_re = re.compile(r'(import|from)\s+[(]?logging') namespace_imports_dot = re.compile(r"import[\s]+([\w]+)[.][^\s]+") namespace_imports_from_dot = re.compile(r"from[\s]+([\w]+)[.]") namespace_imports_from_root = re.compile(r"from[\s]+([\w]+)[\s]+import[\s]+") def _check_imports(regex, submatch, logical_line): m = re.match(regex, logical_line) if m and m.group(1) == submatch: return True return False def _check_namespace_imports(failure_code, namespace, new_ns, logical_line, message_override=None): if message_override is not None: msg_o = "%s: %s" % (failure_code, message_override) else: msg_o = None if _check_imports(namespace_imports_from_dot, namespace, logical_line): msg = ("%s: '%s' must be used instead of '%s'.") % ( failure_code, logical_line.replace('%s.' % namespace, new_ns), logical_line) return (0, msg_o or msg) elif _check_imports(namespace_imports_from_root, namespace, logical_line): msg = ("%s: '%s' must be used instead of '%s'.") % ( failure_code, logical_line.replace( 'from %s import ' % namespace, 'import %s' % new_ns), logical_line) return (0, msg_o or msg) elif _check_imports(namespace_imports_dot, namespace, logical_line): msg = ("%s: '%s' must be used instead of '%s'.") % ( failure_code, logical_line.replace('import', 'from').replace('.', ' import '), logical_line) return (0, msg_o or msg) return None def _translation_checks_not_enforced(filename): # Do not do these validations on tests return any(pat in filename for pat in ["/tests/", "rally-jobs/plugins/"]) @core.flake8ext def assert_true_instance(logical_line): """Check for assertTrue(isinstance(a, b)) sentences O316 """ if assert_trueinst_re.match(logical_line): yield (0, "O316: assertTrue(isinstance(a, b)) sentences not allowed. " "Use assertIsInstance instead.") @core.flake8ext def assert_equal_or_not_none(logical_line): """Check for assertEqual(A, None) or assertEqual(None, A) sentences, assertNotEqual(A, None) or assertNotEqual(None, A) sentences O318 """ msg = ("O318: assertEqual/assertNotEqual(A, None) or " "assertEqual/assertNotEqual(None, A) sentences not allowed") res = (assert_equal_start_with_none_re.match(logical_line) or assert_equal_end_with_none_re.match(logical_line) or assert_not_equal_start_with_none_re.match(logical_line) or assert_not_equal_end_with_none_re.match(logical_line)) if res: yield (0, msg) @core.flake8ext def assert_equal_true_or_false(logical_line): """Check for assertEqual(True, A) or assertEqual(False, A) sentences O323 """ res = (assert_equal_with_true_re.search(logical_line) or assert_equal_with_false_re.search(logical_line)) if res: yield (0, "O323: assertEqual(True, A) or assertEqual(False, A) " "sentences not allowed") @core.flake8ext def no_mutable_default_args(logical_line): msg = "O324: Method's default argument shouldn't be mutable!" if mutable_default_args.match(logical_line): yield (0, msg) @core.flake8ext def assert_equal_in(logical_line): """Check for assertEqual(A in B, True), assertEqual(True, A in B), assertEqual(A in B, False) or assertEqual(False, A in B) sentences O338 """ res = (assert_equal_in_start_with_true_or_false_re.search(logical_line) or assert_equal_in_end_with_true_or_false_re.search(logical_line)) if res: yield (0, "O338: Use assertIn/NotIn(A, B) rather than " "assertEqual(A in B, True/False) when checking collection " "contents.") @core.flake8ext def no_log_warn(logical_line): """Disallow 'LOG.warn(' O339 """ if logical_line.startswith('LOG.warn('): yield(0, "O339:Use LOG.warning() rather than LOG.warn()") @core.flake8ext def no_translate_logs(logical_line, filename): """O341 - Don't translate logs. Check for 'LOG.*(_(' and 'LOG.*(_Lx(' Translators don't provide translations for log messages, and operators asked not to translate them. * This check assumes that 'LOG' is a logger. :param logical_line: The logical line to check. :param filename: The file name where the logical line exists. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ if _translation_checks_not_enforced(filename): return msg = "O341: Log messages should not be translated!" match = _log_translation_hint.match(logical_line) if match: yield (logical_line.index(match.group()), msg) @core.flake8ext def check_raised_localized_exceptions(logical_line, filename): """O342 - Untranslated exception message. :param logical_line: The logical line to check. :param filename: The file name where the logical line exists. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ if _translation_checks_not_enforced(filename): return logical_line = logical_line.strip() raised_search = untranslated_exception_re.match(logical_line) if raised_search: exception_msg = raised_search.groups()[0] if exception_msg.startswith("\"") or exception_msg.startswith("\'"): msg = "O342: Untranslated exception message." yield (logical_line.index(exception_msg), msg) @core.flake8ext def check_no_basestring(logical_line): """O343 - basestring is not Python3-compatible. :param logical_line: The logical line to check. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ if no_basestring_re.search(logical_line): msg = ("O343: basestring is not Python3-compatible, use " "str instead.") yield(0, msg) @core.flake8ext def check_no_eventlet_imports(logical_line): """O345 - Usage of Python eventlet module not allowed. :param logical_line: The logical line to check. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ if no_eventlet_re.match(logical_line): msg = 'O345 Usage of Python eventlet module not allowed' yield logical_line.index('eventlet'), msg @core.flake8ext def check_line_continuation_no_backslash(logical_line, tokens): """O346 - Don't use backslashes for line continuation. :param logical_line: The logical line to check. Not actually used. :param tokens: List of tokens to check. :returns: None if the tokens don't contain any issues, otherwise a tuple is yielded that contains the offending index in the logical line and a message describe the check validation failure. """ backslash = None for token_type, text, start, end, orig_line in tokens: m = no_line_continuation_backslash_re.match(orig_line) if m: backslash = (start[0], m.start(1)) break if backslash is not None: msg = 'O346 Backslash line continuations not allowed' yield backslash, msg @core.flake8ext def check_no_logging_imports(logical_line): """O348 - Usage of Python logging module not allowed. :param logical_line: The logical line to check. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ if no_logging_re.match(logical_line): msg = 'O348 Usage of Python logging module not allowed, use oslo_log' yield logical_line.index('logging'), msg @core.flake8ext def check_no_octavia_namespace_imports(logical_line): """O501 - Direct octavia imports not allowed. :param logical_line: The logical line to check. :returns: None if the logical line passes the check, otherwise a tuple is yielded that contains the offending index in logical line and a message describe the check validation failure. """ x = _check_namespace_imports( 'O501', 'octavia', 'octavia_lib.', logical_line, message_override="O501 Direct octavia imports not allowed") if x is not None: yield x octavia-lib-2.0.0/octavia_lib/hacking/__init__.py0000664000175000017500000000000013641342731021710 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/common/0000775000175000017500000000000013641343053017473 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/common/constants.py0000664000175000017500000002404613641342731022071 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Codes the driver_agent can return to the octavia-lib driver_lib DRVR_STATUS_CODE_FAILED = 500 DRVR_STATUS_CODE_OK = 200 STATUS_CODE = 'status_code' FAULT_STRING = 'fault_string' STATS_OBJECT = 'stats_object' STATS_OBJECT_ID = 'stats_object_id' STATS_RECORD = 'stats_record' STATUS_OBJECT = 'status_object' STATUS_OBJECT_ID = 'status_object_id' STATUS_RECORD = 'status_record' # Octavia objects LOADBALANCERS = 'loadbalancers' LISTENERS = 'listeners' POOLS = 'pools' HEALTHMONITORS = 'healthmonitors' MEMBERS = 'members' L7POLICIES = 'l7policies' L7RULES = 'l7rules' FLAVOR = 'flavor' OBJECT = 'object' # ID fields ID = 'id' # Octavia statistics fields ACTIVE_CONNECTIONS = 'active_connections' BYTES_IN = 'bytes_in' BYTES_OUT = 'bytes_out' REQUEST_ERRORS = 'request_errors' TOTAL_CONNECTIONS = 'total_connections' # Constants common to all Octavia provider drivers HEALTH_MONITOR_PING = 'PING' HEALTH_MONITOR_TCP = 'TCP' HEALTH_MONITOR_HTTP = 'HTTP' HEALTH_MONITOR_HTTPS = 'HTTPS' HEALTH_MONITOR_TLS_HELLO = 'TLS-HELLO' HEALTH_MONITOR_UDP_CONNECT = 'UDP-CONNECT' SUPPORTED_HEALTH_MONITOR_TYPES = (HEALTH_MONITOR_HTTP, HEALTH_MONITOR_HTTPS, HEALTH_MONITOR_PING, HEALTH_MONITOR_TCP, HEALTH_MONITOR_TLS_HELLO, HEALTH_MONITOR_UDP_CONNECT) HEALTH_MONITOR_HTTP_METHOD_GET = 'GET' HEALTH_MONITOR_HTTP_METHOD_HEAD = 'HEAD' HEALTH_MONITOR_HTTP_METHOD_POST = 'POST' HEALTH_MONITOR_HTTP_METHOD_PUT = 'PUT' HEALTH_MONITOR_HTTP_METHOD_DELETE = 'DELETE' HEALTH_MONITOR_HTTP_METHOD_TRACE = 'TRACE' HEALTH_MONITOR_HTTP_METHOD_OPTIONS = 'OPTIONS' HEALTH_MONITOR_HTTP_METHOD_CONNECT = 'CONNECT' HEALTH_MONITOR_HTTP_METHOD_PATCH = 'PATCH' HEALTH_MONITOR_HTTP_DEFAULT_METHOD = HEALTH_MONITOR_HTTP_METHOD_GET SUPPORTED_HEALTH_MONITOR_HTTP_METHODS = ( HEALTH_MONITOR_HTTP_METHOD_GET, HEALTH_MONITOR_HTTP_METHOD_HEAD, HEALTH_MONITOR_HTTP_METHOD_POST, HEALTH_MONITOR_HTTP_METHOD_PUT, HEALTH_MONITOR_HTTP_METHOD_DELETE, HEALTH_MONITOR_HTTP_METHOD_TRACE, HEALTH_MONITOR_HTTP_METHOD_OPTIONS, HEALTH_MONITOR_HTTP_METHOD_CONNECT, HEALTH_MONITOR_HTTP_METHOD_PATCH) L7POLICY_ACTION_REJECT = 'REJECT' L7POLICY_ACTION_REDIRECT_TO_URL = 'REDIRECT_TO_URL' L7POLICY_ACTION_REDIRECT_TO_POOL = 'REDIRECT_TO_POOL' L7POLICY_ACTION_REDIRECT_PREFIX = 'REDIRECT_PREFIX' SUPPORTED_L7POLICY_ACTIONS = (L7POLICY_ACTION_REJECT, L7POLICY_ACTION_REDIRECT_TO_URL, L7POLICY_ACTION_REDIRECT_TO_POOL, L7POLICY_ACTION_REDIRECT_PREFIX) L7RULE_COMPARE_TYPE_REGEX = 'REGEX' L7RULE_COMPARE_TYPE_STARTS_WITH = 'STARTS_WITH' L7RULE_COMPARE_TYPE_ENDS_WITH = 'ENDS_WITH' L7RULE_COMPARE_TYPE_CONTAINS = 'CONTAINS' L7RULE_COMPARE_TYPE_EQUAL_TO = 'EQUAL_TO' SUPPORTED_L7RULE_COMPARE_TYPES = (L7RULE_COMPARE_TYPE_REGEX, L7RULE_COMPARE_TYPE_STARTS_WITH, L7RULE_COMPARE_TYPE_ENDS_WITH, L7RULE_COMPARE_TYPE_CONTAINS, L7RULE_COMPARE_TYPE_EQUAL_TO) L7RULE_TYPE_HOST_NAME = 'HOST_NAME' L7RULE_TYPE_PATH = 'PATH' L7RULE_TYPE_FILE_TYPE = 'FILE_TYPE' L7RULE_TYPE_HEADER = 'HEADER' L7RULE_TYPE_COOKIE = 'COOKIE' L7RULE_TYPE_SSL_CONN_HAS_CERT = 'SSL_CONN_HAS_CERT' L7RULE_TYPE_SSL_VERIFY_RESULT = 'SSL_VERIFY_RESULT' L7RULE_TYPE_SSL_DN_FIELD = 'SSL_DN_FIELD' SUPPORTED_L7RULE_TYPES = (L7RULE_TYPE_HOST_NAME, L7RULE_TYPE_PATH, L7RULE_TYPE_FILE_TYPE, L7RULE_TYPE_HEADER, L7RULE_TYPE_COOKIE, L7RULE_TYPE_SSL_CONN_HAS_CERT, L7RULE_TYPE_SSL_VERIFY_RESULT, L7RULE_TYPE_SSL_DN_FIELD) DISTINGUISHED_NAME_FIELD_REGEX = '^([a-zA-Z][A-Za-z0-9-]*)$' LB_ALGORITHM_ROUND_ROBIN = 'ROUND_ROBIN' LB_ALGORITHM_LEAST_CONNECTIONS = 'LEAST_CONNECTIONS' LB_ALGORITHM_SOURCE_IP = 'SOURCE_IP' LB_ALGORITHM_SOURCE_IP_PORT = 'SOURCE_IP_PORT' SUPPORTED_LB_ALGORITHMS = (LB_ALGORITHM_LEAST_CONNECTIONS, LB_ALGORITHM_ROUND_ROBIN, LB_ALGORITHM_SOURCE_IP, LB_ALGORITHM_SOURCE_IP_PORT) OPERATING_STATUS = 'operating_status' ONLINE = 'ONLINE' OFFLINE = 'OFFLINE' DEGRADED = 'DEGRADED' ERROR = 'ERROR' DRAINING = 'DRAINING' NO_MONITOR = 'NO_MONITOR' SUPPORTED_OPERATING_STATUSES = (ONLINE, OFFLINE, DEGRADED, ERROR, DRAINING, NO_MONITOR) PROTOCOL_TCP = 'TCP' PROTOCOL_UDP = 'UDP' PROTOCOL_HTTP = 'HTTP' PROTOCOL_HTTPS = 'HTTPS' PROTOCOL_TERMINATED_HTTPS = 'TERMINATED_HTTPS' PROTOCOL_PROXY = 'PROXY' SUPPORTED_PROTOCOLS = (PROTOCOL_TCP, PROTOCOL_HTTPS, PROTOCOL_HTTP, PROTOCOL_TERMINATED_HTTPS, PROTOCOL_PROXY, PROTOCOL_UDP) PROVISIONING_STATUS = 'provisioning_status' # Amphora has been allocated to a load balancer AMPHORA_ALLOCATED = 'ALLOCATED' # Amphora is being built AMPHORA_BOOTING = 'BOOTING' # Amphora is ready to be allocated to a load balancer AMPHORA_READY = 'READY' ACTIVE = 'ACTIVE' PENDING_DELETE = 'PENDING_DELETE' PENDING_UPDATE = 'PENDING_UPDATE' PENDING_CREATE = 'PENDING_CREATE' DELETED = 'DELETED' SUPPORTED_PROVISIONING_STATUSES = (ACTIVE, AMPHORA_ALLOCATED, AMPHORA_BOOTING, AMPHORA_READY, PENDING_DELETE, PENDING_CREATE, PENDING_UPDATE, DELETED, ERROR) SESSION_PERSISTENCE_SOURCE_IP = 'SOURCE_IP' SESSION_PERSISTENCE_HTTP_COOKIE = 'HTTP_COOKIE' SESSION_PERSISTENCE_APP_COOKIE = 'APP_COOKIE' SUPPORTED_SP_TYPES = (SESSION_PERSISTENCE_SOURCE_IP, SESSION_PERSISTENCE_HTTP_COOKIE, SESSION_PERSISTENCE_APP_COOKIE) # List of HTTP headers which are supported for insertion SUPPORTED_HTTP_HEADERS = ['X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto'] # List of SSL headers for client certificate SUPPORTED_SSL_HEADERS = ['X-SSL-Client-Verify', 'X-SSL-Client-Has-Cert', 'X-SSL-Client-DN', 'X-SSL-Client-CN', 'X-SSL-Issuer', 'X-SSL-Client-SHA1', 'X-SSL-Client-Not-Before', 'X-SSL-Client-Not-After'] # Client certification authorization options CLIENT_AUTH_NONE = 'NONE' CLIENT_AUTH_OPTIONAL = 'OPTIONAL' CLIENT_AUTH_MANDATORY = 'MANDATORY' SUPPORTED_CLIENT_AUTH_MODES = [CLIENT_AUTH_NONE, CLIENT_AUTH_OPTIONAL, CLIENT_AUTH_MANDATORY] # Constants from the provider driver API ACTION = 'action' ADDITIONAL_VIPS = 'additional_vips' ADDRESS = 'address' ADMIN_STATE_UP = 'admin_state_up' ALLOWED_CIDRS = 'allowed_cidrs' AVAILABILITY_ZONE = 'availability_zone' BACKUP = 'backup' CA_TLS_CONTAINER_DATA = 'ca_tls_container_data' CA_TLS_CONTAINER_REF = 'ca_tls_container_ref' CASCADE = 'cascade' CERTIFICATE = 'certificate' CLIENT_AUTHENTICATION = 'client_authentication' CLIENT_CA_TLS_CONTAINER_DATA = 'client_ca_tls_container_data' CLIENT_CA_TLS_CONTAINER_REF = 'client_ca_tls_container_ref' CLIENT_CRL_CONTAINER_DATA = 'client_crl_container_data' CLIENT_CRL_CONTAINER_REF = 'client_crl_container_ref' COMPARE_TYPE = 'compare_type' CONNECTION_LIMIT = 'connection_limit' COOKIE_NAME = 'cookie_name' CRL_CONTAINER_DATA = 'crl_container_data' CRL_CONTAINER_REF = 'crl_container_ref' DEFAULT_POOL = 'default_pool' DEFAULT_POOL_ID = 'default_pool_id' DEFAULT_TLS_CONTAINER_DATA = 'default_tls_container_data' DEFAULT_TLS_CONTAINER_REF = 'default_tls_container_ref' DELAY = 'delay' DESCRIPTION = 'description' DOMAIN_NAME = 'domain_name' EXPECTED_CODES = 'expected_codes' FALL_THRESHOLD = 'fall_threshold' HEALTHMONITOR = 'healthmonitor' HEALTHMONITOR_ID = 'healthmonitor_id' HTTP_METHOD = 'http_method' HTTP_VERSION = 'http_version' INSERT_HEADERS = 'insert_headers' INTERMEDIATES = 'intermediates' INVERT = 'invert' KEY = 'key' L7POLICY_ID = 'l7policy_id' L7RULE_ID = 'l7rule_id' LB_ALGORITHM = 'lb_algorithm' LISTENER_ID = 'listener_id' LOADBALANCER_ID = 'loadbalancer_id' MAX_RETRIES = 'max_retries' MAX_RETRIES_DOWN = 'max_retries_down' MEMBER_ID = 'member_id' MONITOR_ADDRESS = 'monitor_address' MONITOR_PORT = 'monitor_port' NAME = 'name' NETWORK_ID = 'network_id' PASSPHRASE = 'passphrase' PERSISTENCE_GRANULARITY = 'persistence_granularity' PERSISTENCE_TIMEOUT = 'persistence_timeout' POOL_ID = 'pool_id' POSITION = 'position' PRIMARY_CN = 'primary_cn' PRIVATE_KEY = 'private_key' PROJECT_ID = 'project_id' PROTOCOL = 'protocol' PROTOCOL_PORT = 'protocol_port' REDIRECT_HTTP_CODE = 'redirect_http_code' REDIRECT_POOL_ID = 'redirect_pool_id' REDIRECT_PREFIX = 'redirect_prefix' REDIRECT_URL = 'redirect_url' RISE_THRESHOLD = 'rise_threshold' RULES = 'rules' SESSION_PERSISTENCE = 'session_persistence' SNI_CONTAINER_DATA = 'sni_container_data' SNI_CONTAINER_REFS = 'sni_container_refs' SUBNET_ID = 'subnet_id' TIMEOUT = 'timeout' TIMEOUT_CLIENT_DATA = 'timeout_client_data' TIMEOUT_MEMBER_CONNECT = 'timeout_member_connect' TIMEOUT_MEMBER_DATA = 'timeout_member_data' TIMEOUT_TCP_INSPECT = 'timeout_tcp_inspect' TLS_CIPHERS = 'tls_ciphers' TLS_CONTAINER_DATA = 'tls_container_data' TLS_CONTAINER_REF = 'tls_container_ref' TLS_ENABLED = 'tls_enabled' TLS_VERSIONS = 'tls_versions' SSL_VERSION_3 = 'SSLv3' TLS_VERSION_1 = 'TLSv1' TLS_VERSION_1_1 = 'TLSv1.1' TLS_VERSION_1_2 = 'TLSv1.2' TLS_VERSION_1_3 = 'TLSv1.3' TYPE = 'type' URL_PATH = 'url_path' VALUE = 'value' VIP_ADDRESS = 'vip_address' VIP_NETWORK_ID = 'vip_network_id' VIP_PORT_ID = 'vip_port_id' VIP_SUBNET_ID = 'vip_subnet_id' VIP_QOS_POLICY_ID = 'vip_qos_policy_id' WEIGHT = 'weight' octavia-lib-2.0.0/octavia_lib/common/__init__.py0000664000175000017500000000000013641342731021574 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/0000775000175000017500000000000013641343053017345 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/0000775000175000017500000000000013641343053020324 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/api/0000775000175000017500000000000013641343053021075 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/0000775000175000017500000000000013641343053022553 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/test_data_models.py0000664000175000017500000004644613641342731026460 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from copy import deepcopy from oslo_utils import uuidutils from octavia_lib.api.drivers import data_models from octavia_lib.common import constants from octavia_lib.tests.unit import base class TestProviderDataModels(base.TestCase): def setUp(self): super(TestProviderDataModels, self).setUp() self.loadbalancer_id = uuidutils.generate_uuid() self.project_id = uuidutils.generate_uuid() self.vip_address = '192.0.2.83' self.vip_network_id = uuidutils.generate_uuid() self.vip_port_id = uuidutils.generate_uuid() self.vip_subnet_id = uuidutils.generate_uuid() self.listener_id = uuidutils.generate_uuid() self.vip_qos_policy_id = uuidutils.generate_uuid() self.default_tls_container_ref = uuidutils.generate_uuid() self.sni_container_ref_1 = uuidutils.generate_uuid() self.sni_container_ref_2 = uuidutils.generate_uuid() self.pool_id = uuidutils.generate_uuid() self.session_persistence = {"cookie_name": "sugar", "type": "APP_COOKIE"} self.member_id = uuidutils.generate_uuid() self.mem_subnet_id = uuidutils.generate_uuid() self.healthmonitor_id = uuidutils.generate_uuid() self.l7policy_id = uuidutils.generate_uuid() self.l7rule_id = uuidutils.generate_uuid() self.availability_zone = uuidutils.generate_uuid() self.ref_l7rule = data_models.L7Rule( admin_state_up=True, compare_type='STARTS_WITH', invert=True, key='cookie', l7policy_id=self.l7policy_id, l7rule_id=self.l7rule_id, type='COOKIE', project_id=self.project_id, value='chocolate') self.ref_l7policy = data_models.L7Policy( action='REJECT', admin_state_up=False, description='A L7 Policy', l7policy_id=self.l7policy_id, listener_id=self.listener_id, name='l7policy', position=1, redirect_pool_id=self.pool_id, redirect_url='/test', rules=[self.ref_l7rule], project_id=self.project_id, redirect_prefix='http://example.com', redirect_http_code=301) self.ref_listener = data_models.Listener( admin_state_up=True, connection_limit=5000, default_pool=None, default_pool_id=None, default_tls_container_data='default_cert_data', default_tls_container_ref=self.default_tls_container_ref, description=data_models.Unset, insert_headers={'X-Forwarded-For': 'true'}, l7policies=[self.ref_l7policy], listener_id=self.listener_id, loadbalancer_id=self.loadbalancer_id, name='super_listener', project_id=self.project_id, protocol='avian', protocol_port=42, sni_container_data=['sni_cert_data_1', 'sni_cert_data_2'], sni_container_refs=[self.sni_container_ref_1, self.sni_container_ref_2], timeout_client_data=3, timeout_member_connect=4, timeout_member_data=5, timeout_tcp_inspect=6, client_authentication=None, client_ca_tls_container_data=None, client_ca_tls_container_ref=None, client_crl_container_data=None, client_crl_container_ref=None, allowed_cidrs=None, tls_versions=[constants.SSL_VERSION_3, constants.TLS_VERSION_1, constants.TLS_VERSION_1_1, constants.TLS_VERSION_1_2, constants.TLS_VERSION_1_3], tls_ciphers=None) self.ref_lb = data_models.LoadBalancer( admin_state_up=False, description='One great load balancer', flavor={'cake': 'chocolate'}, listeners=[self.ref_listener], loadbalancer_id=self.loadbalancer_id, name='favorite_lb', project_id=self.project_id, vip_address=self.vip_address, vip_network_id=self.vip_network_id, vip_port_id=self.vip_port_id, vip_subnet_id=self.vip_subnet_id, vip_qos_policy_id=self.vip_qos_policy_id, availability_zone=self.availability_zone) self.ref_vip = data_models.VIP( vip_address=self.vip_address, vip_network_id=self.vip_network_id, vip_port_id=self.vip_port_id, vip_subnet_id=self.vip_subnet_id, vip_qos_policy_id=self.vip_qos_policy_id) self.ref_member = data_models.Member( address='192.0.2.10', admin_state_up=True, member_id=self.member_id, monitor_address='192.0.2.11', monitor_port=8888, name='member', pool_id=self.pool_id, project_id=self.project_id, protocol_port=80, subnet_id=self.mem_subnet_id, weight=1, backup=False) self.ref_healthmonitor = data_models.HealthMonitor( admin_state_up=False, delay=1, expected_codes='200,202', healthmonitor_id=self.healthmonitor_id, http_method='GET', max_retries=2, max_retries_down=3, name='member', pool_id=self.pool_id, project_id=self.project_id, timeout=4, type='HTTP', url_path='/test', http_version=1.1, domain_name='testdomainname.com') self.ref_pool = data_models.Pool( admin_state_up=True, description='A pool', healthmonitor=None, lb_algorithm='fast', loadbalancer_id=self.loadbalancer_id, members=[self.ref_member], name='pool', pool_id=self.pool_id, project_id=self.project_id, listener_id=self.listener_id, protocol='avian', session_persistence=self.session_persistence, tls_versions=[constants.SSL_VERSION_3, constants.TLS_VERSION_1, constants.TLS_VERSION_1_1, constants.TLS_VERSION_1_2, constants.TLS_VERSION_1_3], tls_ciphers=None) self.ref_l7rule_dict = {'admin_state_up': True, 'compare_type': 'STARTS_WITH', 'invert': True, 'key': 'cookie', 'l7policy_id': self.l7policy_id, 'l7rule_id': self.l7rule_id, 'type': 'COOKIE', 'project_id': self.project_id, 'value': 'chocolate'} self.ref_l7policy_dict = {'action': 'REJECT', 'admin_state_up': False, 'description': 'A L7 Policy', 'l7policy_id': self.l7policy_id, 'listener_id': self.listener_id, 'name': 'l7policy', 'position': 1, 'project_id': self.project_id, 'redirect_pool_id': self.pool_id, 'redirect_url': '/test', 'rules': [self.ref_l7rule_dict], 'redirect_prefix': 'http://example.com', 'redirect_http_code': 301} self.ref_lb_dict = {'project_id': self.project_id, 'flavor': {'cake': 'chocolate'}, 'vip_network_id': self.vip_network_id, 'admin_state_up': False, 'loadbalancer_id': self.loadbalancer_id, 'vip_port_id': self.vip_port_id, 'vip_address': self.vip_address, 'description': 'One great load balancer', 'vip_subnet_id': self.vip_subnet_id, 'name': 'favorite_lb', 'vip_qos_policy_id': self.vip_qos_policy_id, 'availability_zone': self.availability_zone} self.ref_listener_dict = { 'admin_state_up': True, 'connection_limit': 5000, 'default_pool': None, 'default_pool_id': None, 'default_tls_container_data': 'default_cert_data', 'default_tls_container_ref': self.default_tls_container_ref, 'description': None, 'insert_headers': {'X-Forwarded-For': 'true'}, 'listener_id': self.listener_id, 'l7policies': [self.ref_l7policy_dict], 'loadbalancer_id': self.loadbalancer_id, 'name': 'super_listener', 'project_id': self.project_id, 'protocol': 'avian', 'protocol_port': 42, 'sni_container_data': ['sni_cert_data_1', 'sni_cert_data_2'], 'sni_container_refs': [self.sni_container_ref_1, self.sni_container_ref_2], 'timeout_client_data': 3, 'timeout_member_connect': 4, 'timeout_member_data': 5, 'timeout_tcp_inspect': 6, 'client_authentication': None, 'client_ca_tls_container_data': None, 'client_ca_tls_container_ref': None, 'client_crl_container_data': None, 'client_crl_container_ref': None, 'allowed_cidrs': None, 'tls_versions': [constants.SSL_VERSION_3, constants.TLS_VERSION_1, constants.TLS_VERSION_1_1, constants.TLS_VERSION_1_2, constants.TLS_VERSION_1_3], 'tls_ciphers': None} self.ref_lb_dict_with_listener = { 'admin_state_up': False, 'description': 'One great load balancer', 'flavor': {'cake': 'chocolate'}, 'listeners': [self.ref_listener_dict], 'loadbalancer_id': self.loadbalancer_id, 'name': 'favorite_lb', 'project_id': self.project_id, 'vip_address': self.vip_address, 'vip_network_id': self.vip_network_id, 'vip_port_id': self.vip_port_id, 'vip_subnet_id': self.vip_subnet_id, 'vip_qos_policy_id': self.vip_qos_policy_id, 'availability_zone': self.availability_zone} self.ref_vip_dict = { 'vip_address': self.vip_address, 'vip_network_id': self.vip_network_id, 'vip_port_id': self.vip_port_id, 'vip_subnet_id': self.vip_subnet_id, 'vip_qos_policy_id': self.vip_qos_policy_id} self.ref_member_dict = { 'address': '192.0.2.10', 'admin_state_up': True, 'member_id': self.member_id, 'monitor_address': '192.0.2.11', 'monitor_port': 8888, 'name': 'member', 'pool_id': self.pool_id, 'project_id': self.project_id, 'protocol_port': 80, 'subnet_id': self.mem_subnet_id, 'weight': 1, 'backup': False} self.ref_healthmonitor_dict = { 'admin_state_up': False, 'delay': 1, 'expected_codes': '200,202', 'healthmonitor_id': self.healthmonitor_id, 'http_method': 'GET', 'max_retries': 2, 'max_retries_down': 3, 'name': 'member', 'pool_id': self.pool_id, 'project_id': self.project_id, 'timeout': 4, 'type': 'HTTP', 'url_path': '/test', 'http_version': 1.1, 'domain_name': 'testdomainname.com'} self.ref_pool_dict = { 'admin_state_up': True, 'description': 'A pool', 'healthmonitor': self.ref_healthmonitor_dict, 'lb_algorithm': 'fast', 'loadbalancer_id': self.loadbalancer_id, 'members': [self.ref_member_dict], 'name': 'pool', 'pool_id': self.pool_id, 'project_id': self.project_id, 'listener_id': self.listener_id, 'protocol': 'avian', 'session_persistence': self.session_persistence, 'tls_versions': [constants.SSL_VERSION_3, constants.TLS_VERSION_1, constants.TLS_VERSION_1_1, constants.TLS_VERSION_1_2, constants.TLS_VERSION_1_3], 'tls_ciphers': None} def test_equality(self): second_ref_lb = deepcopy(self.ref_lb) self.assertEqual(self.ref_lb, second_ref_lb) second_ref_lb.admin_state_up = True self.assertNotEqual(self.ref_lb, second_ref_lb) self.assertNotEqual(self.ref_lb, self.loadbalancer_id) def test_inequality(self): second_ref_lb = deepcopy(self.ref_lb) self.assertEqual(self.ref_lb, second_ref_lb) second_ref_lb.admin_state_up = True self.assertNotEqual(self.ref_lb, second_ref_lb) self.assertNotEqual(self.ref_lb, self.loadbalancer_id) def test_to_dict(self): ref_lb_converted_to_dict = self.ref_lb.to_dict() ref_listener_converted_to_dict = self.ref_listener.to_dict() ref_pool_converted_to_dict = self.ref_pool.to_dict() ref_member_converted_to_dict = self.ref_member.to_dict() ref_healthmon_converted_to_dict = self.ref_healthmonitor.to_dict() ref_l7policy_converted_to_dict = self.ref_l7policy.to_dict() ref_l7rule_converted_to_dict = self.ref_l7rule.to_dict() ref_vip_converted_to_dict = self.ref_vip.to_dict() # This test does not recurse, so remove items for the reference # that should not be rendered ref_list_dict = deepcopy(self.ref_listener_dict) ref_list_dict.pop('l7policies', None) ref_list_dict.pop('sni_container_data', None) ref_list_dict.pop('sni_container_refs', None) ref_list_dict.pop('tls_versions', None) ref_pool_dict = deepcopy(self.ref_pool_dict) ref_pool_dict['healthmonitor'] = None ref_pool_dict.pop('members', None) ref_pool_dict.pop('tls_versions', None) ref_l7policy_dict = deepcopy(self.ref_l7policy_dict) ref_l7policy_dict.pop('rules', None) # This test does not render unsets, so remove those from the reference ref_list_dict.pop('description', None) self.assertEqual(self.ref_lb_dict, ref_lb_converted_to_dict) self.assertEqual(ref_list_dict, ref_listener_converted_to_dict) self.assertEqual(ref_pool_dict, ref_pool_converted_to_dict) self.assertEqual(self.ref_member_dict, ref_member_converted_to_dict) self.assertEqual(self.ref_healthmonitor_dict, ref_healthmon_converted_to_dict) self.assertEqual(ref_l7policy_dict, ref_l7policy_converted_to_dict) self.assertEqual(self.ref_l7rule_dict, ref_l7rule_converted_to_dict) self.assertEqual(self.ref_vip_dict, ref_vip_converted_to_dict) def test_to_dict_private_attrs(self): private_dict = {'_test': 'foo'} ref_lb_converted_to_dict = self.ref_lb.to_dict(**private_dict) self.assertEqual(self.ref_lb_dict, ref_lb_converted_to_dict) def test_to_dict_partial(self): ref_lb = data_models.LoadBalancer(loadbalancer_id=self.loadbalancer_id) ref_lb_dict = {'loadbalancer_id': self.loadbalancer_id} ref_lb_converted_to_dict = ref_lb.to_dict() self.assertEqual(ref_lb_dict, ref_lb_converted_to_dict) def test_to_dict_render_unsets(self): ref_lb_converted_to_dict = self.ref_lb.to_dict(render_unsets=True) new_ref_lib_dict = deepcopy(self.ref_lb_dict) new_ref_lib_dict['pools'] = None new_ref_lib_dict['listeners'] = None new_ref_lib_dict['additional_vips'] = None self.assertEqual(new_ref_lib_dict, ref_lb_converted_to_dict) def test_to_dict_recursive(self): # Render with unsets is not set, so remove the Unset description ref_lb_dict_with_listener = deepcopy(self.ref_lb_dict_with_listener) ref_lb_dict_with_listener['listeners'][0].pop('description', None) ref_lb_converted_to_dict = self.ref_lb.to_dict(recurse=True) self.assertEqual(ref_lb_dict_with_listener, ref_lb_converted_to_dict) def test_to_dict_recursive_partial(self): ref_lb = data_models.LoadBalancer( loadbalancer_id=self.loadbalancer_id, listeners=[self.ref_listener]) ref_lb_dict_with_listener = { 'loadbalancer_id': self.loadbalancer_id, 'listeners': [self.ref_listener_dict]} # Render with unsets is not set, so remove the Unset description ref_lb_dict_with_listener = deepcopy(ref_lb_dict_with_listener) ref_lb_dict_with_listener['listeners'][0].pop('description', None) ref_lb_converted_to_dict = ref_lb.to_dict(recurse=True) self.assertEqual(ref_lb_dict_with_listener, ref_lb_converted_to_dict) def test_to_dict_recursive_render_unset(self): ref_lb = data_models.LoadBalancer( admin_state_up=False, description='One great load balancer', flavor={'cake': 'chocolate'}, listeners=[self.ref_listener], loadbalancer_id=self.loadbalancer_id, project_id=self.project_id, vip_address=self.vip_address, vip_network_id=self.vip_network_id, vip_port_id=self.vip_port_id, vip_subnet_id=self.vip_subnet_id, vip_qos_policy_id=self.vip_qos_policy_id, availability_zone=self.availability_zone) ref_lb_dict_with_listener = deepcopy(self.ref_lb_dict_with_listener) ref_lb_dict_with_listener['pools'] = None ref_lb_dict_with_listener['name'] = None ref_lb_dict_with_listener['additional_vips'] = None ref_lb_converted_to_dict = ref_lb.to_dict(recurse=True, render_unsets=True) self.assertEqual(ref_lb_dict_with_listener, ref_lb_converted_to_dict) def test_from_dict(self): lb_object = data_models.LoadBalancer.from_dict(self.ref_lb_dict) self.assertEqual(self.ref_lb, lb_object) def test_unset_bool(self): self.assertFalse(data_models.Unset) def test_unset_repr(self): self.assertEqual('Unset', repr(data_models.Unset)) octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/test_driver_lib.py0000664000175000017500000002176613641342731026323 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from unittest import mock from octavia_lib.api.drivers import driver_lib from octavia_lib.api.drivers import exceptions as driver_exceptions from octavia_lib.common import constants from octavia_lib.tests.unit import base class TestDriverLib(base.TestCase): @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary.' '_check_for_socket_ready') def setUp(self, mock_check_ready): self.driver_lib = driver_lib.DriverLibrary() super(TestDriverLib, self).setUp() @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary.' '_check_for_socket_ready.retry.sleep') @mock.patch('os.path.exists') def test_check_for_socket_ready(self, mock_path_exists, mock_sleep): mock_path_exists.return_value = True # should not raise an exception self.driver_lib._check_for_socket_ready('bogus') mock_path_exists.return_value = False self.assertRaises(driver_exceptions.DriverAgentNotFound, self.driver_lib._check_for_socket_ready, 'bogus') @mock.patch('builtins.memoryview') def test_recv(self, mock_memoryview): mock_socket = mock.MagicMock() mock_socket.recv.side_effect = [b'1', b'\n', b'2', b'\n', b'3', b'\n'] mock_socket.recv_into.return_value = 1 mv_mock = mock.MagicMock() mock_memoryview.return_value = mv_mock mv_mock.tobytes.return_value = b'"test data"' response = self.driver_lib._recv(mock_socket) calls = [mock.call(1), mock.call(1)] mock_socket.recv.assert_has_calls(calls) mock_socket.recv_into.assert_called_once_with( mv_mock.__getitem__(), 1) self.assertEqual('test data', response) # Test size recv timeout with mock.patch('octavia_lib.api.drivers.driver_lib.' 'time') as mock_time: mock_time.time.side_effect = [0, 1000, 0, 0, 0, 0, 1000] self.assertRaises(driver_exceptions.DriverAgentTimeout, self.driver_lib._recv, mock_socket) # Test payload recv timeout self.assertRaises(driver_exceptions.DriverAgentTimeout, self.driver_lib._recv, mock_socket) @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary._recv') def test_send(self, mock_recv): mock_socket = mock.MagicMock() mock_recv.return_value = 'fake_response' with mock.patch('socket.socket') as socket_mock: socket_mock.return_value = mock_socket response = self.driver_lib._send('fake_path', 'test data') mock_socket.connect.assert_called_once_with('fake_path') mock_socket.send.assert_called_once_with(b'11\n') mock_socket.sendall.assert_called_once_with(b'"test data"') mock_socket.close.assert_called_once() self.assertEqual(mock_recv.return_value, response) @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary._send') def test_update_loadbalancer_status(self, mock_send): error_dict = {'status_code': 500, 'fault_string': 'boom', 'status_object': 'balloon', 'status_object_id': '1', 'status_record': 'tunes'} mock_send.side_effect = [{'status_code': 200}, Exception('boom'), error_dict] # Happy path self.driver_lib.update_loadbalancer_status('fake_status') mock_send.assert_called_once_with('/var/run/octavia/status.sock', 'fake_status') # Test general exception self.assertRaises(driver_exceptions.UpdateStatusError, self.driver_lib.update_loadbalancer_status, 'fake_status') # Test bad status code returned self.assertRaises(driver_exceptions.UpdateStatusError, self.driver_lib.update_loadbalancer_status, 'fake_status') @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary._send') def test_update_listener_statistics(self, mock_send): error_dict = {'status_code': 500, 'fault_string': 'boom', 'status_object': 'balloon', 'status_object_id': '1', 'status_record': 'tunes'} mock_send.side_effect = [{'status_code': 200}, Exception('boom'), error_dict] # Happy path self.driver_lib.update_listener_statistics('fake_stats') mock_send.assert_called_once_with('/var/run/octavia/stats.sock', 'fake_stats') # Test general exception self.assertRaises(driver_exceptions.UpdateStatisticsError, self.driver_lib.update_listener_statistics, 'fake_stats') # Test bad status code returned self.assertRaises(driver_exceptions.UpdateStatisticsError, self.driver_lib.update_listener_statistics, 'fake_stats') @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary._send') def test_get_resource(self, mock_send): fake_resource = 'fake resource' fake_id = 'fake id' mock_send.side_effect = ['some result', driver_exceptions.DriverAgentTimeout, Exception('boom')] result = self.driver_lib._get_resource(fake_resource, fake_id) data = {constants.OBJECT: fake_resource, constants.ID: fake_id} mock_send.assert_called_once_with('/var/run/octavia/get.sock', data) self.assertEqual('some result', result) # Test with driver_exceptions.DriverAgentTimeout self.assertRaises(driver_exceptions.DriverAgentTimeout, self.driver_lib._get_resource, fake_resource, fake_id) # Test with random exception self.assertRaises(driver_exceptions.DriverError, self.driver_lib._get_resource, fake_resource, fake_id) @mock.patch('octavia_lib.api.drivers.driver_lib.DriverLibrary.' '_get_resource') def _test_get_object(self, get_method, name, mock_from_dict, mock_get_resource): mock_get_resource.side_effect = ['some data', None] mock_from_dict.return_value = 'object' result = get_method('fake id') mock_get_resource.assert_called_once_with(name, 'fake id') mock_from_dict.assert_called_once_with('some data') self.assertEqual('object', result) # Test not found result = get_method('fake id') self.assertIsNone(result) @mock.patch('octavia_lib.api.drivers.data_models.LoadBalancer.from_dict') def test_get_loadbalancer(self, mock_from_dict): self._test_get_object(self.driver_lib.get_loadbalancer, constants.LOADBALANCERS, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.Listener.from_dict') def test_get_listener(self, mock_from_dict): self._test_get_object(self.driver_lib.get_listener, constants.LISTENERS, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.Pool.from_dict') def test_get_pool(self, mock_from_dict): self._test_get_object(self.driver_lib.get_pool, constants.POOLS, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.HealthMonitor.from_dict') def test_get_healthmonitor(self, mock_from_dict): self._test_get_object(self.driver_lib.get_healthmonitor, constants.HEALTHMONITORS, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.Member.from_dict') def test_get_member(self, mock_from_dict): self._test_get_object(self.driver_lib.get_member, constants.MEMBERS, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.L7Policy.from_dict') def test_get_l7policy(self, mock_from_dict): self._test_get_object(self.driver_lib.get_l7policy, constants.L7POLICIES, mock_from_dict) @mock.patch('octavia_lib.api.drivers.data_models.L7Rule.from_dict') def test_get_l7rule(self, mock_from_dict): self._test_get_object(self.driver_lib.get_l7rule, constants.L7RULES, mock_from_dict) octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/test_provider_base.py0000664000175000017500000001342213641342731027014 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from octavia_lib.api.drivers import exceptions from octavia_lib.api.drivers import provider_base as driver_base from octavia_lib.tests.unit import base class TestProviderBase(base.TestCase): """Test base methods. Tests that methods not implemented by the drivers raise NotImplementedError. """ def setUp(self): super(TestProviderBase, self).setUp() self.driver = driver_base.ProviderDriver() def test_create_vip_port(self): self.assertRaises(exceptions.NotImplementedError, self.driver.create_vip_port, False, False, False, None) def test_loadbalancer_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.loadbalancer_create, False) def test_loadbalancer_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.loadbalancer_delete, False) def test_loadbalancer_failover(self): self.assertRaises(exceptions.NotImplementedError, self.driver.loadbalancer_failover, False) def test_loadbalancer_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.loadbalancer_update, False, False) def test_listener_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.listener_create, False) def test_listener_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.listener_delete, False) def test_listener_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.listener_update, False, False) def test_pool_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.pool_create, False) def test_pool_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.pool_delete, False) def test_pool_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.pool_update, False, False) def test_member_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.member_create, False) def test_member_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.member_delete, False) def test_member_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.member_update, False, False) def test_member_batch_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.member_batch_update, False, False) def test_health_monitor_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.health_monitor_create, False) def test_health_monitor_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.health_monitor_delete, False) def test_health_monitor_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.health_monitor_update, False, False) def test_l7policy_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7policy_create, False) def test_l7policy_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7policy_delete, False) def test_l7policy_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7policy_update, False, False) def test_l7rule_create(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7rule_create, False) def test_l7rule_delete(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7rule_delete, False) def test_l7rule_update(self): self.assertRaises(exceptions.NotImplementedError, self.driver.l7rule_update, False, False) def test_get_supported_flavor_metadata(self): self.assertRaises(exceptions.NotImplementedError, self.driver.get_supported_flavor_metadata) def test_validate_flavor(self): self.assertRaises(exceptions.NotImplementedError, self.driver.validate_flavor, False) octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/__init__.py0000664000175000017500000000000013641342731024654 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/api/drivers/test_exceptions.py0000664000175000017500000000746713641342731026365 0ustar zuulzuul00000000000000# Copyright 2018 Rackspace, US Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from octavia_lib.api.drivers import exceptions from octavia_lib.tests.unit import base class TestProviderExceptions(base.TestCase): def setUp(self): super(TestProviderExceptions, self).setUp() self.user_fault_string = 'Bad driver' self.operator_fault_string = 'Fix bad driver.' self.fault_object = 'MCP' self.fault_object_id = '-1' self.fault_record = 'skip' def test_DriverError(self): driver_error = exceptions.DriverError( user_fault_string=self.user_fault_string, operator_fault_string=self.operator_fault_string) self.assertEqual(self.user_fault_string, driver_error.user_fault_string) self.assertEqual(self.operator_fault_string, driver_error.operator_fault_string) self.assertIsInstance(driver_error, Exception) def test_NotImplementedError(self): not_implemented_error = exceptions.NotImplementedError( user_fault_string=self.user_fault_string, operator_fault_string=self.operator_fault_string) self.assertEqual(self.user_fault_string, not_implemented_error.user_fault_string) self.assertEqual(self.operator_fault_string, not_implemented_error.operator_fault_string) self.assertIsInstance(not_implemented_error, Exception) def test_UnsupportedOptionError(self): unsupported_option_error = exceptions.UnsupportedOptionError( user_fault_string=self.user_fault_string, operator_fault_string=self.operator_fault_string) self.assertEqual(self.user_fault_string, unsupported_option_error.user_fault_string) self.assertEqual(self.operator_fault_string, unsupported_option_error.operator_fault_string) self.assertIsInstance(unsupported_option_error, Exception) def test_UpdateStatusError(self): update_status_error = exceptions.UpdateStatusError( fault_string=self.user_fault_string, status_object=self.fault_object, status_object_id=self.fault_object_id, status_record=self.fault_record) self.assertEqual(self.user_fault_string, update_status_error.fault_string) self.assertEqual(self.fault_object, update_status_error.status_object) self.assertEqual(self.fault_object_id, update_status_error.status_object_id) self.assertEqual(self.fault_record, update_status_error.status_record) def test_UpdateStatisticsError(self): update_stats_error = exceptions.UpdateStatisticsError( fault_string=self.user_fault_string, stats_object=self.fault_object, stats_object_id=self.fault_object_id, stats_record=self.fault_record) self.assertEqual(self.user_fault_string, update_stats_error.fault_string) self.assertEqual(self.fault_object, update_stats_error.stats_object) self.assertEqual(self.fault_object_id, update_stats_error.stats_object_id) self.assertEqual(self.fault_record, update_stats_error.stats_record) octavia-lib-2.0.0/octavia_lib/tests/unit/api/__init__.py0000664000175000017500000000000013641342731023176 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/hacking/0000775000175000017500000000000013641343053021730 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/hacking/__init__.py0000664000175000017500000000000013641342731024031 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/unit/hacking/test_checks.py0000664000175000017500000002245713641342731024615 0ustar zuulzuul00000000000000# Copyright 2015 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from oslotest import base from octavia_lib.hacking import checks class HackingTestCase(base.BaseTestCase): """Hacking test class. This class tests the hacking checks in octavia_lib.hacking.checks by passing strings to the check methods like the pep8/flake8 parser would. The parser loops over each line in the file and then passes the parameters to the check method. The parameter names in the check method dictate what type of object is passed to the check method. The parameter types are:: logical_line: A processed line with the following modifications: - Multi-line statements converted to a single line. - Stripped left and right. - Contents of strings replaced with "xxx" of same length. - Comments removed. physical_line: Raw line of text from the input file. lines: a list of the raw lines from the input file tokens: the tokens that contribute to this logical line line_number: line number in the input file total_lines: number of lines in the input file blank_lines: blank lines before this one indent_char: indentation character in this file (" " or "\t") indent_level: indentation (with tabs expanded to multiples of 8) previous_indent_level: indentation on previous line previous_logical: previous logical line filename: Path of the file being run through pep8 When running a test on a check method the return will be False/None if there is no violation in the sample input. If there is an error a tuple is returned with a position in the line, and a message. So to check the result just assertTrue if the check is expected to fail and assertFalse if it should pass. """ def assertLinePasses(self, func, *args): with testtools.ExpectedException(StopIteration): next(func(*args)) def assertLineFails(self, func, *args): self.assertIsInstance(next(func(*args)), tuple) def test_assert_true_instance(self): self.assertEqual(1, len(list(checks.assert_true_instance( "self.assertTrue(isinstance(e, " "exception.BuildAbortException))")))) self.assertEqual(0, len(list(checks.assert_true_instance( "self.assertTrue()")))) def test_assert_equal_or_not_none(self): self.assertEqual(1, len(list(checks.assert_equal_or_not_none( "self.assertEqual(A, None)")))) self.assertEqual(1, len(list(checks.assert_equal_or_not_none( "self.assertEqual(None, A)")))) self.assertEqual(1, len(list(checks.assert_equal_or_not_none( "self.assertNotEqual(A, None)")))) self.assertEqual(1, len(list(checks.assert_equal_or_not_none( "self.assertNotEqual(None, A)")))) self.assertEqual(0, len(list(checks.assert_equal_or_not_none( "self.assertIsNone()")))) self.assertEqual(0, len(list(checks.assert_equal_or_not_none( "self.assertIsNotNone()")))) def test_no_mutable_default_args(self): self.assertEqual(0, len(list(checks.no_mutable_default_args( "def foo (bar):")))) self.assertEqual(1, len(list(checks.no_mutable_default_args( "def foo (bar=[]):")))) self.assertEqual(1, len(list(checks.no_mutable_default_args( "def foo (bar={}):")))) def test_assert_equal_in(self): self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(a in b, True)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual('str' in 'string', True)")))) self.assertEqual(0, len(list(checks.assert_equal_in( "self.assertEqual(any(a==1 for a in b), True)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(True, a in b)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(True, 'str' in 'string')")))) self.assertEqual(0, len(list(checks.assert_equal_in( "self.assertEqual(True, any(a==1 for a in b))")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(a in b, False)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual('str' in 'string', False)")))) self.assertEqual(0, len(list(checks.assert_equal_in( "self.assertEqual(any(a==1 for a in b), False)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(False, a in b)")))) self.assertEqual(1, len(list(checks.assert_equal_in( "self.assertEqual(False, 'str' in 'string')")))) self.assertEqual(0, len(list(checks.assert_equal_in( "self.assertEqual(False, any(a==1 for a in b))")))) def test_assert_equal_true_or_false(self): self.assertEqual(1, len(list(checks.assert_equal_true_or_false( "self.assertEqual(True, A)")))) self.assertEqual(1, len(list(checks.assert_equal_true_or_false( "self.assertEqual(False, A)")))) self.assertEqual(0, len(list(checks.assert_equal_true_or_false( "self.assertTrue()")))) self.assertEqual(0, len(list(checks.assert_equal_true_or_false( "self.assertFalse()")))) def test_no_log_warn(self): self.assertEqual(1, len(list(checks.no_log_warn( "LOG.warn()")))) self.assertEqual(0, len(list(checks.no_log_warn( "LOG.warning()")))) def test_no_log_translations(self): for log in checks._all_log_levels: for hint in checks._all_hints: bad = 'LOG.%s(%s("Bad"))' % (log, hint) self.assertEqual( 1, len(list(checks.no_translate_logs(bad, 'f')))) # Catch abuses when used with a variable and not a literal bad = 'LOG.%s(%s(msg))' % (log, hint) self.assertEqual( 1, len(list(checks.no_translate_logs(bad, 'f')))) # Do not do validations in tests ok = 'LOG.%s(_("OK - unit tests"))' % log self.assertEqual( 0, len(list(checks.no_translate_logs(ok, 'f/tests/f')))) def test_check_localized_exception_messages(self): f = checks.check_raised_localized_exceptions self.assertLineFails(f, " raise KeyError('Error text')", '') self.assertLineFails(f, ' raise KeyError("Error text")', '') self.assertLinePasses(f, ' raise KeyError(_("Error text"))', '') self.assertLinePasses(f, ' raise KeyError(_ERR("Error text"))', '') self.assertLinePasses(f, " raise KeyError(translated_msg)", '') self.assertLinePasses(f, '# raise KeyError("Not translated")', '') self.assertLinePasses(f, 'print("raise KeyError("Not ' 'translated")")', '') def test_check_localized_exception_message_skip_tests(self): f = checks.check_raised_localized_exceptions self.assertLinePasses(f, "raise KeyError('Error text')", 'neutron_lib/tests/unit/mytest.py') def test_check_no_basestring(self): self.assertEqual(1, len(list(checks.check_no_basestring( "isinstance('foo', basestring)")))) self.assertEqual(0, len(list(checks.check_no_basestring( "isinstance('foo', str)")))) def test_check_no_eventlet_imports(self): f = checks.check_no_eventlet_imports self.assertLinePasses(f, 'from not_eventlet import greenthread') self.assertLineFails(f, 'from eventlet import greenthread') self.assertLineFails(f, 'import eventlet') def test_line_continuation_no_backslash(self): results = list(checks.check_line_continuation_no_backslash( '', [(1, 'import', (2, 0), (2, 6), 'import \\\n'), (1, 'os', (3, 4), (3, 6), ' os\n')])) self.assertEqual(1, len(results)) self.assertEqual((2, 7), results[0][0]) def test_check_no_logging_imports(self): f = checks.check_no_logging_imports self.assertLinePasses(f, 'from oslo_log import log') self.assertLineFails(f, 'from logging import log') self.assertLineFails(f, 'import logging') def test_check_no_octavia_namespace_imports(self): f = checks.check_no_octavia_namespace_imports self.assertLinePasses(f, 'from octavia_lib import constants') self.assertLinePasses(f, 'import octavia_lib.constants') self.assertLineFails(f, 'from octavia.common import rpc') self.assertLineFails(f, 'from octavia import context') self.assertLineFails(f, 'import octavia.common.config') octavia-lib-2.0.0/octavia_lib/tests/unit/base.py0000664000175000017500000000163313641342731021615 0ustar zuulzuul00000000000000# -*- coding: utf-8 -*- # Copyright 2010-2011 OpenStack Foundation # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from unittest import mock from oslotest import base class TestCase(base.BaseTestCase): """Test case base class for all unit tests.""" def setUp(self): super(TestCase, self).setUp() self.addCleanup(mock.patch.stopall) octavia-lib-2.0.0/octavia_lib/tests/unit/__init__.py0000664000175000017500000000000013641342731022425 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/tests/__init__.py0000664000175000017500000000000013641342731021446 0ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib/version.py0000664000175000017500000000172013641342731020244 0ustar zuulzuul00000000000000# Copyright 2011-2014 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import pbr.version OCTAVIA_LIB_VENDOR = "OpenStack Foundation" OCTAVIA_LIB_PRODUCT = "OpenStack Octavia library" version_info = pbr.version.VersionInfo('octavia-lib') def vendor_string(): return OCTAVIA_LIB_VENDOR def product_string(): return OCTAVIA_LIB_PRODUCT def version_string_with_package(): return version_info.version_string() octavia-lib-2.0.0/octavia_lib/__init__.py0000664000175000017500000000123313641342731020315 0ustar zuulzuul00000000000000# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import pbr.version __version__ = pbr.version.VersionInfo( 'octavia-lib').version_string() octavia-lib-2.0.0/.pylintrc0000664000175000017500000000501113641342731015573 0ustar zuulzuul00000000000000# The format of this file isn't really documented; just use --generate-rcfile [MASTER] # Add to the black list. It should be a base name, not a # path. You may set this option multiple times. ignore=.git,tests [MESSAGES CONTROL] # NOTE: The options which do not need to be suppressed can be removed. disable= # "F" Fatal errors that prevent further processing # "I" Informational noise locally-disabled, # "E" Error for important programming issues (likely bugs) import-error, not-callable, no-member, # "W" Warnings for stylistic problems or minor programming issues abstract-method, anomalous-backslash-in-string, arguments-differ, attribute-defined-outside-init, bad-builtin, broad-except, fixme, global-statement, no-init, pointless-string-statement, protected-access, redefined-builtin, redefined-outer-name, signature-differs, unidiomatic-typecheck, unused-argument, unused-variable, useless-super-delegation, # "C" Coding convention violations bad-continuation, invalid-name, line-too-long, missing-docstring, # "R" Refactor recommendations duplicate-code, interface-not-implemented, no-self-use, too-few-public-methods, too-many-ancestors, too-many-arguments, too-many-branches, too-many-instance-attributes, too-many-lines, too-many-locals, too-many-public-methods, too-many-return-statements, too-many-statements, multiple-statements, duplicate-except, keyword-arg-before-vararg [BASIC] # Variable names can be 1 to 31 characters long, with lowercase and underscores variable-rgx=[a-z_][a-z0-9_]{0,30}$ # Argument names can be 2 to 31 characters long, with lowercase and underscores argument-rgx=[a-z_][a-z0-9_]{1,30}$ # Method names should be at least 3 characters long # and be lowercased with underscores method-rgx=([a-z_][a-z0-9_]{2,}|setUp|tearDown)$ # Module names matching module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ # Don't require docstrings on tests. no-docstring-rgx=((__.*__)|([tT]est.*)|setUp|tearDown)$ [FORMAT] # Maximum number of characters on a single line. max-line-length=79 [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= [CLASSES] [IMPORTS] # Deprecated modules which should not be used, separated by a comma deprecated-modules= [TYPECHECK] # List of module names for which member attributes should not be checked ignored-modules=six.moves,_MovedItems [REPORTS] # Tells whether to display a full report or only the messages reports=no octavia-lib-2.0.0/.stestr.conf0000664000175000017500000000011113641342731016173 0ustar zuulzuul00000000000000[DEFAULT] test_path=${OS_TEST_PATH:-./octavia_lib/tests/unit} top_dir=./ octavia-lib-2.0.0/PKG-INFO0000664000175000017500000000430413641343053015025 0ustar zuulzuul00000000000000Metadata-Version: 1.2 Name: octavia-lib Version: 2.0.0 Summary: A library to support Octavia provider drivers. Home-page: https://docs.openstack.org/octavia-lib/latest/ Author: OpenStack Author-email: openstack-discuss@lists.openstack.org License: Apache License, Version 2.0 Description: ======================== Team and repository tags ======================== .. image:: https://governance.openstack.org/tc/badges/octavia-lib.svg :target: https://governance.openstack.org/tc/reference/tags/index.html .. Change things from this point on =========== octavia-lib =========== .. image:: https://img.shields.io/pypi/v/octavia-lib.svg :target: https://pypi.org/project/octavia-lib/ :alt: Latest Version A library to support Octavia provider drivers. This python module provides a python library for Octavia provider driver developers. See the provider driver development guide for more information: https://docs.openstack.org/octavia/latest/contributor/guides/providers.html Octavia-lib is distributed under the terms of the Apache License, Version 2.0. The full terms and conditions of this license are detailed in the LICENSE file. * Free software: Apache license * Documentation: https://docs.openstack.org/octavia-lib/latest * Source: https://opendev.org/openstack/octavia-lib * Bugs: https://storyboard.openstack.org/#!/project/openstack/octavia-lib Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: OpenStack Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Requires-Python: >=3.6 octavia-lib-2.0.0/requirements.txt0000664000175000017500000000052713641342731017221 0ustar zuulzuul00000000000000# The order of packages is significant, because pip processes them in the order # of appearance. Changing the order has an impact on the overall integration # process, which may cause wedges in the gate later. oslo.i18n>=3.15.3 # Apache-2.0 oslo.serialization>=2.28.1 # Apache-2.0 pbr!=2.1.0,>=2.0.0 # Apache-2.0 tenacity>=5.0.2 # Apache-2.0 octavia-lib-2.0.0/lower-constraints.txt0000664000175000017500000000043013641342731020164 0ustar zuulzuul00000000000000bandit==1.4.0 coverage==4.0 doc8==0.6.0 hacking==0.12.0 oslo.i18n==3.15.3 oslo.serialization==2.28.1 oslo.utils==3.33.0 oslotest==3.2.0 pbr==2.0.0 pylint==1.9.2 python-subunit==1.0.0 six==1.10.0 sphinxcontrib-svg2pdfconverter==0.1.0 stestr==2.0.0 tenacity==5.0.2 testtools==2.2.0 octavia-lib-2.0.0/LICENSE0000664000175000017500000002363713641342731014751 0ustar zuulzuul00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. octavia-lib-2.0.0/HACKING.rst0000664000175000017500000000736313641342731015540 0ustar zuulzuul00000000000000Octavia-lib Style Commandments ============================== This project was ultimately spawned from work done on the Neutron project. As such, we tend to follow Neutron conventions regarding coding style. - We follow the OpenStack Style Commandments: https://docs.openstack.org/hacking/latest -- Read the OpenStack Octavia style guide: - https://docs.openstack.org/octavia/latest/contributor/HACKING.html Octavia Specific Commandments ----------------------------- - [O316] Change assertTrue(isinstance(A, B)) by optimal assert like assertIsInstance(A, B). - [O318] Change assert(Not)Equal(A, None) or assert(Not)Equal(None, A) by optimal assert like assertIs(Not)None(A). - [O319] Validate that debug level logs are not translated. - [O321] Validate that jsonutils module is used instead of json - [O322] Don't use author tags - [O323] Change assertEqual(True, A) or assertEqual(False, A) to the more specific assertTrue(A) or assertFalse(A) - [O324] Method's default argument shouldn't be mutable - [O338] Change assertEqual(A in B, True), assertEqual(True, A in B), assertEqual(A in B, False) or assertEqual(False, A in B) to the more specific assertIn/NotIn(A, B) - [O339] LOG.warn() is not allowed. Use LOG.warning() - [O340] Don't use xrange() - [O341] Don't translate logs. - [0342] Exception messages should be translated - [O343] Python 3: do not use basestring. - [O344] Python 3: do not use dict.iteritems. - [O345] Usage of Python eventlet module not allowed - [O346] Don't use backslashes for line continuation. - [O501] Direct octavia imports not allowed. Creating Unit Tests ------------------- For every new feature, unit tests should be created that both test and (implicitly) document the usage of said feature. If submitting a patch for a bug that had no unit test, a new passing unit test should be added. If a submitted bug fix does have a unit test, be sure to add a new one that fails without the patch and passes with the patch. Everything is python -------------------- Although OpenStack apparently allows either python or C++ code, at this time we don't envision needing anything other than python (and standard, supported open source modules) for anything we intend to do in Octavia-lib. Idempotency ----------- With as much as is going on inside Octavia-lib, its likely that certain messages and commands will be repeatedly processed. It's important that this doesn't break the functionality of the load balancing service. Therefore, as much as possible, algorithms and interfaces should be made as idempotent as possible. Avoid premature optimization ---------------------------- Understand that being "high performance" is often not the same thing as being "scalable." First get the thing to work in an intelligent way. Only worry about making it fast if speed becomes an issue. Don't repeat yourself --------------------- Octavia-lib strives to follow DRY principles. There should be one source of truth, and repetition of code should be avoided. Security is not an afterthought ------------------------------- The load balancer is often both the most visible public interface to a given user application, but load balancers themselves often have direct access to sensitive components and data within the application environment. Security bugs will happen, but in general we should not approve designs which have known significant security problems, or which could be made more secure by better design. Octavia-lib should follow industry standards -------------------------------------------- By "industry standards" we either mean RFCs or well-established best practices. We are generally not interested in defining new standards if a prior open standard already exists. We should also avoid doing things which directly or indirectly contradict established standards. octavia-lib-2.0.0/tox.ini0000664000175000017500000000702313641342731015246 0ustar zuulzuul00000000000000[tox] minversion = 2.5.0 envlist = docs,py37,pep8 skipsdist = True ignore_basepython_conflict = True [testenv] basepython = python3 usedevelop = True install_command = pip install {opts} {packages} setenv = VIRTUAL_ENV={envdir} PYTHONWARNINGS=default::DeprecationWarning OS_LOG_CAPTURE={env:OS_LOG_CAPTURE:true} OS_STDOUT_CAPTURE={env:OS_STDOUT_CAPTURE:true} OS_STDERR_CAPTURE={env:OS_STDERR_CAPTURE:true} OS_TEST_TIMEOUT=60 deps = -c{env:UPPER_CONSTRAINTS_FILE:https://releases.openstack.org/constraints/upper/master} -r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt commands = stestr run {posargs} [testenv:pep8] commands = flake8 doc8 --ignore-path doc/source/contributor/modules \ doc/source octavia_lib HACKING.rst README.rst # Run security linter bandit -r octavia_lib -ll -ii -x octavia_lib/tests {toxinidir}/tools/coding-checks.sh --pylint '{posargs}' [testenv:venv] commands = {posargs} [testenv:cover] setenv = VIRTUAL_ENV={envdir} PYTHON=coverage run --source octavia_lib --parallel-mode commands = stestr run {posargs} coverage combine coverage html -d cover coverage xml -o cover/coverage.xml coverage report --fail-under=95 --skip-covered [testenv:docs] deps = -r{toxinidir}/doc/requirements.txt whitelist_externals = rm commands = rm -rf doc/build doc/source/reference/modules sphinx-build -W -b html doc/source doc/build/html [testenv:pdf-docs] deps = {[testenv:docs]deps} whitelist_externals = make rm commands = rm -rf doc/build/pdf sphinx-build -W -b latex doc/source doc/build/pdf make -C doc/build/pdf [testenv:releasenotes] deps = {[testenv:docs]deps} commands = sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html [testenv:debug] commands = oslo_debug_helper {posargs} [flake8] # W504 line break after binary operator ignore = W504 show-source = True builtins = _ exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build # [H106]: Don't put vim configuration in source files # [H203]: Use assertIs(Not)None to check for None # [H204]: Use assert(Not)Equal to check for equality # [H205]: Use assert(Greater|Less)(Equal) for comparison # [H904]: Delay string interpolations at logging calls enable-extensions=H106,H203,H204,H205,H904 [hacking] import_exceptions = octavia_lib.i18n [flake8:local-plugins] extension = O316 = checks:assert_true_instance O318 = checks:assert_equal_or_not_none O323 = checks:assert_equal_true_or_false O324 = checks:no_mutable_default_args O338 = checks:assert_equal_in O339 = checks:no_log_warn O341 = checks:no_translate_logs O342 = checks:check_raised_localized_exceptions O343 = checks:check_no_basestring O345 = checks:check_no_eventlet_imports O346 = checks:check_line_continuation_no_backslash O348 = checks:check_no_logging_imports O501 = checks:check_no_octavia_namespace_imports paths = ./octavia_lib/hacking [doc8] max-line-length = 79 [testenv:lower-constraints] deps = -c{toxinidir}/lower-constraints.txt -r{toxinidir}/test-requirements.txt -r{toxinidir}/requirements.txt whitelist_externals = sh commands = sh -c 'OS_TEST_PATH={toxinidir}/octavia_lib/tests/unit stestr run {posargs}' [testenv:requirements] deps = -egit+https://opendev.org/openstack/requirements#egg=openstack-requirements whitelist_externals = sh commands = sh -c '{envdir}/src/openstack-requirements/playbooks/files/project-requirements-change.py --req {envdir}/src/openstack-requirements --local {toxinidir} master' octavia-lib-2.0.0/tools/0000775000175000017500000000000013641343053015067 5ustar zuulzuul00000000000000octavia-lib-2.0.0/tools/coding-checks.sh0000775000175000017500000000311713641342731020133 0ustar zuulzuul00000000000000#!/bin/sh # This script is copied from neutron and adapted for octavia-lib. set -eu usage () { echo "Usage: $0 [OPTION]..." echo "Run octavia-lib's coding check(s)" echo "" echo " -Y, --pylint [] Run pylint check on the entire octavia-lib module or just files changed in basecommit (e.g. HEAD~1)" echo " -h, --help Print this usage message" echo exit 0 } join_args() { if [ -z "$scriptargs" ]; then scriptargs="$opt" else scriptargs="$scriptargs $opt" fi } process_options () { i=1 while [ $i -le $# ]; do eval opt=\$$i case $opt in -h|--help) usage;; -Y|--pylint) pylint=1;; *) join_args;; esac i=$((i+1)) done } run_pylint () { local target="${scriptargs:-all}" if [ "$target" = "all" ]; then files="octavia_lib" else case "$target" in *HEAD~[0-9]*) files=$(git diff --diff-filter=AM --name-only $target -- "*.py");; *) echo "$target is an unrecognized basecommit"; exit 1;; esac fi echo "Running pylint..." echo "You can speed this up by running it on 'HEAD~[0-9]' (e.g. HEAD~1, this change only)..." if [ -n "${files}" ]; then pylint --max-nested-blocks 7 --extension-pkg-whitelist netifaces --rcfile=.pylintrc --output-format=colorized ${files} else echo "No python changes in this commit, pylint check not required." exit 0 fi } scriptargs= pylint=1 process_options $@ if [ $pylint -eq 1 ]; then run_pylint exit 0 fi octavia-lib-2.0.0/babel.cfg0000664000175000017500000000002113641342731015450 0ustar zuulzuul00000000000000[python: **.py] octavia-lib-2.0.0/zuul.d/0000775000175000017500000000000013641343053015150 5ustar zuulzuul00000000000000octavia-lib-2.0.0/zuul.d/projects.yaml0000664000175000017500000000053513641342731017672 0ustar zuulzuul00000000000000- project: templates: - check-requirements - openstack-cover-jobs - openstack-lower-constraints-jobs - openstack-python3-ussuri-jobs - publish-openstack-docs-pti - release-notes-jobs-python3 - octavia-tox-tips check: jobs: - octavia-tox-functional-py37-tips: voting: false octavia-lib-2.0.0/README.rst0000664000175000017500000000210313641342731015414 0ustar zuulzuul00000000000000======================== Team and repository tags ======================== .. image:: https://governance.openstack.org/tc/badges/octavia-lib.svg :target: https://governance.openstack.org/tc/reference/tags/index.html .. Change things from this point on =========== octavia-lib =========== .. image:: https://img.shields.io/pypi/v/octavia-lib.svg :target: https://pypi.org/project/octavia-lib/ :alt: Latest Version A library to support Octavia provider drivers. This python module provides a python library for Octavia provider driver developers. See the provider driver development guide for more information: https://docs.openstack.org/octavia/latest/contributor/guides/providers.html Octavia-lib is distributed under the terms of the Apache License, Version 2.0. The full terms and conditions of this license are detailed in the LICENSE file. * Free software: Apache license * Documentation: https://docs.openstack.org/octavia-lib/latest * Source: https://opendev.org/openstack/octavia-lib * Bugs: https://storyboard.openstack.org/#!/project/openstack/octavia-lib octavia-lib-2.0.0/releasenotes/0000775000175000017500000000000013641343053016420 5ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/0000775000175000017500000000000013641343053017720 5ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/train.rst0000664000175000017500000000022113641342731021564 0ustar zuulzuul00000000000000=================================== Train Series Release Notes =================================== .. release-notes:: :branch: stable/train octavia-lib-2.0.0/releasenotes/source/index.rst0000664000175000017500000000026413641342731021565 0ustar zuulzuul00000000000000============================================ octavia_lib Release Notes ============================================ .. toctree:: :maxdepth: 1 unreleased train stein octavia-lib-2.0.0/releasenotes/source/_static/0000775000175000017500000000000013641343053021346 5ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/_static/.placeholder0000664000175000017500000000000013641342731023621 0ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/_templates/0000775000175000017500000000000013641343053022055 5ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/_templates/.placeholder0000664000175000017500000000000013641342731024330 0ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/source/unreleased.rst0000664000175000017500000000016013641342731022600 0ustar zuulzuul00000000000000============================== Current Series Release Notes ============================== .. release-notes:: octavia-lib-2.0.0/releasenotes/source/conf.py0000664000175000017500000002047113641342731021225 0ustar zuulzuul00000000000000# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'openstackdocstheme', 'reno.sphinxext', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. copyright = u'2017, OpenStack Developers' # openstackdocstheme options repository_name = 'openstack/octavia-lib' use_storyboard = True # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'openstackdocs' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'octavia_libReleaseNotesdoc' # -- Options for LaTeX output --------------------------------------------- # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, # documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'octavia_libReleaseNotes.tex', u'octavia_lib Release Notes Documentation', u'OpenStack Foundation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'octavia_librereleasenotes', u'octavia_lib Release Notes Documentation', [u'OpenStack Foundation'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'octavia_lib ReleaseNotes', u'octavia_lib Release Notes Documentation', u'OpenStack Foundation', 'octavia_libReleaseNotes', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # -- Options for Internationalization output ------------------------------ locale_dirs = ['locale/'] octavia-lib-2.0.0/releasenotes/source/stein.rst0000664000175000017500000000022113641342731021571 0ustar zuulzuul00000000000000=================================== Stein Series Release Notes =================================== .. release-notes:: :branch: stable/stein octavia-lib-2.0.0/releasenotes/notes/0000775000175000017500000000000013641343053017550 5ustar zuulzuul00000000000000octavia-lib-2.0.0/releasenotes/notes/add-additional-vip-support-becdb29c5187b514.yaml0000664000175000017500000000021413641342731030073 0ustar zuulzuul00000000000000--- features: - | Add the ability to pass multiple VIP objects to providers. This allows for multiple subnets/IPs on a single LB. octavia-lib-2.0.0/releasenotes/notes/Add-get-methods-to-driver-lib-dae3c217e7ac9e82.yaml0000664000175000017500000000064613641342731030406 0ustar zuulzuul00000000000000--- features: - | The driver-lib now provides "get" methods for drivers to be able to query for objects by id. For example, get_loadbalancer(loadbalancer_id). fixes: - Improved the driver_lib connecting to the driver-agent sockets. - Fixed a bug where the data model to_dict() may not recurse properly. - | Message receiving for the driver_lib will timeout after no response from the driver-agent. ././@LongLink0000000000000000000000000000015100000000000011212 Lustar 00000000000000octavia-lib-2.0.0/releasenotes/notes/add-tls-protocols-for-listener-and-pool-model-e9083b85afc62ef0.yamloctavia-lib-2.0.0/releasenotes/notes/add-tls-protocols-for-listener-and-pool-model-e9083b85afc62ef0.0000664000175000017500000000044313641342731032644 0ustar zuulzuul00000000000000--- features: - | Added a parameter called ``tls_versions`` for passing allowed TLS versions to pools and listeners. The available TLS versions have corresponding constants. The constants are prefixed with ``TLS_VERSION`` (except SSLv3 which is ``SSL_VERSION_3``). ././@LongLink0000000000000000000000000000015300000000000011214 Lustar 00000000000000octavia-lib-2.0.0/releasenotes/notes/adding-cipher-list-support-for-provider-drivers-6a4dbec2d0254aae.yamloctavia-lib-2.0.0/releasenotes/notes/adding-cipher-list-support-for-provider-drivers-6a4dbec2d0254aa0000664000175000017500000000020413641342731033213 0ustar zuulzuul00000000000000--- features: - | Added a parameter called ``tls_ciphers`` for passing OpenSSL cipher strings in pools and listeners. octavia-lib-2.0.0/releasenotes/notes/Initial-cookiecutter-commit-41d89a60d6328b51.yaml0000664000175000017500000000012313641342731030064 0ustar zuulzuul00000000000000--- other: - | This is the initial cookiecutter commit for this new library. octavia-lib-2.0.0/releasenotes/notes/add-constants-66f52c4d4cfd0215.yaml0000664000175000017500000000012213641342731025405 0ustar zuulzuul00000000000000--- fixes: - | Added some missing provider driver API field name constants. octavia-lib-2.0.0/releasenotes/notes/add-az-to-loadbalancer-1e87b46ba29101d3.yaml0000664000175000017500000000015213641342731026746 0ustar zuulzuul00000000000000--- other: - | Load balancer objects now have an ``availability_zone`` attribute. This can be None. octavia-lib-2.0.0/releasenotes/notes/drop-python-2-7-f17da6245b0ebc13.yaml0000664000175000017500000000021213641342731025500 0ustar zuulzuul00000000000000--- upgrade: - | Python 2.7 support has been dropped. The minimum version of Python now supported by Octavia-lib is Python 3.6. octavia-lib-2.0.0/releasenotes/notes/add-lb-algorithm-source-ip-port-5cc83a9e3fcf4763.yaml0000664000175000017500000000015513641342731030744 0ustar zuulzuul00000000000000--- features: - | Added SOURCE_IP_PORT algorithm. Currently supported only by OVN provider driver. octavia-lib-2.0.0/releasenotes/notes/add-availability-zone-validation-ed853a3ee89570be.yaml0000664000175000017500000000014413641342731031246 0ustar zuulzuul00000000000000--- features: - | Add driver interface for validating availability zone metadata and support. octavia-lib-2.0.0/releasenotes/notes/add-listener-allowed-cidrs-ef2cd3afbc3a1ebe.yaml0000664000175000017500000000010613641342731030376 0ustar zuulzuul00000000000000--- features: - Added 'allowed_cidrs' field to Listener data model. octavia-lib-2.0.0/setup.py0000664000175000017500000000200613641342731015441 0ustar zuulzuul00000000000000# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT import setuptools # In python < 2.7.4, a lazy loading of package `pbr` will break # setuptools if some other modules registered functions in `atexit`. # solution from: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing # noqa except ImportError: pass setuptools.setup( setup_requires=['pbr>=2.0.0'], pbr=True) octavia-lib-2.0.0/doc/0000775000175000017500000000000013641343053014474 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/requirements.txt0000664000175000017500000000035613641342731017766 0ustar zuulzuul00000000000000sphinx!=1.6.6,!=1.6.7,!=2.1.0,>=1.6.2;python_version>='3.4' # BSD openstackdocstheme>=1.20.0 # Apache-2.0 sphinxcontrib-apidoc>=0.2.1 # BSD # releasenotes reno>=2.5.0 # Apache-2.0 # PDF Docs sphinxcontrib-svg2pdfconverter>=0.1.0 # BSD octavia-lib-2.0.0/doc/source/0000775000175000017500000000000013641343053015774 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/configuration/0000775000175000017500000000000013641343053020643 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/configuration/index.rst0000664000175000017500000000025713641342731022512 0ustar zuulzuul00000000000000============= Configuration ============= The octavia-lib library does not currently use any `oslo configuration `_ settings. octavia-lib-2.0.0/doc/source/index.rst0000664000175000017500000000275413641342731017647 0ustar zuulzuul00000000000000.. octavia-lib documentation master file, created by sphinx-quickstart on Tue Jul 9 22:26:36 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to the documentation of Octavia lib =========================================== .. only:: html .. include:: ../../README.rst .. only:: latex .. image:: https://governance.openstack.org/tc/badges/octavia-lib.svg A library to support Octavia provider drivers. This python module provides a python library for Octavia provider driver developers. See the provider driver development guide for more information: https://docs.openstack.org/octavia/latest/contributor/guides/providers.html Octavia-lib is distributed under the terms of the Apache License, Version 2.0. The full terms and conditions of this license are detailed in the LICENSE file. * Free software: Apache license * Documentation: https://docs.openstack.org/octavia-lib/latest * Source: https://opendev.org/openstack/octavia-lib * Bugs: https://storyboard.openstack.org/#!/project/openstack/octavia-lib .. only:: html octavia-lib Documentation: -------------------------- .. toctree:: :maxdepth: 1 install/index library/index contributor/index configuration/index cli/index user/index admin/index reference/index .. only:: html Indices and tables ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` octavia-lib-2.0.0/doc/source/cli/0000775000175000017500000000000013641343053016543 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/cli/index.rst0000664000175000017500000000040413641342731020404 0ustar zuulzuul00000000000000================================ Command line interface reference ================================ The octavia-lib library does not provide a CLI. See the python-octaviaclient for the Octavia CLI: https://docs.openstack.org/python-octaviaclient/latest/ octavia-lib-2.0.0/doc/source/admin/0000775000175000017500000000000013641343053017064 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/admin/index.rst0000664000175000017500000000054613641342731020734 0ustar zuulzuul00000000000000==================== Administrators guide ==================== The octavia-lib is a library supporting Octavia provider drivers. There are no administrator tasks or settings for octavia-lib. Information on administrating Octavia deployments is available in the `Octavia Administration Guide `_. octavia-lib-2.0.0/doc/source/library/0000775000175000017500000000000013641343053017440 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/library/index.rst0000664000175000017500000000047113641342731021305 0ustar zuulzuul00000000000000===== Usage ===== Instructions for using the library are provided in the `Provider Driver Development Guide `_. .. only:: html Indices and Search ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` octavia-lib-2.0.0/doc/source/install/0000775000175000017500000000000013641343053017442 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/install/index.rst0000664000175000017500000000031213641342731021301 0ustar zuulzuul00000000000000============ Installation ============ At the command line:: $ pip install octavia-lib Or, if you have virtualenvwrapper installed:: $ mkvirtualenv octavia-lib $ pip install octavia-lib octavia-lib-2.0.0/doc/source/reference/0000775000175000017500000000000013641343053017732 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/reference/index.rst0000664000175000017500000000121013641342731021567 0ustar zuulzuul00000000000000========== References ========== .. toctree:: :glob: :maxdepth: 1 Octavia Introduction Octavia Glossary Octavia Project Documentation Octavia API Reference .. only: html Indices and Search ------------------ * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. only:: latex Module Reference ---------------- .. toctree:: :hidden: modules/modules octavia-lib-2.0.0/doc/source/user/0000775000175000017500000000000013641343053016752 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/user/index.rst0000664000175000017500000000042313641342731020614 0ustar zuulzuul00000000000000=========== Users guide =========== The octavia-lib is a library supporting Octavia provider drivers. Instructions for using the library are provided in the `Provider Driver Development Guide `_. octavia-lib-2.0.0/doc/source/conf.py0000775000175000017500000001076613641342731017312 0ustar zuulzuul00000000000000# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import datetime import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'openstackdocstheme', 'sphinxcontrib.apidoc', 'sphinxcontrib.rsvgconverter' ] # autodoc generation is a bit aggressive and a nuisance when doing heavy # text edit cycles. # execute "export SPHINX_DEBUG=1" in your terminal to disable # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. copyright = u'2018-2019, OpenStack Octavia Team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # Version info from octavia_lib.version import version_info as octavia_lib_version release = octavia_lib_version.release_string() # The short X.Y version. version = octavia_lib_version.version_string() # openstackdocstheme options repository_name = 'openstack/octavia-lib' use_storyboard = True apidoc_output_dir = 'reference/modules' apidoc_module_dir = '../../octavia_lib' apidoc_excluded_paths = [ 'tests', 'db/migration', 'hacking', 'i18n.py' ] # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme_path = ["."] # html_theme = '_theme' # html_static_path = ['static'] html_theme = 'openstackdocs' # Output file base name for HTML help builder. htmlhelp_basename = 'octavia-libdoc' # -- Options for LaTeX output ------------------------------------------------- # Fix Unicode character for sphinx_feature_classification # Sphinx default latex engine (pdflatex) doesn't know much unicode latex_preamble = r""" \usepackage{newunicodechar} \newunicodechar{✖}{\sffamily X} \setcounter{tocdepth}{2} \authoraddress{\textcopyright %s OpenStack Foundation} """ % datetime.datetime.now().year latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # openany: Skip blank pages in generated PDFs 'extraclassoptions': 'openany,oneside', 'makeindex': '', 'printindex': '', 'preamble': latex_preamble } # Disable usage of xindy https://bugzilla.redhat.com/show_bug.cgi?id=1643664 # Some distros are missing xindy latex_use_xindy = False # Fix missing apostrophe smartquotes_excludes = {'builders': ['latex']} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [( 'index', 'doc-octavia-lib.tex', u'Octavia Library Documentation', u'OpenStack Octavia Team', 'manual' )] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. latex_domain_indices = False octavia-lib-2.0.0/doc/source/contributor/0000775000175000017500000000000013641343053020346 5ustar zuulzuul00000000000000octavia-lib-2.0.0/doc/source/contributor/index.rst0000664000175000017500000000062213641342731022211 0ustar zuulzuul00000000000000========================= Contributor Documentation ========================= Contributor Guidelines ---------------------- .. toctree:: :glob: :maxdepth: 1 Octavia Constitution Octavia Style Commandments .. include:: ../../../CONTRIBUTING.rst octavia-lib-2.0.0/CONTRIBUTING.rst0000664000175000017500000000123613641342731016374 0ustar zuulzuul00000000000000If you would like to contribute to the development of OpenStack, you must follow the steps in this page: http://docs.openstack.org/infra/manual/developers.html If you already have a good understanding of how the system works and your OpenStack accounts are set up, you can skip to the development workflow section of this documentation to learn how changes to OpenStack should be submitted for review via the Gerrit tool: http://docs.openstack.org/infra/manual/developers.html#development-workflow Pull requests submitted through GitHub will be ignored. Bugs should be filed on Storyboard https://storyboard.openstack.org/#!/project/openstack/octavia-lib octavia-lib-2.0.0/octavia_lib.egg-info/0000775000175000017500000000000013641343053017675 5ustar zuulzuul00000000000000octavia-lib-2.0.0/octavia_lib.egg-info/pbr.json0000664000175000017500000000005613641343052021353 0ustar zuulzuul00000000000000{"git_version": "99118d2", "is_release": true}octavia-lib-2.0.0/octavia_lib.egg-info/dependency_links.txt0000664000175000017500000000000113641343052023742 0ustar zuulzuul00000000000000 octavia-lib-2.0.0/octavia_lib.egg-info/SOURCES.txt0000664000175000017500000000520413641343053021562 0ustar zuulzuul00000000000000.coveragerc .pylintrc .stestr.conf AUTHORS CONTRIBUTING.rst ChangeLog HACKING.rst LICENSE README.rst babel.cfg lower-constraints.txt requirements.txt setup.cfg setup.py test-requirements.txt tox.ini doc/requirements.txt doc/source/conf.py doc/source/index.rst doc/source/admin/index.rst doc/source/cli/index.rst doc/source/configuration/index.rst doc/source/contributor/index.rst doc/source/install/index.rst doc/source/library/index.rst doc/source/reference/index.rst doc/source/user/index.rst octavia_lib/__init__.py octavia_lib/i18n.py octavia_lib/version.py octavia_lib.egg-info/PKG-INFO octavia_lib.egg-info/SOURCES.txt octavia_lib.egg-info/dependency_links.txt octavia_lib.egg-info/not-zip-safe octavia_lib.egg-info/pbr.json octavia_lib.egg-info/requires.txt octavia_lib.egg-info/top_level.txt octavia_lib/api/__init__.py octavia_lib/api/drivers/__init__.py octavia_lib/api/drivers/data_models.py octavia_lib/api/drivers/driver_lib.py octavia_lib/api/drivers/exceptions.py octavia_lib/api/drivers/provider_base.py octavia_lib/common/__init__.py octavia_lib/common/constants.py octavia_lib/hacking/__init__.py octavia_lib/hacking/checks.py octavia_lib/tests/__init__.py octavia_lib/tests/unit/__init__.py octavia_lib/tests/unit/base.py octavia_lib/tests/unit/api/__init__.py octavia_lib/tests/unit/api/drivers/__init__.py octavia_lib/tests/unit/api/drivers/test_data_models.py octavia_lib/tests/unit/api/drivers/test_driver_lib.py octavia_lib/tests/unit/api/drivers/test_exceptions.py octavia_lib/tests/unit/api/drivers/test_provider_base.py octavia_lib/tests/unit/hacking/__init__.py octavia_lib/tests/unit/hacking/test_checks.py releasenotes/notes/Add-get-methods-to-driver-lib-dae3c217e7ac9e82.yaml releasenotes/notes/Initial-cookiecutter-commit-41d89a60d6328b51.yaml releasenotes/notes/add-additional-vip-support-becdb29c5187b514.yaml releasenotes/notes/add-availability-zone-validation-ed853a3ee89570be.yaml releasenotes/notes/add-az-to-loadbalancer-1e87b46ba29101d3.yaml releasenotes/notes/add-constants-66f52c4d4cfd0215.yaml releasenotes/notes/add-lb-algorithm-source-ip-port-5cc83a9e3fcf4763.yaml releasenotes/notes/add-listener-allowed-cidrs-ef2cd3afbc3a1ebe.yaml releasenotes/notes/add-tls-protocols-for-listener-and-pool-model-e9083b85afc62ef0.yaml releasenotes/notes/adding-cipher-list-support-for-provider-drivers-6a4dbec2d0254aae.yaml releasenotes/notes/drop-python-2-7-f17da6245b0ebc13.yaml releasenotes/source/conf.py releasenotes/source/index.rst releasenotes/source/stein.rst releasenotes/source/train.rst releasenotes/source/unreleased.rst releasenotes/source/_static/.placeholder releasenotes/source/_templates/.placeholder tools/coding-checks.sh zuul.d/projects.yamloctavia-lib-2.0.0/octavia_lib.egg-info/not-zip-safe0000664000175000017500000000000113641343052022122 0ustar zuulzuul00000000000000 octavia-lib-2.0.0/octavia_lib.egg-info/PKG-INFO0000664000175000017500000000430413641343052020772 0ustar zuulzuul00000000000000Metadata-Version: 1.2 Name: octavia-lib Version: 2.0.0 Summary: A library to support Octavia provider drivers. Home-page: https://docs.openstack.org/octavia-lib/latest/ Author: OpenStack Author-email: openstack-discuss@lists.openstack.org License: Apache License, Version 2.0 Description: ======================== Team and repository tags ======================== .. image:: https://governance.openstack.org/tc/badges/octavia-lib.svg :target: https://governance.openstack.org/tc/reference/tags/index.html .. Change things from this point on =========== octavia-lib =========== .. image:: https://img.shields.io/pypi/v/octavia-lib.svg :target: https://pypi.org/project/octavia-lib/ :alt: Latest Version A library to support Octavia provider drivers. This python module provides a python library for Octavia provider driver developers. See the provider driver development guide for more information: https://docs.openstack.org/octavia/latest/contributor/guides/providers.html Octavia-lib is distributed under the terms of the Apache License, Version 2.0. The full terms and conditions of this license are detailed in the LICENSE file. * Free software: Apache license * Documentation: https://docs.openstack.org/octavia-lib/latest * Source: https://opendev.org/openstack/octavia-lib * Bugs: https://storyboard.openstack.org/#!/project/openstack/octavia-lib Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: OpenStack Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: POSIX :: Linux Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Requires-Python: >=3.6 octavia-lib-2.0.0/octavia_lib.egg-info/top_level.txt0000664000175000017500000000001413641343052022421 0ustar zuulzuul00000000000000octavia_lib octavia-lib-2.0.0/octavia_lib.egg-info/requires.txt0000664000175000017500000000012013641343052022265 0ustar zuulzuul00000000000000oslo.i18n>=3.15.3 oslo.serialization>=2.28.1 pbr!=2.1.0,>=2.0.0 tenacity>=5.0.2 octavia-lib-2.0.0/setup.cfg0000664000175000017500000000220513641343053015547 0ustar zuulzuul00000000000000[metadata] name = octavia-lib summary = A library to support Octavia provider drivers. description-file = README.rst author = OpenStack author-email = openstack-discuss@lists.openstack.org home-page = https://docs.openstack.org/octavia-lib/latest/ license = Apache License, Version 2.0 python-requires = >=3.6 classifier = Development Status :: 5 - Production/Stable Environment :: OpenStack Intended Audience :: Developers Intended Audience :: Information Technology Intended Audience :: System Administrators License :: OSI Approved :: Apache Software License Operating System :: POSIX :: Linux Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 [files] packages = octavia_lib [compile_catalog] directory = octavia_lib/locale domain = octavia_lib [update_catalog] domain = octavia_lib output_dir = octavia_lib/locale input_file = octavia_lib/locale/octavia_lib.pot [extract_messages] keywords = _ gettext ngettext l_ lazy_gettext mapping_file = babel.cfg output_file = octavia_lib/locale/octavia_lib.pot [egg_info] tag_build = tag_date = 0