Python kubernetes.client.AppsV1Api() Examples

The following are 30 code examples of kubernetes.client.AppsV1Api(). 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: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 7 votes vote down vote up
def scale_statefulset(name: str, replicas: int, ns: str = "default",
                      secrets: Secrets = None):
    """
    Scale a stateful set up or down. The `name` is the name of the stateful
    set.
    """
    api = create_k8s_api_client(secrets)

    v1 = client.AppsV1Api(api)
    body = {"spec": {"replicas": replicas}}
    try:
        v1.patch_namespaced_stateful_set(name, namespace=ns, body=body)
    except ApiException as e:
        raise ActivityFailed(
            "failed to scale '{s}' to {r} replicas: {e}".format(
                s=name, r=replicas, e=str(e))) 
Example #3
Source File: redis.py    From coach with Apache License 2.0 6 votes vote down vote up
def undeploy(self):
        """
        Undeploy the Redis Pub/Sub service in an orchestrator.
        """
        from kubernetes import client
        if self.params.deployed:
            return

        from kubernetes import client
        api_client = client.AppsV1Api()
        delete_options = client.V1DeleteOptions()
        try:
            api_client.delete_namespaced_deployment(self.redis_server_name, self.params.orchestrator_params['namespace'], delete_options)
        except client.rest.ApiException as e:
            print("Got exception: %s\n while deleting redis-server", e)

        api_client = client.CoreV1Api()
        try:
            api_client.delete_namespaced_service(self.redis_service_name, self.params.orchestrator_params['namespace'], delete_options)
        except client.rest.ApiException as e:
            print("Got exception: %s\n while deleting redis-server", e) 
Example #4
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 6 votes vote down vote up
def create_statefulset(spec_path: str, ns: str = "default",
                       secrets: Secrets = None):
    """
    Create a statefulset described by the service config, which must be
    the path to the JSON or YAML representation of the statefulset.
    """
    api = create_k8s_api_client(secrets)

    with open(spec_path) as f:
        p, ext = os.path.splitext(spec_path)
        if ext == '.json':
            statefulset = json.loads(f.read())
        elif ext in ['.yml', '.yaml']:
            statefulset = yaml.safe_load(f.read())
        else:
            raise ActivityFailed(
                "cannot process {path}".format(path=spec_path))

    v1 = client.AppsV1Api(api)
    v1.create_namespaced_stateful_set(ns, body=statefulset) 
Example #5
Source File: nfs_data_store.py    From coach with Apache License 2.0 6 votes vote down vote up
def undeploy_k8s_nfs(self) -> bool:
        from kubernetes import client as k8sclient

        del_options = k8sclient.V1DeleteOptions()

        k8s_apps_v1_api_client = k8sclient.AppsV1Api()
        try:
            k8s_apps_v1_api_client.delete_namespaced_deployment(self.params.name, self.params.namespace, del_options)
        except k8sclient.rest.ApiException as e:
            print("Got exception: %s\n while deleting nfs-server", e)
            return False

        k8s_core_v1_api_client = k8sclient.CoreV1Api()
        try:
            k8s_core_v1_api_client.delete_namespaced_service(self.params.svc_name, self.params.namespace, del_options)
        except k8sclient.rest.ApiException as e:
            print("Got exception: %s\n while deleting the service for nfs-server", e)
            return False

        return True 
Example #6
Source File: client.py    From conu with GNU General Public License v3.0 6 votes vote down vote up
def get_apps_api():
    """
    Create instance of Apps V1 API of kubernetes:
    https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md
    :return: instance of client
    """
    global apps_api

    if apps_api is None:
        config.load_kube_config()
        if API_KEY is not None:
            # Configure API key authorization: BearerToken
            configuration = client.Configuration()
            configuration.api_key['authorization'] = API_KEY
            configuration.api_key_prefix['authorization'] = 'Bearer'
            apps_api = client.AppsV1Api(client.ApiClient(configuration))
        else:
            apps_api = client.AppsV1Api()

    return apps_api 
Example #7
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_namespaced_apps_deployment_from_yaml(self):
        """
        Should be able to create an apps/v1beta1 deployment
		in a test namespace.
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "apps-deployment.yaml",
            namespace=self.test_namespace)
        app_api = client.AppsV1Api(k8s_client)
        dep = app_api.read_namespaced_deployment(name="nginx-app",
                                                 namespace=self.test_namespace)
        self.assertIsNotNone(dep)
        app_api.delete_namespaced_deployment(
            name="nginx-app", namespace=self.test_namespace,
            body={}) 
Example #8
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_from_list_in_multi_resource_yaml(self):
        """
        Should be able to create the items in the PodList and a deployment
        specified in the multi-resource file
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "multi-resource-with-list.yaml")
        core_api = client.CoreV1Api(k8s_client)
        app_api = client.AppsV1Api(k8s_client)
        pod_0 = core_api.read_namespaced_pod(
            name="mock-pod-0", namespace="default")
        self.assertIsNotNone(pod_0)
        pod_1 = core_api.read_namespaced_pod(
            name="mock-pod-1", namespace="default")
        self.assertIsNotNone(pod_1)
        dep = app_api.read_namespaced_deployment(
            name="mock", namespace="default")
        self.assertIsNotNone(dep)
        core_api.delete_namespaced_pod(
            name="mock-pod-0", namespace="default", body={})
        core_api.delete_namespaced_pod(
            name="mock-pod-1", namespace="default", body={})
        app_api.delete_namespaced_deployment(
            name="mock", namespace="default", body={}) 
Example #9
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_general_list_from_yaml(self):
        """
        Should be able to create a service and a deployment
        from a kind: List yaml file
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "list.yaml")
        core_api = client.CoreV1Api(k8s_client)
        ext_api = client.AppsV1Api(k8s_client)
        svc = core_api.read_namespaced_service(name="list-service-test",
                                               namespace="default")
        self.assertIsNotNone(svc)
        dep = ext_api.read_namespaced_deployment(name="list-deployment-test",
                                                 namespace="default")
        self.assertIsNotNone(dep)
        core_api.delete_namespaced_service(name="list-service-test",
                                           namespace="default", body={})
        ext_api.delete_namespaced_deployment(name="list-deployment-test",
                                             namespace="default", body={}) 
Example #10
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_apps_deployment_from_yaml(self):
        """
        Should be able to create an apps/v1 deployment.
        """
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        utils.create_from_yaml(
            k8s_client, self.path_prefix + "apps-deployment.yaml")
        app_api = client.AppsV1Api(k8s_client)
        dep = app_api.read_namespaced_deployment(name="nginx-app",
                                                 namespace="default")
        self.assertIsNotNone(dep)
        while True:
            try:
                app_api.delete_namespaced_deployment(
                    name="nginx-app", namespace="default",
                    body={})
                break
            except ApiException:
                continue 
Example #11
Source File: deployment_crud.py    From python with Apache License 2.0 6 votes vote down vote up
def main():
    # Configs can be set in Configuration class directly or using helper
    # utility. If no argument provided, the config will be loaded from
    # default location.
    config.load_kube_config()
    apps_v1 = client.AppsV1Api()

    # Uncomment the following lines to enable debug logging
    # c = client.Configuration()
    # c.debug = True
    # apps_v1 = client.AppsV1Api(api_client=client.ApiClient(configuration=c))

    # Create a deployment object with client-python API. The deployment we
    # created is same as the `nginx-deployment.yaml` in the /examples folder.
    deployment = create_deployment_object()

    create_deployment(apps_v1, deployment)

    update_deployment(apps_v1, deployment)

    delete_deployment(apps_v1) 
Example #12
Source File: test_utils.py    From python with Apache License 2.0 6 votes vote down vote up
def test_create_apps_deployment_from_yaml_obj(self):
        k8s_client = client.api_client.ApiClient(configuration=self.config)
        with open(self.path_prefix + "apps-deployment.yaml") as f:
            yml_obj = yaml.safe_load(f)

        yml_obj["metadata"]["name"] = "nginx-app-3"

        utils.create_from_dict(k8s_client, yml_obj)

        app_api = client.AppsV1Api(k8s_client)
        dep = app_api.read_namespaced_deployment(name="nginx-app-3",
                                                 namespace="default")
        self.assertIsNotNone(dep)
        app_api.delete_namespaced_deployment(
            name="nginx-app-3", namespace="default",
            body={}) 
Example #13
Source File: ingress_create.py    From python with Apache License 2.0 6 votes vote down vote up
def main():
    # Fetching and loading local Kubernetes Information
    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()
    networking_v1_beta1_api = client.NetworkingV1beta1Api()

    create_deployment(apps_v1_api)
    create_service()
    create_ingress(networking_v1_beta1_api) 
Example #14
Source File: k8s.py    From eks-rolling-update with Apache License 2.0 6 votes vote down vote up
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 #15
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 #16
Source File: deployment_create.py    From python with Apache License 2.0 6 votes vote down vote up
def main():
    # Configs can be set in Configuration class directly or using helper
    # utility. If no argument provided, the config will be loaded from
    # default location.
    config.load_kube_config()

    with open(path.join(path.dirname(__file__), "nginx-deployment.yaml")) as f:
        dep = yaml.safe_load(f)
        k8s_apps_v1 = client.AppsV1Api()
        resp = k8s_apps_v1.create_namespaced_deployment(
            body=dep, namespace="default")
        print("Deployment created. status='%s'" % resp.metadata.name) 
Example #17
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 5 votes vote down vote up
def remove_statefulset(name: str = None, ns: str = "default",
                       label_selector: str = None, secrets: Secrets = None):
    """
    Remove a statefulset by `name` in the namespace `ns`.

    The statefulset is removed by deleting it without
        a graceful period to trigger an abrupt termination.

    The selected resources are matched by the given `label_selector`.
    """
    field_selector = "metadata.name={name}".format(name=name)
    api = create_k8s_api_client(secrets)

    v1 = client.AppsV1Api(api)
    if label_selector:
        ret = v1.list_namespaced_stateful_set(
            ns, field_selector=field_selector,
            label_selector=label_selector)
    else:
        ret = v1.list_namespaced_stateful_set(ns,
                                              field_selector=field_selector)

    logger.debug("Found {d} statefulset(s) named '{n}' in ns '{s}'".format(
        d=len(ret.items), n=name, s=ns))

    body = client.V1DeleteOptions()
    for d in ret.items:
        res = v1.delete_namespaced_stateful_set(
            d.metadata.name, ns, body=body) 
Example #18
Source File: ctx.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_apps_api(self):
        cfg = self.get_kubecfg()
        return client.AppsV1Api(cfg) 
Example #19
Source File: manager.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def k8s_apps_api(self):
        if not self._k8s_apps_api:
            self._k8s_apps_api = client.AppsV1Api(self.api_client)
        return self._k8s_apps_api 
Example #20
Source File: replicaset.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs) -> None:
        super(ReplicaSet, self).__init__(*args, **kwargs)
        self._add_kubetest_labels()

        client.AppsV1Api.read_namespaced_replica_set() 
Example #21
Source File: test_base.py    From node with Apache License 2.0 5 votes vote down vote up
def update_ds_env(self, ds, ns, env_vars):
        config.load_kube_config(os.environ.get('KUBECONFIG'))
        api = client.AppsV1Api(client.ApiClient())
        node_ds = api.read_namespaced_daemon_set(ds, ns, exact=True, export=True)
        for container in node_ds.spec.template.spec.containers:
            if container.name == ds:
                for k, v in env_vars.items():
                    logger.info("Set %s=%s", k, v)
                    env_present = False
                    for env in container.env:
                        if env.name == k:
                            env_present = True
                    if not env_present:
                        v1_ev = client.V1EnvVar(name=k, value=v, value_from=None)
                        container.env.append(v1_ev)
        api.replace_namespaced_daemon_set(ds, ns, node_ds)

        # Wait until the DaemonSet reports that all nodes have been updated.
        while True:
            time.sleep(10)
            node_ds = api.read_namespaced_daemon_set_status("calico-node", "kube-system")
            logger.info("%d/%d nodes updated",
                      node_ds.status.updated_number_scheduled,
                      node_ds.status.desired_number_scheduled)
            if node_ds.status.updated_number_scheduled == node_ds.status.desired_number_scheduled:
                break 
Example #22
Source File: test_base.py    From node with Apache License 2.0 5 votes vote down vote up
def check_calico_version(self):
        config.load_kube_config(os.environ.get('KUBECONFIG'))
        api = client.AppsV1Api(client.ApiClient())
        node_ds = api.read_namespaced_daemon_set("calico-node", "kube-system", exact=True, export=True)
        for container in node_ds.spec.template.spec.containers:
            if container.name == "calico-node":
                if container.image != "calico/node:latest-amd64":
                    container.image = "calico/node:latest-amd64"
                    api.replace_namespaced_daemon_set("calico-node", "kube-system", node_ds)
                    time.sleep(3)
                    retry_until_success(self.check_pod_status, retries=20, wait_time=3, function_args=["kube-system"]) 
Example #23
Source File: test_base.py    From node with Apache License 2.0 5 votes vote down vote up
def deploy(self, image, name, ns, port, replicas=1, svc_type="NodePort", traffic_policy="Local", cluster_ip=None, ipv6=False):
        """
        Creates a deployment and corresponding service with the given
        parameters.
        """
        # Run a deployment with <replicas> copies of <image>, with the
        # pods labelled with "app": <name>.
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=name),
            spec=client.V1DeploymentSpec(
                replicas=replicas,
                selector={'matchLabels': {'app': name}},
                template=client.V1PodTemplateSpec(
                    metadata=client.V1ObjectMeta(labels={"app": name}),
                    spec=client.V1PodSpec(containers=[
                        client.V1Container(name=name,
                                           image=image,
                                           ports=[client.V1ContainerPort(container_port=port)]),
                    ]))))
        api_response = client.AppsV1Api().create_namespaced_deployment(
            body=deployment,
            namespace=ns)
        logger.debug("Deployment created. status='%s'" % str(api_response.status))

        # Create a service called <name> whose endpoints are the pods
        # with "app": <name>; i.e. those just created above.
        self.create_service(name, name, ns, port, svc_type, traffic_policy, ipv6=ipv6) 
Example #24
Source File: kubernetes_utils.py    From tacker with Apache License 2.0 5 votes vote down vote up
def get_app_v1_api_client(self, auth):
        k8s_client = self.get_k8s_client(auth_plugin=auth)
        return client.AppsV1Api(api_client=k8s_client) 
Example #25
Source File: test_e2e.py    From illuminatio with Apache License 2.0 5 votes vote down vote up
def apps_v1(load_kube_config):
    return client.AppsV1Api() 
Example #26
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def apps_api_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.AppsV1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.AppsV1Api(api_client=client) 
Example #27
Source File: k8s.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def daemonset():
    try:
        valus = defaultdict()
        v1 = client.AppsV1Api()
        tables = ('name','namespace', 'images', 'mount_path', 'cpu_limit','mem_limit','number_ready')
        keys  = ('namespace', 'images', 'mount_path', 'cpu_limit','mem_limit','number_ready')
        ret = v1.list_daemon_set_for_all_namespaces()
        for i in ret.items:
            try:
                mount_path = []
                for path in i.spec.template.spec.containers[0].volume_mounts:
                    mount_path.append(path.mount_path)
                number_ready = i.status.number_ready
                if number_ready == 0:
                    number_ready = 1
                cpu_limit = 'None'
                mem_limit = 'None'
                limits = i.spec.template.spec.containers[0].resources.limits
                if limits:
                    if 'cpu' in limits:
                        cpu_limit = limits['cpu']
                    if 'memory' in limits:
                        mem_limit = limits['memory']
                valus[i.metadata.name]={
                    'namespace':i.metadata.namespace,
                    'images':i.spec.template.spec.containers[0].image,
                    'mount_path':mount_path,
                    'cpu_limit':cpu_limit,
                    'mem_limit':mem_limit,
                    'number_ready': number_ready
                }
            except Exception as e:
                logging.error(e)
        return render_template('k8s-resource.html', valus=valus, tables=tables, keys=keys, resource='Daemonset')
    except Exception as e:
        logging.error(e) 
Example #28
Source File: k8s.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def deployment():
    try:
        valus = defaultdict()
        v1 = client.AppsV1Api()
        tables = ('name','namespace', 'replicas', 'strategy', 'containers','cpu_limit','mem_limit','available')
        keys  = ('namespace', 'replicas', 'strategy', 'containers','cpu_limit','mem_limit','available')
        ret = v1.list_deployment_for_all_namespaces()
        for i in ret.items:
            try:
                containers = []
                for info in i.spec.template.spec.containers:
                    containers.append(info.name)
                if not i.status.unavailable_replicas:
                    available = 100
                else:
                    available = int((float(i.spec.replicas)-float(i.status.unavailable_replicas))/float(i.spec.replicas)*100)
                cpu_limit = 'None'
                mem_limit = 'None'
                limits = i.spec.template.spec.containers[0].resources.limits
                if limits:
                    if 'cpu' in limits:
                        cpu_limit = limits['cpu']
                    if 'memory' in limits:
                        mem_limit = limits['memory']
                valus[i.metadata.name]={
                    'namespace':i.metadata.namespace,
                    'replicas':i.spec.replicas,
                    'strategy':i.spec.strategy.type,
                    'containers':containers,
                    'cpu_limit':cpu_limit,
                    'mem_limit':mem_limit,
                    'available':available
                }

            except Exception as e:
                logging.error(e)
        return render_template('k8s-resource.html', valus=valus, tables=tables, keys=keys, resource='Deployment')
    except Exception as e:
        logging.error(e) 
Example #29
Source File: conftest.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def apps_api_instance(configuration):
    return client.AppsV1Api(K8sApiClient(configuration)) 
Example #30
Source File: kubernetes_resources.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def get_k8s_apps_api_client(id_token):
    apps_api_client = client.AppsV1Api(get_simple_client(id_token))
    return apps_api_client