当前位置: 首页>>代码示例>>Python>>正文


Python kubernetes.config方法代码示例

本文整理汇总了Python中kubernetes.config方法的典型用法代码示例。如果您正苦于以下问题:Python kubernetes.config方法的具体用法?Python kubernetes.config怎么用?Python kubernetes.config使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kubernetes的用法示例。


在下文中一共展示了kubernetes.config方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __load_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def __load_config(self):
        """ Protected method do load kubernetes config"""
        pass 
开发者ID:FairwindsOps,项目名称:reckoner,代码行数:5,代码来源:namespace_manager_mock.py

示例2: __init__

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def __init__(self, kube_config=None, logger=None):
        if kube_config:
            kubernetes.config.load_kube_config(config_file=kube_config)
        else:
            kubernetes.config.load_incluster_config()
        self.kube_config = kube_config
        self.client_corev1api = kubernetes.client.CoreV1Api()
        self.client_appsv1api = kubernetes.client.AppsV1Api()

        self.logger = logger or makeLogger(__name__)
        self.logger.info("Initializing with config: %s", kube_config) 
开发者ID:bloomberg,项目名称:powerfulseal,代码行数:13,代码来源:k8s_client.py

示例3: _binderhub_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def _binderhub_config():
    """Load the binderhub configuration

    Currently separate from the app fixture
    so that it can have a different scope (only once per session).
    """
    cfg = PyFileConfigLoader(minikube_testing_config).load_config()
    cfg.BinderHub.build_namespace = TEST_NAMESPACE
    global KUBERNETES_AVAILABLE
    try:
        kubernetes.config.load_kube_config()
    except Exception:
        cfg.BinderHub.builder_required = False
        KUBERNETES_AVAILABLE = False
        if ON_TRAVIS:
            pytest.fail("Kubernetes should be available on Travis")
    else:
        KUBERNETES_AVAILABLE = True
    if REMOTE_BINDER:
        return

    # check if Hub is running and ready
    try:
        requests.get(cfg.BinderHub.hub_url, timeout=5, allow_redirects=False)
    except Exception as e:
        print(f"JupyterHub not available at {cfg.BinderHub.hub_url}: {e}")
        if ON_TRAVIS:
            pytest.fail("JupyterHub should be available on Travis")
        cfg.BinderHub.hub_url = ''
    else:
        print(f"JupyterHub available at {cfg.BinderHub.hub_url}")
    return cfg 
开发者ID:jupyterhub,项目名称:binderhub,代码行数:34,代码来源:conftest.py

示例4: load_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def load_config(self):
        """
        Load config in the current Kubernetes cluster, either via in cluster config
        or via the local kube config if on a development machine.
        """
        try:
            kubernetes.config.load_incluster_config()
        except kubernetes.config.ConfigException:
            kubernetes.config.load_kube_config() 
开发者ID:botify-labs,项目名称:simpleflow,代码行数:11,代码来源:k8s.py

示例5: schedule

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def schedule(self):
        """
        Schedule a job from the given job template. See example of it here:
        https://github.com/kubernetes-incubator/client-python/blob/master/examples/create_deployment.py
        """
        # build job definition
        job_definition = self.compute_job_definition()

        # load cluster config
        self.load_config()

        # schedule job
        api = kubernetes.client.BatchV1Api()
        namespace = os.getenv("K8S_NAMESPACE", "default")
        api.create_namespaced_job(body=job_definition, namespace=namespace) 
开发者ID:botify-labs,项目名称:simpleflow,代码行数:17,代码来源:k8s.py

示例6: load_incluster_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def load_incluster_config():
    """See `kubernetes.config.load_incluset_config`."""
    kubernetes.config.load_incluster_config() 
开发者ID:CermakM,项目名称:argo-client-python,代码行数:5,代码来源:__init__.py

示例7: load_kube_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def load_kube_config(**kwargs):
    """See `kubernetes.config.load_kube_config`."""
    kubernetes.config.load_kube_config(**kwargs) 
开发者ID:CermakM,项目名称:argo-client-python,代码行数:5,代码来源:__init__.py

示例8: new_client_from_config

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def new_client_from_config(**kwargs):
    """See `kubernetes.config.new_client_from_config`."""
    return kubernetes.config.new_client_from_config(**kwargs) 
开发者ID:CermakM,项目名称:argo-client-python,代码行数:5,代码来源:__init__.py

示例9: discover

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def discover() -> List[str]:
    """Discover plugins for kubernetes based on the kubernetes service
    discovery configuration(s).

    Returns:
        list[str]: A list of host:port addresses for plugins discovered
            via kubernetes.
    """
    addresses = []

    cfg = config.options.get('plugin.discover.kubernetes')
    if not cfg:
        logger.debug('plugin discovery via Kubernetes is disabled')
        return addresses

    # Currently, everything we want to be able to discover (namely, endpoints)
    # should all be in the same namespace, so we define it globally. If other
    # methods of lookup are added later, we could also have a namespace per
    # resource, e.g. so we can look for endpoints in namespace X and pods in
    # namespace Y, etc.
    #
    # If no namespace is provided via user configuration, if will default to
    # the 'default' namespace.
    ns = config.options.get('plugin.discover.kubernetes.namespace', 'default')
    logger.info('plugin discovery via Kubernetes is enabled', namespace=ns)

    # Currently, we only support plugin discovery via kubernetes service
    # endpoints, under the `plugin.discover.kubernetes.endpoints` config
    # field.
    #
    # We can support other means later.
    endpoints_cfg = cfg.get('endpoints')
    if endpoints_cfg:
        addresses.extend(_register_from_endpoints(ns=ns, cfg=endpoints_cfg))
    else:
        # Since we currently only support endpoint discovery, if Kubernetes
        # discovery is configured, but there are no endpoints, issue a warning,
        # since this smells like a configuration issue.
        logger.warning('found no configured endpoints for plugin discovery via Kubernetes')

    return addresses 
开发者ID:vapor-ware,项目名称:synse-server,代码行数:43,代码来源:kubernetes.py

示例10: pytest_configure

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def pytest_configure(config):
    config.addinivalue_line('markers', "e2e: end-to-end tests with real operators.")
    config.addinivalue_line('markers', "resource_clustered: (internal parameterizatiom mark).")

    # Unexpected warnings should fail the tests. Use `-Wignore` to explicitly disable it.
    config.addinivalue_line('filterwarnings', 'error')

    # Warnings from the testing tools out of our control should not fail the tests.
    config.addinivalue_line('filterwarnings', 'ignore:"@coroutine":DeprecationWarning:asynctest.mock')
    config.addinivalue_line('filterwarnings', 'ignore:The loop argument:DeprecationWarning:aiohttp')
    config.addinivalue_line('filterwarnings', 'ignore:The loop argument:DeprecationWarning:aiojobs')
    config.addinivalue_line('filterwarnings', 'ignore:The loop argument:DeprecationWarning:asyncio.queues')  # aiojobs 
开发者ID:zalando-incubator,项目名称:kopf,代码行数:14,代码来源:conftest.py

示例11: pytest_collection_modifyitems

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def pytest_collection_modifyitems(config, items):

    # Put all e2e tests to the end, as they are assumed to be slow.
    def _is_e2e(item):
        path = item.location[0]
        return path.startswith('tests/e2e/') or path.startswith('examples/')
    etc = [item for item in items if not _is_e2e(item)]
    e2e = [item for item in items if _is_e2e(item)]

    # Mark all e2e tests, no matter how they were detected. Just for filtering.
    mark_e2e = pytest.mark.e2e
    for item in e2e:
        item.add_marker(mark_e2e)

    # Minikube tests are heavy and require a cluster. Skip them by default,
    # so that the contributors can run pytest without initial tweaks.
    mark_skip = pytest.mark.skip(reason="E2E tests are not enabled. "
                                        "Use --with-e2e/--only-e2e to enable.")
    if not config.getoption('--with-e2e') and not config.getoption('--only-e2e'):
        for item in e2e:
            item.add_marker(mark_skip)

    # Minify the test-plan if only e2e are requested (all other should be skipped).
    if config.getoption('--only-e2e'):
        items[:] = e2e
    else:
        items[:] = etc + e2e


# Substitute the regular mock with the async-aware mock in the `mocker` fixture. 
开发者ID:zalando-incubator,项目名称:kopf,代码行数:32,代码来源:conftest.py

示例12: enforce_asyncio_mocker

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def enforce_asyncio_mocker():
    pytest_mock.plugin._get_mock_module = lambda config: asynctest
    pytest_mock._get_mock_module = pytest_mock.plugin._get_mock_module 
开发者ID:zalando-incubator,项目名称:kopf,代码行数:5,代码来源:conftest.py

示例13: login_mocks

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def login_mocks(mocker):
    """
    Make all client libraries potentially optional, but do not skip the tests:
    skipping the tests is the tests' decision, not this mocking fixture's one.
    """
    kwargs = {}
    try:
        import pykube
    except ImportError:
        pass
    else:
        cfg = pykube.KubeConfig({
            'current-context': 'self',
            'clusters': [{'name': 'self',
                          'cluster': {'server': 'localhost'}}],
            'contexts': [{'name': 'self',
                          'context': {'cluster': 'self', 'namespace': 'default'}}],
        })
        kwargs.update(
            pykube_in_cluster=mocker.patch.object(pykube.KubeConfig, 'from_service_account', return_value=cfg),
            pykube_from_file=mocker.patch.object(pykube.KubeConfig, 'from_file', return_value=cfg),
        )
    try:
        import kubernetes
    except ImportError:
        pass
    else:
        kwargs.update(
            client_in_cluster=mocker.patch.object(kubernetes.config, 'load_incluster_config'),
            client_from_file=mocker.patch.object(kubernetes.config, 'load_kube_config'),
        )
    return LoginMocks(**kwargs) 
开发者ID:zalando-incubator,项目名称:kopf,代码行数:34,代码来源:conftest.py

示例14: app

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def app(request, io_loop, _binderhub_config):
    """Launch the BinderHub app

    Currently reads minikube test config from the repo.
    TODO: support input of test config files.

    Detects whether kubernetes is available, and if not disables build.
    Detects whether jupyterhub is available, and if not disables launch.

    app.url will contain the base URL of binderhub.
    """
    if REMOTE_BINDER:
        app = RemoteBinderHub()
        # wait for the remote binder to be up
        remaining = 30
        deadline = time.monotonic() + remaining
        success = False
        last_error = None
        while remaining:
            try:
                requests.get(BINDER_URL, timeout=remaining)
            except Exception as e:
                print(f"Waiting for binder: {e}")
                last_error = e
                time.sleep(1)
                remaining = deadline - time.monotonic()
            else:
                success = True
                break
        if not success:
            raise last_error
        app.url = BINDER_URL
        app._configured_bhub = BinderHub(config=_binderhub_config)
        return app

    if hasattr(request, 'param') and request.param is True:
        # load conf for auth test
        cfg = PyFileConfigLoader(minikube_testing_auth_config).load_config()
        _binderhub_config.merge(cfg)
    bhub = BinderHub.instance(config=_binderhub_config)
    bhub.initialize([])
    bhub.start(run_loop=False)
    # instantiating binderhub configures this
    # override again
    AsyncHTTPClient.configure(MockAsyncHTTPClient)

    def cleanup():
        bhub.stop()
        BinderHub.clear_instance()

    request.addfinalizer(cleanup)
    # convenience for accessing binder in tests
    bhub.url = f'http://127.0.0.1:{bhub.port}{bhub.base_url}'.rstrip('/')
    return bhub 
开发者ID:jupyterhub,项目名称:binderhub,代码行数:56,代码来源:conftest.py

示例15: testLaunch_loadKubeConfigSucceed

# 需要导入模块: import kubernetes [as 别名]
# 或者: from kubernetes import config [as 别名]
def testLaunch_loadKubeConfigSucceed(self, mock_core_api_cls,
                                       mock_kube_config, mock_incluster_config,
                                       mock_publisher):
    mock_publisher.return_value.publish_execution.return_value = {}
    mock_incluster_config.side_effect = config.config_exception.ConfigException(
    )
    core_api = mock_core_api_cls.return_value
    core_api.read_namespaced_pod.side_effect = [
        client.rest.ApiException(status=404),  # Mock no existing pod state.
        self._mock_executor_pod(
            'Pending'),  # Mock pending state after creation.
        self._mock_executor_pod('Running'),  # Mock running state after pending.
        self._mock_executor_pod('Succeeded'),  # Mock Succeeded state.
    ]
    # Mock successful pod creation.
    core_api.create_namespaced_pod.return_value = client.V1Pod()
    core_api.read_namespaced_pod_log.return_value.stream.return_value = [
        b'log-1'
    ]
    context = self._create_launcher_context()

    context['launcher'].launch()

    self.assertEqual(4, core_api.read_namespaced_pod.call_count)
    core_api.create_namespaced_pod.assert_called_once()
    core_api.read_namespaced_pod_log.assert_called_once()
    _, mock_kwargs = core_api.create_namespaced_pod.call_args
    self.assertEqual('kubeflow', mock_kwargs['namespace'])
    pod_manifest = mock_kwargs['body']
    self.assertDictEqual(
        {
            'apiVersion': 'v1',
            'kind': 'Pod',
            'metadata': {
                'name': 'test-123-fakecomponent-fakecomponent-123',
            },
            'spec': {
                'restartPolicy':
                    'Never',
                'containers': [{
                    'name': 'main',
                    'image': 'gcr://test',
                    'command': None,
                    'args': [context['input_artifact'].uri],
                }],
            }
        }, pod_manifest) 
开发者ID:tensorflow,项目名称:tfx,代码行数:49,代码来源:kubernetes_component_launcher_test.py


注:本文中的kubernetes.config方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。