Python kubernetes.client.AppsV1beta1Api() Examples

The following are 7 code examples of kubernetes.client.AppsV1beta1Api(). 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: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 6 votes vote down vote up
def create_deployment(spec_path: str, ns: str = "default",
                      secrets: Secrets = None):
    """
    Create a deployment described by the deployment config, which must be the
    path to the JSON or YAML representation of the deployment.
    """
    api = create_k8s_api_client(secrets)

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

    v1 = client.AppsV1beta1Api(api)
    resp = v1.create_namespaced_deployment(ns, body=deployment) 
Example #2
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 5 votes vote down vote up
def delete_deployment(name: str, ns: str = "default",
                      label_selector: str = "name in ({name})",
                      secrets: Secrets = None):
    """
    Delete a deployment by `name` in the namespace `ns`.

    The deployment is deleted without a graceful period to trigger an abrupt
    termination.

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

    v1 = client.AppsV1beta1Api(api)
    if label_selector:
        ret = v1.list_namespaced_deployment(ns, label_selector=label_selector)
    else:
        ret = v1.list_namespaced_deployment(ns)

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

    body = client.V1DeleteOptions()
    for d in ret.items:
        v1.delete_namespaced_deployment(d.metadata.name, ns, body=body) 
Example #3
Source File: probes.py    From chaostoolkit-kubernetes with Apache License 2.0 5 votes vote down vote up
def deployment_available_and_healthy(
        name: str, ns: str = "default",
        label_selector: str = None,
        secrets: Secrets = None) -> Union[bool, None]:
    """
    Lookup a deployment by `name` in the namespace `ns`.

    The selected resources are matched by the given `label_selector`.

    Raises :exc:`chaoslib.exceptions.ActivityFailed` when the state is not
    as expected.
    """

    field_selector = "metadata.name={name}".format(name=name)
    api = create_k8s_api_client(secrets)

    v1 = client.AppsV1beta1Api(api)
    if label_selector:
        ret = v1.list_namespaced_deployment(ns, field_selector=field_selector,
                                            label_selector=label_selector)
    else:
        ret = v1.list_namespaced_deployment(ns, field_selector=field_selector)

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

    if not ret.items:
        raise ActivityFailed(
            "Deployment '{name}' was not found".format(name=name))

    for d in ret.items:
        logger.debug("Deployment has '{s}' available replicas".format(
            s=d.status.available_replicas))

        if d.status.available_replicas != d.spec.replicas:
            raise ActivityFailed(
                "Deployment '{name}' is not healthy".format(name=name))

    return True 
Example #4
Source File: pipeline.py    From freight with Apache License 2.0 5 votes vote down vote up
def rollout_status_deployment(
    api: client.AppsV1beta1Api, name: str, namespace: str,
) -> Tuple[str, bool]:
    # tbh this is mostly ported from Go into Python from:
    # https://github.com/kubernetes/kubernetes/blob/master/pkg/kubectl/rollout_status.go#L76-L92
    deployment = api.read_namespaced_deployment(name=name, namespace=namespace)
    if deployment.metadata.generation > deployment.status.observed_generation:
        return (
            f"Waiting for deployment {repr(name)} spec update to be observed...",
            False,
        )

    # TimedOutReason is added in a deployment when its newest replica set
    # fails to show any progress within the given deadline (progressDeadlineSeconds).
    for condition in deployment.status.conditions or []:
        if condition.type == "Progressing":
            if condition.reason == "ProgressDeadlineExceeded":
                return f"deployment {repr(name)} exceeded its progress deadline", False

    spec_replicas = deployment.spec.replicas
    status_replicas = deployment.status.replicas or 0
    updated_replicas = deployment.status.updated_replicas or 0
    available_replicas = deployment.status.available_replicas or 0

    if updated_replicas < spec_replicas:
        return (
            f"Waiting for deployment {repr(name)} rollout to finish: {updated_replicas} out of {spec_replicas} new replicas have been updated...",
            False,
        )
    if status_replicas > updated_replicas:
        return (
            f"Waiting for deployment {repr(name)} rollout to finish: {status_replicas-updated_replicas} old replicas are pending termination...",
            False,
        )
    if available_replicas < updated_replicas:
        return (
            f"Waiting for deployment {repr(name)} rollout to finish: {available_replicas} of {updated_replicas} updated replicas are available...",
            False,
        )
    return f"Deployment {repr(name)} successfully rolled out", True 
Example #5
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 #6
Source File: client.py    From kube-shell with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(__name__)
        try:
            config_file = os.path.expanduser(kubeconfig_filepath)
            config.load_kube_config(config_file=config_file)
        except:
            self.logger.warning("unable to load kube-config")

        self.v1 = client.CoreV1Api()
        self.v1Beta1 = client.AppsV1beta1Api()
        self.extensionsV1Beta1 = client.ExtensionsV1beta1Api()
        self.autoscalingV1Api = client.AutoscalingV1Api()
        self.rbacApi = client.RbacAuthorizationV1beta1Api()
        self.batchV1Api = client.BatchV1Api()
        self.batchV2Api = client.BatchV2alpha1Api() 
Example #7
Source File: probes.py    From chaostoolkit-kubernetes with Apache License 2.0 4 votes vote down vote up
def _deployment_readiness_has_state(
        name: str, ready: bool,
        ns: str = "default",
        label_selector: str = None,
        timeout: int = 30,
        secrets: Secrets = None) -> Union[bool, None]:
    """
    Check wether if the given deployment state is ready or not
    according to the ready paramter.
    If the state is not reached after `timeout` seconds, a
    :exc:`chaoslib.exceptions.ActivityFailed` exception is raised.
    """
    field_selector = "metadata.name={name}".format(name=name)
    api = create_k8s_api_client(secrets)
    v1 = client.AppsV1beta1Api(api)
    w = watch.Watch()
    timeout = int(timeout)

    if label_selector is None:
        watch_events = partial(w.stream, v1.list_namespaced_deployment,
                               namespace=ns,
                               field_selector=field_selector,
                               _request_timeout=timeout)
    else:
        label_selector = label_selector.format(name=name)
        watch_events = partial(w.stream, v1.list_namespaced_deployment,
                               namespace=ns,
                               field_selector=field_selector,
                               label_selector=label_selector,
                               _request_timeout=timeout)

    try:
        logger.debug("Watching events for {t}s".format(t=timeout))
        for event in watch_events():
            deployment = event['object']
            status = deployment.status
            spec = deployment.spec

            logger.debug(
                "Deployment '{p}' {t}: "
                "Ready Replicas {r} - "
                "Unavailable Replicas {u} - "
                "Desired Replicas {a}".format(
                    p=deployment.metadata.name, t=event["type"],
                    r=status.ready_replicas,
                    a=spec.replicas,
                    u=status.unavailable_replicas))

            readiness = status.ready_replicas == spec.replicas
            if ready == readiness:
                w.stop()
                return True

    except urllib3.exceptions.ReadTimeoutError:
        logger.debug("Timed out!")
        return False