本文整理汇总了Python中kubernetes.config.ConfigException方法的典型用法代码示例。如果您正苦于以下问题:Python config.ConfigException方法的具体用法?Python config.ConfigException怎么用?Python config.ConfigException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kubernetes.config
的用法示例。
在下文中一共展示了config.ConfigException方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_k8s_nodes
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def get_k8s_nodes(exclude_node_label_key=app_config["EXCLUDE_NODE_LABEL_KEY"]):
"""
Returns a list of kubernetes nodes
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
k8s_api = client.CoreV1Api()
logger.info("Getting k8s nodes...")
response = k8s_api.list_node()
if exclude_node_label_key is not None:
nodes = []
for node in response.items:
if exclude_node_label_key not in node.metadata.labels:
nodes.append(node)
response.items = nodes
logger.info("Current k8s node count is {}".format(len(response.items)))
return response.items
示例2: delete_node
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def delete_node(node_name):
"""
Deletes a kubernetes node from the cluster
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Deleting k8s node {}...".format(node_name))
try:
if not app_config['DRY_RUN']:
k8s_api.delete_node(node_name)
else:
k8s_api.delete_node(node_name, dry_run="true")
logger.info("Node deleted")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->delete_node: {}".format(e))
示例3: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Load kubernetes config here, since this is a Singleton and
# so this __init__ will be run way before anything else gets run.
try:
config.load_incluster_config()
except config.ConfigException:
config.load_kube_config()
self.api = shared_client(self.api_group_name)
# FIXME: Protect against malicious labels?
self.label_selector = ','.join(['{}={}'.format(k, v) for k, v in self.labels.items()])
self.field_selector = ','.join(['{}={}'.format(k, v) for k, v in self.fields.items()])
self.first_load_future = Future()
self._stop_event = threading.Event()
self.start()
示例4: detect_environment
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def detect_environment(self):
"""Detect local confs to preserve reproducibility in pipeline steps."""
# When running inside a Kubeflow Notebook Server we can detect the
# running docker image and use it as default in the pipeline steps.
if not self.pipeline_metadata['docker_image']:
docker_image = ""
try:
# will fail in case in cluster config is not found
docker_image = get_docker_base_image()
except ConfigException:
# no K8s config found
# use kfp default image
pass
except Exception:
# some other exception
raise
self.pipeline_metadata["docker_image"] = docker_image
示例5: test_k8s_core_client_from_config
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def test_k8s_core_client_from_config():
with pytest.raises(ConfigException) as err:
k8s.client_from_config(None)
# Client from in-cluster configuration should throws error if it's not
# executed within pod in Kubernetes cluster.
assert err is not None
# If we use valid configuration for Kubernetes client, it should be
# created.
config = k8sclient.Configuration()
config.host = "https://somenonexistedlocation.com:443"
client = k8s.client_from_config(config)
with pytest.raises(MaxRetryError) as err:
# It should when we will use it to call Kubernetes API.
client.list_node()
assert err is not None
示例6: modify_k8s_autoscaler
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def modify_k8s_autoscaler(action):
"""
Pauses or resumes the Kubernetes autoscaler
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
# Configure API key authorization: BearerToken
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.AppsV1Api(client.ApiClient(configuration))
if action == 'pause':
logger.info('Pausing k8s autoscaler...')
body = {'spec': {'replicas': 0}}
elif action == 'resume':
logger.info('Resuming k8s autoscaler...')
body = {'spec': {'replicas': app_config['K8S_AUTOSCALER_REPLICAS']}}
else:
logger.info('Invalid k8s autoscaler option')
sys.exit(1)
try:
k8s_api.patch_namespaced_deployment(
app_config['K8S_AUTOSCALER_DEPLOYMENT'],
app_config['K8S_AUTOSCALER_NAMESPACE'],
body
)
logger.info('K8s autoscaler modified to replicas: {}'.format(body['spec']['replicas']))
except ApiException as e:
logger.info('Scaling of k8s autoscaler failed. Error code was {}, {}. Exiting.'.format(e.reason, e.body))
sys.exit(1)
示例7: cordon_node
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def cordon_node(node_name):
"""
Cordon a kubernetes node to avoid new pods being scheduled on it
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Cordoning k8s node {}...".format(node_name))
try:
api_call_body = client.V1Node(spec=client.V1NodeSpec(unschedulable=True))
if not app_config['DRY_RUN']:
k8s_api.patch_node(node_name, api_call_body)
else:
k8s_api.patch_node(node_name, api_call_body, dry_run=True)
logger.info("Node cordoned")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->patch_node: {}".format(e))
示例8: load_kube_credentials_gcloud
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def load_kube_credentials_gcloud(credentials: Dict[str, str]) -> ApiClient:
# Try to pull credentials from gcloud, but first checking if there
# is a context, using their auto generated naming scheme, to avoid
# calling `gcloud` every time, if we've already authed before.
from subprocess import check_call, DEVNULL
cluster = credentials["cluster"]
project = credentials["project"]
zone = credentials["zone"]
context = f"gke_{project}_{zone}_{cluster}"
try:
return new_client_from_config(context=context)
except (ConfigException, FileNotFoundError):
pass
check_call(
[
"gcloud",
"container",
"clusters",
"get-credentials",
cluster,
"--zone",
zone,
"--project",
project,
],
stdout=DEVNULL,
stderr=DEVNULL,
)
return new_client_from_config(context=context)
示例9: _LoadConfig
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def _LoadConfig(self) -> None: # pylint: disable=invalid-name
"""Load the kubernetes client config.
Depending on the environment (whether it is inside the running kubernetes
cluster or remote host), different location will be searched for the config
file. The loaded config will be used as a default value for the clients this
factory is creating.
If config is already loaded, it is a no-op.
Raises:
kubernetes.config.ConfigException: If fails to locate configuration in
current environment.
"""
try:
# If this code is running inside Kubernetes Pod, service account admission
# controller [1] sets volume mounts in which the service account tokens
# and certificates exists, and it can be loaded using
# `load_incluster_config()`.
#
# [1]
# https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/#service-account-admission-controller
self._inside_cluster = True
k8s_config.load_incluster_config()
except k8s_config.ConfigException:
# If loading incluster config fails, it means we're not running the code
# inside Kubernetes cluster. We try to load ~/.kube/config file, or the
# filename from the KUBECONFIG environment variable.
# It will raise kubernetes.config.ConfigException if no kube config file
# is found.
self._inside_cluster = False
k8s_config.load_kube_config()
self._config_loaded = True
示例10: __init__
# 需要导入模块: from kubernetes import config [as 别名]
# 或者: from kubernetes.config import ConfigException [as 别名]
def __init__(self, config):
self._labels = config['labels']
self._labels[config.get('scope_label', 'cluster-name')] = config['scope']
self._label_selector = ','.join('{0}={1}'.format(k, v) for k, v in self._labels.items())
self._namespace = config.get('namespace') or 'default'
self._role_label = config.get('role_label', 'role')
config['namespace'] = ''
super(Kubernetes, self).__init__(config)
self._retry = Retry(deadline=config['retry_timeout'], max_delay=1, max_tries=-1,
retry_exceptions=(KubernetesRetriableException, HTTPException,
HTTPError, socket.error, socket.timeout))
self._ttl = None
try:
k8s_config.load_incluster_config()
except k8s_config.ConfigException:
k8s_config.load_kube_config(context=config.get('context', 'local'))
self.__my_pod = None
self.__ips = [] if config.get('patronictl') else [config.get('pod_ip')]
self.__ports = []
for p in config.get('ports', [{}]):
port = {'port': int(p.get('port', '5432'))}
port.update({n: p[n] for n in ('name', 'protocol') if p.get(n)})
self.__ports.append(k8s_client.V1EndpointPort(**port))
self._api = CoreV1ApiProxy(config.get('use_endpoints'))
self._should_create_config_service = self._api.use_endpoints
self.reload_config(config)
# leader_observed_record, leader_resource_version, and leader_observed_time are used only for leader race!
self._leader_observed_record = {}
self._leader_observed_time = None
self._leader_resource_version = None
self.__do_not_watch = False
self._condition = Condition()
pods_func = functools.partial(self._api.list_namespaced_pod, self._namespace,
label_selector=self._label_selector)
self._pods = ObjectCache(self, pods_func, self._retry, self._condition)
kinds_func = functools.partial(self._api.list_namespaced_kind, self._namespace,
label_selector=self._label_selector)
self._kinds = ObjectCache(self, kinds_func, self._retry, self._condition, self._name)