| 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, timedelta |
| 8 |
import time |
| 9 |
|
| 10 |
from ansible.module_utils._text import to_native |
| 11 |
|
| 12 |
from ansible_collections.community.okd.plugins.module_utils.openshift_common import ( |
| 13 |
AnsibleOpenshiftModule, |
| 14 |
) |
| 15 |
|
| 16 |
try: |
| 17 |
from kubernetes.dynamic.exceptions import DynamicApiError |
| 18 |
except ImportError as e: |
| 19 |
pass |
| 20 |
|
| 21 |
|
| 22 |
class OpenShiftBuilds(AnsibleOpenshiftModule): |
| 23 |
def __init__(self, **kwargs): |
| 24 |
super(OpenShiftBuilds, self).__init__(**kwargs) |
| 25 |
|
| 26 |
def get_build_config(self, name, namespace): |
| 27 |
params = dict( |
| 28 |
kind="BuildConfig", |
| 29 |
api_version="build.openshift.io/v1", |
| 30 |
name=name, |
| 31 |
namespace=namespace, |
| 32 |
) |
| 33 |
result = self.kubernetes_facts(**params) |
| 34 |
return result["resources"] |
| 35 |
|
| 36 |
def clone_build(self, name, namespace, request): |
| 37 |
try: |
| 38 |
result = self.request( |
| 39 |
method="POST", |
| 40 |
path="/apis/build.openshift.io/v1/namespaces/{namespace}/builds/{name}/clone".format( |
| 41 |
namespace=namespace, name=name |
| 42 |
), |
| 43 |
body=request, |
| 44 |
content_type="application/json", |
| 45 |
) |
| 46 |
return result.to_dict() |
| 47 |
except DynamicApiError as exc: |
| 48 |
msg = "Failed to clone Build %s/%s due to: %s" % (namespace, name, exc.body) |
| 49 |
self.fail_json(msg=msg, status=exc.status, reason=exc.reason) |
| 50 |
except Exception as e: |
| 51 |
msg = "Failed to clone Build %s/%s due to: %s" % ( |
| 52 |
namespace, |
| 53 |
name, |
| 54 |
to_native(e), |
| 55 |
) |
| 56 |
self.fail_json(msg=msg, error=to_native(e), exception=e) |
| 57 |
|
| 58 |
def instantiate_build_config(self, name, namespace, request): |
| 59 |
try: |
| 60 |
result = self.request( |
| 61 |
method="POST", |
| 62 |
path="/apis/build.openshift.io/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate".format( |
| 63 |
namespace=namespace, name=name |
| 64 |
), |
| 65 |
body=request, |
| 66 |
content_type="application/json", |
| 67 |
) |
| 68 |
return result.to_dict() |
| 69 |
except DynamicApiError as exc: |
| 70 |
msg = "Failed to instantiate BuildConfig %s/%s due to: %s" % ( |
| 71 |
namespace, |
| 72 |
name, |
| 73 |
exc.body, |
| 74 |
) |
| 75 |
self.fail_json(msg=msg, status=exc.status, reason=exc.reason) |
| 76 |
except Exception as e: |
| 77 |
msg = "Failed to instantiate BuildConfig %s/%s due to: %s" % ( |
| 78 |
namespace, |
| 79 |
name, |
| 80 |
to_native(e), |
| 81 |
) |
| 82 |
self.fail_json(msg=msg, error=to_native(e), exception=e) |
| 83 |
|
| 84 |
def start_build(self): |
| 85 |
result = None |
| 86 |
name = self.params.get("build_config_name") |
| 87 |
if not name: |
| 88 |
name = self.params.get("build_name") |
| 89 |
|
| 90 |
build_request = { |
| 91 |
"kind": "BuildRequest", |
| 92 |
"apiVersion": "build.openshift.io/v1", |
| 93 |
"metadata": {"name": name}, |
| 94 |
"triggeredBy": [{"message": "Manually triggered"}], |
| 95 |
} |
| 96 |
|
| 97 |
# Overrides incremental |
| 98 |
incremental = self.params.get("incremental") |
| 99 |
if incremental is not None: |
| 100 |
build_request.update( |
| 101 |
{"sourceStrategyOptions": {"incremental": incremental}} |
| 102 |
) |
| 103 |
|
| 104 |
# Environment variable |
| 105 |
if self.params.get("env_vars"): |
| 106 |
build_request.update({"env": self.params.get("env_vars")}) |
| 107 |
|
| 108 |
# Docker strategy option |
| 109 |
if self.params.get("build_args"): |
| 110 |
build_request.update( |
| 111 |
{ |
| 112 |
"dockerStrategyOptions": { |
| 113 |
"buildArgs": self.params.get("build_args") |
| 114 |
}, |
| 115 |
} |
| 116 |
) |
| 117 |
|
| 118 |
# caching option |
| 119 |
no_cache = self.params.get("no_cache") |
| 120 |
if no_cache is not None: |
| 121 |
build_request.update( |
| 122 |
{ |
| 123 |
"dockerStrategyOptions": {"noCache": no_cache}, |
| 124 |
} |
| 125 |
) |
| 126 |
|
| 127 |
# commit |
| 128 |
if self.params.get("commit"): |
| 129 |
build_request.update( |
| 130 |
{"revision": {"git": {"commit": self.params.get("commit")}}} |
| 131 |
) |
| 132 |
|
| 133 |
if self.params.get("build_config_name"): |
| 134 |
# Instantiate Build from Build config |
| 135 |
result = self.instantiate_build_config( |
| 136 |
name=self.params.get("build_config_name"), |
| 137 |
namespace=self.params.get("namespace"), |
| 138 |
request=build_request, |
| 139 |
) |
| 140 |
|
| 141 |
else: |
| 142 |
# Re-run Build |
| 143 |
result = self.clone_build( |
| 144 |
name=self.params.get("build_name"), |
| 145 |
namespace=self.params.get("namespace"), |
| 146 |
request=build_request, |
| 147 |
) |
| 148 |
|
| 149 |
if result and self.params.get("wait"): |
| 150 |
start = datetime.now() |
| 151 |
|
| 152 |
def _total_wait_time(): |
| 153 |
return (datetime.now() - start).seconds |
| 154 |
|
| 155 |
wait_timeout = self.params.get("wait_timeout") |
| 156 |
wait_sleep = self.params.get("wait_sleep") |
| 157 |
last_status_phase = None |
| 158 |
while _total_wait_time() < wait_timeout: |
| 159 |
params = dict( |
| 160 |
kind=result["kind"], |
| 161 |
api_version=result["apiVersion"], |
| 162 |
name=result["metadata"]["name"], |
| 163 |
namespace=result["metadata"]["namespace"], |
| 164 |
) |
| 165 |
facts = self.kubernetes_facts(**params) |
| 166 |
if len(facts["resources"]) > 0: |
| 167 |
last_status_phase = facts["resources"][0]["status"]["phase"] |
| 168 |
if last_status_phase == "Complete": |
| 169 |
result = facts["resources"][0] |
| 170 |
break |
| 171 |
elif last_status_phase in ("Cancelled", "Error", "Failed"): |
| 172 |
self.fail_json( |
| 173 |
msg="Unexpected status for Build %s/%s: %s" |
| 174 |
% ( |
| 175 |
result["metadata"]["name"], |
| 176 |
result["metadata"]["namespace"], |
| 177 |
last_status_phase, |
| 178 |
) |
| 179 |
) |
| 180 |
time.sleep(wait_sleep) |
| 181 |
|
| 182 |
if last_status_phase != "Complete": |
| 183 |
name = result["metadata"]["name"] |
| 184 |
namespace = result["metadata"]["namespace"] |
| 185 |
msg = ( |
| 186 |
"Build %s/%s has not complete after %d second(s)," |
| 187 |
"current status is %s" |
| 188 |
% (namespace, name, wait_timeout, last_status_phase) |
| 189 |
) |
| 190 |
|
| 191 |
self.fail_json(msg=msg) |
| 192 |
|
| 193 |
result = [result] if result else [] |
| 194 |
self.exit_json(changed=True, builds=result) |
| 195 |
|
| 196 |
def cancel_build(self, restart): |
| 197 |
kind = "Build" |
| 198 |
api_version = "build.openshift.io/v1" |
| 199 |
|
| 200 |
namespace = self.params.get("namespace") |
| 201 |
phases = ["new", "pending", "running"] |
| 202 |
build_phases = self.params.get("build_phases", []) |
| 203 |
if build_phases: |
| 204 |
phases = [p.lower() for p in build_phases] |
| 205 |
|
| 206 |
names = [] |
| 207 |
if self.params.get("build_name"): |
| 208 |
names.append(self.params.get("build_name")) |
| 209 |
else: |
| 210 |
build_config = self.params.get("build_config_name") |
| 211 |
# list all builds from namespace |
| 212 |
params = dict(kind=kind, api_version=api_version, namespace=namespace) |
| 213 |
resources = self.kubernetes_facts(**params).get("resources", []) |
| 214 |
|
| 215 |
def _filter_builds(build): |
| 216 |
config = ( |
| 217 |
build["metadata"] |
| 218 |
.get("labels", {}) |
| 219 |
.get("openshift.io/build-config.name") |
| 220 |
) |
| 221 |
return build_config is None or ( |
| 222 |
build_config is not None and config in build_config |
| 223 |
) |
| 224 |
|
| 225 |
for item in list(filter(_filter_builds, resources)): |
| 226 |
name = item["metadata"]["name"] |
| 227 |
if name not in names: |
| 228 |
names.append(name) |
| 229 |
|
| 230 |
if len(names) == 0: |
| 231 |
self.exit_json( |
| 232 |
changed=False, msg="No Build found from namespace %s" % namespace |
| 233 |
) |
| 234 |
|
| 235 |
warning = [] |
| 236 |
builds_to_cancel = [] |
| 237 |
for name in names: |
| 238 |
params = dict( |
| 239 |
kind=kind, api_version=api_version, name=name, namespace=namespace |
| 240 |
) |
| 241 |
|
| 242 |
resource = self.kubernetes_facts(**params).get("resources", []) |
| 243 |
if len(resource) == 0: |
| 244 |
warning.append("Build %s/%s not found" % (namespace, name)) |
| 245 |
continue |
| 246 |
|
| 247 |
resource = resource[0] |
| 248 |
phase = resource["status"].get("phase").lower() |
| 249 |
|
| 250 |
# Build status.phase is matching the requested state and is not completed |
| 251 |
if phase in phases: |
| 252 |
builds_to_cancel.append(resource) |
| 253 |
else: |
| 254 |
warning.append( |
| 255 |
"build %s/%s is not in expected phase, found %s" |
| 256 |
% (namespace, name, phase) |
| 257 |
) |
| 258 |
|
| 259 |
changed = False |
| 260 |
result = [] |
| 261 |
for build in builds_to_cancel: |
| 262 |
# Set cancelled to true |
| 263 |
build["status"]["cancelled"] = True |
| 264 |
name = build["metadata"]["name"] |
| 265 |
changed = True |
| 266 |
try: |
| 267 |
content_type = "application/json" |
| 268 |
cancelled_build = self.request( |
| 269 |
"PUT", |
| 270 |
"/apis/build.openshift.io/v1/namespaces/{0}/builds/{1}".format( |
| 271 |
namespace, name |
| 272 |
), |
| 273 |
body=build, |
| 274 |
content_type=content_type, |
| 275 |
).to_dict() |
| 276 |
result.append(cancelled_build) |
| 277 |
except DynamicApiError as exc: |
| 278 |
self.fail_json( |
| 279 |
msg="Failed to cancel Build %s/%s due to: %s" |
| 280 |
% (namespace, name, exc), |
| 281 |
reason=exc.reason, |
| 282 |
status=exc.status, |
| 283 |
) |
| 284 |
except Exception as e: |
| 285 |
self.fail_json( |
| 286 |
msg="Failed to cancel Build %s/%s due to: %s" % (namespace, name, e) |
| 287 |
) |
| 288 |
|
| 289 |
# Make sure the build phase is really cancelled. |
| 290 |
def _wait_until_cancelled(build, wait_timeout, wait_sleep): |
| 291 |
start = datetime.now() |
| 292 |
last_phase = None |
| 293 |
name = build["metadata"]["name"] |
| 294 |
while (datetime.now() - start).seconds < wait_timeout: |
| 295 |
params = dict( |
| 296 |
kind=kind, api_version=api_version, name=name, namespace=namespace |
| 297 |
) |
| 298 |
resource = self.kubernetes_facts(**params).get("resources", []) |
| 299 |
if len(resource) == 0: |
| 300 |
return None, "Build %s/%s not found" % (namespace, name) |
| 301 |
resource = resource[0] |
| 302 |
last_phase = resource["status"]["phase"] |
| 303 |
if last_phase == "Cancelled": |
| 304 |
return resource, None |
| 305 |
time.sleep(wait_sleep) |
| 306 |
return ( |
| 307 |
None, |
| 308 |
"Build %s/%s is not cancelled as expected, current state is %s" |
| 309 |
% (namespace, name, last_phase), |
| 310 |
) |
| 311 |
|
| 312 |
if result and self.params.get("wait"): |
| 313 |
wait_timeout = self.params.get("wait_timeout") |
| 314 |
wait_sleep = self.params.get("wait_sleep") |
| 315 |
|
| 316 |
wait_result = [] |
| 317 |
for build in result: |
| 318 |
ret, err = _wait_until_cancelled(build, wait_timeout, wait_sleep) |
| 319 |
if err: |
| 320 |
self.exit_json(msg=err) |
| 321 |
wait_result.append(ret) |
| 322 |
result = wait_result |
| 323 |
|
| 324 |
if restart: |
| 325 |
self.start_build() |
| 326 |
|
| 327 |
self.exit_json(builds=result, changed=changed) |
| 328 |
|
| 329 |
def execute_module(self): |
| 330 |
state = self.params.get("state") |
| 331 |
if state == "started": |
| 332 |
self.start_build() |
| 333 |
else: |
| 334 |
restart = bool(state == "restarted") |
| 335 |
self.cancel_build(restart=restart) |
| 336 |
|
| 337 |
|
| 338 |
class OpenShiftPruneBuilds(OpenShiftBuilds): |
| 339 |
def __init__(self, **kwargs): |
| 340 |
super(OpenShiftPruneBuilds, self).__init__(**kwargs) |
| 341 |
|
| 342 |
def execute_module(self): |
| 343 |
# list replicationcontroller candidate for pruning |
| 344 |
kind = "Build" |
| 345 |
api_version = "build.openshift.io/v1" |
| 346 |
resource = self.find_resource(kind=kind, api_version=api_version, fail=True) |
| 347 |
|
| 348 |
self.max_creation_timestamp = None |
| 349 |
keep_younger_than = self.params.get("keep_younger_than") |
| 350 |
if keep_younger_than: |
| 351 |
now = datetime.now(timezone.utc).replace(tzinfo=None) |
| 352 |
self.max_creation_timestamp = now - timedelta(minutes=keep_younger_than) |
| 353 |
|
| 354 |
def _prunable_build(build): |
| 355 |
return build["status"]["phase"] in ( |
| 356 |
"Complete", |
| 357 |
"Failed", |
| 358 |
"Error", |
| 359 |
"Cancelled", |
| 360 |
) |
| 361 |
|
| 362 |
def _orphan_build(build): |
| 363 |
if not _prunable_build(build): |
| 364 |
return False |
| 365 |
|
| 366 |
config = build["status"].get("config", None) |
| 367 |
if not config: |
| 368 |
return True |
| 369 |
build_config = self.get_build_config(config["name"], config["namespace"]) |
| 370 |
return len(build_config) == 0 |
| 371 |
|
| 372 |
def _younger_build(build): |
| 373 |
if not self.max_creation_timestamp: |
| 374 |
return False |
| 375 |
creation_timestamp = datetime.strptime( |
| 376 |
build["metadata"]["creationTimestamp"], "%Y-%m-%dT%H:%M:%SZ" |
| 377 |
) |
| 378 |
return creation_timestamp < self.max_creation_timestamp |
| 379 |
|
| 380 |
predicates = [ |
| 381 |
_prunable_build, |
| 382 |
] |
| 383 |
if self.params.get("orphans"): |
| 384 |
predicates.append(_orphan_build) |
| 385 |
if self.max_creation_timestamp: |
| 386 |
predicates.append(_younger_build) |
| 387 |
|
| 388 |
# Get ReplicationController |
| 389 |
params = dict( |
| 390 |
kind=kind, |
| 391 |
api_version=api_version, |
| 392 |
namespace=self.params.get("namespace"), |
| 393 |
) |
| 394 |
result = self.kubernetes_facts(**params) |
| 395 |
candidates = result["resources"] |
| 396 |
for pred in predicates: |
| 397 |
candidates = list(filter(pred, candidates)) |
| 398 |
|
| 399 |
if self.check_mode: |
| 400 |
changed = len(candidates) > 0 |
| 401 |
self.exit_json(changed=changed, builds=candidates) |
| 402 |
|
| 403 |
changed = False |
| 404 |
for build in candidates: |
| 405 |
changed = True |
| 406 |
try: |
| 407 |
name = build["metadata"]["name"] |
| 408 |
namespace = build["metadata"]["namespace"] |
| 409 |
resource.delete(name=name, namespace=namespace, body={}) |
| 410 |
except DynamicApiError as exc: |
| 411 |
msg = "Failed to delete Build %s/%s due to: %s" % ( |
| 412 |
namespace, |
| 413 |
name, |
| 414 |
exc.body, |
| 415 |
) |
| 416 |
self.fail_json(msg=msg, status=exc.status, reason=exc.reason) |
| 417 |
except Exception as e: |
| 418 |
msg = "Failed to delete Build %s/%s due to: %s" % ( |
| 419 |
namespace, |
| 420 |
name, |
| 421 |
to_native(e), |
| 422 |
) |
| 423 |
self.fail_json(msg=msg, error=to_native(e), exception=e) |
| 424 |
self.exit_json(changed=changed, builds=candidates) |