-
Notifications
You must be signed in to change notification settings - Fork 70
/
engine.py
1505 lines (1240 loc) · 51 KB
/
engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import errno
import os
import uuid
import base64
import shutil
import string
import random
import subprocess
import json
import requests
import urllib3
import docker
import docker.errors
import ruamel.yaml
import yaml
from ruamel.yaml import YAML
from time import sleep
from openshift import client as openshift_client, config as openshift_config
from openshift.helper.openshift import OpenShiftObjectHelper
from jinja2 import Environment, FileSystemLoader
from kubernetes import client as kubernetes_client, config as kubernetes_config
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream as kubernetes_stream
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Handle input in 2.x/3.x
try:
input = raw_input
except NameError:
pass
# Disable insecure request warnings from both packages
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
ROLES_DIR = 'roles'
DAT_DIR = 'dat'
DAT_PATH = os.path.join(os.path.dirname(__file__), DAT_DIR)
SPEC_FILE = 'apb.yml'
EX_SPEC_FILE = 'apb.yml.j2'
EX_SPEC_FILE_PATH = os.path.join(DAT_PATH, EX_SPEC_FILE)
SPEC_FILE_PARAM_OPTIONS = ['name', 'description', 'type', 'default']
DOCKERFILE = 'Dockerfile'
EX_DOCKERFILE = 'Dockerfile.j2'
EX_DOCKERFILE_PATH = os.path.join(DAT_PATH, EX_DOCKERFILE)
MAKEFILE = 'Makefile'
EX_MAKEFILE = 'Makefile.j2'
EX_MAKEFILE_PATH = os.path.join(DAT_PATH, EX_MAKEFILE)
ACTION_TEMPLATE_DICT = {
'provision': {
'playbook_template': 'playbooks/playbook.yml.j2',
'playbook_dir': 'playbooks',
'playbook_file': 'provision.yml',
'role_task_main_template': 'roles/provision/tasks/main.yml.j2',
'role_tasks_dir': 'roles/$role_name/tasks',
'role_task_main_file': 'main.yml'
},
'deprovision': {
'playbook_template': 'playbooks/playbook.yml.j2',
'playbook_dir': 'playbooks',
'playbook_file': 'deprovision.yml',
'role_task_main_template': 'roles/deprovision/tasks/main.yml.j2',
'role_tasks_dir': 'roles/$role_name/tasks',
'role_task_main_file': 'main.yml'
},
'bind': {
'playbook_template': 'playbooks/playbook.yml.j2',
'playbook_dir': 'playbooks',
'playbook_file': 'bind.yml',
'role_task_main_template': 'roles/bind/tasks/main.yml.j2',
'role_tasks_dir': 'roles/$role_name/tasks',
'role_task_main_file': 'main.yml'
},
'unbind': {
'playbook_template': 'playbooks/playbook.yml.j2',
'playbook_dir': 'playbooks',
'playbook_file': 'unbind.yml',
'role_task_main_template': 'roles/unbind/tasks/main.yml.j2',
'role_tasks_dir': 'roles/$role_name/tasks',
'role_task_main_file': 'main.yml'
},
}
SKIP_OPTIONS = ['provision', 'deprovision', 'bind', 'unbind', 'roles']
ASYNC_OPTIONS = ['required', 'optional', 'unsupported']
SPEC_LABEL = 'com.redhat.apb.spec'
VERSION_LABEL = 'com.redhat.apb.version'
WATCH_POD_SLEEP = 5
def load_dockerfile(df_path):
with open(df_path, 'r') as dockerfile:
return dockerfile.readlines()
def load_makefile(apb_dict, params):
env = Environment(loader=FileSystemLoader(DAT_PATH), trim_blocks=True)
template = env.get_template(EX_MAKEFILE)
if not params:
params = []
return template.render(apb_dict=apb_dict, params=params)
def load_example_specfile(apb_dict, params):
env = Environment(loader=FileSystemLoader(DAT_PATH), trim_blocks=True)
template = env.get_template(EX_SPEC_FILE)
if not params:
params = []
return template.render(apb_dict=apb_dict, params=params)
def write_file(file_out, destination, force):
touch(destination, force)
with open(destination, 'w') as outfile:
outfile.write(''.join(file_out))
def insert_encoded_spec(dockerfile, encoded_spec_lines):
apb_spec_idx = [i for i, line in enumerate(dockerfile)
if SPEC_LABEL in line][0]
if not apb_spec_idx:
raise Exception(
"ERROR: %s missing from dockerfile while inserting spec blob" %
SPEC_LABEL
)
# Set end_spec_idx to a list of all lines ending in a quotation mark
end_spec_idx = [i for i, line in enumerate(dockerfile)
if line.endswith('"\n')]
# Find end of spec label if it already exists
if end_spec_idx:
for correct_end_idx in end_spec_idx:
if correct_end_idx > apb_spec_idx:
end_spec_idx = correct_end_idx
del dockerfile[apb_spec_idx + 1:end_spec_idx + 1]
break
split_idx = apb_spec_idx + 1
offset = apb_spec_idx + len(encoded_spec_lines) + 1
# Insert spec label
dockerfile[split_idx:split_idx] = encoded_spec_lines
# Insert newline after spec label
dockerfile.insert(offset, "\n")
return dockerfile
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def write_playbook(project_dir, apb_dict, action):
env = Environment(loader=FileSystemLoader(DAT_PATH))
templates = ACTION_TEMPLATE_DICT[action]
playbook_template = env.get_template(templates['playbook_template'])
playbook_out = playbook_template.render(apb_dict=apb_dict, action_name=action)
playbook_pathname = os.path.join(project_dir,
templates['playbook_dir'],
templates['playbook_file'])
mkdir_p(os.path.join(project_dir, templates['playbook_dir']))
write_file(playbook_out, playbook_pathname, True)
def write_role(project_path, apb_dict, action):
env = Environment(loader=FileSystemLoader(DAT_PATH))
templates = ACTION_TEMPLATE_DICT[action]
template = env.get_template(templates['role_task_main_template'])
main_out = template.render(apb_dict=apb_dict, action_name=action)
role_name = action + '-' + apb_dict['name']
dir_tpl = string.Template(templates['role_tasks_dir'])
dir = dir_tpl.substitute(role_name=role_name)
role_tasks_dir = os.path.join(project_path, dir)
mkdir_p(role_tasks_dir)
main_filepath = os.path.join(role_tasks_dir, templates['role_task_main_file'])
write_file(main_out, main_filepath, True)
def generate_playbook_files(project_path, skip, apb_dict):
print("Generating playbook files")
for action in ACTION_TEMPLATE_DICT.keys():
if not skip[action]:
write_playbook(project_path, apb_dict, action)
if not skip['roles']:
write_role(project_path, apb_dict, action)
def gen_spec_id(spec, spec_path):
new_id = str(uuid.uuid4())
spec['id'] = new_id
with open(spec_path, 'r') as spec_file:
lines = spec_file.readlines()
insert_i = 1 if lines[0] == '---' else 0
id_kvp = "id: %s\n" % new_id
lines.insert(insert_i, id_kvp)
with open(spec_path, 'w') as spec_file:
spec_file.writelines(lines)
def is_valid_spec(spec):
error = False
spec_keys = ['name', 'description', 'bindable', 'async', 'metadata', 'plans']
for key in spec_keys:
if key not in spec:
print("Spec is not valid. `%s` field not found." % key)
error = True
if error:
return False
if spec['async'] not in ASYNC_OPTIONS:
print("Spec is not valid. %s is not a valid `async` option." % spec['async'])
error = True
if not isinstance(spec['metadata'], dict):
print("Spec is not valid. `metadata` field is invalid.")
error = True
for plan in spec['plans']:
plan_keys = ['description', 'free', 'metadata', 'parameters']
if 'name' not in plan:
print("Spec is not valid. Plan name not found.")
return False
for key in plan_keys:
if key not in plan:
print("Spec is not valid. Plan %s is missing a `%s` field." % (plan['name'], key))
return False
if not isinstance(plan['metadata'], dict):
print("Spec is not valid. Plan %s's `metadata` field is invalid." % plan['name'])
error = True
if not isinstance(plan['parameters'], list):
print("Spec is not valid. Plan %s's `parameters` field is invalid." % plan['name'])
error = True
if error:
return False
return True
def load_spec_dict(spec_path):
with open(spec_path, 'r') as spec_file:
return YAML().load(spec_file.read())
def load_spec_str(spec_path):
with open(spec_path, 'r') as spec_file:
return spec_file.read()
def get_spec(project, output="dict"):
spec_path = os.path.join(project, SPEC_FILE)
if not os.path.exists(spec_path):
raise Exception('ERROR: Spec file: [ %s ] not found' % spec_path)
try:
if output == 'string':
spec = load_spec_str(spec_path)
else:
spec = load_spec_dict(spec_path)
except Exception as e:
print('ERROR: Failed to load spec!')
raise e
return spec
# NOTE: Splits up an encoded blob into chunks for insertion into Dockerfile
def make_friendly(blob):
line_break = 76
count = len(blob)
chunks = count / line_break
mod = count % line_break
flines = []
for i in range(chunks):
fmtstr = '{0}\\\n'
# Corner cases
if chunks == 1:
# Exactly 76 chars, two quotes
fmtstr = '"{0}"\n'
elif i == 0:
fmtstr = '"{0}\\\n'
elif i == chunks - 1 and mod == 0:
fmtstr = '{0}"\n'
offset = i * line_break
line = fmtstr.format(blob[offset:(offset + line_break)])
flines.append(line)
if mod != 0:
# Add incomplete chunk if we've got some left over,
# this is the usual case
flines.append('{0}"'.format(blob[line_break * chunks:]))
return flines
def touch(fname, force):
if os.path.exists(fname):
os.utime(fname, None)
if force:
os.remove(fname)
open(fname, 'a').close()
else:
open(fname, 'a').close()
def update_dockerfile(project, dockerfile):
spec_path = os.path.join(project, SPEC_FILE)
dockerfile_path = os.path.join(os.path.join(project, dockerfile))
# TODO: Defensively confirm the strings are encoded
# the way the code expects
blob = base64.b64encode(load_spec_str(spec_path))
dockerfile_out = insert_encoded_spec(
load_dockerfile(dockerfile_path), make_friendly(blob)
)
write_file(dockerfile_out, dockerfile_path, False)
print('Finished writing dockerfile.')
def load_source_dependencies(roles_path):
print('Trying to guess list of dependencies for APB')
cmd = "/bin/grep -R \ image: {} |awk '{print $3}'".format(roles_path)
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
if "{{" in output or "}}" in output:
print("Detected variables being used for dependent image names. " +
"Please double check the dependencies in your spec file.")
return output.split('\n')[:-1]
def get_registry_service_ip(namespace, svc_name):
ip = None
try:
openshift_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
service = api.read_namespaced_service(namespace=namespace, name=svc_name)
if service is None:
print("Couldn't find docker-registry service in namespace default. Erroring.")
return None
if service.spec.ports == []:
print("Service spec appears invalid. Erroring.")
return None
ip = service.spec.cluster_ip + ":" + str(service.spec.ports[0].port)
print("Found registry IP at: " + ip)
except ApiException as e:
print("Exception occurred trying to find %s service in namespace %s: %s" % (svc_name, namespace, e))
return None
return ip
def get_asb_route():
asb_route = None
route_list = None
suffix = None
possible_namespaces = ["ansible-service-broker", "openshift-ansible-service-broker",
"openshift-automation-service-broker"]
for namespace in possible_namespaces:
try:
openshift_config.load_kube_config()
oapi = openshift_client.OapiApi()
route_list = oapi.list_namespaced_route(namespace)
if route_list.items != []:
suffix = namespace
break
except ApiException as e:
print("Didn't find OpenShift Automation Broker route in namespace: %s.\
Reason: [%s]. Trying alternative namespaces." % namespace, e.reason)
if route_list.items == []:
print("No routes found in broker namespaces.")
return None
for route in route_list.items:
if 'asb' in route.metadata.name and 'etcd' not in route.metadata.name:
asb_route = route.spec.host
if asb_route is None:
print("Error finding a route to the OpenShift Automation Broker.")
return None
if suffix is None:
suffix = "openshift-automation-service-broker"
url = asb_route + "/" + suffix
if url.find("http") < 0:
url = "https://" + url
return url
def broker_resource_url(host, broker_name):
return "{}/apis/servicecatalog.k8s.io/v1beta1/clusterservicebrokers/{}".format(host, broker_name)
def relist_service_broker(kwargs):
try:
openshift_config.load_kube_config()
token = openshift_client.Configuration().get_api_key_with_prefix('authorization')
cluster_host = openshift_client.Configuration().host
broker_name = kwargs['broker_name']
headers = {}
if kwargs['basic_auth_username'] is not None and kwargs['basic_auth_password'] is not None:
headers = {'Authorization': "Basic " +
base64.b64encode("{0}:{1}".format(kwargs['basic_auth_username'],
kwargs['basic_auth_password']))
}
elif kwargs['auth_token'] is not None:
headers = {'Authorization': "Bearer " + kwargs['auth_token']}
else:
headers = {'Authorization': token}
if kwargs["cert"] is not None:
verify = kwargs["cert"]
else:
verify = kwargs["verify"]
response = requests.request(
"get",
broker_resource_url(cluster_host, broker_name),
verify=verify, headers=headers)
if response.status_code != 200:
errMsg = "Received non-200 status code while retrieving broker: {}\n".format(broker_name) + \
"Response body:\n" + \
str(response.text)
raise Exception(errMsg)
spec = response.json().get('spec', None)
if spec is None:
errMsg = "Spec not found in broker reponse. Response body: \n{}".format(response.text)
raise Exception(errMsg)
relist_requests = spec.get('relistRequests', None)
if relist_requests is None:
errMsg = "relistRequests not found within the spec of broker: {}\n".format(broker_name) + \
"Are you sure you are using a ServiceCatalog of >= v0.0.21?"
raise Exception(errMsg)
inc_relist_requests = relist_requests + 1
headers['Content-Type'] = 'application/strategic-merge-patch+json'
response = requests.request(
"patch",
broker_resource_url(cluster_host, broker_name),
json={'spec': {'relistRequests': inc_relist_requests}},
verify=verify, headers=headers)
if response.status_code != 200:
errMsg = "Received non-200 status code while patching relistRequests of broker: {}\n".format(
broker_name) + \
"Response body:\n{}".format(str(response.text))
raise Exception(errMsg)
print("Successfully relisted the Service Catalog")
except Exception as e:
print("Relist failure: {}".format(e))
def create_project(project):
print("Creating project {}".format(project))
try:
openshift_config.load_kube_config()
api = openshift_client.OapiApi()
api.create_project_request({
'apiVersion': 'v1',
'kind': 'ProjectRequest',
'metadata': {
'name': project
}
})
print("Created project")
# TODO: Evaluate the project request to get the actual project name
return project
except ApiException as e:
if e.status == 409:
print("Project {} already exists".format(project))
return project
else:
raise e
def delete_project(project):
print("Deleting project {}".format(project))
try:
openshift_config.load_kube_config()
api = openshift_client.OapiApi()
api.delete_project(project)
print("Project deleted")
except ApiException as e:
print("Delete project failure: {}".format(e))
raise e
def create_service_account(name, namespace):
print("Creating service account in {}".format(namespace))
try:
kubernetes_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
api.create_namespaced_service_account(
namespace,
{
'apiVersion': 'v1',
'kind': 'ServiceAccount',
'metadata': {
'name': name,
'namespace': namespace,
},
}
)
print("Created service account")
return name
except ApiException as e:
if e.status == 409:
print("Service account {} already exists".format(name))
return name
raise e
def create_cluster_role_binding(name, user_name, role="cluster-admin"):
print("Creating role binding of {} for {}".format(role, user_name))
try:
kubernetes_config.load_kube_config()
api = openshift_client.OapiApi()
# TODO: Use generateName when it doesn't throw an exception
api.create_cluster_role_binding(
{
'apiVersion': 'v1',
'kind': 'ClusterRoleBinding',
'metadata': {
'name': name,
},
'roleRef': {
'name': role,
},
'userNames': [user_name]
}
)
except ApiException as e:
raise e
except Exception as e:
# TODO:
# Right now you'll see something like --
# Exception occurred! 'module' object has no attribute 'V1RoleBinding'
# Looks like an issue with the openshift-restclient...well the version
# of k8s included by openshift-restclient. Keeping this from below.
pass
print("Created Role Binding")
return name
def create_role_binding(name, namespace, service_account, role="admin"):
print("Creating role binding for {} in {}".format(service_account, namespace))
try:
kubernetes_config.load_kube_config()
api = openshift_client.OapiApi()
# TODO: Use generateName when it doesn't throw an exception
api.create_namespaced_role_binding(
namespace,
{
'apiVersion': 'v1',
'kind': 'RoleBinding',
'metadata': {
'name': name,
'namespace': namespace,
},
'subjects': [{
'kind': 'ServiceAccount',
'name': service_account,
'namespace': namespace,
}],
'roleRef': {
'name': role,
},
}
)
except ApiException as e:
if e.status == 409:
print("Role binding {} already exists".format(name))
return name
raise e
except Exception as e:
# TODO:
# Right now you'll see something like --
# Exception occurred! 'module' object has no attribute 'V1RoleBinding'
# Looks like an issue with the openshift-restclient...well the version
# of k8s included by openshift-restclient
pass
print("Created Role Binding")
return name
def create_pod(image, name, namespace, command, service_account):
print("Creating pod with image {} in {}".format(image, namespace))
try:
kubernetes_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
pod = api.create_namespaced_pod(
namespace,
{
'apiVersion': 'v1',
'kind': 'Pod',
'metadata': {
'generateName': name,
'namespace': namespace
},
'spec': {
'containers': [{
'image': image,
'imagePullPolicy': 'IfNotPresent',
'name': name,
'command': command,
'env': [
{
'name': 'POD_NAME',
'valueFrom': {
'fieldRef': {'fieldPath': 'metadata.name'}
}
},
{
'name': 'POD_NAMESPACE',
'valueFrom': {
'fieldRef': {'fieldPath': 'metadata.namespace'}
}
}
],
}],
'restartPolicy': 'Never',
'serviceAccountName': service_account,
}
}
)
print("Created Pod")
return (pod.metadata.name, pod.metadata.namespace)
except Exception as e:
print("failed - %s" % e)
return ("", "")
def watch_pod(name, namespace):
kubernetes_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
while True:
sleep(WATCH_POD_SLEEP)
pod_status = api.read_namespaced_pod(name, namespace).status
pod_phase = pod_status.phase
print("Pod in phase: {}".format(pod_phase))
if pod_phase == 'Succeeded' or pod_phase == 'Failed':
print(api.read_namespaced_pod_log(name, namespace))
return pod_phase
if pod_phase == 'Pending':
try:
reason = pod_status.container_statuses[0].state.waiting.reason
except ApiException:
pass
if reason == 'ImagePullBackOff':
raise ApiException("APB failed {} - check name".format(reason))
def run_apb(project, image, name, action, parameters={}):
ns = create_project(project)
sa = create_service_account(name, ns)
create_role_binding(name, ns, sa)
parameters['namespace'] = ns
command = ['entrypoint.sh', action, "--extra-vars", json.dumps(parameters)]
return create_pod(
image=image,
name=name,
namespace=ns,
command=command,
service_account=sa
)
def retrieve_test_result(name, namespace):
count = 0
try:
openshift_config.load_kube_config()
api = kubernetes_client.CoreV1Api()
except Exception as e:
print("Failed to get api client: {}".format(e))
while True:
try:
count += 1
api_response = kubernetes_stream(
api.connect_get_namespaced_pod_exec,
name,
namespace,
command="/usr/bin/test-retrieval",
stderr=True, stdin=False,
stdout=True, tty=False)
if "test results are not available" not in api_response:
return api_response
sleep(WATCH_POD_SLEEP)
except ApiException as e:
if count >= 50:
return None
pod_phase = api.read_namespaced_pod(name, namespace).status.phase
if pod_phase == 'Succeeded' or pod_phase == 'Failed':
print("Pod phase {} without returning test results".format(pod_phase))
return None
sleep(WATCH_POD_SLEEP)
except Exception as e:
print("exception: %s" % e)
return None
def broker_request(broker, service_route, method, **kwargs):
if broker is None:
broker = get_asb_route()
if broker is None:
raise Exception("Could not find route to ansible-service-broker. "
"Use --broker or log into the cluster using \"oc login\"")
if not broker.startswith('http'):
broker = 'https://' + broker
if kwargs["cert"] is not None:
verify = kwargs["cert"]
else:
verify = kwargs["verify"]
url = broker + service_route
print("Contacting the ansible-service-broker at: %s" % url)
try:
openshift_config.load_kube_config()
headers = {}
if kwargs['basic_auth_username'] is not None and kwargs['basic_auth_password'] is not None:
headers = {'Authorization': "Basic " +
base64.b64encode("{0}:{1}".format(kwargs['basic_auth_username'],
kwargs['basic_auth_password']))
}
elif kwargs['auth_token'] is not None:
headers = {'Authorization': "Bearer " + kwargs['auth_token']}
else:
token = openshift_client.Configuration().get_api_key_with_prefix('authorization')
headers = {'Authorization': token}
response = requests.request(method, url, verify=verify,
headers=headers, data=kwargs.get("data"))
except Exception as e:
print("ERROR: Failed broker request (%s) %s" % (method, url))
raise e
return response
def cmdrun_list(**kwargs):
response = broker_request(kwargs['broker'], "/v2/catalog", "get",
verify=kwargs["verify"], cert=kwargs["cert"],
basic_auth_username=kwargs.get("basic_auth_username"),
basic_auth_password=kwargs.get("basic_auth_password"),
auth_token=kwargs.get("auth_token"))
if response.status_code != 200:
print("Error: Attempt to list APBs in the broker returned status: %d" % response.status_code)
print("Unable to list APBs in Ansible Service Broker.")
exit(1)
services = response.json()['services']
if not services:
print("No APBs found")
elif kwargs["output"] == 'json':
print_json_list(services)
elif kwargs["verbose"]:
print_verbose_list(services)
else:
print_list(services)
def print_json_list(services):
print(json.dumps(services, indent=4, sort_keys=True))
def print_verbose_list(services):
for service in services:
print_service(service)
def print_service(service):
cmap = ruamel.yaml.comments.CommentedMap()
if 'name' in service:
cmap['name'] = service['name']
if 'id' in service:
cmap['id'] = service['id']
if 'description' in service:
cmap['description'] = service['description']
if 'bindable' in service:
cmap['bindable'] = service['bindable']
if 'metadata' in service:
cmap['metadata'] = service['metadata']
if 'plans' in service:
cmap['plans'] = pretty_plans(service['plans'])
print(ruamel.yaml.dump(cmap, Dumper=ruamel.yaml.RoundTripDumper))
def pretty_plans(plans):
pp = []
if plans is None:
return
for plan in plans:
cmap = ruamel.yaml.comments.CommentedMap()
if 'name' in plan:
cmap['name'] = plan['name']
if 'description' in plan:
cmap['description'] = plan['description']
if 'free' in plan:
cmap['free'] = plan['free']
if 'metadata' in plan:
cmap['metadata'] = plan['metadata']
try:
plan_params = plan['schemas']['service_instance']['create']['parameters']['properties']
except KeyError:
plan_params = []
cmap['parameters'] = plan_params
try:
plan_bind_params = plan['schemas']['service_binding']['create']['parameters']['properties']
except KeyError:
plan_bind_params = []
cmap['bind_parameters'] = plan_bind_params
pp.append(cmap)
return pp
def print_list(services):
max_id = 10
max_name = 10
max_desc = 10
for service in services:
max_id = max(max_id, len(service["id"]))
max_name = max(max_name, len(service["name"]))
max_desc = max(max_desc, len(service["description"]))
template = "{id:%d}{name:%d}{description:%d}" % (max_id + 2, max_name + 2, max_desc + 2)
print(template.format(id="ID", name="NAME", description="DESCRIPTION"))
for service in sorted(services, key=lambda s: s['name']):
print(template.format(**service))
def build_apb(project, dockerfile=None, tag=None):
if dockerfile is None:
dockerfile = "Dockerfile"
spec = get_spec(project)
if 'version' not in spec:
print("APB spec does not have a listed version. Please update apb.yml")
exit(1)
if not tag:
tag = spec['name']
update_dockerfile(project, dockerfile)
print("Building APB using tag: [%s]" % tag)
try:
client = create_docker_client()
client.images.build(path=project, tag=tag, dockerfile=dockerfile)
except docker.errors.DockerException:
print("Error accessing the docker API. Is the daemon running?")
raise
print("Successfully built APB image: %s" % tag)
return tag
def get_registry_images():
try:
openshift_config.load_kube_config()
oapi = openshift_client.OapiApi()
image_list = oapi.list_image(_preload_content=False)
image_list = json.loads(image_list.data)
except Exception as e:
print("Exception retrieving list of images: %s" % e)
raise Exception("Unable to retrieve images in local registry")
return image_list
def get_registry(kwargs):
namespace = kwargs['reg_namespace']
service = kwargs['reg_svc_name']
registry_route = kwargs['reg_route']
if registry_route:
return registry_route
elif is_minishift():
return get_minishift_registry()
else:
registry = get_registry_service_ip(namespace, service)
if registry is None:
print("Failed to find registry service IP address.")
raise Exception("Unable to get registry IP from namespace %s" % namespace)
return registry
def delete_old_images(image_name):
# Let's ignore the registry prefix for now because sometimes our tag doesn't match the registry
registry, image_name = image_name.split('/', 1)
try:
oapi = openshift_client.OapiApi()
image_list = get_registry_images()
for image in image_list['items']:
image_fqn, image_sha = image['dockerImageReference'].split("@")
if image_name in image_fqn:
print("Found image: %s" % image_fqn)
if registry not in image_fqn:
# This warning will only get displayed if a user has used --registry-route
# This is because the route name gets collapsed into the service hostname
# when pushed to the registry.
print("Warning: Tagged image registry prefix doesn't match. Deleting anyway. Given: %s; Found: %s"
% (registry, image_fqn.split('/')[0]))
oapi.delete_image(name=image_sha, body={})
print("Successfully deleted %s" % image_sha)
except Exception as e:
print("Exception deleting old images: %s" % e)
print("Not erroring out, this may cause duplicate images in the registry. Try: `oc get images`.")
return
def push_apb(registry, tag, **kwargs):
try:
client = create_docker_client()
openshift_config.load_kube_config()
if kwargs['auth_token'] is not None:
token = kwargs['auth_token']
else:
api_key = openshift_client.Configuration().get_api_key_with_prefix('authorization')
if api_key is None:
raise Exception(
"No api key found in kubeconfig. NOTE: " +
"system:admin *cannot* be used with apb, since it " +
"does not have a token."
)
token = api_key.split(" ")[1]
username = "developer" if is_minishift() else "unused"
client.login(username=username, password=token, registry=registry, reauth=True)
delete_old_images(tag)
print("Pushing the image, this could take a minute...")
client.images.push(tag)
print("Successfully pushed image: " + tag)
except docker.errors.DockerException:
print("Error accessing the docker API. Is the daemon running?")
raise
except docker.errors.APIError:
print("Failed to login to the docker API.")
raise
def cmdrun_setup(**kwargs):
try:
create_docker_client()
except Exception as e:
print("Error! Failed to connect to Docker client. Please ensure it is running. Exception: %s" % e)
exit(1)