Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ansible/rebuild_module.digest
Original file line number Diff line number Diff line change
@@ -1 +1 @@
6a4d5297b27571c6bb95a6114d5c6a3c -
7117af22373867e9f3ec3c0964ccd0ee -

Large diffs are not rendered by default.

63 changes: 63 additions & 0 deletions examples/ephemeral_project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/usr/bin/python

from __future__ import print_function

import argparse
import logging
import traceback
import openshift as oc
from openshift import OpenShiftPythonException
from openshift.decorators import ephemeral_project

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('EphemeralProject')
logger.setLevel(logging.INFO)


@ephemeral_project
def run_pods(pod_count=5, *, project_name=None):
logger.info('Running in namespace: {}'.format(project_name))

for i in range(pod_count):
pod_name = 'pod-{}'.format(i)
logger.info('Creating: {}'.format(pod_name))

pod_selector = oc.create(oc.build_pod_simple(pod_name, image='python:3', command=['tail', '-f', '/dev/null']))
pod_selector.until_all(1, success_func=oc.status.is_pod_running)

pods = oc.selector('pods').objects()
logger.info('Found {} pods'.format(len(pods)))
assert len(pods) == pod_count


if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Demonstrate the ephemeral_project decorator')
parser.add_argument('-b', '--bastion', default=None,
help='user@host, hostname, or IP on which to execute oc (oc is executed locally if not specified)',
required=False)
parser.add_argument('--insecure-skip-tls-verify', action='store_true',
help='Skip TLS verify during oc interactions (recommended when replacing api certs)')
parser.set_defaults(insecure_skip_tls_verify=False)

params = vars(parser.parse_args())

skip_tls_verify = params['insecure_skip_tls_verify']

if skip_tls_verify:
oc.set_default_skip_tls_verify(True)

bastion_hostname = params['bastion']
if not bastion_hostname:
logging.info('Running in local mode. Expecting "oc" in PATH')

with oc.client_host(hostname=bastion_hostname, username="root", auto_add_host=True, load_system_host_keys=False):
# Ensure tests complete within 5 minutes and track all oc invocations
with oc.timeout(60 * 5), oc.tracking() as t:
try:
run_pods()
except (ValueError, OpenShiftPythonException, Exception):
# Print out exception stack trace via the traceback module
logger.info('Traceback output:\n{}\n'.format(traceback.format_exc()))

# Print out all oc interactions and do not redact secret information
logger.info("OC tracking output:\n{}\n".format(t.get_result().as_json(redact_streams=False)))
34 changes: 33 additions & 1 deletion packages/openshift/base_verbs.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def delete_project(name, ignore_not_found=False, grace_period=None, force=False,
base_args.append("--force")

r.add_action(oc_action(cur_context(), "delete", cmd_args=["project", name, base_args, cmd_args]))
r.fail_if("Unable to create delete project: {}".format(name))
r.fail_if("Unable to delete project: {}".format(name))

# Give the controller time to clean up project resources:
while selector('namespace/{}'.format(name)).count_existing() > 0:
Expand Down Expand Up @@ -1041,6 +1041,38 @@ def build_secret_dockerconfig(secret_name, image_registry_auth_infos, obj_labels
return d


def build_imagestream_simple(imagestream_name,
namespace=None,
labels=None,
local_lookup_policy=False,
api_version='image.openshift.io/v1'):
if not labels:
labels = {}

metadata = {
'name': imagestream_name,
'labels': labels,
}

if namespace:
metadata['namespace'] = namespace

spec = {
'lookupPolicy': {
'local': local_lookup_policy
}
}

imagestream = {
'apiVersion': api_version,
'kind': 'ImageStream',
'metadata': metadata,
'spec': spec,
}

return imagestream


def update_api_resources():
"""
Makes a call to `oc api-resources` and updates openshift-client-python's internal view of
Expand Down
31 changes: 31 additions & 0 deletions packages/openshift/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from __future__ import absolute_import

import functools
import random
import string

from . import new_project, delete_project


def _id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))


def _generate_project_name():
return "ephemeral-project-{}".format(_id_generator())


def ephemeral_project(_func=None, *, project_name=_generate_project_name()):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with new_project(project_name):
value = func(*args, project_name=project_name, **kwargs)
delete_project(project_name)
return value
return wrapper

if _func is None:
return decorator
else:
return decorator(_func)