Python kubernetes.client.CustomObjectsApi() Examples

The following are 18 code examples of kubernetes.client.CustomObjectsApi(). 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.client , or try the search function .
Example #1
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 9 votes vote down vote up
def __init__(self) -> None:
        kube_config.load_kube_config(
            config_file=os.environ.get("KUBECONFIG", KUBE_CONFIG_PATH),
            context=os.environ.get("KUBECONTEXT"),
        )
        models.V1beta1PodDisruptionBudgetStatus.disrupted_pods = property(
            fget=lambda *args, **kwargs: models.V1beta1PodDisruptionBudgetStatus.disrupted_pods(
                *args, **kwargs
            ),
            fset=_set_disrupted_pods,
        )
        self.deployments = kube_client.AppsV1Api()
        self.core = kube_client.CoreV1Api()
        self.policy = kube_client.PolicyV1beta1Api()
        self.apiextensions = kube_client.ApiextensionsV1beta1Api()
        self.custom = kube_client.CustomObjectsApi()
        self.autoscaling = kube_client.AutoscalingV2beta1Api()
        self.request = kube_client.ApiClient().request 
Example #2
Source File: adapters.py    From k8s-handle with Apache License 2.0 8 votes vote down vote up
def get_instance(spec, api_custom_objects=None, api_resources=None):
        # due to https://github.com/kubernetes-client/python/issues/387
        if spec.get('kind') in Adapter.kinds_builtin:
            if spec.get('apiVersion') == 'test/test':
                return AdapterBuiltinKind(spec, K8sClientMock(spec.get('metadata', {}).get('name')))

            api = Adapter.api_versions.get(spec.get('apiVersion'))

            if not api:
                return None

            return AdapterBuiltinKind(spec, api())

        api_custom_objects = api_custom_objects or client.CustomObjectsApi()
        api_resources = api_resources or ResourcesAPI()
        return AdapterCustomKind(spec, api_custom_objects, api_resources) 
Example #3
Source File: k8s.py    From armada with Apache License 2.0 6 votes vote down vote up
def __init__(self, bearer_token=None):
        '''
        Initialize connection to Kubernetes
        '''
        self.bearer_token = bearer_token
        api_client = None

        try:
            config.load_incluster_config()
        except config.config_exception.ConfigException:
            config.load_kube_config()

        if self.bearer_token:
            # Configure API key authorization: Bearer Token
            configuration = client.Configuration()
            configuration.api_key_prefix['authorization'] = 'Bearer'
            configuration.api_key['authorization'] = self.bearer_token
            api_client = client.ApiClient(configuration)

        self.client = client.CoreV1Api(api_client)
        self.batch_api = client.BatchV1Api(api_client)
        self.batch_v1beta1_api = client.BatchV1beta1Api(api_client)
        self.custom_objects = client.CustomObjectsApi(api_client)
        self.api_extensions = client.ApiextensionsV1beta1Api(api_client)
        self.extension_api = client.ExtensionsV1beta1Api(api_client)
        self.apps_v1_api = client.AppsV1Api(api_client) 
Example #4
Source File: kubernetes.py    From airflow with Apache License 2.0 5 votes vote down vote up
def create_custom_resource_definition(self,
                                          group: str,
                                          version: str,
                                          plural: str,
                                          body: Union[str, dict],
                                          namespace: Optional[str] = None
                                          ):
        """
        Creates custom resource definition object in Kubernetes

        :param group: api group
        :type group: str
        :param version: api version
        :type version: str
        :param plural: api plural
        :type plural: str
        :param body: crd object definition
        :type body: Union[str, dict]
        :param namespace: kubernetes namespace
        :type namespace: str
        """
        api = client.CustomObjectsApi(self.get_conn())
        if namespace is None:
            namespace = self.get_namespace()
        if isinstance(body, str):
            body = _load_body_to_dict(body)
        try:
            response = api.create_namespaced_custom_object(
                group=group,
                version=version,
                namespace=namespace,
                plural=plural,
                body=body
            )
            self.log.debug("Response: %s", response)
            return response
        except client.rest.ApiException as e:
            raise AirflowException("Exception when calling -> create_custom_resource_definition: %s\n" % e) 
Example #5
Source File: installRunner.py    From ks-installer with Apache License 2.0 5 votes vote down vote up
def generateConfig():
    config.load_incluster_config()
    api = client.CustomObjectsApi()

    resource = api.get_namespaced_custom_object(
        group="installer.kubesphere.io",
        version="v1alpha1",
        name="ks-installer",
        namespace="kubesphere-system",
        plural="clusterconfigurations",
    )
    try:
      with open(configFile, 'w', encoding='utf-8') as f:
        json.dump(resource['spec'], f, ensure_ascii=False, indent=4)
    except:
      with open(configFile, 'w', encoding='utf-8') as f:
        json.dump({"config": "new"}, f, ensure_ascii=False, indent=4)

    try:
      with open(statusFile, 'w', encoding='utf-8') as f:
        json.dump({"status": resource['status']}, f, ensure_ascii=False, indent=4)
    except:
      with open(statusFile, 'w', encoding='utf-8') as f:
        json.dump({"status": {"enabledComponents": []}}, f, ensure_ascii=False, indent=4)


    # cmdGetConfig = r"kubectl get cm -n kubesphere-system ks-installer -o jsonpath='{.data}' | grep -v '\[\|\]' > /kubesphere/config/ks-config.yaml"
    # os.system(cmdGetConfig) 
Example #6
Source File: k8sHelper.py    From openshift-toolkit with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        config.load_kube_config()

        # Make v1 and cv1 as global pointer that can be called from anywhere when this class instantiated.
        global v1
        global cv1
        v1 = client.CoreV1Api()
        cv1 = client.CustomObjectsApi() 
Example #7
Source File: ctx.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_custom_api(self):
        cfg = self.get_kubecfg()
        return client.CustomObjectsApi(cfg) 
Example #8
Source File: manager.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def k8s_custom_object_api(self):
        if not self._k8s_custom_object_api:
            self._k8s_custom_object_api = client.CustomObjectsApi(self.api_client)
        return self._k8s_custom_object_api 
Example #9
Source File: launch_crd.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def __init__(self, group, plural, version, client):
    self.group = group
    self.plural = plural
    self.version = version
    self.client = k8s_client.CustomObjectsApi(client) 
Example #10
Source File: KubernetesService.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self):
        # Create Kubernetes config.
        load_incluster_config()
        config = Configuration()
        config.debug = Settings.KUBERNETES_SERVICE_DEBUG
        self.api_client = client.ApiClient(config)

        # Re-usable API client instances.
        self.core_api = client.CoreV1Api(self.api_client)
        self.custom_objects_api = client.CustomObjectsApi(self.api_client)
        self.extensions_api = client.ApiextensionsV1beta1Api(self.api_client)
        self.apps_api = client.AppsV1beta1Api(self.api_client) 
Example #11
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def __init__(self, token=None, ca_file=None, context=None, multus=True, host='127.0.0.1', port=443,
                 user='root', debug=False, tags=None, namespace=None, cdi=False, datavolumes=True, readwritemany=False):
        Kubecommon.__init__(self, token=token, ca_file=ca_file, context=context, host=host, port=port,
                            namespace=namespace, readwritemany=readwritemany)
        self.crds = client.CustomObjectsApi(api_client=self.api_client)
        self.debug = debug
        self.multus = multus
        self.tags = tags
        self.cdi = False
        self.datavolumes = False
        if cdi:
            try:
                cdipods = self.core.list_pod_for_all_namespaces(label_selector='app=containerized-data-importer').items
                if cdipods:
                    for pod in cdipods:
                        if pod.metadata.name.startswith('cdi-deployment'):
                            self.cdinamespace = pod.metadata.namespace
                            self.cdi = True
                if self.cdi and datavolumes:
                    try:
                        cm = self.core.read_namespaced_config_map('kubevirt-config', KUBEVIRTNAMESPACE)
                        if 'feature-gates' in cm.data and 'DataVolumes' in cm.data['feature-gates']:
                            self.datavolumes = True
                    except:
                        pass
            except:
                pass
        return 
Example #12
Source File: deploy_utils.py    From aws-eks-deep-learning-benchmark with Apache License 2.0 5 votes vote down vote up
def wait_for_benchmark_job(job_name, namespace, timeout_minutes=20, replicas=1):
  """Wait for benchmark to be complete.
  Args:
    namespace: The name space for the deployment.
    job_name: The name of the benchmark workflow.
    timeout_minutes: Timeout interval in minutes.
    replicas: Number of replicas that must be running.
  Returns:
    deploy: The deploy object describing the deployment.
  Raises:
    TimeoutError: If timeout waiting for deployment to be ready.
  """
  end_time = datetime.datetime.now() + datetime.timedelta(minutes=timeout_minutes)
  config.load_kube_config()

  crd_api = k8s_client.CustomObjectsApi()
  GROUP = "argoproj.io"
  VERSION = "v1alpha1"
  PLURAL = "workflows"

  while datetime.datetime.now() < end_time:
    workflow = crd_api.get_namespaced_custom_object(GROUP, VERSION, namespace, PLURAL, job_name)
    if workflow and workflow['status'] and workflow['status']['phase'] and workflow['status']['phase'] == "Succeeded":
      logging.info("Job Completed")
      return workflow
    logging.info("Waiting for job %s:%s", namespace, job_name)
    time.sleep(10)
  logging.error("Timeout waiting for workflow %s in namespace %s to be "
                "complete", job_name, namespace)
  raise TimeoutError(
    "Timeout waiting for deployment {0} in namespace {1}".format(
      job_name, namespace)) 
Example #13
Source File: conftest.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def get_k8s_custom_obj_client(configuration):
    return client.CustomObjectsApi(K8sApiClient(configuration)) 
Example #14
Source File: pod_utils.py    From kale with Apache License 2.0 5 votes vote down vote up
def _get_k8s_custom_objects_client():
    k8s_config.load_incluster_config()
    return k8s.CustomObjectsApi() 
Example #15
Source File: kubernetes.py    From airflow with Apache License 2.0 5 votes vote down vote up
def get_custom_resource_definition(self,
                                       group: str,
                                       version: str,
                                       plural: str,
                                       name: str,
                                       namespace: Optional[str] = None):
        """
        Get custom resource definition object from Kubernetes

        :param group: api group
        :type group: str
        :param version: api version
        :type version: str
        :param plural: api plural
        :type plural: str
        :param name: crd object name
        :type name: str
        :param namespace: kubernetes namespace
        :type namespace: str
        """
        custom_resource_definition_api = client.CustomObjectsApi(self.get_conn())
        if namespace is None:
            namespace = self.get_namespace()
        try:
            response = custom_resource_definition_api.get_namespaced_custom_object(
                group=group,
                version=version,
                namespace=namespace,
                plural=plural,
                name=name
            )
            return response
        except client.rest.ApiException as e:
            raise AirflowException("Exception when calling -> get_custom_resource_definition: %s\n" % e) 
Example #16
Source File: kubernetes_resources.py    From inference-model-manager with Apache License 2.0 4 votes vote down vote up
def get_k8s_api_custom_client(id_token):
    custom_obj_api_instance = client.CustomObjectsApi(get_simple_client(id_token))
    return custom_obj_api_instance 
Example #17
Source File: custom_object.py    From python with Apache License 2.0 4 votes vote down vote up
def main():
    config.load_kube_config()

    api = client.CustomObjectsApi()

    # it's my custom resource defined as Dict
    my_resource = {
        "apiVersion": "stable.example.com/v1",
        "kind": "CronTab",
        "metadata": {"name": "my-new-cron-object"},
        "spec": {
            "cronSpec": "* * * * */5",
            "image": "my-awesome-cron-image"
        }
    }

    # create the resource
    api.create_namespaced_custom_object(
        group="stable.example.com",
        version="v1",
        namespace="default",
        plural="crontabs",
        body=my_resource,
    )
    print("Resource created")

    # get the resource and print out data
    resource = api.get_namespaced_custom_object(
        group="stable.example.com",
        version="v1",
        name="my-new-cron-object",
        namespace="default",
        plural="crontabs",
    )
    print("Resource details:")
    pprint(resource)

    # delete it
    api.delete_namespaced_custom_object(
        group="stable.example.com",
        version="v1",
        name="my-new-cron-object",
        namespace="default",
        plural="crontabs",
        body=client.V1DeleteOptions(),
    )
    print("Resource deleted") 
Example #18
Source File: k8scrhandler.py    From ewm-cloud-robotics with Apache License 2.0 4 votes vote down vote up
def _watch_on_crs(self) -> None:
        """Stream events on orders and execute callbacks."""
        _LOGGER.info(
            '%s/%s: Starting watcher at resourceVersion "%s"',
            self.group, self.plural, self.resv_watcher)
        try:
            self.watcher = watch.Watch()
            stream = self.watcher.stream(
                self.co_api.list_namespaced_custom_object,
                self.group,
                self.version,
                self.namespace,
                self.plural,
                label_selector=self.label_selector,
                resource_version=self.resv_watcher
            )
            for event in stream:
                # Break loop when thread stops
                if not self.thread_run:
                    break
                # Process event
                obj = event['object']
                operation = event['type']
                # Too old resource version error handling
                # https://github.com/kubernetes-client/python/issues/609
                if obj.get('code') == 410:
                    new_version = parse_too_old_failure(obj.get('message'))
                    if new_version is not None:
                        self.resv_watcher = str(new_version)
                        _LOGGER.error(
                            'Updating resource version to %s due to "too old resource version" '
                            'error', new_version)
                        # CRD could be the reason for a too old resource version error
                        # Refresh status update method
                        self.get_status_update_method()
                        break

                # Skip CRs without a spec or without metadata
                metadata = obj.get('metadata')
                if not metadata:
                    continue
                if metadata.get('resourceVersion'):
                    self.resv_watcher = metadata['resourceVersion']
                name = metadata['name']
                labels = metadata.get('labels', {})
                if not obj.get('spec'):
                    continue
                _LOGGER.debug(
                    '%s/%s: Handling %s on %s', self.group, self.plural,
                    operation, name)
                # Submit callbacks to ThreadPoolExecutor
                self.executor.submit(self._callback, name, labels, operation, obj)
        except ApiException as err:
            _LOGGER.error(
                '%s/%s: Exception when watching CustomObjectsApi: %s',
                self.group, self.plural, err)