/
KubeMasterEnvironment.java
1191 lines (1061 loc) · 52.5 KB
/
KubeMasterEnvironment.java
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-2023 Cask Data, Inc.
*
* 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.
*/
package io.cdap.cdap.master.environment.k8s;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.cdap.cdap.k8s.common.AbstractWatcherThread;
import io.cdap.cdap.k8s.common.DefaultLocalFileProvider;
import io.cdap.cdap.k8s.common.LocalFileProvider;
import io.cdap.cdap.k8s.discovery.KubeDiscoveryService;
import io.cdap.cdap.k8s.runtime.KubeTwillRunnerService;
import io.cdap.cdap.k8s.util.KubeUtil;
import io.cdap.cdap.k8s.util.WorkloadIdentityUtil;
import io.cdap.cdap.master.spi.environment.MasterEnvironment;
import io.cdap.cdap.master.spi.environment.MasterEnvironmentContext;
import io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnable;
import io.cdap.cdap.master.spi.environment.MasterEnvironmentRunnableContext;
import io.cdap.cdap.master.spi.environment.MasterEnvironmentTask;
import io.cdap.cdap.master.spi.environment.spark.SparkConfig;
import io.cdap.cdap.master.spi.environment.spark.SparkDriverWatcher;
import io.cdap.cdap.master.spi.environment.spark.SparkLocalizeResource;
import io.cdap.cdap.master.spi.environment.spark.SparkSubmitContext;
import io.cdap.cdap.master.spi.namespace.NamespaceDetail;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ConfigMapBuilder;
import io.kubernetes.client.openapi.models.V1ConfigMapVolumeSourceBuilder;
import io.kubernetes.client.openapi.models.V1Container;
import io.kubernetes.client.openapi.models.V1ContainerBuilder;
import io.kubernetes.client.openapi.models.V1DownwardAPIVolumeFile;
import io.kubernetes.client.openapi.models.V1DownwardAPIVolumeSource;
import io.kubernetes.client.openapi.models.V1EnvVar;
import io.kubernetes.client.openapi.models.V1ObjectFieldSelector;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
import io.kubernetes.client.openapi.models.V1OwnerReference;
import io.kubernetes.client.openapi.models.V1OwnerReferenceBuilder;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodSpec;
import io.kubernetes.client.openapi.models.V1PodSpecBuilder;
import io.kubernetes.client.openapi.models.V1ServiceAccount;
import io.kubernetes.client.openapi.models.V1Volume;
import io.kubernetes.client.openapi.models.V1VolumeMount;
import io.kubernetes.client.util.Yaml;
import io.kubernetes.client.util.generic.options.ListOptions;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;
import javax.annotation.Nullable;
import org.apache.twill.api.TwillRunnerService;
import org.apache.twill.discovery.DiscoveryService;
import org.apache.twill.discovery.DiscoveryServiceClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link MasterEnvironment} to provide the environment for running in
* Kubernetes.
*/
public class KubeMasterEnvironment implements MasterEnvironment {
public static final String DISABLE_POD_DELETION = "disablePodDeletion";
public static final String NAMESPACE_PROPERTY = "k8s.namespace";
private static final Logger LOG = LoggerFactory.getLogger(KubeMasterEnvironment.class);
public static final String SECURITY_CONFIG_NAME = "cdap-security";
// Contains the list of configuration / secret names coming from the Pod information, which are
// needed to propagate to deployments created via the KubeTwillRunnerService
private static final Set<String> CONFIG_NAMES = ImmutableSet.of("cdap-conf", "hadoop-conf",
"cdap-security");
private static final Set<String> CUSTOM_VOLUME_PREFIX = ImmutableSet.of("cdap-cm-vol-",
"cdap-se-vol-");
private static final String MASTER_MAX_INSTANCES = "master.service.max.instances";
private static final String DATA_TX_ENABLED = "data.tx.enabled";
private static final String JOB_CLEANUP_INTERVAL = "master.environment.k8s.job.cleaner.interval.mins";
private static final String JOB_CLEANUP_BATCH_SIZE = "master.environment.k8s.job.cleaner.batch.size";
public static final String JOB_CLEANER_ENABLED = "master.environment.k8s.job.cleaner.enabled";
public static final String NAMESPACE_KEY = "master.environment.k8s.namespace";
private static final String INSTANCE_LABEL = "master.environment.k8s.instance.label";
// Label for the container name
private static final String CONTAINER_LABEL = "master.environment.k8s.container.label";
private static final String POD_INFO_DIR = "master.environment.k8s.pod.info.dir";
private static final String POD_NAME_FILE = "master.environment.k8s.pod.name.file";
private static final String POD_UID_FILE = "master.environment.k8s.pod.uid.file";
private static final String POD_LABELS_FILE = "master.environment.k8s.pod.labels.file";
private static final String POD_NAMESPACE_FILE = "master.environment.k8s.pod.namespace.file";
private static final String POD_KILLER_SELECTOR = "master.environment.k8s.pod.killer.selector";
private static final String POD_KILLER_DELAY_MILLIS = "master.environment.k8s.pod.killer.delay.millis";
private static final String SPARK_CONFIGS_PREFIX = "spark.kubernetes";
private static final String SPARK_KUBERNETES_DRIVER_LABEL_PREFIX = "spark.kubernetes.driver.label.";
private static final String SPARK_KUBERNETES_EXECUTOR_LABEL_PREFIX = "spark.kubernetes.executor.label.";
private static final String SPARK_KUBERNETES_NAMESPACE = "spark.kubernetes.namespace";
private static final String SPARK_KUBERNETES_WAIT_IN_SUBMIT = "spark.kubernetes.submission.waitAppCompletion";
// A comma separated list of service names for which service of type LoadBalancer are to be created.
private static final String LOAD_BALANCER_SERVICES = "master.environment.k8s.loadBalancerServices";
// A comma separated list of key value pairs to be added as annotations in the k8s load balancer services.
// Keys and values are separated by "=" (without quotes). The implementation of load balancer service type
// is dependent on cloud providers such as GCP, AWS etc. To configure cloud provider specific behaviour
// we need to add cloud provider specific annotations.
// For example "networking.gke.io/load-balancer-type" annotation can be used
// in GCP to specify the type of load balancer to use.
private static final String LOAD_BALANCER_SERVICE_ANNOTATIONS
= "master.environment.k8s.loadBalancerServices.annotations";
@VisibleForTesting
static final String SPARK_KUBERNETES_DRIVER_POD_TEMPLATE = "spark.kubernetes.driver.podTemplateFile";
@VisibleForTesting
static final String SPARK_KUBERNETES_EXECUTOR_POD_TEMPLATE = "spark.kubernetes.executor.podTemplateFile";
private static final String SPARK_KUBERNETES_DRIVER_SERVICE_ACCOUNT
= "spark.kubernetes.authenticate.driver.serviceAccountName";
private static final String SPARK_KUBERNETES_EXECUTOR_SERVICE_ACCOUNT
= "spark.kubernetes.authenticate.executor.serviceAccountName";
private static final String SPARK_KUBERNETES_METRICS_PROPERTIES_CONF = "spark.metrics.conf";
private static final String POD_TEMPLATE_FILE_NAME = "podTemplate-";
private static final String CDAP_LOCALIZE_FILES_PATH = "/etc/cdap/localizefiles";
private static final String CDAP_CONFIG_MAP_PREFIX = "cdap-compressed-files-";
private static final String SPARK_DRIVER_POD_CPU_REQUEST = "spark.kubernetes.driver.request.cores";
private static final String SPARK_DRIVER_POD_CPU_LIMIT = "spark.kubernetes.driver.limit.cores";
private static final String SPARK_EXECUTOR_POD_CPU_REQUEST = "spark.kubernetes.executor.request.cores";
private static final String SPARK_EXECUTOR_POD_CPU_LIMIT = "spark.kubernetes.executor.limit.cores";
static final String SPARK_DRIVER_REQUEST_TIMEOUT_MILLIS = "spark.kubernetes.driver.requestTimeout";
static final String SPARK_DRIVER_CONNECTION_TIMEOUT_MILLIS = "spark.kubernetes.driver.connectionTimeout";
private static final String PROGRAM_CPU_MULTIPLIER = "program.k8s.container.cpu.multiplier";
private static final String DEFAULT_PROGRAM_CPU_MULTIPLIER = "0.5";
// Workload Identity Constants
// Needed to be read from KubeTwillPreparer.
public static final String WORKLOAD_IDENTITY_ENABLED = "master.environment.k8s.workload.identity.enabled";
public static final String WORKLOAD_IDENTITY_POOL = "master.environment.k8s.workload.identity.pool";
public static final String WORKLOAD_IDENTITY_PROVIDER = "master.environment.k8s.workload.identity.provider";
public static final String WORKLOAD_IDENTITY_SERVICE_ACCOUNT_TOKEN_TTL_SECONDS
= "master.environment.k8s.workload.identity.service.account.token.ttl.seconds";
// Workload Launcher Constants
/**
* The ClusterRole which defines the permissions required by the workload pod for the namespace in
* which it is running, e.g. pod, deployment, and statefulset creation permissions. The CDAP
* system service account must be assigned this role at the cluster level.
*/
private static final String WORKLOAD_LAUNCHER_NAMESPACE_ROLE_NAME
= "master.environment.k8s.workload.launcher.namespace.role.name";
/**
* The ClusterRole which defines the permissions required by the workload pod across all
* namespaces, e.g. service get and list permissions for DiscoveryService. The CDAP system service
* account must be assigned this role at the cluster level.
*/
private static final String WORKLOAD_LAUNCHER_CLUSTER_ROLE_NAME
= "master.environment.k8s.workload.launcher.cluster.role.name";
private static final String DEFAULT_WORKLOAD_LAUNCHER_NAMESPACE_ROLE_NAME = "cdap-workload-launcher";
private static final String DEFAULT_WORKLOAD_LAUNCHER_CLUSTER_ROLE_NAME = "cdap-cluster-workload-launcher";
public static final String DEFAULT_NAMESPACE = "default";
private static final String DEFAULT_INSTANCE_LABEL = "cdap.instance";
private static final String CDAP_INSTALL_NAMESPACE_LABEL = "cdap.k8s.namespace";
private static final String DEFAULT_CONTAINER_LABEL = "cdap.container";
private static final String DEFAULT_POD_INFO_DIR = "/etc/podinfo";
private static final String DEFAULT_POD_NAME_FILE = "pod.name";
private static final String DEFAULT_POD_UID_FILE = "pod.uid";
private static final String DEFAULT_POD_NAMESPACE_FILE = "pod.namespace";
private static final String DEFAULT_POD_LABELS_FILE = "pod.labels.properties";
private static final long DEFAULT_POD_KILLER_DELAY_MILLIS = TimeUnit.HOURS.toMillis(1L);
// Environment Property Names used by JMX metrics collector to tag metrics.
// Names better be short to reduce the serialized metric value size.
// Common prefix is added to properties to help main services identify tags relevant to
// environment properties.
// Name of the CDAP service running in this pod. Eg: appfabric, messaging, metrics etc.
private static final String COMPONENT_ENV_PROPERTY =
MasterEnvironmentContext.ENVIRONMENT_PROPERTY_PREFIX + "cmp";
// Name of the Kubernetes namespace this pod is deployed in. Eg: default
private static final String NAMESPACE_ENV_PROPERTY =
MasterEnvironmentContext.ENVIRONMENT_PROPERTY_PREFIX + "ns";
private static final Pattern LABEL_PATTERN = Pattern.compile("(cdap\\..+?)=\"(.*)\"");
private static final Pattern NAMESPACE_LABEL_PATTERN = Pattern.compile(
"(k8s\\.namespace)=\"(.*)\"");
private static final String SPARK_KUBERNETES_DRIVER_CONTAINER_VALUE = "spark-kubernetes-driver";
private static final String SPARK_KUBERNETES_EXECUTOR_CONTAINER_VALUE = "spark-kubernetes-executor";
private static final String SPARK_ROLE_LABEL = "spark-role";
private static final String SPARK_DRIVER_LABEL_VALUE = "driver";
private static final String CDAP_CONTAINER_LABEL = "cdap.container";
private static final String TWILL_RUNNER_SERVICE_MONITOR_DISABLE = "twill.runner.service.monitor.disable";
private static final String CONNECT_TIMEOUT = "master.environment.k8s.connect.timeout.sec";
static final String CONNECT_TIMEOUT_DEFAULT = "120";
private static final String READ_TIMEOUT = "master.environment.k8s.read.timeout.sec";
static final String READ_TIMEOUT_DEFAULT = "300";
private final List<MasterEnvironmentTask> tasks;
private KubeDiscoveryService discoveryService;
private KubeTwillRunnerService twillRunner;
private PodInfo podInfo;
private ApiClientFactory apiClientFactory;
private Map<String, String> additionalSparkConfs;
private File podInfoDir;
private File podLabelsFile;
private File podNameFile;
private File podUidFile;
private File podNamespaceFile;
// In memory state for holding configmap name. Used to delete this configmap upon master environment destroy.
private String configMapName;
private CoreV1Api coreV1Api;
private KubeMasterPathProvider kubeMasterPathProvider;
private LocalFileProvider localFileProvider;
private boolean workloadIdentityEnabled;
private String workloadIdentityPool;
private long workloadIdentityServiceAccountTokenTtlSeconds;
private String programCpuMultiplier;
private String cdapInstallNamespace;
private int connectTimeoutSec;
private int readTimeoutSec;
public KubeMasterEnvironment() {
this.tasks = new ArrayList<>();
}
@Override
public void initialize(MasterEnvironmentContext context)
throws IOException, IllegalArgumentException, ApiException {
LOG.info("Initializing Kubernetes environment");
Map<String, String> conf = context.getConfigurations();
connectTimeoutSec = Integer.parseInt(
conf.getOrDefault(CONNECT_TIMEOUT, CONNECT_TIMEOUT_DEFAULT));
readTimeoutSec = Integer.parseInt(conf.getOrDefault(READ_TIMEOUT, READ_TIMEOUT_DEFAULT));
apiClientFactory = new DefaultApiClientFactory(connectTimeoutSec, readTimeoutSec);
ApiClient apiClient = apiClientFactory.create();
kubeMasterPathProvider = new DefaultKubeMasterPathProvider(apiClient);
localFileProvider = new DefaultLocalFileProvider();
podInfoDir = new File(conf.getOrDefault(POD_INFO_DIR, DEFAULT_POD_INFO_DIR));
podLabelsFile = new File(podInfoDir,
conf.getOrDefault(POD_LABELS_FILE, DEFAULT_POD_LABELS_FILE));
podNameFile = new File(podInfoDir, conf.getOrDefault(POD_NAME_FILE, DEFAULT_POD_NAME_FILE));
podUidFile = new File(podInfoDir, conf.getOrDefault(POD_UID_FILE, DEFAULT_POD_UID_FILE));
podNamespaceFile = new File(podInfoDir,
conf.getOrDefault(POD_NAMESPACE_FILE, DEFAULT_POD_NAMESPACE_FILE));
workloadIdentityEnabled = Boolean.parseBoolean(conf.get(WORKLOAD_IDENTITY_ENABLED));
String workloadIdentityProvider = null;
if (workloadIdentityEnabled) {
// Validate all workload identity configurations are set
String missingConfig = null;
workloadIdentityPool = conf.get(WORKLOAD_IDENTITY_POOL);
if (workloadIdentityPool == null) {
missingConfig = WORKLOAD_IDENTITY_POOL;
}
workloadIdentityProvider = conf.get(WORKLOAD_IDENTITY_PROVIDER);
if (workloadIdentityProvider == null) {
missingConfig = WORKLOAD_IDENTITY_PROVIDER;
}
workloadIdentityServiceAccountTokenTtlSeconds = WorkloadIdentityUtil
.convertWorkloadIdentityTTLFromString(
conf.get(WORKLOAD_IDENTITY_SERVICE_ACCOUNT_TOKEN_TTL_SECONDS));
if (missingConfig != null) {
throw new IllegalArgumentException(
String.format("Missing expected workload identity config '%s'",
missingConfig));
}
}
// We don't support scaling from inside pod. Scaling should be done via CDAP operator.
// Currently, we don't support more than one instance per system service, hence set it to "1".
conf.put(MASTER_MAX_INSTANCES, "1");
// No TX in K8s
conf.put(DATA_TX_ENABLED, Boolean.toString(false));
coreV1Api = new CoreV1Api(apiClient);
// Load the pod labels from the configured path. It should be setup by the CDAP operator
podInfo = createPodInfo(conf);
String namespace = podInfo.getNamespace();
cdapInstallNamespace = conf.getOrDefault(NAMESPACE_KEY, DEFAULT_NAMESPACE);
additionalSparkConfs = getSparkConfigurations(conf);
programCpuMultiplier = conf.getOrDefault(PROGRAM_CPU_MULTIPLIER,
DEFAULT_PROGRAM_CPU_MULTIPLIER);
// Get the instance label to set up prefix for K8s services
String instanceLabel = conf.getOrDefault(INSTANCE_LABEL, DEFAULT_INSTANCE_LABEL);
Map<String, String> podLabels = podInfo.getLabels();
String instanceName = podLabels.get(instanceLabel);
if (instanceName == null) {
throw new IllegalStateException(
"Missing instance label '" + instanceLabel + "' from pod labels.");
}
// Add Environment Related conf properties
String componentName = getComponentName(podInfo.getLabels().get(instanceLabel),
podInfo.getName());
conf.put(COMPONENT_ENV_PROPERTY, componentName);
conf.put(NAMESPACE_ENV_PROPERTY, podInfo.getNamespace());
// Services are publish to K8s with a prefix
List<String> loadBalancerServiceList = new ArrayList<>();
if (!Strings.isNullOrEmpty(conf.get(LOAD_BALANCER_SERVICES))) {
loadBalancerServiceList = Arrays.asList(
conf.get(LOAD_BALANCER_SERVICES).split(","));
}
discoveryService = new KubeDiscoveryService(cdapInstallNamespace, "cdap-" + instanceName + "-",
podLabels, podInfo.getOwnerReferences(), apiClientFactory,
loadBalancerServiceList,
parseLoadBalancerAnnotations(conf.get(LOAD_BALANCER_SERVICE_ANNOTATIONS)));
// Optionally creates the pod killer task
String podKillerSelector = conf.get(POD_KILLER_SELECTOR);
if (!Strings.isNullOrEmpty(podKillerSelector)) {
long delayMillis = DEFAULT_POD_KILLER_DELAY_MILLIS;
String confDelay = conf.get(POD_KILLER_DELAY_MILLIS);
if (!Strings.isNullOrEmpty(confDelay)) {
try {
delayMillis = Long.parseLong(confDelay);
if (delayMillis <= 0) {
delayMillis = DEFAULT_POD_KILLER_DELAY_MILLIS;
LOG.warn("Only positive value is allowed for configuration {}. Defaulting to {}",
POD_KILLER_DELAY_MILLIS, delayMillis);
}
} catch (NumberFormatException e) {
LOG.warn("Invalid value for configuration {}. Expected a positive integer, but get {}.",
POD_KILLER_DELAY_MILLIS, confDelay);
}
}
tasks.add(new PodKillerTask(namespace, podKillerSelector, delayMillis, apiClientFactory));
LOG.info("Created pod killer task on namespace {}, with selector {} and delay {}",
namespace, podKillerSelector, delayMillis);
}
String twillRunnables = context.getConfigurations().get(TWILL_RUNNER_SERVICE_MONITOR_DISABLE);
boolean enableMonitor = true;
if (twillRunnables != null) {
for (String twillRunnable : twillRunnables.split(",")) {
if (podLabels.containsKey(DEFAULT_CONTAINER_LABEL)
&& podLabels.get(DEFAULT_CONTAINER_LABEL).equals(twillRunnable)) {
enableMonitor = false;
}
}
}
String workloadLauncherRoleNameForNamespace = conf.getOrDefault(
WORKLOAD_LAUNCHER_NAMESPACE_ROLE_NAME,
DEFAULT_WORKLOAD_LAUNCHER_NAMESPACE_ROLE_NAME);
String workloadLauncherRoleNameForCluster = conf.getOrDefault(
WORKLOAD_LAUNCHER_CLUSTER_ROLE_NAME,
DEFAULT_WORKLOAD_LAUNCHER_CLUSTER_ROLE_NAME);
// Services are publish to K8s with a prefix
String resourcePrefix = "cdap-" + instanceName + "-";
twillRunner = new KubeTwillRunnerService(context, apiClientFactory, namespace, discoveryService,
podInfo, resourcePrefix,
ImmutableMap.of(instanceLabel, instanceName, CDAP_INSTALL_NAMESPACE_LABEL, cdapInstallNamespace),
enableMonitor,
workloadIdentityEnabled,
workloadLauncherRoleNameForNamespace,
workloadLauncherRoleNameForCluster,
workloadIdentityPool,
workloadIdentityProvider);
int batchSize = Integer.parseInt(conf.get(JOB_CLEANUP_BATCH_SIZE));
int interval = Integer.parseInt(conf.get(JOB_CLEANUP_INTERVAL));
boolean jobCleanerEnabled = Boolean.parseBoolean(conf.get(JOB_CLEANER_ENABLED));
if (jobCleanerEnabled) {
tasks.add(new KubeJobCleaner(twillRunner.getSelector(), batchSize, interval, apiClientFactory));
} else {
LOG.info("KubeJobCleaner is disabled.");
}
LOG.info("Kubernetes environment initialized with pod labels {}", podLabels);
}
@Override
public void destroy() {
if (!Strings.isNullOrEmpty(configMapName)) {
try {
coreV1Api.deleteNamespacedConfigMap(configMapName, podInfo.getNamespace(), null, null, null,
null, null, null);
} catch (ApiException e) {
LOG.warn("Error cleaning up configmap {}, it will be retried. {} ", configMapName,
e.getResponseBody(), e);
}
}
discoveryService.close();
LOG.info("Kubernetes environment destroyed");
}
@Override
public String getName() {
return "k8s";
}
@Override
public Supplier<DiscoveryService> getDiscoveryServiceSupplier() {
return () -> discoveryService;
}
@Override
public Supplier<DiscoveryServiceClient> getDiscoveryServiceClientSupplier() {
return () -> discoveryService;
}
@Override
public Supplier<TwillRunnerService> getTwillRunnerSupplier() {
return () -> twillRunner;
}
@Override
public Collection<MasterEnvironmentTask> getTasks() {
return tasks;
}
@Override
public MasterEnvironmentRunnable createRunnable(MasterEnvironmentRunnableContext context,
Class<? extends MasterEnvironmentRunnable> cls) throws Exception {
return cls.getConstructor(MasterEnvironmentRunnableContext.class, MasterEnvironment.class)
.newInstance(context, this);
}
@Override
public SparkConfig generateSparkSubmitConfig(SparkSubmitContext sparkSubmitContext)
throws Exception {
Map<String, String> sparkConfMap = new HashMap<>(additionalSparkConfs);
// CDAP-19468 -- Spark seems to have a bug where it can wait forever for the driver to complete even after the
// driver has already completed.
sparkConfMap.put(SPARK_KUBERNETES_WAIT_IN_SUBMIT, "false");
// Create pod template with config maps and add to spark conf.
sparkConfMap.put(SPARK_KUBERNETES_DRIVER_POD_TEMPLATE,
getDriverPodTemplate(podInfo, sparkSubmitContext).getAbsolutePath());
sparkConfMap.put(SPARK_KUBERNETES_EXECUTOR_POD_TEMPLATE,
getExecutorPodTemplateFile(sparkSubmitContext).getAbsolutePath());
if (sparkSubmitContext.getLocalizeResources().containsKey("metrics.properties")) {
sparkConfMap.put(SPARK_KUBERNETES_METRICS_PROPERTIES_CONF,
"/opt/spark/work-dir/metrics.properties");
}
Map<String, String> submitConfigs = sparkSubmitContext.getConfig();
String executionNamespace = submitConfigs.getOrDefault(NAMESPACE_PROPERTY,
podInfo.getNamespace());
sparkConfMap.put(SPARK_KUBERNETES_NAMESPACE, executionNamespace);
String connectTimeout = submitConfigs.getOrDefault(SPARK_DRIVER_CONNECTION_TIMEOUT_MILLIS,
String.format("%d", connectTimeoutSec * 1000));
sparkConfMap.put(SPARK_DRIVER_CONNECTION_TIMEOUT_MILLIS, connectTimeout);
String requestTimeout = submitConfigs.getOrDefault(SPARK_DRIVER_REQUEST_TIMEOUT_MILLIS,
String.format("%d", readTimeoutSec * 1000));
sparkConfMap.put(SPARK_DRIVER_REQUEST_TIMEOUT_MILLIS, requestTimeout);
// Set spark service account for both driver and executor to be inherited from app-fabric. Since the service account
// is created by CDAP specifically for the namespace, it is granted reduced permissions.
// TODO(CDAP-19149): Cleanup strong coupling currently present in CDAP service accounts to avoid copying.
String workloadServiceAccountName = podInfo.getServiceAccountName();
sparkConfMap.put(SPARK_KUBERNETES_DRIVER_SERVICE_ACCOUNT, workloadServiceAccountName);
sparkConfMap.put(SPARK_KUBERNETES_EXECUTOR_SERVICE_ACCOUNT, workloadServiceAccountName);
// Add spark driver and executor pod cpu limits: https://spark.apache.org/docs/latest/running-on-kubernetes.html
// We are not adding memory limits because it will be same as what is requested by spark driver and executor pods.
// On spark on kubernetes, currently there is no way to override memory limits:
// https://github.com/GoogleCloudPlatform/spark-on-k8s-operator/issues/783
int driverCpuRequested =
(int) (sparkSubmitContext.getDriverVirtualCores() * 1000 * Float.parseFloat(
programCpuMultiplier));
int driverCpuLimit = sparkSubmitContext.getDriverVirtualCores() * 1000;
int executorCpuRequested =
(int) (sparkSubmitContext.getExecutorVirtualCores() * 1000 * Float.parseFloat(
programCpuMultiplier));
int executorCpuLimit = sparkSubmitContext.getExecutorVirtualCores() * 1000;
sparkConfMap.put(SPARK_DRIVER_POD_CPU_REQUEST, String.format("%dm", driverCpuRequested));
sparkConfMap.put(SPARK_DRIVER_POD_CPU_LIMIT, String.format("%dm", driverCpuLimit));
sparkConfMap.put(SPARK_EXECUTOR_POD_CPU_REQUEST, String.format("%dm", executorCpuRequested));
sparkConfMap.put(SPARK_EXECUTOR_POD_CPU_LIMIT, String.format("%dm", executorCpuLimit));
// Add spark pod labels. This will be same as job labels
populateLabels(sparkConfMap);
// Get k8s master path for spark submit
String master = kubeMasterPathProvider.getMasterPath();
// Kube Master environment would always contain spark job jar file.
// https://github.com/cdapio/cdap/blob/develop/cdap-spark-core3_2.12/src/k8s/Dockerfile#L46
return new SparkConfig("k8s://" + master,
URI.create("local:/opt/cdap/cdap-spark-core/cdap-spark-core.jar"),
sparkConfMap, getPodWatcherThread(),
// In Spark v3.2.0 and later, max netty direct memory must be
// >= spark.network.maxRemoteBlockSizeFetchToMem for executors.
// So we set max netty direct memory = spark.network.maxRemoteBlockSizeFetchToMem
// See CDAP-20758 for details.
// NOTE: If spark.network.maxRemoteBlockSizeFetchToMem is changed in ETLSpark.java,
// DataStreamsSparkLaunch.java, then io.netty.maxDirectMemory will need also need to changed
// here.
String.format("-Dio.netty.maxDirectMemory=%d", Integer.MAX_VALUE - 512));
}
@Override
public void onNamespaceCreation(String cdapNamespace, Map<String, String> properties)
throws Exception {
NamespaceDetail namespaceDetail = new NamespaceDetail(cdapNamespace, properties);
twillRunner.onNamespaceCreation(namespaceDetail);
}
@Override
public void createIdentity(String k8sNamespace, String identity) throws ApiException {
KubeUtil.validateRFC1123LabelName(identity);
try {
LOG.info("Creating credential identity: {}", identity);
createK8sSaIfNotExists(k8sNamespace, identity);
} catch (ApiException e) {
LOG.error(
String.format("Unable to create the service account %s with status %s and body: %s",
identity, e.getCode(), e.getResponseBody()), e);
throw e;
}
}
private void createK8sSaIfNotExists(String k8sNamespace, String serviceAccountName)
throws ApiException {
try {
coreV1Api.readNamespacedServiceAccount(serviceAccountName, k8sNamespace, null);
} catch (ApiException e) {
if (e.getCode() != HttpURLConnection.HTTP_NOT_FOUND) {
throw e;
}
V1ObjectMeta serviceAccountMetadata = new V1ObjectMeta();
serviceAccountMetadata.setName(serviceAccountName);
V1ServiceAccount serviceAccount = new V1ServiceAccount();
serviceAccount.setMetadata(serviceAccountMetadata);
coreV1Api.createNamespacedServiceAccount(k8sNamespace, serviceAccount,
null, null, null, null);
}
}
@Override
public void deleteIdentity(String k8sNamespace, @Nullable String identity) throws ApiException {
if (identity == null || identity.equals("default")) {
// skip deleting default service account.
return;
}
LOG.info("Creating credential identity: {}", identity);
try {
coreV1Api.deleteNamespacedServiceAccount(identity, k8sNamespace,
null, null, null, null, null, null);
} catch (ApiException e) {
if (e.getCode() == 404) {
// return if not found as it means that service account does not exist.
return;
}
LOG.error(
String.format("Unable to delete the service account %s with status %s and body: %s",
identity, e.getCode(), e.getResponseBody()), e);
throw e;
}
}
@Override
public void onNamespaceDeletion(String cdapNamespace, Map<String, String> properties)
throws Exception {
NamespaceDetail namespaceDetail = new NamespaceDetail(cdapNamespace, properties);
twillRunner.onNamespaceDeletion(namespaceDetail);
}
public ApiClientFactory getApiClientFactory() {
return apiClientFactory;
}
/**
* <p>Parses k8s pod name to find name of CDAP service running in this pod by removing prefix
* "cdap-" and instance name from the pod name. Eg: pod name "cdap-abc-metrics-0" and instance
* name "abc" will return component name "metrics-0". </p>
*
* @param instanceName Name of CDAP instance
* @param podName Name of K8s pod in which this service is running
* @return componentName after parsing pod name
*/
@VisibleForTesting
static String getComponentName(String instanceName, String podName) {
String componentName = podName;
// remove prefix "cdap-"
componentName = componentName.replaceFirst("^(cdap-)", "");
// remove instance name
componentName = componentName.replaceFirst(Pattern.quote(instanceName), "");
// Strip "-" from the beginning.
componentName = componentName.replaceAll("^-+", "");
return componentName;
}
/**
* Returns the {@link PodInfo} of the current environment.
*/
public PodInfo getPodInfo() {
if (podInfo == null) {
throw new IllegalStateException("This environment is not yet initialized");
}
return podInfo;
}
private PodInfo createPodInfo(Map<String, String> conf) throws IOException, ApiException {
String systemNamespace = conf.getOrDefault(NAMESPACE_KEY, DEFAULT_NAMESPACE);
if (!podInfoDir.isDirectory()) {
throw new IllegalArgumentException(
String.format("%s is not a directory.", podInfoDir.getAbsolutePath()));
}
String namespace = podNamespaceFile.exists()
? Files.lines(podNamespaceFile.toPath()).findFirst().orElse(null) : systemNamespace;
// Load the pod labels from the configured path. It should be setup by the CDAP operator
Map<String, String> podLabels = new HashMap<>();
try (BufferedReader reader = Files.newBufferedReader(podLabelsFile.toPath(),
StandardCharsets.UTF_8)) {
String line = reader.readLine();
while (line != null) {
Matcher matcher = LABEL_PATTERN.matcher(line);
if (matcher.matches()) {
podLabels.put(matcher.group(1), matcher.group(2));
}
// Use namespace from podLabels instead if it exists
Matcher namespaceMatcher = NAMESPACE_LABEL_PATTERN.matcher(line);
if (namespaceMatcher.matches()) {
namespace = namespaceMatcher.group(2);
podLabels.put(namespaceMatcher.group(1), namespaceMatcher.group(2));
}
line = reader.readLine();
}
}
String podName = Files.lines(podNameFile.toPath()).findFirst().orElse(null);
if (Strings.isNullOrEmpty(podName)) {
throw new IOException("Failed to get pod name from file " + podNameFile);
}
String podUid = Files.lines(podUidFile.toPath()).findFirst().orElse(null);
if (Strings.isNullOrEmpty(podUid)) {
throw new IOException("Failed to get pod uid from file " + podUidFile);
}
// Query pod information.
V1Pod pod;
try {
pod = coreV1Api.readNamespacedPod(podName, namespace, null);
} catch (ApiException e) {
throw new IOException("Error occurred while getting pod. Error code = "
+ e.getCode() + ", Body = " + e.getResponseBody(), e);
}
V1ObjectMeta podMeta = pod.getMetadata();
List<V1OwnerReference> ownerReferences =
podMeta == null || podMeta.getOwnerReferences() == null
? Collections.emptyList() : podMeta.getOwnerReferences();
// Find the container that is having this CDAP process running inside (because a pod can have multiple containers).
// If there is no such label, default to the first container.
// The name of the label will be used to hold the name of new container created by this process.
// We use the same label name so that we don't need to alter the configuration for new pod
String containerLabelName = conf.getOrDefault(CONTAINER_LABEL, DEFAULT_CONTAINER_LABEL);
String containerName = podLabels.get(containerLabelName);
V1Container container = pod.getSpec().getContainers().stream()
.filter(c -> Objects.equals(containerName, c.getName()))
.findFirst()
.orElse(pod.getSpec().getContainers().get(0));
// Get the config volumes from the pod
List<V1Volume> volumes = pod.getSpec().getVolumes().stream()
.filter(v -> CONFIG_NAMES.contains(v.getName()) || isCustomVolumePrefix(v.getName()))
.collect(Collectors.toList());
// Get the volume mounts from the container
List<V1VolumeMount> mounts = container.getVolumeMounts().stream()
.filter(m -> CONFIG_NAMES.contains(m.getName()) || isCustomVolumePrefix(m.getName()))
.collect(Collectors.toList());
List<V1EnvVar> envs = container.getEnv();
// Use the same service account and the runtime class as the current process for now.
// Ideally we should use a more restricted role.
String serviceAccountName = pod.getSpec().getServiceAccountName();
String runtimeClassName = pod.getSpec().getRuntimeClassName();
return new PodInfo(podName, podLabelsFile.getParentFile().getAbsolutePath(),
podLabelsFile.getName(),
podNameFile.getName(), podUid, podUidFile.getName(), podNamespaceFile.getName(),
namespace, podLabels, ownerReferences,
serviceAccountName, runtimeClassName,
volumes, containerLabelName, container.getImage(), mounts,
envs == null ? Collections.emptyList() : envs, pod.getSpec().getSecurityContext(),
container.getImagePullPolicy());
}
/**
* Returns {@code true} if the given volume name is prefixed with the custom volume mapping from
* the CRD.
*/
private boolean isCustomVolumePrefix(String name) {
return CUSTOM_VOLUME_PREFIX.stream().anyMatch(name::startsWith);
}
/**
* Adds secrets from the host pod as volume and volume mounts.
* TODO(CDAP-19400): Remove this logic when decoupling privileged and unprivileged workflows.
*
* @param podInfo Host pod info
* @param podSpec Pod specification to mount secret volumes to
*/
private void mountHostSecretVolumes(PodInfo podInfo, V1PodSpec podSpec) {
Set<String> secretVolumeNames = new HashSet<>();
List<V1VolumeMount> secretVolumeMounts = new ArrayList<>();
for (V1Volume volume : podInfo.getVolumes()) {
if (volume.getSecret() != null) {
secretVolumeNames.add(volume.getName());
podSpec.addVolumesItem(volume);
}
}
// Mount volumes to all containers.
for (V1VolumeMount volumeMount : podInfo.getContainerVolumeMounts()) {
if (secretVolumeNames.contains(volumeMount.getName())) {
for (V1Container container : podSpec.getContainers()) {
container.addVolumeMountsItem(volumeMount);
}
}
}
}
private File getDriverPodTemplate(PodInfo podInfo, SparkSubmitContext sparkSubmitContext)
throws Exception {
V1Pod driverPod = new V1Pod();
// set owner references for driver pod
driverPod.setMetadata(new V1ObjectMetaBuilder()
.addToOwnerReferences(new V1OwnerReferenceBuilder()
.withBlockOwnerDeletion(true)
.withKind("Pod")
.withApiVersion("v1")
.withUid(podInfo.getUid())
.withName(podInfo.getName()).build()).build());
V1PodSpec driverPodSpec = createBasePodSpec();
driverPod.setSpec(driverPodSpec);
// While generating driver pod template, need to create config map that has compressed localize files
try {
V1ConfigMapBuilder configMapBuilder = new V1ConfigMapBuilder();
// create config map with localize resources
for (Map.Entry<String, SparkLocalizeResource> resource : sparkSubmitContext.getLocalizeResources()
.entrySet()) {
String fileName =
resource.getValue().isArchive() ? resource.getKey() : resource.getKey() + ".zip";
configMapBuilder.addToBinaryData(fileName, getContents(resource.getValue().getURI(),
!resource.getValue().isArchive()));
}
String configMapName = CDAP_CONFIG_MAP_PREFIX + UUID.randomUUID();
coreV1Api.createNamespacedConfigMap(podInfo.getNamespace(),
configMapBuilder.withMetadata(
new V1ObjectMetaBuilder()
.withName(configMapName)
.withLabels(podInfo.getLabels())
.withOwnerReferences(podInfo.getOwnerReferences())
.build()).build(),
null, null, null, null);
this.configMapName = configMapName;
// Add configmap and secrets as a volume to be added to the pod template
driverPodSpec.addVolumesItem(new V1Volume().name(configMapName)
.configMap(new V1ConfigMapVolumeSourceBuilder().withName(configMapName).build()));
// Add configmap and secrets as a volume mount
for (V1Container container : driverPodSpec.getContainers()) {
container.addVolumeMountsItem(new V1VolumeMount().name(configMapName)
.mountPath(CDAP_LOCALIZE_FILES_PATH).readOnly(true));
}
// TODO(CDAP-19400): Remove this logic when decoupling privileged and unprivileged workflows.
mountHostSecretVolumes(podInfo, driverPodSpec);
if (workloadIdentityEnabled) {
setupWorkloadIdentityForPodSpecIfExists(sparkSubmitContext, driverPodSpec,
workloadIdentityPool,
workloadIdentityServiceAccountTokenTtlSeconds);
}
} catch (ApiException e) {
throw new IOException("Error occurred while creating pod spec. Error code = "
+ e.getCode() + ", Body = " + e.getResponseBody(), e);
} catch (IOException e) {
throw new IOException("Error while creating compressed files to generate pod spec.", e);
}
return serializePodTemplate(driverPod);
}
private File getExecutorPodTemplateFile(SparkSubmitContext sparkSubmitContext) throws Exception {
V1Pod executorPod = new V1Pod();
V1PodSpec executorPodSpec = createBasePodSpec();
executorPod.setSpec(executorPodSpec);
// Add configmap as a volume
executorPodSpec.addVolumesItem(new V1Volume().name(configMapName)
.configMap(new V1ConfigMapVolumeSourceBuilder().withName(configMapName).build()));
// Add configmap as a volume mount
for (V1Container container : executorPodSpec.getContainers()) {
container.addVolumeMountsItem(new V1VolumeMount().name(configMapName)
.mountPath(CDAP_LOCALIZE_FILES_PATH).readOnly(true));
}
// TODO(CDAP-19400): Remove this logic when decoupling privileged and unprivileged workflows.
mountHostSecretVolumes(podInfo, executorPodSpec);
if (workloadIdentityEnabled) {
setupWorkloadIdentityForPodSpecIfExists(sparkSubmitContext, executorPodSpec,
workloadIdentityPool,
workloadIdentityServiceAccountTokenTtlSeconds);
}
// Create spark template file. We do not delete it because pod will get deleted at the end of job completion.
return serializePodTemplate(executorPod);
}
private File serializePodTemplate(V1Pod v1Pod) throws IOException {
// Uses a relative path to create the Spark driver and executor template files.
File templateFile = localFileProvider.getWritableFileRef(
POD_TEMPLATE_FILE_NAME + UUID.randomUUID());
String podTemplateYaml = Yaml.dump(v1Pod);
try (FileWriter writer = new FileWriter(templateFile)) {
writer.write(podTemplateYaml);
} catch (IOException e) {
// should not happen
throw new IOException("Exception while writing pod spec to temp file.", e);
}
LOG.trace("Pod template: {}", podTemplateYaml);
return templateFile;
}
/**
* Creates the base pod spec to use as a template for all pods that Spark creates.
*
* @return pod template to use for Spark pods
*/
private V1PodSpec createBasePodSpec() {
/*
define the podinfo volume. This uses downwardAPI, which tells k8s to store pod information in files:
- downwardAPI:
defaultMode: 420
items:
- fieldRef:
fieldPath: metadata.labels
path: pod.labels.properties
- fieldRef:
fieldPath: metadata.name
path: pod.name
- fieldRef:
fieldPath: metadata.uid
path: pod.uid
- fieldRef:
fieldPath: metadata.namespace
path: pod.namespace
name: podinfo
*/
V1PodSpecBuilder v1PodSpecBuilder = new V1PodSpecBuilder();
List<V1Volume> volumes = new ArrayList<>();
V1DownwardAPIVolumeFile labelsFile = new V1DownwardAPIVolumeFile()
.fieldRef(new V1ObjectFieldSelector().fieldPath("metadata.labels"))
.path(podLabelsFile.getName());
V1DownwardAPIVolumeFile nameFile = new V1DownwardAPIVolumeFile()
.fieldRef(new V1ObjectFieldSelector().fieldPath("metadata.name"))
.path(podNameFile.getName());
V1DownwardAPIVolumeFile uidFile = new V1DownwardAPIVolumeFile()
.fieldRef(new V1ObjectFieldSelector().fieldPath("metadata.uid"))
.path(podUidFile.getName());
V1DownwardAPIVolumeFile namespaceFile = new V1DownwardAPIVolumeFile()
.fieldRef(new V1ObjectFieldSelector().fieldPath("metadata.namespace"))
.path(podNamespaceFile.getName());
V1DownwardAPIVolumeSource podinfoVolume = new V1DownwardAPIVolumeSource()
.defaultMode(420)
.items(Arrays.asList(labelsFile, nameFile, uidFile, namespaceFile));
String podInfoVolumeName = "podinfo";
volumes.add(new V1Volume().downwardAPI(podinfoVolume).name(podInfoVolumeName));
List<V1VolumeMount> volumeMounts = new ArrayList<>();
volumeMounts.add(
new V1VolumeMount().name(podInfoVolumeName).mountPath(podInfoDir.getAbsolutePath()));
v1PodSpecBuilder
.withVolumes(volumes)
.withContainers(new V1ContainerBuilder()
.withVolumeMounts(volumeMounts)
.build());
return v1PodSpecBuilder.build();
}
private void populateLabels(Map<String, String> sparkConfMap) {
for (Map.Entry<String, String> label : podInfo.getLabels().entrySet()) {
if (label.getKey().equals(CDAP_CONTAINER_LABEL)) {
// Make sure correct container name label is being added for driver and executor containers
sparkConfMap.put(SPARK_KUBERNETES_DRIVER_LABEL_PREFIX + label.getKey(),
SPARK_KUBERNETES_DRIVER_CONTAINER_VALUE);
sparkConfMap.put(SPARK_KUBERNETES_EXECUTOR_LABEL_PREFIX + label.getKey(),
SPARK_KUBERNETES_EXECUTOR_CONTAINER_VALUE);
} else {
sparkConfMap.put(SPARK_KUBERNETES_DRIVER_LABEL_PREFIX + label.getKey(), label.getValue());
sparkConfMap.put(SPARK_KUBERNETES_EXECUTOR_LABEL_PREFIX + label.getKey(), label.getValue());
}
}
}
private byte[] getContents(URI uri, boolean shouldCompress) throws IOException {
byte[] buffer = new byte[1024 * 500]; // use 500kb buffer
ByteArrayOutputStream baos = new ByteArrayOutputStream();
File file = new File(uri);
try (OutputStream os = shouldCompress ? new GZIPOutputStream(baos) : baos;
FileInputStream fis = new FileInputStream(file)) {
int length;
while ((length = fis.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}
return baos.toByteArray();
}
private Map<String, String> getSparkConfigurations(Map<String, String> cConf) {
Map<String, String> sparkConfs = new HashMap<>();
for (Map.Entry<String, String> entry : cConf.entrySet()) {
if (entry.getKey().startsWith(SPARK_CONFIGS_PREFIX)) {
sparkConfs.put(entry.getKey(), entry.getValue());
}
}
return sparkConfs;
}
/**
* Applies workload identity configurations to a given pod specification. For additional details,
* see steps 6-7 of
* https://cloud.google.com/anthos/multicluster-management/fleets/workload-identity#impersonate_a_service_account
*
* @param podSpec The pod spec to setup workload identity for.
*/
private void setupWorkloadIdentityForPodSpecIfExists(SparkSubmitContext sparkSubmitContext,
V1PodSpec podSpec,
String workloadIdentityPool,
long workloadIdentityServiceAccountTokenTtlSeconds) {
// If the namespace service account does not exist, do not attempt to mount the ConfigMap.
// If the program is executing in the install namespace, always mount the ConfigMap.
String executionNamespace = sparkSubmitContext.getConfig().getOrDefault(NAMESPACE_PROPERTY,
podInfo.getNamespace());
String workloadIdentityServiceAccount = sparkSubmitContext.getConfig()
.get(KubeTwillRunnerService.WORKLOAD_IDENTITY_GCP_SERVICE_ACCOUNT_EMAIL_PROPERTY);
if (!WorkloadIdentityUtil.shouldMountWorkloadIdentity(cdapInstallNamespace, executionNamespace,
workloadIdentityServiceAccount)) {
return;
}
// Mount volume to expected directory
V1Volume workloadIdentityVolume = WorkloadIdentityUtil
.generateWorkloadIdentityVolume(workloadIdentityServiceAccountTokenTtlSeconds,
workloadIdentityPool);