def test_install_arp_responder(self):
     br = self.br
     with mock.patch.object(br, '_send_msg') as sendmsg:
         br.install_arp_responder(table_id=99)
     (dp, ofp, ofpp) = br._get_dp()
     arp = importutils.import_module('ryu.lib.packet.arp')
     ether = importutils.import_module('ryu.ofproto.ether')
     call = mock.call
     expected_calls = [
         call(
             ofpp.OFPFlowMod(
                 dp,
                 instructions=[
                     ofpp.OFPInstructionActions(
                         ofp.OFPIT_APPLY_ACTIONS,
                         [ofpp.OFPActionOutput(ofp.OFPP_CONTROLLER)])
                 ],
                 match=ofpp.OFPMatch(arp_op=arp.ARP_REQUEST,
                                     eth_type=ether.ETH_TYPE_ARP),
                 priority=1,
                 table_id=99)),
         call(
             ofpp.OFPFlowMod(
                 dp,
                 instructions=[ofpp.OFPInstructionGotoTable(table_id=100)],
                 priority=0,
                 table_id=99)),
     ]
     sendmsg.assert_has_calls(expected_calls)
Example #2
0
    def __init__(self, virtapi, read_only=False):
        super(IronicDriver, self).__init__(virtapi)
        global ironic
        if ironic is None:
            ironic = importutils.import_module('ironicclient')
            # NOTE(deva): work around a lack of symbols in the current version.
            if not hasattr(ironic, 'exc'):
                ironic.exc = importutils.import_module('ironicclient.exc')
            if not hasattr(ironic, 'client'):
                ironic.client = importutils.import_module(
                                                    'ironicclient.client')

        self.firewall_driver = firewall.load_driver(
            default='nova.virt.firewall.NoopFirewallDriver')
        self.node_cache = {}
        self.node_cache_time = 0

        # TODO(mrda): Bug ID 1365230 Logging configurability needs
        # to be addressed
        ironicclient_log_level = CONF.ironic.client_log_level
        if ironicclient_log_level:
            level = py_logging.getLevelName(ironicclient_log_level)
            logger = py_logging.getLogger('ironicclient')
            logger.setLevel(level)

        self.ironicclient = client_wrapper.IronicClientWrapper()
Example #3
0
    def test_call_ok_auth_uri_ks_authtoken(self):
        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystonemiddleware.auth_token')
        dummy_url = 'http://123:5000/v2.0'
        cfg.CONF.set_override('auth_uri',
                              dummy_url,
                              group='keystone_authtoken')
        ec2 = ec2token.EC2Token(app='woot', conf={})
        params = {'AWSAccessKeyId': 'foo', 'Signature': 'xyz'}
        req_env = {
            'SERVER_NAME': 'heat',
            'SERVER_PORT': '8000',
            'PATH_INFO': '/v1'
        }
        dummy_req = self._dummy_GET_request(params, req_env)

        ok_resp = json.dumps({
            'access': {
                'metadata': {},
                'token': {
                    'id': 123,
                    'tenant': {
                        'name': 'tenant',
                        'id': 'abcd1234'
                    }
                }
            }
        })
        self._stub_http_connection(response=ok_resp,
                                   params={'AWSAccessKeyId': 'foo'})
        self.m.ReplayAll()
        self.assertEqual('woot', ec2.__call__(dummy_req))

        self.m.VerifyAll()
Example #4
0
    def before(self, state):
        headers = state.request.headers
        user = headers.get('X-User')
        user_id = headers.get('X-User-Id')
        project = headers.get('X-Project-Name')
        project_id = headers.get('X-Project-Id')
        domain_id = headers.get('X-User-Domain-Id')
        domain_name = headers.get('X-User-Domain-Name')
        auth_token = headers.get('X-Storage-Token')
        auth_token = headers.get('X-Auth-Token', auth_token)
        auth_token_info = state.request.environ.get('keystone.token_info')

        auth_url = headers.get('X-Auth-Url')
        if auth_url is None:
            importutils.import_module('keystonemiddleware.auth_token')
            auth_url = cfg.CONF.keystone_authtoken.auth_uri

        state.request.context = context.make_context(
            auth_token=auth_token,
            auth_url=auth_url,
            auth_token_info=auth_token_info,
            user=user,
            user_id=user_id,
            project=project,
            project_id=project_id,
            domain_id=domain_id,
            domain_name=domain_name)
    def __init__(self, context):
        # If a trust_id is specified in the context, we immediately
        # authenticate so we can populate the context with a trust token
        # otherwise, we delay client authentication until needed to avoid
        # unnecessary calls to keystone.
        #
        # Note that when you obtain a token using a trust, it cannot be
        # used to reauthenticate and get another token, so we have to
        # get a new trust-token even if context.auth_token is set.
        #
        # - context.auth_url is expected to contain a versioned keystone
        #   path, we will work with either a v2.0 or v3 path
        self.context = context
        self._client = None
        self._admin_client = None

        if self.context.auth_url:
            self.v3_endpoint = self.context.auth_url.replace('v2.0', 'v3')
        else:
            # Import auth_token to have keystone_authtoken settings setup.
            importutils.import_module('keystonemiddleware.auth_token')
            self.v3_endpoint = cfg.CONF.keystone_authtoken.auth_uri.replace(
                'v2.0', 'v3')

        if self.context.trust_id:
            # Create a client with the specified trust_id, this
            # populates self.context.auth_token with a trust-scoped token
            self._client = self._v3_client_init()
Example #6
0
    def __init__(self, context):
        # If a trust_id is specified in the context, we immediately
        # authenticate so we can populate the context with a trust token
        # otherwise, we delay client authentication until needed to avoid
        # unnecessary calls to keystone.
        #
        # Note that when you obtain a token using a trust, it cannot be
        # used to reauthenticate and get another token, so we have to
        # get a new trust-token even if context.auth_token is set.
        #
        # - context.auth_url is expected to contain a versioned keystone
        #   path, we will work with either a v2.0 or v3 path
        self.context = context
        self._client = None
        self._admin_client = None
        self._domain_admin_client = None

        self.session = session.Session.construct(self._ssl_options())

        if self.context.auth_url:
            self.v3_endpoint = self.context.auth_url.replace('v2.0', 'v3')
        else:
            # Import auth_token to have keystone_authtoken settings setup.
            importutils.import_module('keystonemiddleware.auth_token')
            self.v3_endpoint = cfg.CONF.keystone_authtoken.auth_uri.replace(
                'v2.0', 'v3')

        if self.context.trust_id:
            # Create a client with the specified trust_id, this
            # populates self.context.auth_token with a trust-scoped token
            self._client = self._v3_client_init()

        # The stack domain user ID should be set in heat.conf
        # It can be created via python-openstackclient
        # openstack --os-identity-api-version=3 domain create heat
        # If the domain is specified, then you must specify a domain
        # admin user.  If no domain is specified, we fall back to
        # legacy behavior with warnings.
        self._stack_domain_is_id = True
        self._stack_domain_id = None
        self.stack_domain = cfg.CONF.stack_user_domain_id
        if not self.stack_domain and cfg.CONF.stack_user_domain_name:
            self.stack_domain = cfg.CONF.stack_user_domain_name
            self._stack_domain_is_id = False
        self.domain_admin_user = cfg.CONF.stack_domain_admin
        self.domain_admin_password = cfg.CONF.stack_domain_admin_password
        if self.stack_domain:
            if not (self.domain_admin_user and self.domain_admin_password):
                raise exception.Error(
                    _('heat.conf misconfigured, cannot '
                      'specify "stack_user_domain_id" or '
                      '"stack_user_domain_name" without '
                      '"stack_domain_admin" and '
                      '"stack_domain_admin_password"'))
        else:
            LOG.warn(
                _LW('stack_user_domain_id or stack_user_domain_name not '
                    'set in heat.conf falling back to using default'))
        LOG.debug('Using stack domain %s' % self.stack_domain)
Example #7
0
 def _mk_test_dp(self, name):
     ofp = importutils.import_module("ryu.ofproto.ofproto_v1_3")
     ofpp = importutils.import_module("ryu.ofproto.ofproto_v1_3_parser")
     dp = mock.Mock()
     dp.ofproto = ofp
     dp.ofproto_parser = ofpp
     dp.__repr__ = mock.Mock(return_value=name)
     return dp
 def _mk_test_dp(self, name):
     ofp = importutils.import_module('ryu.ofproto.ofproto_v1_3')
     ofpp = importutils.import_module('ryu.ofproto.ofproto_v1_3_parser')
     dp = mock.Mock()
     dp.ofproto = ofp
     dp.ofproto_parser = ofpp
     dp.__repr__ = mock.Mock(return_value=name)
     return dp
Example #9
0
 def _get_auth_url(self):
     if 'auth_uri' in self.conf:
         return self.conf['auth_uri']
     else:
         # Import auth_token to have keystone_authtoken settings setup.
         auth_token_module = 'keystonemiddleware.auth_token'
         importutils.import_module(auth_token_module)
         return cfg.CONF.keystone_authtoken.auth_uri
Example #10
0
    def _keystone_v3_endpoint(self):
        if self.auth_url:
            auth_uri = self.auth_url
        else:
            importutils.import_module('keystonemiddleware.auth_token')
            auth_uri = cfg.CONF.keystone_authtoken.auth_uri

        return auth_uri.replace('v2.0', 'v3')
Example #11
0
 def _get_auth_url(self):
     if 'auth_uri' in self.conf:
         return self.conf['auth_uri']
     else:
         # Import auth_token to have keystone_authtoken settings setup.
         auth_token_module = 'keystoneclient.middleware.auth_token'
         importutils.import_module(auth_token_module)
         return cfg.CONF.keystone_authtoken.auth_uri
Example #12
0
 def _conf_get_auth_uri(self):
     auth_uri = self._conf_get('auth_uri')
     if auth_uri:
         return auth_uri
     else:
         # Import auth_token to have keystone_authtoken settings setup.
         # We can use the auth_uri from the keystone_authtoken section
         importutils.import_module('keystonemiddleware.auth_token')
         return cfg.CONF.keystone_authtoken['auth_uri']
Example #13
0
 def _conf_get_auth_uri(self):
     auth_uri = self._conf_get('auth_uri')
     if auth_uri:
         return auth_uri
     else:
         # Import auth_token to have keystone_authtoken settings setup.
         # We can use the auth_uri from the keystone_authtoken section
         importutils.import_module('keystonemiddleware.auth_token')
         return cfg.CONF.keystone_authtoken['auth_uri']
Example #14
0
 def _service_admin_creds(self):
     # Import auth_token to have keystone_authtoken settings setup.
     importutils.import_module('keystonemiddleware.auth_token')
     creds = {
         'username': cfg.CONF.keystone_authtoken.admin_user,
         'password': cfg.CONF.keystone_authtoken.admin_password,
         'auth_url': self.v3_endpoint,
         'endpoint': self.v3_endpoint,
         'project_name': cfg.CONF.keystone_authtoken.admin_tenant_name}
     return creds
Example #15
0
    def __init__(self, context):
        # If a trust_id is specified in the context, we immediately
        # authenticate so we can populate the context with a trust token
        # otherwise, we delay client authentication until needed to avoid
        # unnecessary calls to keystone.
        #
        # Note that when you obtain a token using a trust, it cannot be
        # used to reauthenticate and get another token, so we have to
        # get a new trust-token even if context.auth_token is set.
        #
        # - context.auth_url is expected to contain a versioned keystone
        #   path, we will work with either a v2.0 or v3 path
        self.context = context
        self._client = None
        self._admin_client = None
        self._domain_admin_client = None

        if self.context.auth_url:
            self.v3_endpoint = self.context.auth_url.replace('v2.0', 'v3')
        else:
            # Import auth_token to have keystone_authtoken settings setup.
            importutils.import_module('keystonemiddleware.auth_token')
            self.v3_endpoint = cfg.CONF.keystone_authtoken.auth_uri.replace(
                'v2.0', 'v3')

        if self.context.trust_id:
            # Create a client with the specified trust_id, this
            # populates self.context.auth_token with a trust-scoped token
            self._client = self._v3_client_init()

        # The stack domain user ID should be set in heat.conf
        # It can be created via python-openstackclient
        # openstack --os-identity-api-version=3 domain create heat
        # If the domain is specified, then you must specify a domain
        # admin user.  If no domain is specified, we fall back to
        # legacy behavior with warnings.
        self._stack_domain_is_id = True
        self._stack_domain_id = None
        self.stack_domain = cfg.CONF.stack_user_domain_id
        if not self.stack_domain and cfg.CONF.stack_user_domain_name:
            self.stack_domain = cfg.CONF.stack_user_domain_name
            self._stack_domain_is_id = False
        self.domain_admin_user = cfg.CONF.stack_domain_admin
        self.domain_admin_password = cfg.CONF.stack_domain_admin_password
        if self.stack_domain:
            if not (self.domain_admin_user and self.domain_admin_password):
                raise exception.Error(_('heat.conf misconfigured, cannot '
                                      'specify "stack_user_domain_id" or '
                                      '"stack_user_domain_name" without '
                                      '"stack_domain_admin" and '
                                      '"stack_domain_admin_password"'))
        else:
            LOG.warn(_LW('stack_user_domain_id or stack_user_domain_name not '
                         'set in heat.conf falling back to using default'))
        LOG.debug('Using stack domain %s' % self.stack_domain)
Example #16
0
 def _service_admin_creds(self):
     # Import auth_token to have keystone_authtoken settings setup.
     importutils.import_module('keystoneclient.middleware.auth_token')
     creds = {
         'username': cfg.CONF.keystone_authtoken.admin_user,
         'password': cfg.CONF.keystone_authtoken.admin_password,
         'auth_url': self.v3_endpoint,
         'endpoint': self.v3_endpoint,
         'project_name': cfg.CONF.keystone_authtoken.admin_tenant_name
     }
     return creds
Example #17
0
 def test_setup_default_table(self):
     br = self.br
     with mock.patch.object(br, '_send_msg') as sendmsg:
         br.setup_default_table()
     (dp, ofp, ofpp) = br._get_dp()
     arp = importutils.import_module('ryu.lib.packet.arp')
     ether = importutils.import_module('ryu.ofproto.ether')
     call = mock.call
     expected_calls = [
         call(ofpp.OFPFlowMod(dp, command=ofp.OFPFC_DELETE,
              match=ofpp.OFPMatch(), out_group=ofp.OFPG_ANY,
              out_port=ofp.OFPP_ANY, priority=0, table_id=ofp.OFPTT_ALL)),
         call(ofpp.OFPFlowMod(dp, priority=0, table_id=0)),
         call(ofpp.OFPFlowMod(dp, priority=0, table_id=1)),
         call(ofpp.OFPFlowMod(dp, priority=0, table_id=2)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=7)],
              priority=0, table_id=3)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=5)],
              priority=0, table_id=4)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=6)],
              priority=0, table_id=5)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,
              [ofpp.OFPActionOutput(ofp.OFPP_CONTROLLER)])],
              match=ofpp.OFPMatch(arp_op=arp.ARP_REQUEST,
              eth_type=ether.ETH_TYPE_ARP), priority=1, table_id=6)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=7)],
              priority=0, table_id=6)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=8)],
              priority=0, table_id=7)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=9)],
              priority=0, table_id=8)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=10)],
              priority=0, table_id=9)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=11)],
              priority=0, table_id=10)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=12)],
              priority=0, table_id=11)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=13)],
              priority=0, table_id=12)),
         call(ofpp.OFPFlowMod(dp, priority=0, table_id=13)),
     ]
     sendmsg.assert_has_calls(expected_calls, any_order=True)
Example #18
0
    def before(self, state):
        if not CONF.get('enable_authentication'):
            return
        # Skip authentication for public endpoints
        if AUTH.is_endpoint_public(state.request.path):
            return

        headers = state.request.headers
        user_id = headers.get('X-User-Id')
        if user_id is None:
            LOG.debug("X-User-Id header was not found in the request")
            raise Exception('Not authorized')

        roles = self._get_roles(state.request)

        project_id = headers.get('X-Project-Id')
        user_name = headers.get('X-User-Name', '')

        domain = headers.get('X-Domain-Name')
        project_domain_id = headers.get('X-Project-Domain-Id', '')
        user_domain_id = headers.get('X-User-Domain-Id', '')

        # Get the auth token
        try:
            recv_auth_token = headers.get('X-Auth-Token',
                                          headers.get(
                                              'X-Storage-Token'))
        except ValueError:
            LOG.debug("No auth token found in the request.")
            raise Exception('Not authorized')
        auth_url = headers.get('X-Auth-Url')
        if auth_url is None:
            importutils.import_module('keystonemiddleware.auth_token')
            auth_url = cfg.CONF.keystone_authtoken.auth_uri

        auth_token_info = state.request.environ.get('keystone.token_info')
        identity_status = headers.get('X-Identity-Status')
        if identity_status == 'Confirmed':
            ctx = context.RequestContext(auth_token=recv_auth_token,
                                         auth_token_info=auth_token_info,
                                         user=user_id,
                                         tenant=project_id,
                                         domain=domain,
                                         user_domain=user_domain_id,
                                         project_domain=project_domain_id,
                                         user_name=user_name,
                                         roles=roles,
                                         auth_url=auth_url)
            state.request.security_context = ctx
        else:
            LOG.debug("The provided identity is not confirmed.")
            raise Exception('Not authorized. Identity not confirmed.')
        return
Example #19
0
    def _service_admin_creds():
        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystonemiddleware.auth_token')

        creds = {
            'username': cfg.CONF.keystone_authtoken.admin_user,
            'password': cfg.CONF.keystone_authtoken.admin_password,
            'auth_url': cfg.CONF.keystone_authtoken.auth_uri,
            'tenant_name': cfg.CONF.keystone_authtoken.admin_tenant_name,
        }

        return creds
Example #20
0
    def _service_admin_creds():
        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystonemiddleware.auth_token')

        creds = {
            'username': cfg.CONF.keystone_authtoken.admin_user,
            'password': cfg.CONF.keystone_authtoken.admin_password,
            'auth_url': cfg.CONF.keystone_authtoken.auth_uri,
            'tenant_name': cfg.CONF.keystone_authtoken.admin_tenant_name,
        }

        return creds
Example #21
0
def _get_keystone_settings():
    importutils.import_module('keystonemiddleware.auth_token')
    return {
        'auth_url': cfg.CONF.keystone_authtoken.auth_uri.replace('v2.0', 'v3'),
        'username': cfg.CONF.keystone_authtoken.admin_user,
        'password': cfg.CONF.keystone_authtoken.admin_password,
        'project_name': cfg.CONF.keystone_authtoken.admin_tenant_name,
        'ssl': {
            'cacert': cfg.CONF.keystone.ca_file,
            'insecure': cfg.CONF.keystone.insecure,
            'cert': cfg.CONF.keystone.cert_file,
            'key': cfg.CONF.keystone.key_file
        }
    }
Example #22
0
def _get_keystone_settings():
    importutils.import_module('keystonemiddleware.auth_token')
    return {
        'auth_url': cfg.CONF.keystone_authtoken.auth_uri.replace('v2.0', 'v3'),
        'username': cfg.CONF.keystone_authtoken.admin_user,
        'password': cfg.CONF.keystone_authtoken.admin_password,
        'project_name': cfg.CONF.keystone_authtoken.admin_tenant_name,
        'ssl': {
            'cacert': cfg.CONF.keystone.ca_file,
            'insecure': cfg.CONF.keystone.insecure,
            'cert': cfg.CONF.keystone.cert_file,
            'key': cfg.CONF.keystone.key_file
        }
    }
Example #23
0
 def __init__(self, db_driver=None):
     # NOTE(mriedem): Without this call, multiple inheritance involving
     # the db Base class does not work correctly.
     super(Base, self).__init__()
     if not db_driver:
         db_driver = CONF.db_driver
     self.db = importutils.import_module(db_driver)  # pylint: disable=C0103
Example #24
0
 def test_arp_passthrough(self):
     br = self.br
     with mock.patch.object(br, '_send_msg') as sendmsg:
         br.arp_passthrough(network=1234, tpa='192.0.2.1')
     (dp, ofp, ofpp) = br._get_dp()
     arp = importutils.import_module('ryu.lib.packet.arp')
     ether = importutils.import_module('ryu.ofproto.ether')
     call = mock.call
     expected_calls = [
         call(ofpp.OFPFlowMod(dp, idle_timeout=5,
              instructions=[ofpp.OFPInstructionGotoTable(table_id=7)],
              match=ofpp.OFPMatch(arp_op=arp.ARP_REQUEST,
              arp_tpa="192.0.2.1", eth_type=ether.ETH_TYPE_ARP,
              metadata=meta.mk_metadata(1234)), priority=1, table_id=5))
     ]
     sendmsg.assert_has_calls(expected_calls)
Example #25
0
    def __init__(self):
        """Initialise the IronicClientWrapper for use.

        Initialise IronicClientWrapper by loading ironicclient
        dynamically so that ironicclient is not a dependency for
        Nova.
        """
        global ironic
        if ironic is None:
            ironic = importutils.import_module('ironicclient')
            # NOTE(deva): work around a lack of symbols in the current version.
            if not hasattr(ironic, 'exc'):
                ironic.exc = importutils.import_module('ironicclient.exc')
            if not hasattr(ironic, 'client'):
                ironic.client = importutils.import_module(
                                                    'ironicclient.client')
Example #26
0
 def __init__(self, db_driver=None):
     # NOTE(mriedem): Without this call, multiple inheritance involving
     # the db Base class does not work correctly.
     super(Base, self).__init__()
     if not db_driver:
         db_driver = CONF.db_driver
     self.db = importutils.import_module(db_driver)  # pylint: disable=C0103
Example #27
0
    def setUp(self):
        super(KeystoneClientTest, self).setUp()
        self.ctx = utils.dummy_context()

        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystonemiddleware.auth_token')

        dummy_url = 'http://server.test:5000/v2.0'
        cfg.CONF.set_override('auth_uri', dummy_url,
                              group='keystone_authtoken')
        cfg.CONF.set_override('admin_user', 'heat',
                              group='keystone_authtoken')
        cfg.CONF.set_override('admin_password', 'verybadpass',
                              group='keystone_authtoken')
        cfg.CONF.set_override('admin_tenant_name', 'service',
                              group='keystone_authtoken')
        self.addCleanup(self.m.VerifyAll)
Example #28
0
def main():
    cfg.CONF(default_config_files=([NUAGE_CONFIG_FILE]))
    config.nuage_register_cfg_opts()
    server = cfg.CONF.RESTPROXY.server
    serverauth = cfg.CONF.RESTPROXY.serverauth
    serverssl = cfg.CONF.RESTPROXY.serverssl
    base_uri = cfg.CONF.RESTPROXY.base_uri
    auth_resource = cfg.CONF.RESTPROXY.auth_resource
    organization = cfg.CONF.RESTPROXY.organization
    fipquota = str(cfg.CONF.RESTPROXY.default_floatingip_quota)
    logging = importutils.import_module('logging')
    nuageclientinst = importutils.import_module('nuagenetlib.nuageclient')
    nuageclient = nuageclientinst.NuageClient(server, base_uri, serverssl,
                                              serverauth, auth_resource,
                                              organization)
    logging.basicConfig(level=logging.DEBUG)
    SyncManager(nuageclient).synchronize(fipquota)
    def setUp(self):
        super(OFAAgentTestCase, self).setUp()

        Net = collections.namedtuple('Net', 'net, mac, ip')
        self.nets = [
            Net(net=10, mac='11:11:11:44:55:66', ip='10.1.2.20'),
            Net(net=10, mac='11:11:11:44:55:67', ip='10.1.2.21'),
            Net(net=20, mac='22:22:22:44:55:66', ip='10.2.2.20')
        ]

        self.packet_mod = mock.Mock()
        self.proto_ethernet_mod = mock.Mock()
        self.proto_vlan_mod = mock.Mock()
        self.proto_vlan_mod.vid = 999
        self.proto_arp_mod = mock.Mock()
        self.fake_get_protocol = mock.Mock(return_value=self.proto_vlan_mod)
        self.packet_mod.get_protocol = self.fake_get_protocol
        self.fake_add_protocol = mock.Mock()
        self.packet_mod.add_protocol = self.fake_add_protocol
        self.arp = importutils.import_module('ryu.lib.packet.arp')
        self.ethernet = importutils.import_module('ryu.lib.packet.ethernet')
        self.vlan = importutils.import_module('ryu.lib.packet.vlan')
        mock.patch('ryu.lib.packet.packet.Packet',
                   return_value=self.packet_mod).start()

        self.ryuapp = 'ryuapp'
        self.inport = '1'
        self.ev = mock.Mock()
        self.datapath = self._mk_test_dp('tun_br')
        self.ofproto = importutils.import_module('ryu.ofproto.ofproto_v1_3')
        self.ofpp = mock.Mock()
        self.datapath.ofproto = self.ofproto
        self.datapath.ofproto_parser = self.ofpp
        self.OFPActionOutput = mock.Mock()
        self.OFPActionOutput.return_value = 'OFPActionOutput'
        self.ofpp.OFPActionOutput = self.OFPActionOutput
        self.msg = mock.Mock()
        self.msg.datapath = self.datapath
        self.msg.buffer_id = self.ofproto.OFP_NO_BUFFER
        self.msg_data = 'test_message_data'
        self.msg.data = self.msg_data
        self.ev.msg = self.msg
        self.msg.match = {
            'in_port': self.inport,
            'metadata': meta.LOCAL | self.nets[0].net
        }
Example #30
0
 def __init__(self, service_name=None, *args, **kwargs):
     self.service = importutils.import_module(self.driver_name)
     self.az = CONF.storage_availability_zone
     self.volume_managers = {}
     self._setup_volume_drivers()
     self.backup_rpcapi = backup_rpcapi.BackupAPI()
     super(BackupManager, self).__init__(service_name='backup',
                                         *args, **kwargs)
Example #31
0
 def __init__(self, service_name=None, *args, **kwargs):
     self.service = importutils.import_module(self.driver_name)
     self.az = CONF.storage_availability_zone
     self.volume_managers = {}
     self._setup_volume_drivers()
     self.backup_rpcapi = backup_rpcapi.BackupAPI()
     super(BackupManager, self).__init__(service_name='backup',
                                         *args, **kwargs)
Example #32
0
 def setUp(self):
     self.socket_mock = mock.patch(
         SERVERMANAGER + '.socket.create_connection').start()
     self.wrap_mock = mock.patch(SERVERMANAGER + '.ssl.wrap_socket').start()
     super(ServerManagerTests, self).setUp()
     # http patch must not be running or it will mangle the servermanager
     # import where the https connection classes are defined
     self.httpPatch.stop()
     self.sm = importutils.import_module(SERVERMANAGER)
Example #33
0
 def _patch(self, client):
     try:
         # if applicable patch the client
         module = (importutils.import_module(
             "powervc.common.client.patch.%s" % (self.base_name)))
         module.patch_client(self, client)
     except ImportError:
         pass
     return client
Example #34
0
 def __init__(self):
     factory = importutils.import_module('powervc.common.client.factory')
     self._novaclient = factory.POWERVC.new_client(
         str(constants.SERVICE_TYPES.compute))
     self._cinderclient = factory.POWERVC.new_client(
         str(constants.SERVICE_TYPES.volume))
     self._localkeystoneclient = factory.LOCAL.new_client(
         str(constants.SERVICE_TYPES.identity))
     self.scg_cache = self.get_scg_cache(self._novaclient)
Example #35
0
    def _import_ucsmsdk(self):
        """Imports the Ucsm SDK module.

        This module is not installed as part of the normal Neutron
        distributions. It is imported dynamically in this module so that
        the import can be mocked, allowing unit testing without requiring
        the installation of UcsSdk.

        """
        return importutils.import_module('UcsSdk')
Example #36
0
 def test_install_arp_responder(self):
     br = self.br
     with mock.patch.object(br, '_send_msg') as sendmsg:
         br.install_arp_responder(table_id=99)
     (dp, ofp, ofpp) = br._get_dp()
     arp = importutils.import_module('ryu.lib.packet.arp')
     ether = importutils.import_module('ryu.ofproto.ether')
     call = mock.call
     expected_calls = [
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,
              [ofpp.OFPActionOutput(ofp.OFPP_CONTROLLER)])],
              match=ofpp.OFPMatch(arp_op=arp.ARP_REQUEST,
              eth_type=ether.ETH_TYPE_ARP), priority=1, table_id=99)),
         call(ofpp.OFPFlowMod(dp, instructions=[
              ofpp.OFPInstructionGotoTable(table_id=100)],
              priority=0, table_id=99)),
     ]
     sendmsg.assert_has_calls(expected_calls)
Example #37
0
def _import_module(mod_str):
    try:
        if mod_str.startswith('bin.'):
            imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
            return sys.modules[mod_str[4:]]
        else:
            return importutils.import_module(mod_str)
    except Exception as e:
        sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e)))
        return None
Example #38
0
def main():
    cfg.CONF(default_config_files=(
        [NUAGE_CONFIG_FILE]))
    config.nuage_register_cfg_opts()
    server = cfg.CONF.RESTPROXY.server
    serverauth = cfg.CONF.RESTPROXY.serverauth
    serverssl = cfg.CONF.RESTPROXY.serverssl
    base_uri = cfg.CONF.RESTPROXY.base_uri
    auth_resource = cfg.CONF.RESTPROXY.auth_resource
    organization = cfg.CONF.RESTPROXY.organization
    fipquota = str(cfg.CONF.RESTPROXY.default_floatingip_quota)
    logging = importutils.import_module('logging')
    nuageclientinst = importutils.import_module('nuagenetlib.nuageclient')
    nuageclient = nuageclientinst.NuageClient(server, base_uri,
                                              serverssl, serverauth,
                                              auth_resource,
                                              organization)
    logging.basicConfig(level=logging.DEBUG)
    SyncManager(nuageclient).synchronize(fipquota)
    def _import_ncclient(self):
        """Import the NETCONF client (ncclient) module.

        The ncclient module is not installed as part of the normal Neutron
        distributions. It is imported dynamically in this module so that
        the import can be mocked, allowing unit testing without requiring
        the installation of ncclient.

        """
        return importutils.import_module('ncclient.manager')
Example #40
0
    def _service_admin_creds(api_version=2):
        # Import auth_token to have keystone_authtoken settings setup.
        importutils.import_module('keystoneclient.middleware.auth_token')

        creds = {
            'username': cfg.CONF.keystone_authtoken.admin_user,
            'password': cfg.CONF.keystone_authtoken.admin_password,
        }
        if api_version >= 3:
            creds['auth_url'] =\
                cfg.CONF.keystone_authtoken.auth_uri.replace('v2.0', 'v3')
            creds['project_name'] =\
                cfg.CONF.keystone_authtoken.admin_tenant_name
        else:
            creds['auth_url'] = cfg.CONF.keystone_authtoken.auth_uri
            creds['tenant_name'] =\
                cfg.CONF.keystone_authtoken.admin_tenant_name

        return creds
Example #41
0
def _import_module(mod_str):
    try:
        if mod_str.startswith('bin.'):
            imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
            return sys.modules[mod_str[4:]]
        else:
            return importutils.import_module(mod_str)
    except Exception as e:
        sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e)))
        return None
Example #42
0
    def setUp(self):
        super(OFAAgentTestCase, self).setUp()

        Net = collections.namedtuple('Net', 'net, mac, ip')
        self.nets = [Net(net=10, mac='11:11:11:44:55:66', ip='10.1.2.20'),
                     Net(net=10, mac='11:11:11:44:55:67', ip='10.1.2.21'),
                     Net(net=20, mac='22:22:22:44:55:66', ip='10.2.2.20')]

        self.packet_mod = mock.Mock()
        self.proto_ethernet_mod = mock.Mock()
        self.proto_vlan_mod = mock.Mock()
        self.proto_vlan_mod.vid = 999
        self.proto_arp_mod = mock.Mock()
        self.fake_get_protocol = mock.Mock(return_value=self.proto_vlan_mod)
        self.packet_mod.get_protocol = self.fake_get_protocol
        self.fake_add_protocol = mock.Mock()
        self.packet_mod.add_protocol = self.fake_add_protocol
        self.arp = importutils.import_module('ryu.lib.packet.arp')
        self.ethernet = importutils.import_module('ryu.lib.packet.ethernet')
        self.vlan = importutils.import_module('ryu.lib.packet.vlan')
        mock.patch('ryu.lib.packet.packet.Packet',
                   return_value=self.packet_mod).start()

        self.ryuapp = 'ryuapp'
        self.inport = '1'
        self.ev = mock.Mock()
        self.datapath = self._mk_test_dp('tun_br')
        self.ofproto = importutils.import_module('ryu.ofproto.ofproto_v1_3')
        self.ofpp = mock.Mock()
        self.datapath.ofproto = self.ofproto
        self.datapath.ofproto_parser = self.ofpp
        self.OFPActionOutput = mock.Mock()
        self.OFPActionOutput.return_value = 'OFPActionOutput'
        self.ofpp.OFPActionOutput = self.OFPActionOutput
        self.msg = mock.Mock()
        self.msg.datapath = self.datapath
        self.msg.buffer_id = self.ofproto.OFP_NO_BUFFER
        self.msg_data = 'test_message_data'
        self.msg.data = self.msg_data
        self.ev.msg = self.msg
        self.msg.match = {'in_port': self.inport,
                          'metadata': meta.LOCAL | self.nets[0].net}
Example #43
0
def load_network_driver(network_driver=None):
    if not network_driver:
        network_driver = CONF.network_driver

    if not network_driver:
        LOG.error(_LE("Network driver option required, but not specified"))
        sys.exit(1)

    LOG.info(_LI("Loading network driver '%s'"), network_driver)

    return importutils.import_module(network_driver)
Example #44
0
    def setUp(self):
        super(TestArpLib, self).setUp()

        self.mod_arplib = importutils.import_module(_OFALIB_NAME)
        self.arplib = self.mod_arplib.ArpLib(self.ryuapp)
        self.packet_mod.get_protocol = self._fake_get_protocol
        self._fake_get_protocol_ethernet = True
        self._fake_get_protocol_vlan = True
        self._fake_get_protocol_arp = True
        self.br = mock.Mock(datapath=self.datapath)
        self.arplib.set_bridge(self.br)
Example #45
0
 def _load_backend(self):
     with self._lock:
         if not self._backend:
             # Import the untranslated name if we don't have a mapping
             backend_path = self._backend_mapping.get(self._backend_name,
                                                      self._backend_name)
             LOG.debug('Loading backend %(name)r from %(path)r',
                       {'name': self._backend_name,
                        'path': backend_path})
             backend_mod = importutils.import_module(backend_path)
             self._backend = backend_mod.get_backend()
Example #46
0
def import_relative_module(relative_import_str, import_str):
    """
    Imports a module relative to another. Can be used when more
    than 1 module of the given name exists in the python path
    to resolve any discrepency in multiple paths.

    :param relative_import_str: a module import string which
    neighbors the actual import. for example 'glanceclient'.
    :param import_str: the module import string. for example
    'tests.utils'

    example:
    utils = import_relative_module('glanceclient', 'tests.utils')
    fapi = utils.FakeAPI(...)
    """
    mod = importutils.import_module(relative_import_str)
    mpath = os.path.dirname(os.path.dirname(os.path.realpath(mod.__file__)))
    if not sys.path[0] is mpath:
        sys.path.insert(0, mpath)
    return importutils.import_module(import_str)
    def setUp(self):
        super(TestArpLib, self).setUp()

        self.mod_arplib = importutils.import_module(_OFALIB_NAME)
        self.arplib = self.mod_arplib.ArpLib(self.ryuapp)
        self.packet_mod.get_protocol = self._fake_get_protocol
        self._fake_get_protocol_ethernet = True
        self._fake_get_protocol_vlan = True
        self._fake_get_protocol_arp = True
        self.br = mock.Mock(datapath=self.datapath)
        self.arplib.set_bridge(self.br)
Example #48
0
 def _get_classes_from_module(self, module_name):
     """Get the classes from a module that match the type we want."""
     classes = []
     module = importutils.import_module(module_name)
     for obj_name in dir(module):
         # Skip objects that are meant to be private.
         if obj_name.startswith('_'):
             continue
         itm = getattr(module, obj_name)
         if self._is_correct_class(itm):
             classes.append(itm)
     return classes
Example #49
0
    def __init__(self, imgfile, imgfmt='raw', partition=None):
        super(VFSGuestFS, self).__init__(imgfile, imgfmt, partition)

        global guestfs
        if guestfs is None:
            try:
                guestfs = importutils.import_module('guestfs')
            except Exception as e:
                raise exception.NovaException(
                    _("libguestfs is not installed (%s)") % e)

        self.handle = None
Example #50
0
 def _load_backend(self):
     with self._lock:
         if not self._backend:
             # Import the untranslated name if we don't have a mapping
             backend_path = self._backend_mapping.get(
                 self._backend_name, self._backend_name)
             LOG.debug('Loading backend %(name)r from %(path)r', {
                 'name': self._backend_name,
                 'path': backend_path
             })
             backend_mod = importutils.import_module(backend_path)
             self._backend = backend_mod.get_backend()
Example #51
0
 def _get_classes_from_module(self, module_name):
     """Get the classes from a module that match the type we want."""
     classes = []
     module = importutils.import_module(module_name)
     for obj_name in dir(module):
         # Skip objects that are meant to be private.
         if obj_name.startswith('_'):
             continue
         itm = getattr(module, obj_name)
         if self._is_correct_class(itm):
             classes.append(itm)
     return classes
 def test_arp_passthrough(self):
     br = self.br
     with mock.patch.object(br, '_send_msg') as sendmsg:
         br.arp_passthrough(network=1234, tpa='192.0.2.1')
     (dp, ofp, ofpp) = br._get_dp()
     arp = importutils.import_module('ryu.lib.packet.arp')
     ether = importutils.import_module('ryu.ofproto.ether')
     call = mock.call
     expected_calls = [
         call(
             ofpp.OFPFlowMod(
                 dp,
                 idle_timeout=5,
                 instructions=[ofpp.OFPInstructionGotoTable(table_id=7)],
                 match=ofpp.OFPMatch(arp_op=arp.ARP_REQUEST,
                                     arp_tpa="192.0.2.1",
                                     eth_type=ether.ETH_TYPE_ARP,
                                     metadata=meta.mk_metadata(1234)),
                 priority=1,
                 table_id=5))
     ]
     sendmsg.assert_has_calls(expected_calls)
Example #53
0
 def __init__(self, virtapi, get_connection, **kwargs):
     super(NWFilterFirewall, self).__init__(virtapi)
     global libvirt
     if libvirt is None:
         try:
             libvirt = importutils.import_module('libvirt')
         except ImportError:
             LOG.warn(
                 _LW("Libvirt module could not be loaded. "
                     "NWFilterFirewall will not work correctly."))
     self._libvirt_get_connection = get_connection
     self.static_filters_configured = False
     self.handle_security_groups = False
Example #54
0
def get_db_version(extension=None):
    if not extension:
        return migration.db_version(sql.get_engine(), find_migrate_repo(),
                                    migrate_repo.DB_INIT_VERSION)

    try:
        package_name = '.'.join((contrib.__name__, extension))
        package = importutils.import_module(package_name)
    except ImportError:
        raise ImportError(_("%s extension does not exist.") % package_name)

    return migration.db_version(sql.get_engine(), find_migrate_repo(package),
                                0)
Example #55
0
    def _create_auth_plugin(self):
        if self.trust_id:
            importutils.import_module('keystonemiddleware.auth_token')
            username = cfg.CONF.keystone_authtoken.admin_user
            password = cfg.CONF.keystone_authtoken.admin_password

            return v3.Password(username=username,
                               password=password,
                               user_domain_id='default',
                               auth_url=self._keystone_v3_endpoint,
                               trust_id=self.trust_id)

        if self.auth_token_info:
            auth_ref = access.AccessInfo.factory(body=self.auth_token_info,
                                                 auth_token=self.auth_token)
            return _AccessInfoPlugin(self._keystone_v3_endpoint, auth_ref)

        if self.auth_token:
            # FIXME(jamielennox): This is broken but consistent. If you
            # only have a token but don't load a service catalog then
            # url_for wont work. Stub with the keystone endpoint so at
            # least it might be right.
            return token_endpoint.Token(endpoint=self._keystone_v3_endpoint,
                                        token=self.auth_token)

        if self.password:
            return v3.Password(username=self.username,
                               password=self.password,
                               project_id=self.tenant_id,
                               user_domain_id='default',
                               auth_url=self._keystone_v3_endpoint)

        LOG.error(
            _LE("Keystone v3 API connection failed, no password "
                "trust or auth_token!"))
        raise exception.AuthorizationFailure()