Python kubernetes.config.ConfigException() Examples
The following are 10
code examples of kubernetes.config.ConfigException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
kubernetes.config
, or try the search function
.
Example #1
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 8 votes |
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
Example #2
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 7 votes |
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))
Example #3
Source File: reflector.py From kubespawner with BSD 3-Clause "New" or "Revised" License | 7 votes |
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()
Example #4
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 6 votes |
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)
Example #5
Source File: core.py From kale with Apache License 2.0 | 6 votes |
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
Example #6
Source File: test_k8s.py From CPU-Manager-for-Kubernetes with Apache License 2.0 | 6 votes |
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
Example #7
Source File: pipeline.py From freight with Apache License 2.0 | 5 votes |
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)
Example #8
Source File: kube_utils.py From tfx with Apache License 2.0 | 5 votes |
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
Example #9
Source File: k8s.py From eks-rolling-update with Apache License 2.0 | 4 votes |
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))
Example #10
Source File: kubernetes.py From patroni with MIT License | 4 votes |
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)