-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcontainer.rs
More file actions
1632 lines (1515 loc) · 64.1 KB
/
container.rs
File metadata and controls
1632 lines (1515 loc) · 64.1 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
//! This module configures required HDFS containers and their volumes.
//!
//! ## Features
//!
//! - Create all required main, side and init containers for Namenodes, Datanodes and Journalnodes
//! - Adds required volumes and volume mounts
//! - Set required env variables
//! - Build container commands and args
//! - Set resources
//! - Add tcp probes and container ports (to the main containers)
//!
use std::{collections::BTreeMap, str::FromStr};
use indoc::formatdoc;
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
builder::{
self,
pod::{
PodBuilder,
container::ContainerBuilder,
resources::ResourceRequirementsBuilder,
volume::{
ListenerOperatorVolumeSourceBuilder, ListenerOperatorVolumeSourceBuilderError,
ListenerReference, SecretFormat, SecretOperatorVolumeSourceBuilder,
SecretOperatorVolumeSourceBuilderError, VolumeBuilder, VolumeMountBuilder,
},
},
},
commons::product_image_selection::ResolvedProductImage,
k8s_openapi::{
api::core::v1::{
ConfigMapKeySelector, ConfigMapVolumeSource, Container, ContainerPort,
EmptyDirVolumeSource, EnvVar, EnvVarSource, ObjectFieldSelector, PersistentVolumeClaim,
Probe, ResourceRequirements, TCPSocketAction, Volume, VolumeMount,
},
apimachinery::pkg::util::intstr::IntOrString,
},
kube::{ResourceExt, core::ObjectMeta},
kvp::{LabelExt, Labels},
product_logging::{
self,
framework::{
LoggingError, create_vector_shutdown_file_command, remove_vector_shutdown_file_command,
},
spec::{
AutomaticContainerLogConfig, ConfigMapLogConfig, ContainerLogConfig,
ContainerLogConfigChoice, CustomContainerLogConfig,
},
},
role_utils::RoleGroupRef,
utils::{COMMON_BASH_TRAP_FUNCTIONS, cluster_info::KubernetesClusterInfo},
};
use strum::{Display, EnumDiscriminants, IntoStaticStr};
use crate::{
config::{
self,
jvm::{construct_global_jvm_args, construct_role_specific_jvm_args},
},
crd::{
AnyNodeConfig, DataNodeContainer, HdfsNodeRole, HdfsPodRef, NameNodeContainer,
UpgradeState,
constants::{
DATANODE_ROOT_DATA_DIR_PREFIX, DEFAULT_DATA_NODE_METRICS_PORT,
DEFAULT_JOURNAL_NODE_METRICS_PORT, DEFAULT_NAME_NODE_METRICS_PORT, LISTENER_VOLUME_DIR,
LISTENER_VOLUME_NAME, LIVENESS_PROBE_FAILURE_THRESHOLD,
LIVENESS_PROBE_INITIAL_DELAY_SECONDS, LIVENESS_PROBE_PERIOD_SECONDS, LOG4J_PROPERTIES,
NAMENODE_ROOT_DATA_DIR, READINESS_PROBE_FAILURE_THRESHOLD,
READINESS_PROBE_INITIAL_DELAY_SECONDS, READINESS_PROBE_PERIOD_SECONDS,
SERVICE_PORT_NAME_HTTP, SERVICE_PORT_NAME_HTTPS, SERVICE_PORT_NAME_IPC,
SERVICE_PORT_NAME_RPC, STACKABLE_ROOT_DATA_DIR,
},
storage::DataNodeStorageConfig,
v1alpha1,
},
product_logging::{
FORMAT_NAMENODES_LOG4J_CONFIG_FILE, FORMAT_ZOOKEEPER_LOG4J_CONFIG_FILE,
HDFS_LOG4J_CONFIG_FILE, MAX_FORMAT_NAMENODE_LOG_FILE_SIZE,
MAX_FORMAT_ZOOKEEPER_LOG_FILE_SIZE, MAX_HDFS_LOG_FILE_SIZE,
MAX_WAIT_NAMENODES_LOG_FILE_SIZE, MAX_ZKFC_LOG_FILE_SIZE, STACKABLE_LOG_DIR,
WAIT_FOR_NAMENODES_LOG4J_CONFIG_FILE, ZKFC_LOG4J_CONFIG_FILE,
},
security::kerberos::KERBEROS_CONTAINER_PATH,
};
pub(crate) const TLS_STORE_DIR: &str = "/stackable/tls";
pub(crate) const TLS_STORE_VOLUME_NAME: &str = "tls";
pub(crate) const TLS_STORE_PASSWORD: &str = "changeit";
pub(crate) const KERBEROS_VOLUME_NAME: &str = "kerberos";
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Snafu, Debug, EnumDiscriminants)]
#[strum_discriminants(derive(IntoStaticStr))]
pub enum Error {
#[snafu(display("missing secret lifetime"))]
MissingSecretLifetime,
#[snafu(display("object has no namespace"))]
ObjectHasNoNamespace,
#[snafu(display("failed to construct JVM arguments fro role {role:?}"))]
ConstructJvmArguments {
source: config::jvm::Error,
role: String,
},
#[snafu(display(
"could not determine any ContainerConfig actions for {container_name:?}. Container not recognized."
))]
UnrecognizedContainerName { container_name: String },
#[snafu(display("invalid container name {name:?}"))]
InvalidContainerName {
source: stackable_operator::builder::pod::container::Error,
name: String,
},
#[snafu(display("failed to build secret volume for {volume_name:?}"))]
BuildSecretVolume {
source: SecretOperatorVolumeSourceBuilderError,
volume_name: String,
},
#[snafu(display("failed to build listener volume"))]
BuildListenerVolume {
source: ListenerOperatorVolumeSourceBuilderError,
},
#[snafu(display("missing or invalid labels for the listener volume"))]
ListenerVolumeLabels {
source: ListenerOperatorVolumeSourceBuilderError,
},
#[snafu(display("failed to configure logging"))]
ConfigureLogging { source: LoggingError },
#[snafu(display("failed to add needed volume"))]
AddVolume { source: builder::pod::Error },
#[snafu(display("failed to add needed volumeMount"))]
AddVolumeMount {
source: builder::pod::container::Error,
},
#[snafu(display("vector agent is enabled but vector aggregator ConfigMap is missing"))]
VectorAggregatorConfigMapMissing,
}
/// ContainerConfig contains information to create all main, side and init containers for
/// the HDFS cluster.
#[derive(Display)]
pub enum ContainerConfig {
Hdfs {
/// HDFS role (name-, data-, journal-node) which will be the container_name.
role: HdfsNodeRole,
/// The container name derived from the provided role.
container_name: String,
/// Volume mounts for config and logging.
volume_mounts: ContainerVolumeDirs,
/// Port name of the IPC/RPC port, used for the readiness probe.
ipc_port_name: &'static str,
/// Port name of the web UI HTTP port, used for the liveness probe.
web_ui_http_port_name: &'static str,
/// Port name of the web UI HTTPS port, used for the liveness probe.
web_ui_https_port_name: &'static str,
/// The JMX Exporter metrics port.
metrics_port: u16,
},
Zkfc {
/// The provided custom container name.
container_name: String,
/// Volume mounts for config and logging.
volume_mounts: ContainerVolumeDirs,
},
FormatNameNodes {
/// The provided custom container name.
container_name: String,
/// Volume mounts for config and logging.
volume_mounts: ContainerVolumeDirs,
},
FormatZooKeeper {
/// The provided custom container name.
container_name: String,
/// Volume mounts for config and logging.
volume_mounts: ContainerVolumeDirs,
},
WaitForNameNodes {
/// The provided custom container name.
container_name: String,
/// Volume mounts for config and logging.
volume_mounts: ContainerVolumeDirs,
},
}
impl ContainerConfig {
pub const DATA_VOLUME_MOUNT_NAME: &'static str = "data";
const FORMAT_NAMENODES_CONFIG_VOLUME_MOUNT_NAME: &'static str = "format-namenodes-config";
const FORMAT_NAMENODES_LOG_VOLUME_MOUNT_NAME: &'static str = "format-namenodes-log-config";
const FORMAT_ZOOKEEPER_CONFIG_VOLUME_MOUNT_NAME: &'static str = "format-zookeeper-config";
const FORMAT_ZOOKEEPER_LOG_VOLUME_MOUNT_NAME: &'static str = "format-zookeeper-log-config";
const HADOOP_HOME: &'static str = "/stackable/hadoop";
pub const HDFS_CONFIG_VOLUME_MOUNT_NAME: &'static str = "hdfs-config";
const HDFS_LOG_VOLUME_MOUNT_NAME: &'static str = "hdfs-log-config";
// volumes
pub const STACKABLE_LOG_VOLUME_MOUNT_NAME: &'static str = "log";
const WAIT_FOR_NAMENODES_CONFIG_VOLUME_MOUNT_NAME: &'static str = "wait-for-namenodes-config";
const WAIT_FOR_NAMENODES_LOG_VOLUME_MOUNT_NAME: &'static str = "wait-for-namenodes-log-config";
const ZKFC_CONFIG_VOLUME_MOUNT_NAME: &'static str = "zkfc-config";
const ZKFC_LOG_VOLUME_MOUNT_NAME: &'static str = "zkfc-log-config";
/// Add all main, side and init containers as well as required volumes to the pod builder.
#[allow(clippy::too_many_arguments)]
pub fn add_containers_and_volumes(
pb: &mut PodBuilder,
hdfs: &v1alpha1::HdfsCluster,
cluster_info: &KubernetesClusterInfo,
role: &HdfsNodeRole,
rolegroup_ref: &RoleGroupRef<v1alpha1::HdfsCluster>,
resolved_product_image: &ResolvedProductImage,
merged_config: &AnyNodeConfig,
env_overrides: Option<&BTreeMap<String, String>>,
zk_config_map_name: &str,
namenode_podrefs: &[HdfsPodRef],
labels: &Labels,
) -> Result<(), Error> {
// HDFS main container
let main_container_config = Self::from(*role);
let object_name = rolegroup_ref.object_name();
pb.add_volumes(main_container_config.volumes(merged_config, &object_name, labels)?)
.context(AddVolumeSnafu)?;
pb.add_container(main_container_config.main_container(
hdfs,
cluster_info,
role,
rolegroup_ref,
resolved_product_image,
zk_config_map_name,
env_overrides,
merged_config,
labels,
)?);
// Vector side container
if merged_config.vector_logging_enabled() {
match &hdfs.spec.cluster_config.vector_aggregator_config_map_name {
Some(vector_aggregator_config_map_name) => {
pb.add_container(
product_logging::framework::vector_container(
resolved_product_image,
ContainerConfig::HDFS_CONFIG_VOLUME_MOUNT_NAME,
ContainerConfig::STACKABLE_LOG_VOLUME_MOUNT_NAME,
Some(&merged_config.vector_logging()),
ResourceRequirementsBuilder::new()
.with_cpu_request("250m")
.with_cpu_limit("500m")
.with_memory_request("128Mi")
.with_memory_limit("128Mi")
.build(),
vector_aggregator_config_map_name,
)
.context(ConfigureLoggingSnafu)?,
);
}
None => {
VectorAggregatorConfigMapMissingSnafu.fail()?;
}
}
}
if let Some(authentication_config) = hdfs.authentication_config() {
pb.add_volume(
VolumeBuilder::new(TLS_STORE_VOLUME_NAME)
.ephemeral(
SecretOperatorVolumeSourceBuilder::new(
&authentication_config.tls_secret_class,
)
.with_pod_scope()
.with_node_scope()
// To scrape metrics behind TLS endpoint (without FQDN)
.with_service_scope(rolegroup_ref.rolegroup_metrics_service_name())
.with_format(SecretFormat::TlsPkcs12)
.with_tls_pkcs12_password(TLS_STORE_PASSWORD)
.with_auto_tls_cert_lifetime(
merged_config
.requested_secret_lifetime()
.context(MissingSecretLifetimeSnafu)?,
)
.build()
.context(BuildSecretVolumeSnafu {
volume_name: TLS_STORE_VOLUME_NAME,
})?,
)
.build(),
)
.context(AddVolumeSnafu)?;
pb.add_volume(
VolumeBuilder::new(KERBEROS_VOLUME_NAME)
.ephemeral(
SecretOperatorVolumeSourceBuilder::new(
&authentication_config.kerberos.secret_class,
)
.with_service_scope(hdfs.name_any())
.with_kerberos_service_name(role.kerberos_service_name())
.with_kerberos_service_name("HTTP")
.build()
.context(BuildSecretVolumeSnafu {
volume_name: KERBEROS_VOLUME_NAME,
})?,
)
.build(),
)
.context(AddVolumeSnafu)?;
}
// role specific pod settings configured here
match role {
HdfsNodeRole::Name => {
// Zookeeper fail over container
let zkfc_container_config = Self::try_from(NameNodeContainer::Zkfc.to_string())?;
pb.add_volumes(zkfc_container_config.volumes(
merged_config,
&object_name,
labels,
)?)
.context(AddVolumeSnafu)?;
pb.add_container(zkfc_container_config.main_container(
hdfs,
cluster_info,
role,
rolegroup_ref,
resolved_product_image,
zk_config_map_name,
env_overrides,
merged_config,
labels,
)?);
// Format namenode init container
let format_namenodes_container_config =
Self::try_from(NameNodeContainer::FormatNameNodes.to_string())?;
pb.add_volumes(format_namenodes_container_config.volumes(
merged_config,
&object_name,
labels,
)?)
.context(AddVolumeSnafu)?;
pb.add_init_container(format_namenodes_container_config.init_container(
hdfs,
cluster_info,
role,
&rolegroup_ref.role_group,
resolved_product_image,
zk_config_map_name,
env_overrides,
namenode_podrefs,
merged_config,
labels,
)?);
// Format ZooKeeper init container
let format_zookeeper_container_config =
Self::try_from(NameNodeContainer::FormatZooKeeper.to_string())?;
pb.add_volumes(format_zookeeper_container_config.volumes(
merged_config,
&object_name,
labels,
)?)
.context(AddVolumeSnafu)?;
pb.add_init_container(format_zookeeper_container_config.init_container(
hdfs,
cluster_info,
role,
&rolegroup_ref.role_group,
resolved_product_image,
zk_config_map_name,
env_overrides,
namenode_podrefs,
merged_config,
labels,
)?);
}
HdfsNodeRole::Data => {
// Wait for namenode init container
let wait_for_namenodes_container_config =
Self::try_from(DataNodeContainer::WaitForNameNodes.to_string())?;
pb.add_volumes(wait_for_namenodes_container_config.volumes(
merged_config,
&object_name,
labels,
)?)
.context(AddVolumeSnafu)?;
pb.add_init_container(wait_for_namenodes_container_config.init_container(
hdfs,
cluster_info,
role,
&rolegroup_ref.role_group,
resolved_product_image,
zk_config_map_name,
env_overrides,
namenode_podrefs,
merged_config,
labels,
)?);
}
HdfsNodeRole::Journal => {}
}
Ok(())
}
pub fn volume_claim_templates(
merged_config: &AnyNodeConfig,
labels: &Labels,
) -> Result<Vec<PersistentVolumeClaim>> {
match merged_config {
AnyNodeConfig::Name(node) => {
let listener = ListenerOperatorVolumeSourceBuilder::new(
&ListenerReference::ListenerClass(node.listener_class.to_string()),
labels,
)
.build_ephemeral()
.context(BuildListenerVolumeSnafu)?
.volume_claim_template
.unwrap();
let pvcs = vec![
node.resources
.storage
.data
.build_pvc(
ContainerConfig::DATA_VOLUME_MOUNT_NAME,
Some(vec!["ReadWriteOnce"]),
)
.add_labels(labels.clone())
.to_owned(),
PersistentVolumeClaim {
metadata: ObjectMeta {
name: Some(LISTENER_VOLUME_NAME.to_string()),
labels: Some(labels.clone().into()),
..listener.metadata.unwrap()
},
spec: Some(listener.spec),
..Default::default()
},
];
Ok(pvcs)
}
AnyNodeConfig::Journal(node) => Ok(vec![
node.resources
.storage
.data
.build_pvc(
ContainerConfig::DATA_VOLUME_MOUNT_NAME,
Some(vec!["ReadWriteOnce"]),
)
.add_labels(labels.clone())
.to_owned(),
]),
AnyNodeConfig::Data(node) => Ok(DataNodeStorageConfig {
pvcs: node.resources.storage.clone(),
}
.build_pvcs()
.into_iter()
.map(|mut pvc| pvc.add_labels(labels.clone()).to_owned())
.collect()),
}
}
/// Creates the main/side containers for:
/// - Namenode main process
/// - Namenode ZooKeeper fail over controller (ZKFC)
/// - Datanode main process
/// - Journalnode main process
#[allow(clippy::too_many_arguments)]
fn main_container(
&self,
hdfs: &v1alpha1::HdfsCluster,
cluster_info: &KubernetesClusterInfo,
role: &HdfsNodeRole,
rolegroup_ref: &RoleGroupRef<v1alpha1::HdfsCluster>,
resolved_product_image: &ResolvedProductImage,
zookeeper_config_map_name: &str,
env_overrides: Option<&BTreeMap<String, String>>,
merged_config: &AnyNodeConfig,
labels: &Labels,
) -> Result<Container, Error> {
let mut cb =
ContainerBuilder::new(self.name()).with_context(|_| InvalidContainerNameSnafu {
name: self.name().to_string(),
})?;
let resources = self.resources(merged_config);
cb.image_from_product_image(resolved_product_image)
.command(Self::command())
.args(self.args(hdfs, cluster_info, role, merged_config, &[])?)
.add_env_vars(self.env(
hdfs,
&rolegroup_ref.role_group,
zookeeper_config_map_name,
env_overrides,
resources.as_ref(),
)?)
.add_volume_mounts(self.volume_mounts(hdfs, merged_config, labels)?)
.context(AddVolumeMountSnafu)?
.add_container_ports(self.container_ports(hdfs));
if let Some(resources) = resources {
cb.resources(resources);
}
if let Some(probe) = self.web_ui_port_probe(
hdfs,
LIVENESS_PROBE_PERIOD_SECONDS,
LIVENESS_PROBE_INITIAL_DELAY_SECONDS,
LIVENESS_PROBE_FAILURE_THRESHOLD,
) {
cb.liveness_probe(probe);
}
if let Some(probe) = self.ipc_port_probe(
READINESS_PROBE_PERIOD_SECONDS,
READINESS_PROBE_INITIAL_DELAY_SECONDS,
READINESS_PROBE_FAILURE_THRESHOLD,
) {
cb.readiness_probe(probe.clone());
}
Ok(cb.build())
}
/// Creates respective init containers for:
/// - Namenode (format-namenodes, format-zookeeper)
/// - Datanode (wait-for-namenodes)
#[allow(clippy::too_many_arguments)]
fn init_container(
&self,
hdfs: &v1alpha1::HdfsCluster,
cluster_info: &KubernetesClusterInfo,
role: &HdfsNodeRole,
role_group: &str,
resolved_product_image: &ResolvedProductImage,
zookeeper_config_map_name: &str,
env_overrides: Option<&BTreeMap<String, String>>,
namenode_podrefs: &[HdfsPodRef],
merged_config: &AnyNodeConfig,
labels: &Labels,
) -> Result<Container, Error> {
let mut cb = ContainerBuilder::new(self.name())
.with_context(|_| InvalidContainerNameSnafu { name: self.name() })?;
cb.image_from_product_image(resolved_product_image)
.command(Self::command())
.args(self.args(hdfs, cluster_info, role, merged_config, namenode_podrefs)?)
.add_env_vars(self.env(
hdfs,
role_group,
zookeeper_config_map_name,
env_overrides,
None,
)?)
.add_volume_mounts(self.volume_mounts(hdfs, merged_config, labels)?)
.context(AddVolumeMountSnafu)?;
// We use the main app container resources here in contrast to several operators (which use
// hardcoded resources) due to the different code structure.
// Going forward this should be replaced by calculating init container resources in the pod builder.
if let Some(resources) = self.resources(merged_config) {
cb.resources(resources);
}
Ok(cb.build())
}
/// Return the container name.
fn name(&self) -> &str {
match &self {
ContainerConfig::Hdfs { container_name, .. } => container_name.as_str(),
ContainerConfig::Zkfc { container_name, .. } => container_name.as_str(),
ContainerConfig::FormatNameNodes { container_name, .. } => container_name.as_str(),
ContainerConfig::FormatZooKeeper { container_name, .. } => container_name.as_str(),
ContainerConfig::WaitForNameNodes { container_name, .. } => container_name.as_str(),
}
}
/// Return volume mount directories depending on the container.
fn volume_mount_dirs(&self) -> &ContainerVolumeDirs {
match &self {
ContainerConfig::Hdfs { volume_mounts, .. } => volume_mounts,
ContainerConfig::Zkfc { volume_mounts, .. } => volume_mounts,
ContainerConfig::FormatNameNodes { volume_mounts, .. } => volume_mounts,
ContainerConfig::FormatZooKeeper { volume_mounts, .. } => volume_mounts,
ContainerConfig::WaitForNameNodes { volume_mounts, .. } => volume_mounts,
}
}
/// Returns the container command.
fn command() -> Vec<String> {
vec![
"/bin/bash".to_string(),
"-x".to_string(),
"-euo".to_string(),
"pipefail".to_string(),
"-c".to_string(),
]
}
/// Returns the container command arguments.
fn args(
&self,
hdfs: &v1alpha1::HdfsCluster,
cluster_info: &KubernetesClusterInfo,
role: &HdfsNodeRole,
merged_config: &AnyNodeConfig,
namenode_podrefs: &[HdfsPodRef],
) -> Result<Vec<String>, Error> {
let mut args = String::new();
args.push_str(&self.create_config_directory_cmd());
args.push_str(&self.copy_config_xml_cmd());
// This env var is required for reading the core-site.xml
if hdfs.has_kerberos_enabled() {
args.push_str(&Self::export_kerberos_real_env_var_command());
}
let upgrade_args = if hdfs.upgrade_state().ok() == Some(Some(UpgradeState::Upgrading))
&& *role == HdfsNodeRole::Name
{
"-rollingUpgrade started"
} else {
""
};
match self {
ContainerConfig::Hdfs { role, .. } => {
args.push_str(&self.copy_log4j_properties_cmd(
HDFS_LOG4J_CONFIG_FILE,
&merged_config.hdfs_logging(),
));
args.push_str(&formatdoc!(
r#"\
{COMMON_BASH_TRAP_FUNCTIONS}
{remove_vector_shutdown_file_command}
prepare_signal_handlers
containerdebug --output={STACKABLE_LOG_DIR}/containerdebug-state.json --loop &
if [[ -d {LISTENER_VOLUME_DIR} ]]; then
export POD_ADDRESS=$(cat {LISTENER_VOLUME_DIR}/default-address/address)
for i in {LISTENER_VOLUME_DIR}/default-address/ports/*; do
export $(basename $i | tr a-z- A-Z_)_PORT="$(cat $i)"
done
fi
{hadoop_home}/bin/hdfs {role} {upgrade_args} &
wait_for_termination $!
{create_vector_shutdown_file_command}
"#,
hadoop_home = Self::HADOOP_HOME,
remove_vector_shutdown_file_command =
remove_vector_shutdown_file_command(STACKABLE_LOG_DIR),
create_vector_shutdown_file_command =
create_vector_shutdown_file_command(STACKABLE_LOG_DIR),
));
}
ContainerConfig::Zkfc { .. } => {
if let Some(container_config) = merged_config
.as_namenode()
.map(|node| node.logging.for_container(&NameNodeContainer::Zkfc))
{
args.push_str(
&self.copy_log4j_properties_cmd(ZKFC_LOG4J_CONFIG_FILE, &container_config),
);
}
args.push_str(&format!(
"{hadoop_home}/bin/hdfs zkfc\n",
hadoop_home = Self::HADOOP_HOME
));
}
ContainerConfig::FormatNameNodes { container_name, .. } => {
args.push_str(&bash_capture_shell_helper(container_name));
if let Some(container_config) = merged_config.as_namenode().map(|node| {
node.logging
.for_container(&NameNodeContainer::FormatNameNodes)
}) {
args.push_str(&self.copy_log4j_properties_cmd(
FORMAT_NAMENODES_LOG4J_CONFIG_FILE,
&container_config,
));
}
// First step we check for active namenodes. This step should return an active namenode
// for e.g. scaling. It may fail if the active namenode is restarted and the standby
// namenode takes over.
// This is why in the second part we check if the node is formatted already via
// $NAMENODE_DIR/current/VERSION. Then we don't do anything.
// If there is no active namenode, the current pod is not formatted we format as
// active namenode. Otherwise as standby node.
if hdfs.has_kerberos_enabled() {
args.push_str(&Self::get_kerberos_ticket(hdfs, role, cluster_info)?);
}
args.push_str(&formatdoc!(
r###"
echo "Start formatting namenode $POD_NAME. Checking for active namenodes:"
for namenode_id in {pod_names}
do
echo -n "Checking pod $namenode_id... "
# We only redirect 2 (stderr) to 4 (console).
# We leave 1 (stdout) alone so the $(...) can catch it.
SERVICE_STATE=$({hadoop_home}/bin/hdfs haadmin -getServiceState "$namenode_id" 2>&4 | tail -n1 || true)
if [ "$SERVICE_STATE" == "active" ]
then
ACTIVE_NAMENODE="$namenode_id"
echo "active"
break
else
echo "unknown / unreachable"
fi
done
if [ ! -f "{NAMENODE_ROOT_DATA_DIR}/current/VERSION" ]
then
if [ -z ${{ACTIVE_NAMENODE+x}} ]
then
echo "No active namenode found. Formatting $POD_NAME as active."
exclude_from_capture {hadoop_home}/bin/hdfs namenode -format -noninteractive
else
echo "Active namenode is $ACTIVE_NAMENODE. Bootstrapping standby."
exclude_from_capture {hadoop_home}/bin/hdfs namenode -bootstrapStandby -nonInteractive
fi
else
# Sanity check for initial format data corruption: VERSION file exists but no fsimage files were created.
FSIMAGE_COUNT=$(find "{NAMENODE_ROOT_DATA_DIR}/current" -maxdepth 1 -regextype posix-egrep -regex ".*/fsimage_[0-9]+" | wc -l)
if [ "${{FSIMAGE_COUNT}}" -eq 0 ]
then
echo "WARNING: {NAMENODE_ROOT_DATA_DIR}/current/VERSION file exists but no fsimage files were found."
echo "This indicates an incomplete and corrupted namenode formatting. Please check the troubleshooting guide."
exit 1
fi
cat "{NAMENODE_ROOT_DATA_DIR}/current/VERSION"
echo "Pod $POD_NAME already formatted. Skipping..."
fi
"###,
hadoop_home = Self::HADOOP_HOME,
pod_names = namenode_podrefs
.iter()
.map(|pod_ref| pod_ref.pod_name.as_ref())
.collect::<Vec<&str>>()
.join(" "),
));
}
ContainerConfig::FormatZooKeeper { container_name, .. } => {
args.push_str(&bash_capture_shell_helper(container_name));
if let Some(container_config) = merged_config.as_namenode().map(|node| {
node.logging
.for_container(&NameNodeContainer::FormatZooKeeper)
}) {
args.push_str(&self.copy_log4j_properties_cmd(
FORMAT_ZOOKEEPER_LOG4J_CONFIG_FILE,
&container_config,
));
}
args.push_str(&formatdoc!(
r###"
echo "Attempt to format ZooKeeper ZNode for $POD_NAME ..."
if [[ "0" -eq "$(echo $POD_NAME | sed -e 's/.*-//')" ]] ; then
EXITCODE=$(exclude_from_capture {hadoop_home}/bin/hdfs zkfc -formatZK -nonInteractive)
if [[ $EXITCODE -eq 0 ]]; then
echo "Successfully formatted ZooKeeper ZNode."
elif [[ $EXITCODE -eq 2 ]]; then
echo "ZNode already exists, nothing to do."
else
echo "ZooKeeper format ZNode failed with exit code $EXITCODE".
exit $EXITCODE
fi
else
echo "ZooKeeper ZNode already formatted!"
fi
"###,
hadoop_home = Self::HADOOP_HOME,
));
}
ContainerConfig::WaitForNameNodes { container_name, .. } => {
args.push_str(&bash_capture_shell_helper(container_name));
if let Some(container_config) = merged_config.as_datanode().map(|node| {
node.logging
.for_container(&DataNodeContainer::WaitForNameNodes)
}) {
args.push_str(&self.copy_log4j_properties_cmd(
WAIT_FOR_NAMENODES_LOG4J_CONFIG_FILE,
&container_config,
));
}
if hdfs.has_kerberos_enabled() {
args.push_str(&Self::get_kerberos_ticket(hdfs, role, cluster_info)?);
}
args.push_str(&formatdoc!(
r###"
echo "Waiting for namenodes to get ready:"
n=0
while [ ${{n}} -lt 12 ];
do
ALL_NODES_READY=true
for namenode_id in {pod_names}
do
echo -n "Checking pod $namenode_id... "
# We only redirect 2 (stderr) to 4 (console).
# We leave 1 (stdout) alone so the $(...) can catch it.
SERVICE_STATE=$({hadoop_home}/bin/hdfs haadmin -getServiceState "$namenode_id" 2>&4 | tail -n1 || true)
if [ "$SERVICE_STATE" = "active" ] || [ "$SERVICE_STATE" = "standby" ]
then
echo "$SERVICE_STATE"
else
echo "not ready"
ALL_NODES_READY=false
fi
done
if [ "$ALL_NODES_READY" == "true" ]
then
echo "All namenodes ready!"
break
fi
echo ""
n=$(( n + 1))
sleep 5
done
"###,
hadoop_home = Self::HADOOP_HOME,
pod_names = namenode_podrefs
.iter()
.map(|pod_ref| pod_ref.pod_name.as_ref())
.collect::<Vec<&str>>()
.join(" ")
));
}
}
Ok(vec![args])
}
// Command to export `KERBEROS_REALM` env var to default real from krb5.conf, e.g. `CLUSTER.LOCAL`
fn export_kerberos_real_env_var_command() -> String {
format!(
"export KERBEROS_REALM=$(grep -oP 'default_realm = \\K.*' {KERBEROS_CONTAINER_PATH}/krb5.conf)\n"
)
}
/// Command to `kinit` a ticket using the principal created for the specified hdfs role
/// Needs the KERBEROS_REALM env var, which will be written with `export_kerberos_real_env_var_command`
/// Needs the POD_NAME env var to be present, which will be provided by the PodSpec
fn get_kerberos_ticket(
hdfs: &v1alpha1::HdfsCluster,
role: &HdfsNodeRole,
cluster_info: &KubernetesClusterInfo,
) -> Result<String, Error> {
let principal = format!(
"{service_name}/{hdfs_name}.{namespace}.svc.{cluster_domain}@${{KERBEROS_REALM}}",
service_name = role.kerberos_service_name(),
hdfs_name = hdfs.name_any(),
namespace = hdfs.namespace().context(ObjectHasNoNamespaceSnafu)?,
cluster_domain = cluster_info.cluster_domain,
);
Ok(formatdoc!(
r###"
echo "Getting ticket for {principal}" from {KERBEROS_CONTAINER_PATH}/keytab
kinit "{principal}" -kt {KERBEROS_CONTAINER_PATH}/keytab
"###,
))
}
/// Returns the container env variables.
fn env(
&self,
hdfs: &v1alpha1::HdfsCluster,
role_group: &str,
zookeeper_config_map_name: &str,
env_overrides: Option<&BTreeMap<String, String>>,
resources: Option<&ResourceRequirements>,
) -> Result<Vec<EnvVar>, Error> {
// Maps env var name to env var object. This allows env_overrides to work
// as expected (i.e. users can override the env var value).
let mut env: BTreeMap<String, EnvVar> = BTreeMap::new();
env.extend(
Self::shared_env_vars(
self.volume_mount_dirs().final_config(),
zookeeper_config_map_name,
)
.into_iter()
.map(|env_var| (env_var.name.clone(), env_var)),
);
// For the main container we use specialized env variables for every role
// (think of like HDFS_NAMENODE_OPTS or HDFS_DATANODE_OPTS)
// We do so, so that users shelling into the hdfs Pods will not have problems
// because the will read out the HADOOP_OPTS env var as well for the cli clients
// (but *not* the HDFS_NAMENODE_OPTS env var)!
// The hadoop opts contain a Prometheus metric emitter, which binds itself to a static port.
// When the users tries to start a cli tool the port is already taken by the hdfs services,
// so we don't want to stuff all the config into HADOOP_OPTS, but rather into the specialized env variables
// See https://github.com/stackabletech/hdfs-operator/issues/138 for details
if let ContainerConfig::Hdfs { role, .. } = self {
let role_opts_name = role.hadoop_opts_env_var_for_role().to_string();
env.insert(
role_opts_name.clone(),
EnvVar {
name: role_opts_name,
value: Some(self.build_hadoop_opts(hdfs, role_group, resources)?),
..EnvVar::default()
},
);
}
env.insert(
"HADOOP_OPTS".to_string(),
EnvVar {
name: "HADOOP_OPTS".to_string(),
value: Some(construct_global_jvm_args(hdfs.has_kerberos_enabled())),
..EnvVar::default()
},
);
if hdfs.has_kerberos_enabled() {
env.insert(
"KRB5_CONFIG".to_string(),
EnvVar {
name: "KRB5_CONFIG".to_string(),
value: Some(format!("{KERBEROS_CONTAINER_PATH}/krb5.conf")),
..EnvVar::default()
},
);
env.insert(
"KRB5_CLIENT_KTNAME".to_string(),
EnvVar {
name: "KRB5_CLIENT_KTNAME".to_string(),
value: Some(format!("{KERBEROS_CONTAINER_PATH}/keytab")),
..EnvVar::default()
},
);
}
// Needed for the `containerdebug` process to log it's tracing information to.
env.insert(
"CONTAINERDEBUG_LOG_DIRECTORY".to_string(),
EnvVar {
name: "CONTAINERDEBUG_LOG_DIRECTORY".to_string(),
value: Some(format!("{STACKABLE_LOG_DIR}/containerdebug")),
value_from: None,
},
);
// Overrides need to come last
let mut env_override_vars: BTreeMap<String, EnvVar> =
Self::transform_env_overrides_to_env_vars(env_overrides)
.into_iter()
.map(|env_var| (env_var.name.clone(), env_var))
.collect();
env.append(&mut env_override_vars);
Ok(env.into_values().collect())
}
/// Returns the container resources.
pub fn resources(&self, merged_config: &AnyNodeConfig) -> Option<ResourceRequirements> {
match self {
// Namenode sidecar containers
ContainerConfig::Zkfc { .. } => Some(
ResourceRequirementsBuilder::new()
.with_cpu_request("100m")
.with_cpu_limit("400m")
.with_memory_request("512Mi")
.with_memory_limit("512Mi")
.build(),
),
// Main container and init containers
ContainerConfig::Hdfs { .. }
| ContainerConfig::FormatNameNodes { .. }
| ContainerConfig::FormatZooKeeper { .. }
| ContainerConfig::WaitForNameNodes { .. } => match merged_config {
AnyNodeConfig::Name(node) => Some(node.resources.clone().into()),
AnyNodeConfig::Data(node) => Some(node.resources.clone().into()),
AnyNodeConfig::Journal(node) => Some(node.resources.clone().into()),
},
}
}
/// Creates a probe for the web UI port
fn web_ui_port_probe(
&self,
hdfs: &v1alpha1::HdfsCluster,