Python kubernetes.client.V1DeleteOptions() Examples

The following are 30 code examples of kubernetes.client.V1DeleteOptions(). 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 7 votes vote down vote up
def delete_pods(name: str, ns: str = "default",
                label_selector: str = "name in ({name})",
                secrets: Secrets = None):
    """
    Delete pods by `name` in the namespace `ns`.

    The pods are 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.CoreV1Api(api)
    if label_selector:
        ret = v1.list_namespaced_pod(ns, label_selector=label_selector)
    else:
        ret = v1.list_namespaced_pod(ns)

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

    body = client.V1DeleteOptions()
    for p in ret.items:
        v1.delete_namespaced_pod(p.metadata.name, ns, body=body) 
Example #2
Source File: kube_configmap.py    From wc-devops-utilities with Apache License 2.0 7 votes vote down vote up
def deleteConfigMap(parser_args,CorV1Client):
        print("delete config map")
        if listConfigMap(parser_args,CorV1Client):
            # create an instance of the API class
            name = parser_args.name  # str | name of the ConfigMap
            namespace = parser_args.namespace  # str | object name and auth scope, such as for teams and projects
            body = client.V1DeleteOptions()  # V1DeleteOptions |
            pretty = 'pretty_example'  # str | If 'true', then the output is pretty printed. (optional)

            try:
                api_response = CorV1Client.delete_namespaced_config_map(name, namespace, body, pretty=pretty)
                print(api_response)
            except ApiException as e:
                print("Exception when calling CoreV1Api->delete_namespaced_config_map: %s\n" % e)
        else:
            print("Not Found target cofigMap ojbect %s exist" % parser_args.name)

#Delete configMap 
Example #3
Source File: controller_wrappers.py    From paasta with Apache License 2.0 6 votes vote down vote up
def delete_pod_disruption_budget(self, kube_client: KubeClient) -> None:
        try:
            kube_client.policy.delete_namespaced_pod_disruption_budget(
                name=self.item.metadata.name,
                namespace=self.item.metadata.namespace,
                body=V1DeleteOptions(),
            )
        except ApiException as e:
            if e.status == 404:
                # Deployment does not exist, nothing to delete but
                # we can consider this a success.
                self.logging.debug(
                    "not deleting nonexistent pod disruption budget/{} from namespace/{}".format(
                        self.item.metadata.name, self.item.metadata.namespace
                    )
                )
            else:
                raise
        else:
            self.logging.info(
                "deleted pod disruption budget/{} from namespace/{}".format(
                    self.item.metadata.name, self.item.metadata.namespace
                )
            ) 
Example #4
Source File: adapters.py    From k8s-handle with Apache License 2.0 6 votes vote down vote up
def delete(self):
        self._validate()

        try:
            if self.namespace:
                return self.api.delete_namespaced_custom_object(
                    self.group, self.version, self.namespace, self.plural, self.name,
                    client.V1DeleteOptions(propagation_policy='Foreground')
                )

            return self.api.delete_cluster_custom_object(
                self.group, self.version, self.plural, self.name,
                client.V1DeleteOptions(propagation_policy='Foreground')
            )

        except ApiException as e:
            if e.reason == 'Not Found':
                return None

            log.error(
                '{}'.format(add_indent(e.body)))
            raise ProvisioningError(e) 
Example #5
Source File: persistentvolumeclaim.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the PersistentVolumeClaim.

        This method expects the PersistentVolumeClaim to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
             options: Options for PersistentVolumeClaim deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info('deleting persistentvolumeclaim "%s"', self.name)
        log.debug('delete options: %s', options)
        log.debug('persistentvolumeclaim: %s', self.obj)

        return self.api_client.delete_namespaced_persistent_volume_claim(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #6
Source File: pod.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the Pod.

        This method expects the Pod to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will
        need to be set manually.

        Args:
            options: Options for Pod deletion.

        Return:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting pod "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'pod: {self.obj}')

        return self.api_client.delete_namespaced_pod(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #7
Source File: service.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the Service.

        This method expects the Service to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for Service deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting service "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'service: {self.obj}')

        return self.api_client.delete_namespaced_service(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #8
Source File: replicaset.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the ReplicaSet.

        This method expects the ReplicaSet to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for ReplicaSet deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting replicaset "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'replicaset: {self.obj}')

        return self.api_client.delete_namespaced_replica_set(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #9
Source File: deployment.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the Deployment.

        This method expects the Deployment to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for Deployment deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting deployment "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'deployment: {self.obj}')

        return self.api_client.delete_namespaced_deployment(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #10
Source File: secret.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the Secret.

        This method expects the Secret to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for Secret deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting secret "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'secret: {self.obj}')

        return self.api_client.delete_namespaced_secret(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #11
Source File: clusterrolebinding.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the ClusterRoleBinding.

        This method expects the ClusterRoleBinding to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
             options: Options for ClusterRoleBinding deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting clusterrolebinding "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'clusterrolebinding: {self.obj}')

        return self.api_client.delete_cluster_role_binding(
            name=self.name,
            body=options,
        ) 
Example #12
Source File: daemonset.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the DaemonSet.

        This method expects the DaemonSet to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for DaemonSet deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting daemonset "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'daemonset: {self.obj}')

        return self.api_client.delete_namespaced_daemon_set(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #13
Source File: serviceaccount.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the Namespace.
        Args:
             options: Options for ServiceAccount deletion.
        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting ServiceAccount "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'service account: {self.obj}')

        return self.api_client.delete_namespaced_service_account(
            name=self.name,
            namespace=self.namespace,
            body=options
        ) 
Example #14
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 6 votes vote down vote up
def delete_replica_set(name: str, ns: str = "default",
                       label_selector: str = "name in ({name})",
                       secrets: Secrets = None):
    """
    Delete a replica set by `name` in the namespace `ns`.

    The replica set 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.ExtensionsV1beta1Api(api)
    if label_selector:
        ret = v1.list_namespaced_replica_set(ns, label_selector=label_selector)
    else:
        ret = v1.list_namespaced_replica_set(ns)

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

    body = client.V1DeleteOptions()
    for r in ret.items:
        v1.delete_namespaced_replica_set(r.metadata.name, ns, body=body) 
Example #15
Source File: statefulset.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the StatefulSet.

        This method expects the StatefulSet to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
            options: Options for StatefulSet deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting statefulset "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'statefulset: {self.obj}')

        return self.api_client.delete_namespaced_stateful_set(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #16
Source File: configmap.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def delete(self, options: client.V1DeleteOptions = None) -> client.V1Status:
        """Delete the ConfigMap.

        This method expects the ConfigMap to have been loaded or otherwise
        assigned a namespace already. If it has not, the namespace will need
        to be set manually.

        Args:
             options: Options for ConfigMap deletion.

        Returns:
            The status of the delete operation.
        """
        if options is None:
            options = client.V1DeleteOptions()

        log.info(f'deleting configmap "{self.name}"')
        log.debug(f'delete options: {options}')
        log.debug(f'configmap: {self.obj}')

        return self.api_client.delete_namespaced_config_map(
            name=self.name,
            namespace=self.namespace,
            body=options,
        ) 
Example #17
Source File: kube_secret.py    From wc-devops-utilities with Apache License 2.0 6 votes vote down vote up
def _deleteSecrete(secretName,CorV1Client=None,namespace="default"):
    print("delete Secret for current environment")
    body = client.V1DeleteOptions()  # V1DeleteOptions |
    pretty = 'pretty_example'  # str | If 'true', then the output is pretty printed. (optional)
    grace_period_seconds = 0  # int | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. (optional)
    orphan_dependents = True  # bool | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. (optional)
    propagation_policy = 'propagation_policy_example'  # str | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. (optional)

    try:
        api_response = CorV1Client.delete_namespaced_secret(secretName, namespace, body, pretty=pretty,
                                                             grace_period_seconds=grace_period_seconds,
                                                             orphan_dependents=orphan_dependents,
                                                             propagation_policy=propagation_policy)
        print(api_response)
    except ApiException as e:
        print("Exception when calling CoreV1Api->delete_namespaced_secret: %s\n" % e) 
Example #18
Source File: kube_pvc.py    From wc-devops-utilities with Apache License 2.0 6 votes vote down vote up
def DeleteKubePVC(parser_args):
    if parser_args.component=="search":
        # {tenantName}-{environment}-search-master-gluster-volume
        if parser_args.envtype == "auth":
            pvc_name=parser_args.tenant+parser_args.env+"-search-master-"+"volume"
        elif parser_args.envtype == "live":
            pvc_name=parser_args.tenant+parser_args.env+"-search-repeater-"+"volume"

        # Below config boby still need refine to accept more flexible extension
        body=client.V1DeleteOptions()
        try:
             apiInstance = globalvars.get_value('KubCoreV1Api')
             if not apiInstance:
                 factory.Factory_InitKubeClient(parser_args.configtype, parser_args.configfile)
                 apiInstance = globalvars.get_value('KubCoreV1Api')
             api_response = apiInstance.delete_namespaced_persistent_volume_claim(pvc_name, parser_args.namespace, body)
             print(api_response)
        except ApiException as e:
            print("Exception when calling CoreV1Api->delete_namespaced_persistent_volume_claim: %s\n" % e)
    else:
        print("Compoennt %s should not have any persistent volumes" %(parser_args.component)) 
Example #19
Source File: kube_configmap.py    From wc-devops-utilities with Apache License 2.0 6 votes vote down vote up
def DeleteConfigMap(parser_args):
    _CoreV1Api = globalvars.get_value('KubCoreV1Api')
    if not _CoreV1Api:
        factory.Factory_InitKubeClient(parser_args.configtype, parser_args.configfile)
        _CoreV1Api = globalvars.get_value('KubCoreV1Api')
    print("delete config map")
    if listConfigMap(parser_args, _CoreV1Api):
       # create an instance of the API class
       name = parser_args.name  # str | name of the ConfigMap
       namespace = parser_args.namespace  # str | object name and auth scope, such as for teams and projects
       body = client.V1DeleteOptions()  # V1DeleteOptions |
       pretty = 'pretty_example'  # str | If 'true', then the output is pretty printed. (optional)

       try:
          api_response = _CoreV1Api.delete_namespaced_config_map(parser_args.tenant+parser_args.env+parser_args.envtype+"-"+name, namespace, body, pretty=pretty)
          print(api_response)
       except ApiException as e:
          print("Exception when calling CoreV1Api->delete_namespaced_config_map: %s\n" % e)
    else:
       print("Not Found target cofigMap ojbect %s exist" % parser_args.name)

#DetectExistConfigMap 
Example #20
Source File: controller_wrappers.py    From paasta with Apache License 2.0 6 votes vote down vote up
def delete_horizontal_pod_autoscaler(self, kube_client: KubeClient) -> None:
        try:
            kube_client.autoscaling.delete_namespaced_horizontal_pod_autoscaler(
                name=self.item.metadata.name,
                namespace=self.item.metadata.namespace,
                body=V1DeleteOptions(),
            )
        except ApiException as e:
            if e.status == 404:
                # Deployment does not exist, nothing to delete but
                # we can consider this a success.
                self.logging.debug(
                    f"not deleting nonexistent HPA/{self.item.metadata.name} from namespace/{self.item.metadata.namespace}"
                )
            else:
                raise
        else:
            self.logging.info(
                "deleted HPA/{} from namespace/{}".format(
                    self.item.metadata.name, self.item.metadata.namespace
                )
            ) 
Example #21
Source File: kubernetes_remove_evicted_pods.py    From paasta with Apache License 2.0 6 votes vote down vote up
def remove_pods(
    client: KubeClient, services: Mapping[str, Sequence[EvictedPod]], dry_run: bool,
) -> None:
    delete_options = V1DeleteOptions()
    for service in services:
        # Do not remove more than 2 pods per run
        for pod in services[service][0:2]:
            if dry_run:
                log.info(f"Would have removed pod {pod.podname}")
            else:
                client.core.delete_namespaced_pod(
                    pod.podname,
                    pod.namespace,
                    body=delete_options,
                    grace_period_seconds=0,
                    propagation_policy="Background",
                )
                log.info(f"Removing pod {pod.podname}") 
Example #22
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 6 votes vote down vote up
def delete_custom_resource(
    kube_client: KubeClient,
    name: str,
    namespace: str,
    group: str,
    version: str,
    plural: str,
) -> None:
    return kube_client.custom.delete_namespaced_custom_object(
        name=name,
        namespace=namespace,
        group=group,
        version=version,
        plural=plural,
        body=V1DeleteOptions(),
    ) 
Example #23
Source File: app.py    From pipelines with Apache License 2.0 6 votes vote down vote up
def delete_deployment(params):
    from kubernetes.client import V1DeleteOptions

    spec = get_seldon_spec(params)
    name = get_deployment_name(params)  # spec["metadata"]["name"]
    namespace = "default"               # TODO: the namespace should be configured or be figured out dynamically
    plural = spec["kind"].lower()+"s"   # TODO: verify the "rule" for constructing plural
    group, version = spec["apiVersion"].split("/")

    del_opts = V1DeleteOptions()
    api_client = get_custom_objects_api_client()
    api_response = api_client.list_namespaced_custom_object(group, version, namespace, plural)

    if name in [deployment["metadata"]["name"] for deployment in api_response["items"]]:
        api_response = api_client.delete_namespaced_custom_object(group, version, namespace, plural, name, del_opts)
    else:
        LOG.error("Could not find the Seldon deployment '%s'" % name)
        return {
            "status": "Error",
            "details": "Could not find a Seldon deployment with name '%s'" % name
        }

    # api_response_filtered = {key: api_response[key] for key in ["apiVersion", "kind"]}
    LOG.info("%s ..." % str(api_response)[:160])
    return api_response 
Example #24
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 6 votes vote down vote up
def delete_ds(config, version, ds_name, ns_name="default",
              body=V1DeleteOptions()):
    k8s_api_core = client_from_config(config)

    if version >= util.parse_version("v1.9.0"):
        k8s_api_apps = apps_api_client_from_config(config)
        k8s_api_apps.delete_namespaced_daemon_set(ds_name,
                                                  ns_name,
                                                  grace_period_seconds=0,
                                                  orphan_dependents=False)
    else:
        k8s_api_ext = extensions_client_from_config(config)
        k8s_api_ext.delete_namespaced_daemon_set(ds_name,
                                                 ns_name,
                                                 grace_period_seconds=0,
                                                 orphan_dependents=False)

    # Pod in ds has fixed label so we use label selector
    data = k8s_api_core.list_namespaced_pod(
        ns_name, label_selector="app={}".format(ds_name)).to_dict()
    # There should be only one pod
    for pod in data["items"]:
        logging.debug("Removing pod \"{}\"".format(pod["metadata"]["name"]))
        delete_pod(None, pod["metadata"]["name"], ns_name)
    return 
Example #25
Source File: tenants_utils.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def delete_namespace(name, id_token):
    body = k8s_client.V1DeleteOptions()
    response = 'Namespace {} does not exist'.format(name)
    api_instance = get_k8s_api_client(id_token)
    existed = True
    try:
        response = api_instance.delete_namespace(name, body)
    except ApiException as apiException:
        if apiException.status != RESOURCE_DOES_NOT_EXIST and \
                apiException.status != NAMESPACE_BEING_DELETED:
            raise KubernetesDeleteException('namespace', apiException)
        existed = False
    if existed:
        logger.info('Namespace {} deleted'.format(name))
    else:
        logger.info('Namespace {} does not exist'.format(name))

    return response 
Example #26
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def prepare_pvc(self, name, size=1):
        core = self.core
        namespace = self.namespace
        now = datetime.datetime.now().strftime("%Y%M%d%H%M")
        podname = '%s-%s-prepare' % (now, name)
        size = 1024 * int(size) - 48
        pod = {'kind': 'Pod', 'spec': {'restartPolicy': 'OnFailure',
                                       'containers': [{'image': 'alpine', 'volumeMounts': [{'mountPath': '/storage1',
                                                                                            'name': 'storage1'}],
                                                       'name': 'prepare', 'command': ['fallocate'],
                                                       'args': ['-l', '%sM' % size, '/storage1/disk.img']}],
                                       'volumes': [{'name': 'storage1', 'persistentVolumeClaim': {'claimName': name}}]},
               'apiVersion': 'v1', 'metadata': {'name': podname}}
        core.create_namespaced_pod(namespace, pod)
        completed = self.pod_completed(podname, namespace)
        if not completed:
            common.pprint("Using with pod %s. Leaving it for debugging purposes" % podname, color='red')
            return {'result': 'failure', 'reason': 'timeout waiting for preparation of disk to finish'}
        else:
            core.delete_namespaced_pod(podname, namespace, client.V1DeleteOptions())
        return {'result': 'success'} 
Example #27
Source File: context.py    From inference-model-manager with Apache License 2.0 6 votes vote down vote up
def _delete_crd_server(self, object_to_delete):
        delete_body = client.V1DeleteOptions()
        try:
            response = self.k8s_client_custom.delete_namespaced_custom_object(
                CRD_GROUP, CRD_VERSION, object_to_delete['namespace'], CRD_PLURAL,
                object_to_delete['name'], delete_body, grace_period_seconds=0)
        except Exception as e:
            logging.error(e)
            raise

        deletion_status = self._wait_server_deletion(object_to_delete)
        if deletion_status == OperationStatus.SUCCESS:
            logging.info('CRD {} deleted successfully.'.format(object_to_delete['name']))
        elif deletion_status == OperationStatus.TERMINATED:
            logging.info('CRD {} status unknown.'.format(object_to_delete['name']))
        else:
            logging.info('CRD {} deletion timeout.'.format(object_to_delete['name']))
        return response 
Example #28
Source File: k8s_manage.py    From sparrow with GNU General Public License v3.0 6 votes vote down vote up
def modify_k8s_hpa():
    infos = None
    status = None
    try:
        Infos = request.get_json()
        api_instance = client.AutoscalingV1Api()
        if request.method == 'POST':
            try:
                api_instance.patch_namespaced_horizontal_pod_autoscaler(name=Infos['name'], namespace=namespace,
                                                                          body=client.V1HorizontalPodAutoscaler(
                                                                              spec=client.V1HorizontalPodAutoscalerSpec(
                                                                                  max_replicas=int(Infos['max_update']),
                                                                                  target_cpu_utilization_percentage=int(Infos['cpu_update'].replace('%','')),
                                                                                  scale_target_ref=client.V1CrossVersionObjectReference(
                                                                                      kind='Deployment',
                                                                                      name=Infos['target_ref']))))
            except Exception as e:
                logging.error(e)
                infos = '修改参数失败!'
            else:
                status = 'ok'
                infos = '修改参数成功!'
        if request.method == 'DELETE':
            try:
                api_instance.delete_namespaced_horizontal_pod_autoscaler(name=Infos['name'], namespace=namespace,body=client.V1DeleteOptions())
            except Exception as e:
                logging.error(e)
                infos = '删除%s失败!' %Infos['name']
            else:
                status = 'ok'
                infos = '删除%s成功!' %Infos['name']
    except Exception as e:
        logging.error(e)
    finally:
        return jsonify({'status':status,'infos':infos}) 
Example #29
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def delete_image(self, image):
        common.pprint("Deleting image %s" % image)
        core = self.core
        if self.cdi:
            cdinamespace = self.cdinamespace
            pvc = core.list_namespaced_persistent_volume_claim(cdinamespace)
            images = [p.metadata.name for p in pvc.items if p.metadata.annotations is not None and
                      'cdi.kubevirt.io/storage.import.endpoint' in p.metadata.annotations and
                      self.get_image_name(p.metadata.annotations['cdi.kubevirt.io/storage.import.endpoint']) ==
                      image]
            if images:
                core.delete_namespaced_persistent_volume_claim(images[0], cdinamespace, client.V1DeleteOptions())
                return {'result': 'success'}
        else:
            pvc = core.list_namespaced_persistent_volume_claim(self.namespace)
            images = [p.metadata.name for p in pvc.items
                      if p.metadata.annotations is not None and 'kcli/image' in p.metadata.annotations and
                      p.metadata.annotations['kcli/image'] == image]
            if images:
                core.delete_namespaced_persistent_volume_claim(images[0], self.namespace, client.V1DeleteOptions())
                return {'result': 'success'}
        return {'result': 'failure', 'reason': 'image %s not found' % image} 
Example #30
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def delete(self, name, snapshots=False):
        crds = self.crds
        core = self.core
        namespace = self.namespace
        try:
            vm = crds.get_namespaced_custom_object(DOMAIN, VERSION, namespace, 'virtualmachines', name)
            crds.delete_namespaced_custom_object(DOMAIN, VERSION, namespace, 'virtualmachines', name,
                                                 client.V1DeleteOptions())
        except:
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        pvcvolumes = [v['persistentVolumeClaim']['claimName'] for v in vm['spec']['template']['spec']['volumes'] if
                      'persistentVolumeClaim' in v]
        pvcs = [pvc for pvc in core.list_namespaced_persistent_volume_claim(namespace).items
                if pvc.metadata.name in pvcvolumes]
        for p in sorted(pvcs):
            pvcname = p.metadata.name
            common.pprint("Deleting pvc %s" % pvcname, color='blue')
            core.delete_namespaced_persistent_volume_claim(pvcname, namespace, client.V1DeleteOptions())
        try:
            core.delete_namespaced_service('%s-ssh' % name, namespace)
        except:
            pass
        return {'result': 'success'}