forked from openshift/openshift-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase_verbs.py
More file actions
1646 lines (1329 loc) · 63.4 KB
/
base_verbs.py
File metadata and controls
1646 lines (1329 loc) · 63.4 KB
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
from __future__ import print_function
from __future__ import absolute_import
import os
import base64
import io
import sys
import traceback
import time
import json
import yaml
import six
from .selector import Selector, selector
from .action import oc_action
from .context import cur_context, project, no_tracking
from .result import Result
from .apiobject import APIObject
from .model import Model, Missing, OpenShiftPythonException
from . import util
from . import naming
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def __new_objects_action_selector(verb, cmd_args=None, stdin_obj=None, no_namespace=False, auto_raise=True):
"""
Performs and oc action and records objects output from the verb
as changed in the content.
:param verb: The verb to execute
:param cmd_args: A list of str|list<str> which will be flattened into command line arguments
:param stdin_obj: The standard input to feed to the invocation.
:param no_namespace: If the incoming objects have namespace information, set to True.
:param auto_raise: If True, errors from oc will raise an exception.
:return: A selector for the newly created objects
"""
sel = Selector(verb,
object_action=oc_action(cur_context(), verb, cmd_args=['-o=name', cmd_args], stdin_obj=stdin_obj,
no_namespace=no_namespace))
if auto_raise:
sel.fail_if('{} returned an error: {}'.format(verb, sel.err().strip()))
return sel
def new_app(cmd_args=None):
return __new_objects_action_selector("new-app", cmd_args=cmd_args)
def new_build(cmd_args=None):
return __new_objects_action_selector("new-build", cmd_args=cmd_args)
def start_build(cmd_args=None):
return __new_objects_action_selector("start-build", cmd_args=cmd_args)
def get_project_name(cmd_args=None):
"""
:return: Returns the name of the project selected by the current project. If no project
context has been established, returns KUBECONFIG project using `oc project`.
"""
context_project = cur_context().get_project()
if context_project:
return context_project
r = Result("project-name")
r.add_action(oc_action(cur_context(), "project", cmd_args=["-q", cmd_args]))
r.fail_if("Unable to determine current project")
return r.out().strip()
def whoami(cmd_args=None):
"""
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: The current user
"""
r = Result("whoami")
r.add_action(oc_action(cur_context(), "whoami", cmd_args=cmd_args))
r.fail_if("Unable to determine current user")
return r.out().strip()
def get_auth_token(cmd_args=None):
"""
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: The current user's token
"""
r = Result("whoami")
r.add_action(oc_action(cur_context(), "whoami", cmd_args=['-t', cmd_args]))
r.fail_if("Unable to determine current token")
return r.out().strip()
def get_serviceaccount_auth_token(sa_name, cmd_args=None):
"""
Uses `oc serviceaccounts get-token <sa_name>`
:param sa_name: The name of the service account from which to extract the token
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: The specified service accounts' token
"""
r = Result("sa_token")
r.add_action(oc_action(cur_context(), "serviceaccounts", cmd_args=['get-token', sa_name, cmd_args]))
r.fail_if("Unable to determine serviceaccount token")
return r.out().strip()
def get_config_context(cmd_args=None):
"""
:param cmd_args: An optional list of additional arguments to pass on the command line
:returns: Returns the result of 'oc config current-context' . If no context currently
exists, None is returned.
"""
r = Result("current-context")
r.add_action(oc_action(cur_context(), "config", cmd_args=['current-context', cmd_args]))
if r.status() != 0:
return None
return r.out()
def use_config_context(context, cmd_args=None):
"""
Sets the current context to use.
:param context: The context name to pass into use-context. If None, no action is taken.
exists, None is returned.
:param cmd_args: An optional list of additional arguments to pass on the command line
"""
if not context:
return
r = Result("use-context")
r.add_action(oc_action(cur_context(), "config", cmd_args=['use-context', context, cmd_args]))
r.fail_if('Error when trying to use to use-context: {}'.format(context))
return True
def login(username, password, cmd_args=None):
"""
Executes a login operation with the specified username and password. You usually want to invoke
this inside of an api_server() context.
:param username: The username to supply to the login
:param password: The password to supply to the login
:param cmd_args: An optional list of additional arguments to pass on the command line
:return:
"""
r = Result("login")
r.add_action(oc_action(cur_context(), "login", cmd_args=['-u', username, '-p', password, cmd_args]))
r.fail_if('Error when trying to login')
return True
def new_project(name, ok_if_exists=False, cmd_args=None, description=None, display_name=None, adm=False):
"""
Creates a new project
:param name: The name of the project to create
:param ok_if_exists: Do not raise an error if the project already exists
:param cmd_args: An optional list of additional arguments to pass on the command line
:param description: The project's description name
:param display_name: The project's display name
:param adm: If true, 'oc adm new-project' will be used. This avoid project templates and can
create privileged namespaces (e.g. openshift-*).
:return: A context manager that can be used with 'with' statement.
"""
# If user is ok with the project already existing, see if it is and return immediately if detected
if ok_if_exists:
if selector('project/{}'.format(name)).count_existing() > 0:
return project(name)
other_args = []
if description:
other_args.extend(['--description', description])
if display_name:
other_args.extend(['--display-name', display_name])
r = Result("new-project")
if adm:
r.add_action(oc_action(cur_context(), 'adm', cmd_args=['new-project', name, cmd_args, other_args]))
else:
r.add_action(oc_action(cur_context(), "new-project", cmd_args=[name, cmd_args, other_args, '--skip-config-write']))
r.fail_if("Unable to create new project: {}".format(name))
return project(name)
def delete_project(name, ignore_not_found=False, grace_period=None, force=False, cmd_args=None):
"""
Deletes the identified project.
:param name: The name of the project to delete (e.g. 'project/x', 'namespace/x', or 'x')
:param ignore_not_found: Pass --ignore-not-found to oc delete
:param grace_period: If specified, sets the --grace-period arguments.
:param force: If True, pass --force to delete
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: n/a
"""
r = Result("delete-project")
_, _, name = naming.split_fqn(name) # Allow project/x, namespace/x, etc. Just out actual name.
base_args = list()
if ignore_not_found:
base_args.append("--ignore-not-found")
if grace_period is not None:
base_args.append("--grace-period={}".format(grace_period))
if force:
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 delete project: {}".format(name))
# Give the controller time to clean up project resources:
while selector('namespace/{}'.format(name)).count_existing() > 0:
time.sleep(1)
def _to_dict_list(str_dict_model_apiobject_or_list_thereof):
"""
Normalizes the parameter into a python list<dict>.
:param str_dict_model_apiobject_or_list_thereof: The parameter to convert. Could be a yaml/json string,
dict, Model, apiobject, or a list of any of those.
:return: A normalized list<dict>, and a boolean of whether namespace information was detected in the result.
"""
normalized_list = []
namespace_detected = False
# If incoming is not a list, make it a list so we can keep DRY
if not isinstance(str_dict_model_apiobject_or_list_thereof, list):
str_dict_model_apiobject_or_list_thereof = [str_dict_model_apiobject_or_list_thereof]
for i in str_dict_model_apiobject_or_list_thereof:
if i is None:
continue
if isinstance(i, APIObject):
i = i.model
if isinstance(i, six.string_types):
if i.strip().startswith('{'):
i = json.loads(i)
else:
i = yaml.safe_load(i)
if not isinstance(i, dict):
raise ValueError('Unable to convert type into list items dict: {}'.format(type(i)))
if not isinstance(i, Model):
i = Model(dict_to_model=i)
# At this point, we should have a Model to make analyzing the structure easier
# See if a modeled object has a defined, non-empty string for namesapce
if i.metadata.namespace is not Missing and i.metadata.namespace:
namespace_detected = True
# If we received a List, extract the underlying items. This should include unwrapping things like
# kind: ImageStreamList.
if i.kind.endswith("List") and i.items is not Missing:
# can't use .items here since that is interpreted as a method reference
normalized_list.extend(i['items']._primitive())
else:
normalized_list.append(i._primitive())
return normalized_list, namespace_detected
def drain_node(apiobj_node_name_or_qname, ignore_daemonsets=True,
delete_local_data=True, force=False, timeout_seconds=None,
grace_period_seconds=None, cmd_args=None, auto_raise=True):
r = Result('drain')
base_args = list()
if isinstance(apiobj_node_name_or_qname, APIObject):
node_name = apiobj_node_name_or_qname.name()
else:
_, _, node_name = naming.split_fqn(apiobj_node_name_or_qname)
if ignore_daemonsets:
base_args.append('--ignore-daemonsets')
if delete_local_data:
# The '--delete-local-data' flag is being deprecated.
# A new flag was introduced in OpenShift 4.7 ('--delete-emptydir-data').
# The following logic is to provide backward compatibility for folks that
# may not update their 'oc' binaries all that often.
version = get_client_version()
pieces = version.split('.')
major = int(pieces[0])
minor = int(pieces[1])
# Local builds of OC have `alpha` in their version string. We are going
# to assume that anyone building their own version of 'oc' will most
# likely have the latest/greatest code that contains the new flag.
if 'alpha' in version or major > 4 or (major == 4 and minor >= 7):
base_args.append('--delete-emptydir-data')
else:
base_args.append('--delete-local-data')
if force:
base_args.append('--force')
if timeout_seconds is not None and timeout_seconds > 0:
base_args.append('--timeout={}s'.format(timeout_seconds))
if grace_period_seconds is not None and grace_period_seconds > -1:
base_args.append('--grace-period={}'.format(grace_period_seconds))
r.add_action(oc_action(cur_context(), 'adm', cmd_args=['drain', node_name, base_args, cmd_args], no_namespace=True))
if auto_raise:
r.fail_if('Error during drain of node: {}'.format(node_name))
return r
def create(str_dict_model_apiobject_or_list_thereof, cmd_args=None):
"""
Runs oc create against an object or list of objects. The objects will be normalized into a
kube List object and set to the create verb.
:param str_dict_model_apiobject_or_list_thereof: A single json/yaml string, Model, apiobject, or a
list of any of those.
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: Returns a selector which can select the items just created (if namespace is correct)
"""
items, namespace_detected = _to_dict_list(str_dict_model_apiobject_or_list_thereof)
# If nothing is going to be acted on, return an empty selected
if not items:
return selector([])
m = {
'kind': 'List',
'apiVersion': 'v1',
'metadata': {},
'items': items
}
return __new_objects_action_selector("create",
cmd_args=["-f", "-", cmd_args],
stdin_obj=m,
no_namespace=namespace_detected)
def delete(str_dict_model_apiobject_or_list_thereof, ignore_not_found=False,
grace_period=None, force=False, cmd_args=None):
"""
Deletes one or more objects
:param str_dict_model_apiobject_or_list_thereof:
:param ignore_not_found: Pass --ignore-not-found to oc delete
:param grace_period: If specified, sets the --grace-period arguments.
:param force: Pass --force to oc delete
:param cmd_args: An optional list of additional arguments to pass on the command line
:return: If successful, returns a list of qualified names to the caller (can be empty)
"""
items, namespace_detected = _to_dict_list(str_dict_model_apiobject_or_list_thereof)
# If there is nothing to act on, return empty selector
if not items:
return []
m = {
'kind': 'List',
'apiVersion': 'v1',
'metadata': {},
'items': items
}
base_args = ['-o=name', '-f', '-']
if ignore_not_found:
base_args.append('--ignore-not-found')
if grace_period is not None:
base_args.append('--grace-period={}'.format(grace_period))
if force:
base_args.append('--force')
r = Result('delete')
r.add_action(oc_action(cur_context(), "delete",
cmd_args=[base_args, cmd_args],
stdin_obj=m,
no_namespace=namespace_detected))
r.fail_if("Delete operation failed")
return r.out().strip().split()
def invoke_create(cmd_args=None, no_namespace=False):
"""
Relies on caller to provide sensible command line arguments. -o=name will
be added to the arguments automatically.
:param cmd_args: An optional list of additional arguments to pass on the command line
:param no_namespace: If False, the context based namespace will not be passed along with the invocation.
:return: A selector for the newly created objects
"""
return __new_objects_action_selector("create", cmd_args, no_namespace=no_namespace)
def invoke(verb, cmd_args=None, stdin_str=None, no_namespace=False, auto_raise=True):
"""
Invokes oc with the supplied arguments.
:param verb: The verb to execute
:param cmd_args: An optional list of additional arguments to pass on the command line
:param stdin_str: The standard input to supply to the process
:param no_namespace: If False, the context based namespace will not be passed along with the invocation.
:param auto_raise: Raise an exception if the command returns a non-zero return code
:return: A Result object containing the executed Action(s) with the output captured.
"""
r = Result('invoke')
r.add_action(oc_action(cur_context(),
verb=verb,
cmd_args=cmd_args,
stdin_str=stdin_str,
no_namespace=no_namespace))
if auto_raise:
r.fail_if("Non-zero return code from invoke action")
return r
def get_pod_metrics(pod_obj, auto_raise=True):
"""
Returns a 'PodMetrics' APIObject object for the specified pod.
e.g.
{"kind":"PodMetrics","apiVersion":"metrics.k8s.io/v1beta1","metadata":{"name":"sync-zv8ck","namespace":"openshift-node","selfLink":"/apis/metrics.k8s.io/v1beta1/namespaces/openshift-node/pods/sync-zv8ck","creationTimestamp":"2018-11-29T19:55:04Z"},"timestamp":"2018-11-29T19:54:30Z","window":"1m0s","containers":[{"name":"sync","usage":{"cpu":"0","memory":"35664Ki"}}]}
:param pod_obj: A Pod APIObject
:param auto_raise: If True, raise an exception if the command fails. Else return Missing.
:return: A 'PodMetrics' APIObject
"""
r = Result('raw-metrics')
cmd_args = [
'--raw',
'/apis/metrics.k8s.io/v1beta1/namespaces/{}/pods/{}'.format(pod_obj.namespace(), pod_obj.name())
]
r.add_action(oc_action(cur_context(), verb='get', cmd_args=cmd_args, no_namespace=True))
if auto_raise:
r.fail_if("Non-zero return code from get --raw to metrics.k8s.io")
elif r.status() != 0:
return Missing
return APIObject(string_to_model=r.out())
def get_pods_by_node(apiobj_node_name_or_qname):
"""
Returns a list<APIObject> where each APIObject is a pod running on the specified node.
:param apiobj_node_name_or_qname: The name of the node ("xyz" or "node/xyz") or apiobject
:return: A list of apiobjects. List may be empty.
"""
if isinstance(apiobj_node_name_or_qname, APIObject):
node_name = apiobj_node_name_or_qname.name()
else:
# permit node/xyz, but and strip off node/
_, _, node_name = naming.split_fqn(apiobj_node_name_or_qname)
return selector('pod', all_namespaces=True,
field_selectors={'spec.nodeName': node_name}).objects(ignore_not_found=True)
def get_client_version():
"""
:return: Returns the version of the oc binary being used (e.g. '3.11.28')
"""
r = Result('version3')
r.add_action(oc_action(cur_context(), verb='version'))
r.fail_if('Unable to determine version')
# Example OpenShift 3 output:
# oc v3.11.82
# kubernetes v1.11.0+d4cacc0
# features: Basic-Auth GSSAPI Kerberos SPNEGO
for line in r.out().splitlines():
if line.startswith('oc v'):
return line.split()[1].lstrip('v')
r = Result('version4')
r.add_action(oc_action(cur_context(), verb='version', cmd_args=['-o=json']))
r.fail_if('Unable to determine version')
version_dict = json.loads(r.out())
version_model = Model(dict_to_model=version_dict, case_insensitive=True)
if version_model.clientVersion.gitVersion:
return version_model.clientVersion.gitVersion.lstrip('v')
raise OpenShiftPythonException('Unable extract version from json: {}'.format(r.out()))
def get_server_version():
"""
:return: Returns the version of the oc server being accessed (e.g '3.11.28')
"""
r = Result('version3')
r.add_action(oc_action(cur_context(), verb='version'))
r.fail_if('Unable to determine version')
# Example OpenShift 3 output:
# oc v3.11.82
# kubernetes v1.11.0+d4cacc0
# features: Basic-Auth GSSAPI Kerberos SPNEGO
#
# Server https://internal.api.starter-us-east-2.openshift.com:443
# openshift v3.11.82
# kubernetes v1.11.0+d4cacc0
for line in reversed(r.out().splitlines()):
if line.startswith('openshift v'):
return line.split()[1].strip().lstrip('v')
elif line.startswith('Server Version: '):
version_string = line.split()[2].strip().lstrip()
if not version_string.startswith('version.Info{'):
return version_string
# If not found, this is a 4.0 cluster where this output line was removed. The best
# alternative is the version returned by the API.
r = Result('version4')
r.add_action(oc_action(cur_context(), 'adm', cmd_args=['release', 'info', '-o=json']))
r.fail_if('Error returning release info')
version_dict = json.loads(r.out())
version_model = Model(dict_to_model=version_dict, case_insensitive=True)
if version_model.metadata.version:
return version_model.metadata.version
raise OpenShiftPythonException('Unable find version string in json: {}'.format(r.out()))
def apply(str_dict_model_apiobject_or_list_thereof, overwrite=False, cmd_args=None,
fetch_resource_versions=False,
auto_raise=True):
"""
Applies the specifies resource(s) on the server.
:param str_dict_model_apiobject_or_list_thereof: The definition of one or more API object.
Can be string containing json or yaml, a python dict, an openshift.Model, or an openshift.APIObject.
You can also provide a list containing multiple of these elements to update.
:param overwrite: If --overwrite should be sent to apply.
:param cmd_args: Additional apply arguments
:param fetch_resource_versions: If True, before trying to apply the resources, a get operation will be used to
fetch any existing resourceVersion(s). Those resourceVersions will be populated into the apply payload before
being sent to the server. See https://github.com/kubernetes/kubernetes/issues/70674 for why this is sometimes
necessary.
:param auto_raise: If True, errors from oc will raise an exception.
:return: A selector for the updated objects and Result.
"""
base_args = list()
if overwrite:
base_args.append('--overwrite')
items, namespace_detected = _to_dict_list(str_dict_model_apiobject_or_list_thereof)
# If there is nothing to act on, return empty selector
if not items:
return selector([])
m = {
'kind': 'List',
'apiVersion': 'v1',
'metadata': {},
'items': items
}
# If we are supposed to update resource versions before performing the apply,
# get a current copy of the incoming resources and update the incoming
# objects with the server's resourceVersions, ignoring those which don't exist.
if items and fetch_resource_versions:
# I wish this could be implemented efficiently (single oc invocation which returns
# content from across multiple namespaces), but https://bugzilla.redhat.com/show_bug.cgi?id=1727917
# prevents it.
for item in items:
apiobj = APIObject(dict_to_model=item)
server_apiobj = apiobj.current(ignore_not_found=True)
# Does the object exist on the server?
if server_apiobj:
new_metadata = item.get('metadata', {})
new_metadata['resourceVersion'] = server_apiobj.resource_version()
item['metadata'] = new_metadata
return __new_objects_action_selector("apply",
cmd_args=["-f", "-", base_args, cmd_args],
stdin_obj=m,
no_namespace=namespace_detected,
auto_raise=auto_raise)
def replace(str_dict_model_apiobject_or_list_thereof, force=False, cmd_args=None, auto_raise=True):
"""
:param str_dict_model_apiobject_or_list_thereof: The definition of one or more API object.
Can be string containing json or yaml, a python dict, an openshift.Model, or an openshift.APIObject.
You can also provide a list containing multiple of these elements to update.
:param force: Whether to send the --force argument to oc replace.
:param cmd_args: Additional arguments for the verb.
:param auto_raise: If True, errors from oc will raise an exception.
:return: A selector for the updated objects and Result.
"""
base_args = list()
if force:
base_args.append('--force')
items, namespace_detected = _to_dict_list(str_dict_model_apiobject_or_list_thereof)
# If there is nothing to act on, return empty selector
if not items:
return selector([])
m = {
'kind': 'List',
'apiVersion': 'v1',
'metadata': {},
'items': items
}
return __new_objects_action_selector("replace",
cmd_args=["-f", "-", base_args, cmd_args],
stdin_obj=m,
no_namespace=namespace_detected,
auto_raise=auto_raise)
def build_configmap_dict(configmap_name, dir_path_or_paths=None, dir_ext_include=None, data_map=None, obj_labels=None):
"""
Creates a python dict structure for a configmap (if remains to the caller to send
the yaml to the server with create()). This method does not use/require oc to be resident
on the python host.
:param configmap_name: The metadata.name to include
:param dir_path_or_paths: All files within the specified directory (or list of directories) will be included
in the configmap. Note that the directory must be relative to the python application
(it cannot be on an ssh client host).
:param dir_ext_include: List of file extensions should should be included (e.g. ['.py', '.ini']). If None,
all extensions are allowed.
:param data_map: A set of key value pairs to include in the configmap (will be combined with dir_path
entries if both are specified.
:param obj_labels: Additional labels to include in the resulting configmap metadata.
:return: A python dict of a configmap resource.
"""
if data_map is None:
data_map = {}
if obj_labels is None:
obj_labels = {}
dm = dict(data_map)
if dir_path_or_paths:
# If we received a string, turn it into a list
if isinstance(dir_path_or_paths, six.string_types):
dir_path_or_paths = [dir_path_or_paths]
for dir_path in dir_path_or_paths:
for entry in os.listdir(dir_path):
path = os.path.join(dir_path, entry)
if os.path.isfile(path):
if dir_ext_include:
filename, file_extension = os.path.splitext(path)
if file_extension.lower() not in dir_ext_include:
continue
with io.open(path, mode='r', encoding="utf-8") as f:
file_basename = os.path.basename(path)
dm[file_basename] = f.read()
d = {
'kind': 'ConfigMap',
'apiVersion': 'v1',
'metadata': {
'name': configmap_name,
'labels': obj_labels,
},
'data': dm
}
return d
def build_secret_dict(secret_name, dir_path_or_paths=None, dir_ext_include=None, data_map=None, obj_labels=None):
"""
Creates a python dict structure for a secret (it remains to the caller to send
the yaml to the server with create()). This method does not use/require oc to be resident
on the python host.
:param secret_name: The metadata.name to include
:param dir_path_or_paths: All files within the specified directory (or list of directories) will be included
in the configmap. Note that the directory must be relative to the python application
(it cannot be on an ssh client host).
:param dir_ext_include: List of file extensions should should be included (e.g. ['.py', '.ini'])
:param data_map: A set of key value pairs to include in the secret (will be combined with dir_path
entries if both are specified. The values will be b64encoded automatically.
:param obj_labels: Additional labels to include in the resulting secret metadata.
:return: A python dict of a secret resource.
"""
if data_map is None:
data_map = {}
if obj_labels is None:
obj_labels = {}
dm = dict()
# base64 encode the incoming data_map values
for k, v in six.iteritems(data_map):
dm[k] = base64.b64encode(v)
if dir_path_or_paths:
# If we received a string, turn it into a list
if isinstance(dir_path_or_paths, six.string_types):
dir_path_or_paths = [dir_path_or_paths]
for dir_path in dir_path_or_paths:
for entry in os.listdir(dir_path):
path = os.path.join(dir_path, entry)
if dir_ext_include:
filename, file_extension = os.path.splitext(path)
if file_extension.lower() not in dir_ext_include:
continue
if os.path.isfile(path):
with io.open(path, mode='r', encoding="utf-8") as f:
file_basename = os.path.basename(path)
dm[file_basename] = base64.b64encode(f.read())
d = {
'kind': 'Secret',
'apiVersion': 'v1',
'metadata': {
'name': secret_name,
'labels': obj_labels,
},
'data': dm
}
return d
class ImageRegistryAuthInfo(object):
"""
Simple struct to pass around information about image registry authentication information.
"""
def __init__(self, registry_url, username, password, email=None):
self.registry_url = registry_url
self.username = username
self.password = password
if not email:
email = '{}@example.org'.format(username)
self.email = email
def build_secret_dockerconfigjson(secret_name, image_registry_auth_infos, obj_labels=None):
"""
Creates a python dict structure for a 'kubernetes.io/dockerconfigjson' secret (it remains to the caller to send
the yaml to the server with create()). This method does not use/require oc to be resident
on the python host.
:param secret_name: The metadata.name to include
:param image_registry_auth_infos: An iterable collection of ImageRegistryAuthInfo
:param obj_labels: Additional labels to include in the resulting secret metadata.
:return: A python dict of a secret resource.
"""
if obj_labels is None:
obj_labels = {}
auths = {} # A map of registry urls to a map with a single element called 'auth'
for ira in image_registry_auth_infos:
b64_username_password = base64.b64encode('{}:{}'.format(ira.username, ira.password).encode()).decode()
auths[ira.registry_url] = {
'auth': b64_username_password
}
# this is the content you would see if you cat your dockerconfig json file
dockerconfig = {
'auths': auths
}
# Lazy load to avoid dragging unnecessary dependencies
import json
# Next, base64 encode the entire file.
b64_dockerconfigjson = base64.b64encode(json.dumps(dockerconfig, indent=4).encode()).decode()
# And stick it into the secret's data
data = {
'.dockerconfigjson': b64_dockerconfigjson,
}
d = {
'kind': 'Secret',
'apiVersion': 'v1',
'metadata': {
'name': secret_name,
'labels': obj_labels,
},
'type': 'kubernetes.io/dockerconfigjson',
'data': data
}
return d
def build_list(*args):
"""
Converts an arbitrary list of resources into a dict modeling a kube List.
:param args: The incoming arguments can be json/yaml strings, dicts, or apiobjects.
:return: A dict modeling a kube dict
"""
return _to_dict_list(args)
def build_pod_simple(pod_name, image,
command=None,
namespace=None,
labels=None,
working_dir=None,
port=None,
host_network=False,
node_name=None,
restart_policy=None,
termination_grace_period=None,
service_account_name=None,
privileged=False,
host_mount=False,
api_version='v1',
):
if not labels:
labels = {}
metadata = {
'name': pod_name,
'labels': labels,
}
if namespace:
metadata['namespace'] = namespace
container0 = {
'name': pod_name,
'image': image,
}
if port:
ports = [
{
'containerPort': port,
},
]
container0['ports'] = ports
if command:
# If command is not a list of some sort, make it into one
if not util.is_collection_type(command):
command = [command]
container0['command'] = command
if working_dir:
container0['workingDir'] = working_dir
if privileged or host_mount:
container0['securityContext'] = {
'privileged': True,
}
if host_mount:
container0['volumeMounts'] = [
{
'name': 'host-volume',
'mountPath': '/host',
'readOnly': True,
}
]
spec = {
'containers': [container0],
}
if restart_policy is not None:
spec['restartPolicy'] = restart_policy
if termination_grace_period is not None:
spec['terminationGracePeriodSeconds'] = termination_grace_period
if service_account_name:
spec['serviceAccountName'] = service_account_name
if host_network:
spec['host_network'] = host_network
if node_name:
spec['node_name'] = node_name
if host_mount:
spec['volumes'] = [
{
'name': 'host-volume',
'hostPath': {
'path': '/',
}
}
]
pod = {
'apiVersion': api_version,
'kind': 'Pod',
'metadata': metadata,
'spec': spec,
}
return pod
def build_service_simple(service_name,
selector,
target_port,
namespace=None,
protocol='TCP',
service_port=None,
labels=None,
type='ClusterIP',
api_version='v1'):
if not service_port:
service_port = target_port
if not labels:
labels = {}
metadata = {
'name': service_name,
'labels': labels,
}
if namespace:
metadata['namespace'] = namespace
spec = {
'ports': [
{
'name': '{}'.format(target_port),
'port': int(service_port),
'protocol': protocol,
'targetPort': int(target_port),
}
],
'selector': selector,
'type': type,
}
service = {
'apiVersion': api_version,
'kind': 'Service',
'metadata': metadata,
'spec': spec,
}
return service
def build_secret_dockerconfig(secret_name, image_registry_auth_infos, obj_labels=None):
"""
Creates a python dict structure for a kubernetes.io/dockercfg secret (it remains to the caller to send
the yaml to the server with create()). This method does not use/require oc to be resident
on the python host.
:param secret_name: The metadata.name to include
:paran image_registry_auth_infos: An iterable collection of ImageRegistryAuthInfo
:param obj_labels: Additional labels to include in the resulting secret metadata.
:return: A python dict of a secret resource.
"""
# the data elements of this secret points to a base64 encoded blob which decoded looks like:
# {
# "172.30.208.107:5000": {
# "username": "serviceaccount",
# "password": "<base64 password>,
# "email": "serviceaccount@example.org",
# "auth": "<base64 username:password>"
# },
# "docker-registry.default.svc.cluster.local:5000": {