Skip to content

Commit 9029ecf

Browse files
committed
Adding an Ephemeral Projects decorator
Fixing incorrect error message Adding the ability to create an imagestream Adding ansible updates
1 parent f1e2497 commit 9029ecf

File tree

5 files changed

+129
-3
lines changed

5 files changed

+129
-3
lines changed

ansible/rebuild_module.digest

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
6a4d5297b27571c6bb95a6114d5c6a3c -
1+
7117af22373867e9f3ec3c0964ccd0ee -

ansible/roles/openshift_client_python/library/openshift_client_python.py

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/ephemeral_project.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/python
2+
3+
from __future__ import print_function
4+
5+
import argparse
6+
import logging
7+
import traceback
8+
import openshift as oc
9+
from openshift import OpenShiftPythonException
10+
from openshift.decorators import ephemeral_project
11+
12+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
13+
logger = logging.getLogger('EphemeralProject')
14+
logger.setLevel(logging.INFO)
15+
16+
17+
@ephemeral_project
18+
def run_pods(pod_count=5, *, project_name=None):
19+
logger.info('Running in namespace: {}'.format(project_name))
20+
21+
for i in range(pod_count):
22+
pod_name = 'pod-{}'.format(i)
23+
logger.info('Creating: {}'.format(pod_name))
24+
25+
pod_selector = oc.create(oc.build_pod_simple(pod_name, image='python:3', command=['tail', '-f', '/dev/null']))
26+
pod_selector.until_all(1, success_func=oc.status.is_pod_running)
27+
28+
pods = oc.selector('pods').objects()
29+
logger.info('Found {} pods'.format(len(pods)))
30+
assert len(pods) == pod_count
31+
32+
33+
if __name__ == '__main__':
34+
parser = argparse.ArgumentParser(description='Demonstrate the ephemeral_project decorator')
35+
parser.add_argument('-b', '--bastion', default=None,
36+
help='user@host, hostname, or IP on which to execute oc (oc is executed locally if not specified)',
37+
required=False)
38+
parser.add_argument('--insecure-skip-tls-verify', action='store_true',
39+
help='Skip TLS verify during oc interactions (recommended when replacing api certs)')
40+
parser.set_defaults(insecure_skip_tls_verify=False)
41+
42+
params = vars(parser.parse_args())
43+
44+
skip_tls_verify = params['insecure_skip_tls_verify']
45+
46+
if skip_tls_verify:
47+
oc.set_default_skip_tls_verify(True)
48+
49+
bastion_hostname = params['bastion']
50+
if not bastion_hostname:
51+
logging.info('Running in local mode. Expecting "oc" in PATH')
52+
53+
with oc.client_host(hostname=bastion_hostname, username="root", auto_add_host=True, load_system_host_keys=False):
54+
# Ensure tests complete within 5 minutes and track all oc invocations
55+
with oc.timeout(60 * 5), oc.tracking() as t:
56+
try:
57+
run_pods()
58+
except (ValueError, OpenShiftPythonException, Exception):
59+
# Print out exception stack trace via the traceback module
60+
logger.info('Traceback output:\n{}\n'.format(traceback.format_exc()))
61+
62+
# Print out all oc interactions and do not redact secret information
63+
logger.info("OC tracking output:\n{}\n".format(t.get_result().as_json(redact_streams=False)))

packages/openshift/base_verbs.py

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def delete_project(name, ignore_not_found=False, grace_period=None, force=False,
218218
base_args.append("--force")
219219

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

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

10431043

1044+
def build_imagestream_simple(imagestream_name,
1045+
namespace=None,
1046+
labels=None,
1047+
local_lookup_policy=False,
1048+
api_version='image.openshift.io/v1'):
1049+
if not labels:
1050+
labels = {}
1051+
1052+
metadata = {
1053+
'name': imagestream_name,
1054+
'labels': labels,
1055+
}
1056+
1057+
if namespace:
1058+
metadata['namespace'] = namespace
1059+
1060+
spec = {
1061+
'lookupPolicy': {
1062+
'local': local_lookup_policy
1063+
}
1064+
}
1065+
1066+
imagestream = {
1067+
'apiVersion': api_version,
1068+
'kind': 'ImageStream',
1069+
'metadata': metadata,
1070+
'spec': spec,
1071+
}
1072+
1073+
return imagestream
1074+
1075+
10441076
def update_api_resources():
10451077
"""
10461078
Makes a call to `oc api-resources` and updates openshift-client-python's internal view of

packages/openshift/decorators.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from __future__ import absolute_import
2+
3+
import functools
4+
import random
5+
import string
6+
7+
from . import new_project, delete_project
8+
9+
10+
def _id_generator(size=6, chars=string.ascii_lowercase + string.digits):
11+
return ''.join(random.choice(chars) for _ in range(size))
12+
13+
14+
def _generate_project_name():
15+
return "ephemeral-project-{}".format(_id_generator())
16+
17+
18+
def ephemeral_project(_func=None, *, project_name=_generate_project_name()):
19+
def decorator(func):
20+
@functools.wraps(func)
21+
def wrapper(*args, **kwargs):
22+
with new_project(project_name):
23+
value = func(*args, project_name=project_name, **kwargs)
24+
delete_project(project_name)
25+
return value
26+
return wrapper
27+
28+
if _func is None:
29+
return decorator
30+
else:
31+
return decorator(_func)

0 commit comments

Comments
 (0)