mirror of
https://github.com/openshift/community.okd.git
synced 2026-05-06 21:22:36 +00:00
update collection with latest feature from kubernetes.core (#181)
* Rebase code with kubernetes.core stable-2.4
This commit is contained in:
@@ -9,18 +9,7 @@ import time
|
||||
|
||||
from ansible.module_utils._text import to_native
|
||||
|
||||
try:
|
||||
from ansible_collections.kubernetes.core.plugins.module_utils.common import (
|
||||
K8sAnsibleMixin,
|
||||
get_api_client,
|
||||
)
|
||||
HAS_KUBERNETES_COLLECTION = True
|
||||
k8s_collection_import_exception = None
|
||||
K8S_COLLECTION_ERROR = None
|
||||
except ImportError as e:
|
||||
HAS_KUBERNETES_COLLECTION = False
|
||||
k8s_collection_import_exception = e
|
||||
K8S_COLLECTION_ERROR = traceback.format_exc()
|
||||
from ansible_collections.community.okd.plugins.module_utils.openshift_common import AnsibleOpenshiftModule
|
||||
|
||||
try:
|
||||
from kubernetes.dynamic.exceptions import DynamicApiError
|
||||
@@ -28,24 +17,9 @@ except ImportError as e:
|
||||
pass
|
||||
|
||||
|
||||
class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
def __init__(self, module):
|
||||
self.module = module
|
||||
self.fail_json = self.module.fail_json
|
||||
self.exit_json = self.module.exit_json
|
||||
|
||||
if not HAS_KUBERNETES_COLLECTION:
|
||||
self.module.fail_json(
|
||||
msg="The kubernetes.core collection must be installed",
|
||||
exception=K8S_COLLECTION_ERROR,
|
||||
error=to_native(k8s_collection_import_exception),
|
||||
)
|
||||
|
||||
super(OpenShiftBuilds, self).__init__(self.module)
|
||||
|
||||
self.params = self.module.params
|
||||
self.check_mode = self.module.check_mode
|
||||
self.client = get_api_client(self.module)
|
||||
class OpenShiftBuilds(AnsibleOpenshiftModule):
|
||||
def __init__(self, **kwargs):
|
||||
super(OpenShiftBuilds, self).__init__(**kwargs)
|
||||
|
||||
def get_build_config(self, name, namespace):
|
||||
params = dict(
|
||||
@@ -57,78 +31,9 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
result = self.kubernetes_facts(**params)
|
||||
return result["resources"]
|
||||
|
||||
def prune(self):
|
||||
# list replicationcontroller candidate for pruning
|
||||
kind = 'Build'
|
||||
api_version = 'build.openshift.io/v1'
|
||||
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
|
||||
|
||||
self.max_creation_timestamp = None
|
||||
keep_younger_than = self.params.get("keep_younger_than")
|
||||
if keep_younger_than:
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
self.max_creation_timestamp = now - timedelta(minutes=keep_younger_than)
|
||||
|
||||
def _prunable_build(build):
|
||||
return build["status"]["phase"] in ("Complete", "Failed", "Error", "Cancelled")
|
||||
|
||||
def _orphan_build(build):
|
||||
if not _prunable_build(build):
|
||||
return False
|
||||
|
||||
config = build["status"].get("config", None)
|
||||
if not config:
|
||||
return True
|
||||
build_config = self.get_build_config(config["name"], config["namespace"])
|
||||
return len(build_config) == 0
|
||||
|
||||
def _younger_build(build):
|
||||
if not self.max_creation_timestamp:
|
||||
return False
|
||||
creation_timestamp = datetime.strptime(build['metadata']['creationTimestamp'], '%Y-%m-%dT%H:%M:%SZ')
|
||||
return creation_timestamp < self.max_creation_timestamp
|
||||
|
||||
predicates = [
|
||||
_prunable_build,
|
||||
]
|
||||
if self.params.get("orphans"):
|
||||
predicates.append(_orphan_build)
|
||||
if self.max_creation_timestamp:
|
||||
predicates.append(_younger_build)
|
||||
|
||||
# Get ReplicationController
|
||||
params = dict(
|
||||
kind=kind,
|
||||
api_version=api_version,
|
||||
namespace=self.params.get("namespace"),
|
||||
)
|
||||
result = self.kubernetes_facts(**params)
|
||||
candidates = result["resources"]
|
||||
for pred in predicates:
|
||||
candidates = list(filter(pred, candidates))
|
||||
|
||||
if self.check_mode:
|
||||
changed = len(candidates) > 0
|
||||
self.exit_json(changed=changed, builds=candidates)
|
||||
|
||||
changed = False
|
||||
for build in candidates:
|
||||
changed = True
|
||||
try:
|
||||
name = build["metadata"]["name"]
|
||||
namespace = build["metadata"]["namespace"]
|
||||
resource.delete(name=name, namespace=namespace, body={})
|
||||
except DynamicApiError as exc:
|
||||
msg = "Failed to delete Build %s/%s due to: %s" % (namespace, name, exc.body)
|
||||
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
|
||||
except Exception as e:
|
||||
msg = "Failed to delete Build %s/%s due to: %s" % (namespace, name, to_native(e))
|
||||
self.fail_json(msg=msg, error=to_native(e), exception=e)
|
||||
self.exit_json(changed=changed, builds=candidates)
|
||||
|
||||
def clone_build(self, name, namespace, request):
|
||||
try:
|
||||
result = self.client.request(
|
||||
result = self.request(
|
||||
method="POST",
|
||||
path="/apis/build.openshift.io/v1/namespaces/{namespace}/builds/{name}/clone".format(
|
||||
namespace=namespace,
|
||||
@@ -147,7 +52,7 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
|
||||
def instantiate_build_config(self, name, namespace, request):
|
||||
try:
|
||||
result = self.client.request(
|
||||
result = self.request(
|
||||
method="POST",
|
||||
path="/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate".format(
|
||||
namespace=namespace,
|
||||
@@ -300,8 +205,9 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
|
||||
namespace = self.params.get("namespace")
|
||||
phases = ["new", "pending", "running"]
|
||||
if len(self.params.get("build_phases")):
|
||||
phases = [p.lower() for p in self.params.get("build_phases")]
|
||||
build_phases = self.params.get("build_phases", [])
|
||||
if build_phases:
|
||||
phases = [p.lower() for p in build_phases]
|
||||
|
||||
names = []
|
||||
if self.params.get("build_name"):
|
||||
@@ -318,7 +224,7 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
|
||||
def _filter_builds(build):
|
||||
config = build["metadata"].get("labels", {}).get("openshift.io/build-config.name")
|
||||
return config in build_config
|
||||
return build_config is None or (build_config is not None and config in build_config)
|
||||
|
||||
for item in list(filter(_filter_builds, resources)):
|
||||
name = item["metadata"]["name"]
|
||||
@@ -361,7 +267,7 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
changed = True
|
||||
try:
|
||||
content_type = "application/json"
|
||||
cancelled_build = self.client.request(
|
||||
cancelled_build = self.request(
|
||||
"PUT",
|
||||
"/apis/build.openshift.io/v1/namespaces/{0}/builds/{1}".format(
|
||||
namespace, name
|
||||
@@ -427,3 +333,77 @@ class OpenShiftBuilds(K8sAnsibleMixin):
|
||||
else:
|
||||
restart = bool(state == "restarted")
|
||||
self.cancel_build(restart=restart)
|
||||
|
||||
|
||||
class OpenShiftPruneBuilds(OpenShiftBuilds):
|
||||
def __init__(self, **kwargs):
|
||||
super(OpenShiftPruneBuilds, self).__init__(**kwargs)
|
||||
|
||||
def execute_module(self):
|
||||
# list replicationcontroller candidate for pruning
|
||||
kind = 'Build'
|
||||
api_version = 'build.openshift.io/v1'
|
||||
resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
|
||||
|
||||
self.max_creation_timestamp = None
|
||||
keep_younger_than = self.params.get("keep_younger_than")
|
||||
if keep_younger_than:
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
self.max_creation_timestamp = now - timedelta(minutes=keep_younger_than)
|
||||
|
||||
def _prunable_build(build):
|
||||
return build["status"]["phase"] in ("Complete", "Failed", "Error", "Cancelled")
|
||||
|
||||
def _orphan_build(build):
|
||||
if not _prunable_build(build):
|
||||
return False
|
||||
|
||||
config = build["status"].get("config", None)
|
||||
if not config:
|
||||
return True
|
||||
build_config = self.get_build_config(config["name"], config["namespace"])
|
||||
return len(build_config) == 0
|
||||
|
||||
def _younger_build(build):
|
||||
if not self.max_creation_timestamp:
|
||||
return False
|
||||
creation_timestamp = datetime.strptime(build['metadata']['creationTimestamp'], '%Y-%m-%dT%H:%M:%SZ')
|
||||
return creation_timestamp < self.max_creation_timestamp
|
||||
|
||||
predicates = [
|
||||
_prunable_build,
|
||||
]
|
||||
if self.params.get("orphans"):
|
||||
predicates.append(_orphan_build)
|
||||
if self.max_creation_timestamp:
|
||||
predicates.append(_younger_build)
|
||||
|
||||
# Get ReplicationController
|
||||
params = dict(
|
||||
kind=kind,
|
||||
api_version=api_version,
|
||||
namespace=self.params.get("namespace"),
|
||||
)
|
||||
result = self.kubernetes_facts(**params)
|
||||
candidates = result["resources"]
|
||||
for pred in predicates:
|
||||
candidates = list(filter(pred, candidates))
|
||||
|
||||
if self.check_mode:
|
||||
changed = len(candidates) > 0
|
||||
self.exit_json(changed=changed, builds=candidates)
|
||||
|
||||
changed = False
|
||||
for build in candidates:
|
||||
changed = True
|
||||
try:
|
||||
name = build["metadata"]["name"]
|
||||
namespace = build["metadata"]["namespace"]
|
||||
resource.delete(name=name, namespace=namespace, body={})
|
||||
except DynamicApiError as exc:
|
||||
msg = "Failed to delete Build %s/%s due to: %s" % (namespace, name, exc.body)
|
||||
self.fail_json(msg=msg, status=exc.status, reason=exc.reason)
|
||||
except Exception as e:
|
||||
msg = "Failed to delete Build %s/%s due to: %s" % (namespace, name, to_native(e))
|
||||
self.fail_json(msg=msg, error=to_native(e), exception=e)
|
||||
self.exit_json(changed=changed, builds=candidates)
|
||||
|
||||
Reference in New Issue
Block a user