def _run(self, application, socket): """Start a WSGI service in a new green thread.""" logger = logging.getLogger('eventlet.wsgi.server') eventlet.wsgi.server(socket, application, custom_pool=self.pool, protocol=UnixDomainHttpProtocol, log=logging.WritableLogger(logger))
def __call__(self, func): if self.logger is None: LOG = logging.getLogger(func.__module__) self.logger = LOG.exception def call(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: with excutils.save_and_reraise_exception(): self.logger(e) return call
def notify(_context, message): """Notifies the recipient of the desired event given the model. Log notifications using openstack's default logging system. """ priority = message.get('priority', CONF.default_notification_level) priority = priority.lower() logger = logging.getLogger( 'neutron.openstack.common.notification.%s' % message['event_type']) getattr(logger, priority)(jsonutils.dumps(message))
def log(method): """Decorator helping to log method calls.""" LOG = logging.getLogger(method.__module__) @functools.wraps(method) def wrapper(*args, **kwargs): instance = args[0] data = {"class_name": "%s.%s" % (instance.__class__.__module__, instance.__class__.__name__), "method_name": method.__name__, "args": args[1:], "kwargs": kwargs} LOG.debug('%(class_name)s method %(method_name)s' ' called with arguments %(args)s %(kwargs)s', data) return method(*args, **kwargs) return wrapper
def test_not_called_with_low_log_level(self): LOG = logging.getLogger(__name__) # make sure we return logging to previous level current_log_level = LOG.logger.getEffectiveLevel() self.addCleanup(LOG.logger.setLevel, current_log_level) my_func = mock.MagicMock() delayed = utils.DelayedStringRenderer(my_func) # set to warning so we shouldn't be logging debug messages LOG.logger.setLevel(logging.logging.WARNING) LOG.debug("Hello %s", delayed) self.assertFalse(my_func.called) # but it should be called with the debug level LOG.logger.setLevel(logging.logging.DEBUG) LOG.debug("Hello %s", delayed) self.assertTrue(my_func.called)
# # 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 json from neutron.common import exceptions from neutron.openstack.common import log as logging from oslo.config import cfg LOG = logging.getLogger("neutron.quark") CONF = cfg.CONF quark_opts = [ cfg.StrOpt('default_net_strategy', default='{}', help=_("Default network assignment strategy")) ] CONF.register_opts(quark_opts, "QUARK") class JSONStrategy(object): def __init__(self, strategy=None): self.reverse_strategy = {} self.strategy = {} if not strategy: self._compile_strategy(CONF.QUARK.default_net_strategy)
from neutron import manager from neutron.openstack.common import log as logging from neutron import wsgi RESOURCE_NAME = 'mac_address_range' RESOURCE_COLLECTION = RESOURCE_NAME + "s" EXTENDED_ATTRIBUTES_2_0 = { RESOURCE_COLLECTION: {} } attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION] attr_dict[RESOURCE_NAME] = {'allow_post': True, 'allow_put': False, 'is_visible': True} LOG = logging.getLogger("neutron.quark.api.extensions.mac_address_ranges") def mac_range_dict(mac_range): return dict(address=mac_range["cidr"], id=mac_range["id"]) class MacAddressRangesController(wsgi.Controller): def __init__(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin def create(self, request, body=None): body = self._deserialize(request.body, request.get_content_type())
import new import random import eventlet from eventlet.green import urllib2 import mock from neutron.openstack.common.gettextutils import _LI from neutron.openstack.common import log as logging from neutron.plugins.vmware.api_client import eventlet_client as client from neutron.plugins.vmware.api_client import eventlet_request as request from neutron.tests import base from neutron.tests.unit import vmware LOG = logging.getLogger("test_api_request_eventlet") REQUEST_TIMEOUT = 1 def fetch(url): return urllib2.urlopen(url).read() class ApiRequestEventletTest(base.BaseTestCase): def setUp(self): super(ApiRequestEventletTest, self).setUp() self.client = client.EventletApiClient(
# 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. """ Optimized NVP client for Quark """ from neutron.openstack.common import log as logging from quark.db import models from quark.drivers.nvp_driver import NVPDriver import sqlalchemy as sa from sqlalchemy import orm LOG = logging.getLogger("neutron.quark.nvplib") class OptimizedNVPDriver(NVPDriver): def delete_network(self, context, network_id): lswitches = self._lswitches_for_network(context, network_id) for switch in lswitches: self._lswitch_delete(context, switch.nvp_id) def create_port(self, context, network_id, port_id, status=True, security_groups=[], allowed_pairs=[]): nvp_port = super(OptimizedNVPDriver, self).\ create_port(context, network_id, port_id, status=status, security_groups=security_groups, allowed_pairs=allowed_pairs)
from neutron import manager from neutron.openstack.common import log as logging from neutron import wsgi RESOURCE_NAME = 'ip_address' RESOURCE_COLLECTION = RESOURCE_NAME + "es" EXTENDED_ATTRIBUTES_2_0 = { RESOURCE_COLLECTION: {} } attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION] attr_dict[RESOURCE_NAME] = {'allow_post': True, 'allow_put': True, 'is_visible': True} LOG = logging.getLogger("neutron.quark.api.extensions.ip_addresses") class IpAddressesController(wsgi.Controller): def __init__(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin def index(self, request): context = request.context return {"ip_addresses": self._plugin.get_ip_addresses(context, **request.GET)} def show(self, request, id): context = request.context
# Import Neutron Database API from neutron.db import api as db try: from neutron.openstack.common import log as logger except ImportError: from oslo_log import log as logger from neutron.plugins.ml2 import driver_api as api import ch10_ml2_mech_driver_network as cookbook_network_driver import ch10_ml2_mech_driver_subnet as cookbook_subnet_driver import ch10_ml2_mech_driver_port as cookbook_port_driver driver_logger = logger.getLogger(__name__) class CookbookMechanismDriver(cookbook_network_driver.CookbookNetworkMechanismDriver, cookbook_subnet_driver.CookbookSubnetMechanismDriver, cookbook_port_driver.CookbookPortMechanismDriver): def initialize(self): driver_logger.info("Inside Mech Driver Initialize")
import logging as py_logging from neutron.openstack.common import log as logging logging.setup("swtich") # TODO(morgbara) figure out how to use a config file for this LOG = logging.getLogger("ironic_neutron_plugin.drivers.cisco.driver") LOG.logger.setLevel(py_logging.DEBUG) from ironic_neutron_plugin.drivers import base from ironic_neutron_plugin.drivers.cisco import driver as cisco_driver def create_port(port, driver): driver.create(port) def delete_port(port, driver): driver.delete(port) def add_vlan(port, driver): driver.attach(port) def remove_vlan(port, driver): driver.detach(port) def show(port, driver): driver.show(port)
# License for the specific language governing permissions and limitations # under the License. from neutron.openstack.common import context from neutron.common import exceptions import eventlet from keystoneclient.v2_0 import client as kc from keystoneclient.v3 import client as kc_v3 from oslo.config import cfg from neutron.openstack.common import importutils from neutron.openstack.common import log as logging logger = logging.getLogger( 'neutron.plugins.cascading_proxy_agent.keystoneclient') class KeystoneClient(object): """ Wrap keystone client so we can encapsulate logic used in resources Note this is intended to be initialized from a resource on a per-session basis, so the session context is passed in on initialization Also note that a copy of this is created every resource as self.keystone() via the code in engine/client.py, so there should not be any need to directly instantiate instances of this class inside resources themselves """ def __init__(self, context): # We have to maintain two clients authenticated with keystone:
@author: gongysh ''' from sqlalchemy.orm import exc from neutron.common import constants as l3_constants from neutron.common import rpc as n_rpc from neutron.common import utils as common_utils from neutron import context as n_context from neutron.db import db_base_plugin_v2 from neutron.db import models_v2 from neutron.extensions import uosfloatingip from neutron.openstack.common import log as logging LOG = logging.getLogger('uos') DEVICE_OWNER_ROUTER_GW = l3_constants.DEVICE_OWNER_ROUTER_GW class UosFloatingIPMixin(object): @common_utils.exception_logger() def associate_floatingip_router(self, context, floatingip_id, router_id): with context.session.begin(subtransactions=True): floatingip_db = self._get_floatingip(context, floatingip_id) floating_network_id = floatingip_db['floating_network_id'] gw_portdb = None try: port_qry = context.elevated().session.query(models_v2.Port) gw_portdb = port_qry.filter_by(
import six from neutron.agent.linux import ip_lib from neutron.agent.linux import utils from neutron.api.rpc.agentnotifiers import helo_rpc_agent_api from neutron.common import rpc as q_rpc from neutron import context from neutron.openstack.common import jsonutils from neutron.openstack.common import lockutils from neutron.openstack.common import log as logging from neutron.plugins.common import constants from neutron.services.vpn.common import topics from neutron.services.vpn import device_drivers LOG = logging.getLogger('pptp_agent') TEMPLATE_PATH = os.path.dirname(__file__) pptp_opts = [ cfg.StrOpt( 'config_base_dir', default='$state_path/pptp', help=_('Location to store pptp server config files')), cfg.IntOpt('pptp_status_check_interval', default=60, help=_("Interval for checking pptpd status")), cfg.StrOpt( 'pptpd_config_template', default=os.path.join( TEMPLATE_PATH, 'template/pptp/pptpd.conf.template'),
import os from oslo.config import cfg import routes import webob.dec import webob.exc from neutron.api.v2 import attributes from neutron.common import exceptions import neutron.extensions from neutron.manager import NeutronManager from neutron.openstack.common import log as logging from neutron import wsgi LOG = logging.getLogger("neutron.api.extensions") class PluginInterface(object): __metaclass__ = ABCMeta @classmethod def __subclasshook__(cls, klass): """Checking plugin class. The __subclasshook__ method is a class method that will be called everytime a class is tested using issubclass(klass, PluginInterface). In that case, it will check that every method marked with the abstractmethod decorator is provided by the plugin class.
def setup_logging(): logging.setup("neutron") logging.getLogger("neutron").logger LOG.debug("Logging setup complete")
# 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. # @author: Haojie Jia, Huawei from oslo.config import cfg #from heat.openstack.common import importutils #from heat.openstack.common import log as logging from neutron.openstack.common import importutils from neutron.openstack.common import log as logging logger = logging.getLogger(__name__) from neutron.plugins.l2_proxy.agent import neutron_keystoneclient as hkc from novaclient import client as novaclient from novaclient import shell as novashell try: from swiftclient import client as swiftclient except ImportError: swiftclient = None logger.info('swiftclient not available') try: from neutronclient.v2_0 import client as neutronclient except ImportError: neutronclient = None logger.info('neutronclient not available')
# 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 copy import traceback from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import utils as common_utils from neutron.openstack.common import jsonutils from neutron.openstack.common import lockutils from neutron.openstack.common import log as logging LOG = logging.getLogger('uos_l3') TOP_CHAIN = 'meter-uos' WRAP_NAME = 'neutron-vpn-agen-' FIP_CHAIN_SIZE = 10 TOP_CHAIN_NAME = WRAP_NAME + TOP_CHAIN class L3AgentMixin(object): def _uos_get_ex_gw_port(self, ri): gw_port = ri.router.get('gw_port') if not gw_port: return gw_port if gw_port.get('_uos_fip'): return gw_port gateway_ips = ri.router.get('gateway_ips', [])
# # 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 # from neutron.openstack.common import log as logging LOG = logging.getLogger("neutron.quark.base") class BaseDriver(object): """Base interface for all Quark drivers. Usable as a replacement for the sample plugin. """ def load_config(self): LOG.info("load_config") def get_connection(self): LOG.info("get_connection") def create_network(self, context, network_name, tags=None, network_id=None, **kwargs):
import functools from neutron.common import topics from neutron.db import l3_db from neutron.db import l3_rpc_base as l3_rpc from neutron.extensions import portsecurity as psec from neutron.extensions import securitygroup as ext_sg from neutron.openstack.common import log as logging from neutron.openstack.common import rpc from neutron.plugins.nicira.dhcp_meta import rpc as nvp_rpc from neutron.plugins.nicira.NeutronPlugin import nicira_db from neutron.plugins.nicira import NeutronPlugin as nvp from akanda.neutron.plugins import decorators as akanda LOG = logging.getLogger("NeutronPlugin") akanda.monkey_patch_ipv6_generator() def akanda_nvp_ipv6_port_security_wrapper(f): @functools.wraps(f) def wrapper(lport_obj, mac_address, fixed_ips, port_security_enabled, security_profiles, queue_id, mac_learning_enabled, allowed_address_pairs): f(lport_obj, mac_address, fixed_ips, port_security_enabled, security_profiles, queue_id, mac_learning_enabled, allowed_address_pairs) # evaulate the state so that we only override the value when enabled # otherwise we are preserving the underlying behavior of the NVP plugin
import logging as py_logging from neutron.openstack.common import log as logging logging.setup("swtich") # TODO(morgbara) figure out how to use a config file for this LOG = logging.getLogger('baremetal_neutron_extension.drivers.cisco.driver') LOG.logger.setLevel(py_logging.DEBUG) from baremetal_neutron_extension.drivers import base from baremetal_neutron_extension.drivers.cisco import driver as cisco_driver def create_port(port, driver): driver.create(port) def delete_port(port, driver): driver.delete(port) def add_vlan(port, driver): driver.attach(port) def remove_vlan(port, driver): driver.detach(port) def show(port, driver): driver.show(port)
from neutron import manager from neutron.openstack.common import log as logging from neutron import wsgi RESOURCE_NAME = 'route' RESOURCE_COLLECTION = RESOURCE_NAME + "s" EXTENDED_ATTRIBUTES_2_0 = { RESOURCE_COLLECTION: {} } attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION] attr_dict[RESOURCE_NAME] = {'allow_post': True, 'allow_put': True, 'is_visible': True} LOG = logging.getLogger("neutron.quark.api.extensions.routes") def route_dict(route): return dict(cidr=route["cidr"], gateway=route["gateway"], id=route["id"], subnet_id=route["subnet_id"]) class RoutesController(wsgi.Controller): def __init__(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin
from ryu import cfg import sys from neutron.openstack.common import log as os_logging from neutron.common import config as osn_config from ryu import flags from ryu import version from ryu.app import wsgi from ryu.base.app_manager import AppManager from ryu.controller import controller from ryu.topology import switches LOG = os_logging.getLogger(__name__) CONF = cfg.CONF CONF.register_cli_opts([ cfg.ListOpt('app-lists', default=[], help='application module name to run'), cfg.MultiStrOpt('app', positional=True, default=[], help='application module name to run') ]) def main(): try: CONF(project='ryu', version='ofa_neutron_agent %s' % version, default_config_files=['/usr/local/etc/ryu/ryu.conf']) except cfg.ConfigFilesNotFoundError: CONF(project='ryu', version='ofa_neutron_agent %s' % version)
import os from oslo.config import cfg import routes import webob.dec import webob.exc from neutron.api.v2 import attributes from neutron.common import exceptions import neutron.extensions from neutron.manager import NeutronManager from neutron.openstack.common import log as logging from neutron import wsgi LOG = logging.getLogger('neutron.api.extensions') class PluginInterface(object): __metaclass__ = ABCMeta @classmethod def __subclasshook__(cls, klass): """Checking plugin class. The __subclasshook__ method is a class method that will be called everytime a class is tested using issubclass(klass, PluginInterface). In that case, it will check that every method marked with the abstractmethod decorator is provided by the plugin class.
from neutron.common import rpc as q_rpc from neutron import context from neutron.openstack.common import jsonutils from neutron.openstack.common import log as logging from neutron.openstack.common import lockutils from neutron.plugins.common import constants from neutron.services.vpn.common import topics from neutron.services.vpn.common import constants as vpn_constants from neutron.services.vpn import device_drivers from neutron.services.vpn import ca reload(sys) sys.setdefaultencoding("utf-8") LOG = logging.getLogger("openvpn_agent") TEMPLATE_PATH = os.path.dirname(__file__) NS_PREFIX = l3_agent.NS_PREFIX openvpn_opts = [ cfg.StrOpt( "openvpn_ca_file", default="$state_path/openvpn/ca/ca.crt", help=_("ca absolute path for server and client") ), cfg.StrOpt( "openvpn_dh_file", default="$state_path/openvpn/ca/dh.pem", help=_("ca absolute path for server and client") ), cfg.StrOpt( "openvpn_ca_file", default="$state_path/openvpn/ca/ca.crt", help=_("ca absolute path for server and client") ), cfg.StrOpt("config_base_dir", default="$state_path/openvpn", help=_("Location to store pptp server config files")),
from sqlalchemy import orm from sqlalchemy.ext import associationproxy from sqlalchemy.ext import declarative from sqlalchemy.ext import hybrid import neutron.db.model_base from neutron.db import models_v2 as models from neutron.openstack.common import log as logging from neutron.openstack.common import timeutils from quark.db import custom_types HasId = models.HasId LOG = logging.getLogger("neutron.quark.db.models") def _default_list_getset(collection_class, proxy): attr = proxy.value_attr def getter(obj): if obj: return getattr(obj, attr, None) return [] if collection_class is dict: setter = lambda o, k, v: setattr(o, attr, v) else: setter = lambda o, v: setattr(o, attr, v) return getter, setter
# under the License. """ Quark Pluggable IPAM """ import netaddr from neutron.common import exceptions from neutron.openstack.common import log as logging from neutron.openstack.common import timeutils from quark.db import api as db_api LOG = logging.getLogger("neutron") class QuarkIpam(object): @staticmethod def get_ip_policy_rule_set(subnet): ip_policy = subnet["ip_policy"] or \ subnet["network"]["ip_policy"] or \ dict() ip_policy_rules = ip_policy.get("exclude", []) ip_policy_rules = netaddr.IPSet( [netaddr.IPNetwork((int(ippr["address"]), ippr["prefix"])) for ippr in ip_policy_rules]) subnet_set = netaddr.IPSet([netaddr.IPNetwork(subnet["cidr"])]) ip_policy_rules = subnet_set & ip_policy_rules return ip_policy_rules
# See the License for the specific language governing permissions and # limitations under the License. from neutron.api import extensions from neutron import manager from neutron.openstack.common import log as logging from neutron import wsgi RESOURCE_NAME = "ip_policy" RESOURCE_COLLECTION = "ip_policies" EXTENDED_ATTRIBUTES_2_0 = {RESOURCE_COLLECTION: {}} attr_dict = EXTENDED_ATTRIBUTES_2_0[RESOURCE_COLLECTION] attr_dict[RESOURCE_NAME] = {"allow_post": True, "allow_put": False, "is_visible": True} LOG = logging.getLogger("neutron.quark.api.extensions.ip_policies") class IPPoliciesController(wsgi.Controller): def __init__(self, plugin): self._resource_name = RESOURCE_NAME self._plugin = plugin def create(self, request, body=None): body = self._deserialize(request.body, request.get_content_type()) return {RESOURCE_NAME: self._plugin.create_ip_policy(request.context, body)} def index(self, request): context = request.context return {RESOURCE_COLLECTION: self._plugin.get_ip_policies(context)}
# # 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 neutron.common import constants from neutron.extensions import portbindings from neutron.openstack.common import log from neutron.plugins.ml2 import driver_api as api from neutron.plugins.ml2.drivers import mech_agent LOG = log.getLogger(__name__) class LinuxbridgeMechanismDriver(mech_agent.AgentMechanismDriverBase): """Attach to networks using linuxbridge L2 agent. The LinuxbridgeMechanismDriver integrates the ml2 plugin with the linuxbridge L2 agent. Port binding with this driver requires the linuxbridge agent to be running on the port's host, and that agent to have connectivity to at least one segment of the port's network. """ def __init__(self): super(LinuxbridgeMechanismDriver, self).__init__( constants.AGENT_TYPE_LINUXBRIDGE,
# 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. # # @author: Abhishek Raut, Cisco Systems Inc. # @author: Sourabh Patwardhan, Cisco Systems Inc. from neutron.openstack.common import log as logging from neutron.plugins.cisco.common import cisco_exceptions as c_exc from neutron.plugins.cisco.n1kv import n1kv_client LOG = logging.getLogger(__name__) _resource_metadata = { 'port': ['id', 'macAddress', 'ipAddress', 'subnetId'], 'vmnetwork': [ 'name', 'networkSegmentId', 'networkSegment', 'portProfile', 'portProfileId', 'tenantId', 'portId', 'macAddress', 'ipAddress', 'subnetId' ] } class TestClient(n1kv_client.Client): def __init__(self, **kwargs): self.broken = False self.inject_params = False