| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
from __future__ import absolute_import, division, print_function |
| 4 |
|
| 5 |
__metaclass__ = type |
| 6 |
|
| 7 |
from datetime import datetime, timezone |
| 8 |
|
| 9 |
from ansible.module_utils._text import to_native |
| 10 |
|
| 11 |
from ansible_collections.community.okd.plugins.module_utils.openshift_common import ( |
| 12 |
AnsibleOpenshiftModule, |
| 13 |
) |
| 14 |
|
| 15 |
try: |
| 16 |
from kubernetes import client |
| 17 |
from kubernetes.dynamic.exceptions import DynamicApiError |
| 18 |
except ImportError as e: |
| 19 |
pass |
| 20 |
|
| 21 |
|
| 22 |
def get_deploymentconfig_for_replicationcontroller(replica_controller): |
| 23 |
# DeploymentConfigAnnotation is an annotation name used to correlate a deployment with the |
| 24 |
# DeploymentConfig on which the deployment is based. |
| 25 |
# This is set on replication controller pod template by deployer controller. |
| 26 |
DeploymentConfigAnnotation = "openshift.io/deployment-config.name" |
| 27 |
try: |
| 28 |
deploymentconfig_name = replica_controller["metadata"]["annotations"].get( |
| 29 |
DeploymentConfigAnnotation |
| 30 |
) |
| 31 |
if deploymentconfig_name is None or deploymentconfig_name == "": |
| 32 |
return None |
| 33 |
return deploymentconfig_name |
| 34 |
except Exception: |
| 35 |
return None |
| 36 |
|
| 37 |
|
| 38 |
class OpenShiftAdmPruneDeployment(AnsibleOpenshiftModule): |
| 39 |
def __init__(self, **kwargs): |
| 40 |
super(OpenShiftAdmPruneDeployment, self).__init__(**kwargs) |
| 41 |
|
| 42 |
def filter_replication_controller(self, replicacontrollers): |
| 43 |
def _deployment(obj): |
| 44 |
return get_deploymentconfig_for_replicationcontroller(obj) is not None |
| 45 |
|
| 46 |
def _zeroReplicaSize(obj): |
| 47 |
return obj["spec"]["replicas"] == 0 and obj["status"]["replicas"] == 0 |
| 48 |
|
| 49 |
def _complete_failed(obj): |
| 50 |
DeploymentStatusAnnotation = "openshift.io/deployment.phase" |
| 51 |
try: |
| 52 |
# validate that replication controller status is either 'Complete' or 'Failed' |
| 53 |
deployment_phase = obj["metadata"]["annotations"].get( |
| 54 |
DeploymentStatusAnnotation |
| 55 |
) |
| 56 |
return deployment_phase in ("Failed", "Complete") |
| 57 |
except Exception: |
| 58 |
return False |
| 59 |
|
| 60 |
def _younger(obj): |
| 61 |
creation_timestamp = datetime.strptime( |
| 62 |
obj["metadata"]["creationTimestamp"], "%Y-%m-%dT%H:%M:%SZ" |
| 63 |
) |
| 64 |
now = datetime.now(timezone.utc).replace(tzinfo=None) |
| 65 |
age = (now - creation_timestamp).seconds / 60 |
| 66 |
return age > self.params["keep_younger_than"] |
| 67 |
|
| 68 |
def _orphan(obj): |
| 69 |
try: |
| 70 |
# verify if the deploymentconfig associated to the replication controller is still existing |
| 71 |
deploymentconfig_name = get_deploymentconfig_for_replicationcontroller( |
| 72 |
obj |
| 73 |
) |
| 74 |
params = dict( |
| 75 |
kind="DeploymentConfig", |
| 76 |
api_version="apps.openshift.io/v1", |
| 77 |
name=deploymentconfig_name, |
| 78 |
namespace=obj["metadata"]["name"], |
| 79 |
) |
| 80 |
exists = self.kubernetes_facts(**params) |
| 81 |
return not (exists.get["api_found"] and len(exists["resources"]) > 0) |
| 82 |
except Exception: |
| 83 |
return False |
| 84 |
|
| 85 |
predicates = [_deployment, _zeroReplicaSize, _complete_failed] |
| 86 |
if self.params["orphans"]: |
| 87 |
predicates.append(_orphan) |
| 88 |
if self.params["keep_younger_than"]: |
| 89 |
predicates.append(_younger) |
| 90 |
|
| 91 |
results = replicacontrollers.copy() |
| 92 |
for pred in predicates: |
| 93 |
results = filter(pred, results) |
| 94 |
return list(results) |
| 95 |
|
| 96 |
def execute_module(self): |
| 97 |
# list replicationcontroller candidate for pruning |
| 98 |
kind = "ReplicationController" |
| 99 |
api_version = "v1" |
| 100 |
resource = self.find_resource(kind=kind, api_version=api_version, fail=True) |
| 101 |
|
| 102 |
# Get ReplicationController |
| 103 |
params = dict( |
| 104 |
kind=kind, |
| 105 |
api_version="v1", |
| 106 |
namespace=self.params.get("namespace"), |
| 107 |
) |
| 108 |
candidates = self.kubernetes_facts(**params) |
| 109 |
candidates = self.filter_replication_controller(candidates["resources"]) |
| 110 |
|
| 111 |
if len(candidates) == 0: |
| 112 |
self.exit_json(changed=False, replication_controllers=[]) |
| 113 |
|
| 114 |
changed = True |
| 115 |
delete_options = client.V1DeleteOptions(propagation_policy="Background") |
| 116 |
replication_controllers = [] |
| 117 |
for replica in candidates: |
| 118 |
try: |
| 119 |
result = replica |
| 120 |
if not self.check_mode: |
| 121 |
name = replica["metadata"]["name"] |
| 122 |
namespace = replica["metadata"]["namespace"] |
| 123 |
result = resource.delete( |
| 124 |
name=name, namespace=namespace, body=delete_options |
| 125 |
).to_dict() |
| 126 |
replication_controllers.append(result) |
| 127 |
except DynamicApiError as exc: |
| 128 |
msg = "Failed to delete ReplicationController {namespace}/{name} due to: {msg}".format( |
| 129 |
namespace=namespace, name=name, msg=exc.body |
| 130 |
) |
| 131 |
self.fail_json(msg=msg) |
| 132 |
except Exception as e: |
| 133 |
msg = "Failed to delete ReplicationController {namespace}/{name} due to: {msg}".format( |
| 134 |
namespace=namespace, name=name, msg=to_native(e) |
| 135 |
) |
| 136 |
self.fail_json(msg=msg) |
| 137 |
self.exit_json(changed=changed, replication_controllers=replication_controllers) |