-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy path_container_op.py
1616 lines (1312 loc) · 62.3 KB
/
_container_op.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
# Copyright 2019 The Kubeflow Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import warnings
from typing import (Any, Callable, Dict, List, Optional, Sequence, Tuple,
TypeVar, Union)
from kfp.deprecated._config import COMPILING_FOR_V2
from kfp.deprecated.components import _components, _structures
from kfp.deprecated.dsl import _pipeline_param
from kfp.pipeline_spec import pipeline_spec_pb2
from kubernetes.client import V1Affinity, V1Toleration
from kubernetes.client.models import (V1Container, V1ContainerPort,
V1EnvFromSource, V1EnvVar, V1Lifecycle,
V1Probe, V1ResourceRequirements,
V1SecurityContext, V1Volume,
V1VolumeDevice, V1VolumeMount)
# generics
T = TypeVar('T')
# type alias: either a string or a list of string
StringOrStringList = Union[str, List[str]]
ContainerOpArgument = Union[str, int, float, bool,
_pipeline_param.PipelineParam]
ArgumentOrArguments = Union[ContainerOpArgument, List]
ALLOWED_RETRY_POLICIES = (
'Always',
'OnError',
'OnFailure',
'OnTransientError',
)
# Shorthand for PipelineContainerSpec
_PipelineContainerSpec = pipeline_spec_pb2.PipelineDeploymentConfig.PipelineContainerSpec
# Unit constants for k8s size string.
_E = 10**18 # Exa
_EI = 1 << 60 # Exa: power-of-two approximate
_P = 10**15 # Peta
_PI = 1 << 50 # Peta: power-of-two approximate
# noinspection PyShadowingBuiltins
_T = 10**12 # Tera
_TI = 1 << 40 # Tera: power-of-two approximate
_G = 10**9 # Giga
_GI = 1 << 30 # Giga: power-of-two approximate
_M = 10**6 # Mega
_MI = 1 << 20 # Mega: power-of-two approximate
_K = 10**3 # Kilo
_KI = 1 << 10 # Kilo: power-of-two approximate
_GKE_ACCELERATOR_LABEL = 'cloud.google.com/gke-accelerator'
_DEFAULT_CUSTOM_JOB_MACHINE_TYPE = 'n1-standard-4'
# util functions
def deprecation_warning(func: Callable, op_name: str,
container_name: str) -> Callable:
"""Decorator function to give a pending deprecation warning."""
def _wrapped(*args, **kwargs):
warnings.warn(
'`dsl.ContainerOp.%s` will be removed in future releases. '
'Use `dsl.ContainerOp.container.%s` instead.' %
(op_name, container_name), PendingDeprecationWarning)
return func(*args, **kwargs)
return _wrapped
def _create_getter_setter(prop):
"""Create a tuple of getter and setter methods for a property in
`Container`."""
def _getter(self):
return getattr(self._container, prop)
def _setter(self, value):
return setattr(self._container, prop, value)
return _getter, _setter
def _proxy_container_op_props(cls: 'ContainerOp'):
"""Takes the `ContainerOp` class and proxy the PendingDeprecation
properties in `ContainerOp` to the `Container` instance."""
# properties mapping to proxy: ContainerOps.<prop> => Container.<prop>
prop_map = dict(image='image', env_variables='env')
# itera and create class props
for op_prop, container_prop in prop_map.items():
# create getter and setter
_getter, _setter = _create_getter_setter(container_prop)
# decorate with deprecation warning
getter = deprecation_warning(_getter, op_prop, container_prop)
setter = deprecation_warning(_setter, op_prop, container_prop)
# update attribites with properties
setattr(cls, op_prop, property(getter, setter))
return cls
def as_string_list(
list_or_str: Optional[Union[Any, Sequence[Any]]]) -> List[str]:
"""Convert any value except None to a list if not already a list."""
if list_or_str is None:
return None
if isinstance(list_or_str, Sequence) and not isinstance(list_or_str, str):
list_value = list_or_str
else:
list_value = [list_or_str]
return [str(item) for item in list_value]
def create_and_append(current_list: Union[List[T], None], item: T) -> List[T]:
"""Create a list (if needed) and appends an item to it."""
current_list = current_list or []
current_list.append(item)
return current_list
class Container(V1Container):
"""A wrapper over k8s container definition object
(io.k8s.api.core.v1.Container), which is used to represent the `container`
property in argo's workflow template
(io.argoproj.workflow.v1alpha1.Template).
`Container` class also comes with utility functions to set and update the
the various properties for a k8s container definition.
NOTE: A notable difference is that `name` is not required and will not be
processed for `Container` (in contrast to `V1Container` where `name` is a
required property).
See:
*
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_container.py
* https://github.com/argoproj/argo-workflows/blob/master/api/openapi-spec/swagger.json
Example::
from kfp.dsl import ContainerOp
from kubernetes.client.models import V1EnvVar
# creates a operation
op = ContainerOp(name='bash-ops',
image='busybox:latest',
command=['echo'],
arguments=['$MSG'])
# returns a `Container` object from `ContainerOp`
# and add an environment variable to `Container`
op.container.add_env_variable(V1EnvVar(name='MSG', value='hello world'))
Attributes:
attribute_map (dict): The key is attribute name and the value is json key
in definition.
"""
# remove `name` from attribute_map, swagger_types and openapi_types so `name` is not generated in the JSON
if hasattr(V1Container, 'swagger_types'):
swagger_types = {
key: value
for key, value in V1Container.swagger_types.items()
if key != 'name'
}
if hasattr(V1Container, 'openapi_types'):
openapi_types = {
key: value
for key, value in V1Container.openapi_types.items()
if key != 'name'
}
attribute_map = {
key: value
for key, value in V1Container.attribute_map.items()
if key != 'name'
}
def __init__(self, image: str, command: List[str], args: List[str],
**kwargs):
"""Creates a new instance of `Container`.
Args:
image {str}: image to use, e.g. busybox:latest
command {List[str]}: entrypoint array. Not executed within a shell.
args {List[str]}: arguments to entrypoint.
**kwargs: keyword arguments for `V1Container`
"""
# set name to '' if name is not provided
# k8s container MUST have a name
# argo workflow template does not need a name for container def
if not kwargs.get('name'):
kwargs['name'] = ''
# v2 container_spec
self._container_spec = None
self.env_dict = {}
super(Container, self).__init__(
image=image, command=command, args=args, **kwargs)
def _validate_size_string(self, size_string):
"""Validate a given string is valid for memory/ephemeral-storage
request or limit."""
if isinstance(size_string, _pipeline_param.PipelineParam):
if size_string.value:
size_string = size_string.value
else:
return
if re.match(r'^[0-9]+(E|Ei|P|Pi|T|Ti|G|Gi|M|Mi|K|Ki){0,1}$',
size_string) is None:
raise ValueError(
'Invalid memory string. Should be an integer, or integer followed '
'by one of "E|Ei|P|Pi|T|Ti|G|Gi|M|Mi|K|Ki"')
def _validate_cpu_string(self, cpu_string):
"""Validate a given string is valid for cpu request or limit."""
if isinstance(cpu_string, _pipeline_param.PipelineParam):
if cpu_string.value:
cpu_string = cpu_string.value
else:
return
if re.match(r'^[0-9]+m$', cpu_string) is not None:
return
try:
float(cpu_string)
except ValueError:
raise ValueError(
'Invalid cpu string. Should be float or integer, or integer followed '
'by "m".')
def _validate_positive_number(self, str_value, param_name):
"""Validate a given string is in positive integer format."""
if isinstance(str_value, _pipeline_param.PipelineParam):
if str_value.value:
str_value = str_value.value
else:
return
try:
int_value = int(str_value)
except ValueError:
raise ValueError(
'Invalid {}. Should be integer.'.format(param_name))
if int_value <= 0:
raise ValueError('{} must be positive integer.'.format(param_name))
def add_resource_limit(self, resource_name, value) -> 'Container':
"""Add the resource limit of the container.
Args:
resource_name: The name of the resource. It can be cpu, memory, etc.
value: The string value of the limit.
"""
self.resources = self.resources or V1ResourceRequirements()
self.resources.limits = self.resources.limits or {}
self.resources.limits.update({resource_name: value})
return self
def add_resource_request(self, resource_name, value) -> 'Container':
"""Add the resource request of the container.
Args:
resource_name: The name of the resource. It can be cpu, memory, etc.
value: The string value of the request.
"""
self.resources = self.resources or V1ResourceRequirements()
self.resources.requests = self.resources.requests or {}
self.resources.requests.update({resource_name: value})
return self
def get_resource_limit(self, resource_name: str) -> Optional[str]:
"""Get the resource limit of the container.
Args:
resource_name: The name of the resource. It can be cpu, memory, etc.
"""
if not self.resources or not self.resources.limits:
return None
return self.resources.limits.get(resource_name)
def get_resource_request(self, resource_name: str) -> Optional[str]:
"""Get the resource request of the container.
Args:
resource_name: The name of the resource. It can be cpu, memory, etc.
"""
if not self.resources or not self.resources.requests:
return None
return self.resources.requests.get(resource_name)
def set_memory_request(
self, memory: Union[str,
_pipeline_param.PipelineParam]) -> 'Container':
"""Set memory request (minimum) for this operator.
Args:
memory(Union[str, PipelineParam]): a string which can be a number or a number followed by one of
"E", "P", "T", "G", "M", "K".
"""
if not isinstance(memory, _pipeline_param.PipelineParam):
self._validate_size_string(memory)
return self.add_resource_request('memory', memory)
def set_memory_limit(
self, memory: Union[str,
_pipeline_param.PipelineParam]) -> 'Container':
"""Set memory limit (maximum) for this operator.
Args:
memory(Union[str, PipelineParam]): a string which can be a number or a number followed by one of
"E", "P", "T", "G", "M", "K".
"""
if not isinstance(memory, _pipeline_param.PipelineParam):
self._validate_size_string(memory)
if self._container_spec:
self._container_spec.resources.memory_limit = _get_resource_number(
memory)
return self.add_resource_limit('memory', memory)
def set_ephemeral_storage_request(self, size) -> 'Container':
"""Set ephemeral-storage request (minimum) for this operator.
Args:
size: a string which can be a number or a number followed by one of
"E", "P", "T", "G", "M", "K".
"""
self._validate_size_string(size)
return self.add_resource_request('ephemeral-storage', size)
def set_ephemeral_storage_limit(self, size) -> 'Container':
"""Set ephemeral-storage request (maximum) for this operator.
Args:
size: a string which can be a number or a number followed by one of
"E", "P", "T", "G", "M", "K".
"""
self._validate_size_string(size)
return self.add_resource_limit('ephemeral-storage', size)
def set_cpu_request(
self, cpu: Union[str,
_pipeline_param.PipelineParam]) -> 'Container':
"""Set cpu request (minimum) for this operator.
Args:
cpu(Union[str, PipelineParam]): A string which can be a number or a number followed by "m", which
means 1/1000.
"""
if not isinstance(cpu, _pipeline_param.PipelineParam):
self._validate_cpu_string(cpu)
return self.add_resource_request('cpu', cpu)
def set_cpu_limit(
self, cpu: Union[str,
_pipeline_param.PipelineParam]) -> 'Container':
"""Set cpu limit (maximum) for this operator.
Args:
cpu(Union[str, PipelineParam]): A string which can be a number or a number followed by "m", which
means 1/1000.
"""
if not isinstance(cpu, _pipeline_param.PipelineParam):
self._validate_cpu_string(cpu)
if self._container_spec:
self._container_spec.resources.cpu_limit = _get_cpu_number(cpu)
return self.add_resource_limit('cpu', cpu)
def set_gpu_limit(
self,
gpu: Union[str, _pipeline_param.PipelineParam],
vendor: Union[str, _pipeline_param.PipelineParam] = 'nvidia'
) -> 'Container':
"""Set gpu limit for the operator.
This function add '<vendor>.com/gpu' into resource limit.
Note that there is no need to add GPU request. GPUs are only supposed to
be specified in the limits section. See
https://kubernetes.io/docs/tasks/manage-gpus/scheduling-gpus/.
Args:
gpu(Union[str, PipelineParam]): A string which must be a positive number.
vendor(Union[str, PipelineParam]): Optional. A string which is the vendor of the requested gpu.
The supported values are: 'nvidia' (default), and 'amd'. The value is
ignored in v2.
"""
if not isinstance(gpu, _pipeline_param.PipelineParam):
self._validate_positive_number(gpu, 'gpu')
if self._container_spec:
# For backforward compatibiliy, allow `gpu` to be a string.
self._container_spec.resources.accelerator.count = int(gpu)
if vendor != 'nvidia' and vendor != 'amd':
raise ValueError('vendor can only be nvidia or amd.')
return self.add_resource_limit('%s.com/gpu' % vendor, gpu)
return self.add_resource_limit(vendor, gpu)
def add_volume_mount(self, volume_mount) -> 'Container':
"""Add volume to the container.
Args:
volume_mount: Kubernetes volume mount For detailed spec, check volume
mount definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_volume_mount.py
"""
if not isinstance(volume_mount, V1VolumeMount):
raise ValueError(
'invalid argument. Must be of instance `V1VolumeMount`.')
self.volume_mounts = create_and_append(self.volume_mounts, volume_mount)
return self
def add_volume_devices(self, volume_device) -> 'Container':
"""Add a block device to be used by the container.
Args:
volume_device: Kubernetes volume device For detailed spec, volume
device definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_volume_device.py
"""
if not isinstance(volume_device, V1VolumeDevice):
raise ValueError(
'invalid argument. Must be of instance `V1VolumeDevice`.')
self.volume_devices = create_and_append(self.volume_devices,
volume_device)
return self
def set_env_variable(self, name: str, value: str) -> 'Container':
"""Sets environment variable to the container (v2 only).
Args:
name: The name of the environment variable.
value: The value of the environment variable.
"""
if not COMPILING_FOR_V2:
raise ValueError(
'set_env_variable is v2 only. Use add_env_variable for v1.')
# Merge with any existing environment varaibles
self.env_dict = {
env.name: env.value for env in self._container_spec.env or []
}
self.env_dict[name] = value
del self._container_spec.env[:]
self._container_spec.env.extend([
_PipelineContainerSpec.EnvVar(name=name, value=value)
for name, value in self.env_dict.items()
])
return self
def add_env_variable(self, env_variable) -> 'Container':
"""Add environment variable to the container.
Args:
env_variable: Kubernetes environment variable For detailed spec, check
environment variable definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_env_var.py
"""
if not isinstance(env_variable, V1EnvVar):
raise ValueError(
'invalid argument. Must be of instance `V1EnvVar`.')
self.env = create_and_append(self.env, env_variable)
return self
def add_env_from(self, env_from) -> 'Container':
"""Add a source to populate environment variables int the container.
Args:
env_from: Kubernetes environment from source For detailed spec, check
environment from source definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_env_var_source.py
"""
if not isinstance(env_from, V1EnvFromSource):
raise ValueError(
'invalid argument. Must be of instance `V1EnvFromSource`.')
self.env_from = create_and_append(self.env_from, env_from)
return self
def set_image_pull_policy(self, image_pull_policy) -> 'Container':
"""Set image pull policy for the container.
Args:
image_pull_policy: One of `Always`, `Never`, `IfNotPresent`.
"""
if image_pull_policy not in ['Always', 'Never', 'IfNotPresent']:
raise ValueError(
'Invalid imagePullPolicy. Must be one of `Always`, `Never`, `IfNotPresent`.'
)
self.image_pull_policy = image_pull_policy
return self
def add_port(self, container_port) -> 'Container':
"""Add a container port to the container.
Args:
container_port: Kubernetes container port For detailed spec, check
container port definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_container_port.py
"""
if not isinstance(container_port, V1ContainerPort):
raise ValueError(
'invalid argument. Must be of instance `V1ContainerPort`.')
self.ports = create_and_append(self.ports, container_port)
return self
def set_security_context(self, security_context) -> 'Container':
"""Set security configuration to be applied on the container.
Args:
security_context: Kubernetes security context For detailed spec, check
security context definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_security_context.py
"""
if not isinstance(security_context, V1SecurityContext):
raise ValueError(
'invalid argument. Must be of instance `V1SecurityContext`.')
self.security_context = security_context
return self
def set_stdin(self, stdin=True) -> 'Container':
"""Whether this container should allocate a buffer for stdin in the
container runtime. If this is not set, reads from stdin in the
container will always result in EOF.
Args:
stdin: boolean flag
"""
self.stdin = stdin
return self
def set_stdin_once(self, stdin_once=True) -> 'Container':
"""Whether the container runtime should close the stdin channel after
it has been opened by a single attach. When stdin is true the stdin
stream will remain open across multiple attach sessions. If stdinOnce
is set to true, stdin is opened on container start, is empty until the
first client attaches to stdin, and then remains open and accepts data
until the client disconnects, at which time stdin is closed and remains
closed until the container is restarted. If this flag is false, a
container processes that reads from stdin will never receive an EOF.
Args:
stdin_once: boolean flag
"""
self.stdin_once = stdin_once
return self
def set_termination_message_path(self,
termination_message_path) -> 'Container':
"""Path at which the file to which the container's termination message
will be written is mounted into the container's filesystem. Message
written is intended to be brief final status, such as an assertion
failure message. Will be truncated by the node if greater than 4096
bytes. The total message length across all containers will be limited
to 12kb.
Args:
termination_message_path: path for the termination message
"""
self.termination_message_path = termination_message_path
return self
def set_termination_message_policy(
self, termination_message_policy) -> 'Container':
"""Indicate how the termination message should be populated. File will
use the contents of terminationMessagePath to populate the container
status message on both success and failure. FallbackToLogsOnError will
use the last chunk of container log output if the termination message
file is empty and the container exited with an error. The log output is
limited to 2048 bytes or 80 lines, whichever is smaller.
Args:
termination_message_policy: `File` or `FallbackToLogsOnError`
"""
if termination_message_policy not in ['File', 'FallbackToLogsOnError']:
raise ValueError(
'terminationMessagePolicy must be `File` or `FallbackToLogsOnError`'
)
self.termination_message_policy = termination_message_policy
return self
def set_tty(self, tty: bool = True) -> 'Container':
"""Whether this container should allocate a TTY for itself, also
requires 'stdin' to be true.
Args:
tty: boolean flag
"""
self.tty = tty
return self
def set_readiness_probe(self, readiness_probe) -> 'Container':
"""Set a readiness probe for the container.
Args:
readiness_probe: Kubernetes readiness probe For detailed spec, check
probe definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_probe.py
"""
if not isinstance(readiness_probe, V1Probe):
raise ValueError('invalid argument. Must be of instance `V1Probe`.')
self.readiness_probe = readiness_probe
return self
def set_liveness_probe(self, liveness_probe) -> 'Container':
"""Set a liveness probe for the container.
Args:
liveness_probe: Kubernetes liveness probe For detailed spec, check
probe definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_probe.py
"""
if not isinstance(liveness_probe, V1Probe):
raise ValueError('invalid argument. Must be of instance `V1Probe`.')
self.liveness_probe = liveness_probe
return self
def set_lifecycle(self, lifecycle) -> 'Container':
"""Setup a lifecycle config for the container.
Args:
lifecycle: Kubernetes lifecycle For detailed spec, lifecycle
definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_lifecycle.py
"""
if not isinstance(lifecycle, V1Lifecycle):
raise ValueError(
'invalid argument. Must be of instance `V1Lifecycle`.')
self.lifecycle = lifecycle
return self
class UserContainer(Container):
"""Represents an argo workflow UserContainer
(io.argoproj.workflow.v1alpha1.UserContainer) to be used in `UserContainer`
property in argo's workflow template
(io.argoproj.workflow.v1alpha1.Template).
`UserContainer` inherits from `Container` class with an addition of
`mirror_volume_mounts`
attribute (`mirrorVolumeMounts` property).
See
https://github.com/argoproj/argo-workflows/blob/master/api/openapi-spec/swagger.json
Args:
name: unique name for the user container
image: image to use for the user container, e.g. redis:alpine
command: entrypoint array. Not executed within a shell.
args: arguments to the entrypoint.
mirror_volume_mounts: MirrorVolumeMounts will mount the same volumes
specified in the main container to the container (including
artifacts), at the same mountPaths. This enables dind daemon to
partially see the same filesystem as the main container in order to
use features such as docker volume binding
**kwargs: keyword arguments available for `Container`
Attributes:
swagger_types (dict): The key is attribute name and the value is attribute
type.
Example ::
from kfp.dsl import ContainerOp, UserContainer
# creates a `ContainerOp` and adds a redis init container
op = (ContainerOp(name='foo-op', image='busybox:latest')
.add_initContainer(UserContainer(name='redis', image='redis:alpine')))
"""
# adds `mirror_volume_mounts` to `UserContainer` swagger definition
# NOTE inherits definition from `V1Container` rather than `Container`
# because `Container` has no `name` property.
if hasattr(V1Container, 'swagger_types'):
swagger_types = dict(
**V1Container.swagger_types, mirror_volume_mounts='bool')
if hasattr(V1Container, 'openapi_types'):
openapi_types = dict(
**V1Container.openapi_types, mirror_volume_mounts='bool')
attribute_map = dict(
**V1Container.attribute_map, mirror_volume_mounts='mirrorVolumeMounts')
def __init__(self,
name: str,
image: str,
command: StringOrStringList = None,
args: StringOrStringList = None,
mirror_volume_mounts: bool = None,
**kwargs):
super().__init__(
name=name,
image=image,
command=as_string_list(command),
args=as_string_list(args),
**kwargs)
self.mirror_volume_mounts = mirror_volume_mounts
def set_mirror_volume_mounts(self, mirror_volume_mounts=True):
"""Setting mirrorVolumeMounts to true will mount the same volumes
specified in the main container to the container (including artifacts),
at the same mountPaths. This enables dind daemon to partially see the
same filesystem as the main container in order to use features such as
docker volume binding.
Args:
mirror_volume_mounts: boolean flag
"""
self.mirror_volume_mounts = mirror_volume_mounts
return self
@property
def inputs(self):
"""A list of PipelineParam found in the UserContainer object."""
return _pipeline_param.extract_pipelineparams_from_any(self)
class Sidecar(UserContainer):
"""Creates a new instance of `Sidecar`.
Args:
name: unique name for the sidecar container
image: image to use for the sidecar container, e.g. redis:alpine
command: entrypoint array. Not executed within a shell.
args: arguments to the entrypoint.
mirror_volume_mounts: MirrorVolumeMounts will mount the same volumes
specified in the main container to the sidecar (including artifacts),
at the same mountPaths. This enables dind daemon to partially see the
same filesystem as the main container in order to use features such as
docker volume binding
**kwargs: keyword arguments available for `Container`
"""
def __init__(self,
name: str,
image: str,
command: StringOrStringList = None,
args: StringOrStringList = None,
mirror_volume_mounts: bool = None,
**kwargs):
super().__init__(
name=name,
image=image,
command=command,
args=args,
mirror_volume_mounts=mirror_volume_mounts,
**kwargs)
def _make_hash_based_id_for_op(op):
# Generating a unique ID for Op. For class instances, the hash is the object's memory address which is unique.
return op.human_name + ' ' + hex(2**63 + hash(op))[2:]
# Pointer to a function that generates a unique ID for the Op instance (Possibly by registering the Op instance in some system).
_register_op_handler = _make_hash_based_id_for_op
class BaseOp(object):
"""Base operator.
Args:
name: the name of the op. It does not have to be unique within a
pipeline because the pipeline will generates a unique new name in case
of conflicts.
init_containers: the list of `UserContainer` objects describing the
InitContainer to deploy before the `main` container.
sidecars: the list of `Sidecar` objects describing the sidecar
containers to deploy together with the `main` container.
is_exit_handler: Deprecated.
"""
# list of attributes that might have pipeline params - used to generate
# the input parameters during compilation.
# Excludes `file_outputs` and `outputs` as they are handled separately
# in the compilation process to generate the DAGs and task io parameters.
attrs_with_pipelineparams = [
'node_selector', 'volumes', 'pod_annotations', 'pod_labels',
'num_retries', 'init_containers', 'sidecars', 'tolerations'
]
def __init__(self,
name: str,
init_containers: List[UserContainer] = None,
sidecars: List[Sidecar] = None,
is_exit_handler: bool = False):
if is_exit_handler:
warnings.warn('is_exit_handler=True is no longer needed.',
DeprecationWarning)
self.is_exit_handler = is_exit_handler
# human_name must exist to construct operator's name
self.human_name = name
self.display_name = None #TODO Set display_name to human_name
# ID of the current Op. Ideally, it should be generated by the compiler that sees the bigger context.
# However, the ID is used in the task output references (PipelineParams) which can be serialized to strings.
# Because of this we must obtain a unique ID right now.
self.name = _register_op_handler(self)
# TODO: proper k8s definitions so that `convert_k8s_obj_to_json` can be used?
# `io.argoproj.workflow.v1alpha1.Template` properties
self.node_selector = {}
self.volumes = []
self.tolerations = []
self.affinity = {}
self.pod_annotations = {}
self.pod_labels = {}
# Retry strategy
self.num_retries = 0
self.retry_policy = None
self.backoff_factor = None
self.backoff_duration = None
self.backoff_max_duration = None
self.timeout = 0
self.init_containers = init_containers or []
self.sidecars = sidecars or []
# used to mark this op with loop arguments
self.loop_args = None
# Placeholder for inputs when adding ComponentSpec metadata to this
# ContainerOp. This holds inputs defined in ComponentSpec that have
# a corresponding PipelineParam.
self._component_spec_inputs_with_pipeline_params = []
# attributes specific to `BaseOp`
self._inputs = []
self.dependent_names = []
# Caching option, default to True
self.enable_caching = True
@property
def inputs(self):
"""List of PipelineParams that will be converted into input parameters
(io.argoproj.workflow.v1alpha1.Inputs) for the argo workflow."""
# Iterate through and extract all the `PipelineParam` in Op when
# called the 1st time (because there are in-place updates to `PipelineParam`
# during compilation - remove in-place updates for easier debugging?)
if not self._inputs:
self._inputs = self._component_spec_inputs_with_pipeline_params or []
# TODO replace with proper k8s obj?
for key in self.attrs_with_pipelineparams:
self._inputs += _pipeline_param.extract_pipelineparams_from_any(
getattr(self, key))
# keep only unique
self._inputs = list(set(self._inputs))
return self._inputs
@inputs.setter
def inputs(self, value):
# to support in-place updates
self._inputs = value
def apply(self, mod_func):
"""Applies a modifier function to self.
The function should return the passed object.
This is needed to chain "extention methods" to this class.
Example::
from kfp.gcp import use_gcp_secret
task = (
train_op(...)
.set_memory_request('1G')
.apply(use_gcp_secret('user-gcp-sa'))
.set_memory_limit('2G')
)
"""
return mod_func(self) or self
def after(self, *ops):
"""Specify explicit dependency on other ops."""
for op in ops:
self.dependent_names.append(op.name)
return self
def add_volume(self, volume):
"""Add K8s volume to the container.
Args:
volume: Kubernetes volumes For detailed spec, check volume definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_volume.py
"""
self.volumes.append(volume)
return self
def add_toleration(self, tolerations: V1Toleration):
"""Add K8s tolerations.
Args:
tolerations: Kubernetes toleration For detailed spec, check toleration
definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_toleration.py
"""
self.tolerations.append(tolerations)
return self
def add_affinity(self, affinity: V1Affinity):
"""Add K8s Affinity.
Args:
affinity: Kubernetes affinity For detailed spec, check affinity
definition
https://github.com/kubernetes-client/python/blob/master/kubernetes/client/models/v1_affinity.py
Example::
V1Affinity(
node_affinity=V1NodeAffinity(
required_during_scheduling_ignored_during_execution=V1NodeSelector(
node_selector_terms=[V1NodeSelectorTerm(
match_expressions=[V1NodeSelectorRequirement(
key='beta.kubernetes.io/instance-type',
operator='In',
values=['p2.xlarge'])])])))
"""
self.affinity = affinity
return self
def add_node_selector_constraint(
self, label_name: Union[str, _pipeline_param.PipelineParam],
value: Union[str, _pipeline_param.PipelineParam]):
"""Add a constraint for nodeSelector.
Each constraint is a key-value pair label.
For the container to be eligible to run on a node, the node must have each
of the constraints appeared as labels.
Args:
label_name(Union[str, PipelineParam]): The name of the constraint label.
value(Union[str, PipelineParam]): The value of the constraint label.
"""
self.node_selector[label_name] = value
return self
def add_pod_annotation(self, name: str, value: str):
"""Adds a pod's metadata annotation.
Args:
name: The name of the annotation.
value: The value of the annotation.
"""