-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmod.rs
1846 lines (1701 loc) · 60.4 KB
/
mod.rs
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
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap},
num::TryFromIntError,
ops::Deref,
};
use futures::future::try_join_all;
use product_config::types::PropertyNameKind;
use security::AuthorizationConfig;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt, Snafu};
#[cfg(doc)]
use stackable_operator::commons::listener::ListenerClass;
use stackable_operator::{
commons::{
affinity::StackableAffinity,
cluster_operation::ClusterOperation,
listener::Listener,
product_image_selection::ProductImage,
resources::{
CpuLimitsFragment, MemoryLimitsFragment, NoRuntimeLimits, NoRuntimeLimitsFragment,
PvcConfigFragment, Resources, ResourcesFragment,
},
},
config::{
fragment::{self, Fragment, ValidationError},
merge::Merge,
},
k8s_openapi::{
api::core::v1::{Pod, PodTemplateSpec},
apimachinery::pkg::api::resource::Quantity,
},
kube::{runtime::reflector::ObjectRef, CustomResource, ResourceExt},
kvp::{LabelError, Labels},
product_config_utils::{Configuration, Error as ConfigError},
product_logging::{
self,
spec::{ContainerLogConfig, Logging},
},
role_utils::{
self, GenericRoleConfig, JavaCommonConfig, JvmArgumentOverrides, Role, RoleGroup,
RoleGroupRef,
},
schemars::{self, JsonSchema},
status::condition::{ClusterCondition, HasStatusCondition},
time::Duration,
utils::cluster_info::KubernetesClusterInfo,
};
use stackable_versioned::versioned;
use strum::{Display, EnumIter, EnumString, IntoStaticStr};
use crate::crd::{
affinity::get_affinity,
constants::{
APP_NAME, CORE_SITE_XML, DEFAULT_DATA_NODE_DATA_PORT,
DEFAULT_DATA_NODE_GRACEFUL_SHUTDOWN_TIMEOUT, DEFAULT_DATA_NODE_HTTPS_PORT,
DEFAULT_DATA_NODE_HTTP_PORT, DEFAULT_DATA_NODE_IPC_PORT, DEFAULT_DATA_NODE_METRICS_PORT,
DEFAULT_DFS_REPLICATION_FACTOR, DEFAULT_JOURNAL_NODE_GRACEFUL_SHUTDOWN_TIMEOUT,
DEFAULT_JOURNAL_NODE_HTTPS_PORT, DEFAULT_JOURNAL_NODE_HTTP_PORT,
DEFAULT_JOURNAL_NODE_METRICS_PORT, DEFAULT_JOURNAL_NODE_RPC_PORT, DEFAULT_LISTENER_CLASS,
DEFAULT_NAME_NODE_GRACEFUL_SHUTDOWN_TIMEOUT, DEFAULT_NAME_NODE_HTTPS_PORT,
DEFAULT_NAME_NODE_HTTP_PORT, DEFAULT_NAME_NODE_METRICS_PORT, DEFAULT_NAME_NODE_RPC_PORT,
DFS_REPLICATION, HADOOP_POLICY_XML, HDFS_SITE_XML, JVM_SECURITY_PROPERTIES_FILE,
LISTENER_VOLUME_NAME, SERVICE_PORT_NAME_DATA, SERVICE_PORT_NAME_HTTP,
SERVICE_PORT_NAME_HTTPS, SERVICE_PORT_NAME_IPC, SERVICE_PORT_NAME_METRICS,
SERVICE_PORT_NAME_RPC, SSL_CLIENT_XML, SSL_SERVER_XML,
},
security::{AuthenticationConfig, KerberosConfig},
storage::{
DataNodePvcFragment, DataNodeStorageConfigInnerType, HdfsStorageConfig,
HdfsStorageConfigFragment, HdfsStorageType,
},
};
pub mod affinity;
pub mod constants;
pub mod security;
pub mod storage;
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("object has no associated namespace"))]
NoNamespace,
#[snafu(display("missing role {role:?}"))]
MissingRole { role: String },
#[snafu(display("missing role group {role_group:?} for role {role:?}"))]
MissingRoleGroup { role: String, role_group: String },
#[snafu(display("fragment validation failure"))]
FragmentValidationFailure { source: ValidationError },
#[snafu(display("unable to get {listener} (for {pod})"))]
GetPodListener {
source: stackable_operator::client::Error,
listener: ObjectRef<Listener>,
pod: ObjectRef<Pod>,
},
#[snafu(display("{listener} (for {pod}) has no address"))]
PodListenerHasNoAddress {
listener: ObjectRef<Listener>,
pod: ObjectRef<Pod>,
},
#[snafu(display("port {port} ({port_name:?}) is out of bounds, must be within {range:?}", range = 0..=u16::MAX))]
PortOutOfBounds {
source: TryFromIntError,
port_name: String,
port: i32,
},
#[snafu(display("failed to build role-group selector label"))]
BuildRoleGroupSelectorLabel { source: LabelError },
#[snafu(display("failed to merge jvm argument overrides"))]
MergeJvmArgumentOverrides { source: role_utils::Error },
}
#[versioned(version(name = "v1alpha1"))]
pub mod versioned {
/// An HDFS cluster stacklet. This resource is managed by the Stackable operator for Apache Hadoop HDFS.
/// Find more information on how to use it and the resources that the operator generates in the
/// [operator documentation](DOCS_BASE_URL_PLACEHOLDER/hdfs/).
///
/// The CRD contains three roles: `nameNodes`, `dataNodes` and `journalNodes`.
#[versioned(k8s(
group = "hdfs.stackable.tech",
kind = "HdfsCluster",
plural = "hdfsclusters",
shortname = "hdfs",
status = "HdfsClusterStatus",
namespaced,
crates(
kube_core = "stackable_operator::kube::core",
k8s_openapi = "stackable_operator::k8s_openapi",
schemars = "stackable_operator::schemars"
)
))]
#[derive(Clone, CustomResource, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HdfsClusterSpec {
/// Configuration that applies to all roles and role groups.
/// This includes settings for authentication, logging and the ZooKeeper cluster to use.
pub cluster_config: v1alpha1::HdfsClusterConfig,
// no doc string - See ProductImage struct
pub image: ProductImage,
// no doc string - See ClusterOperation struct
#[serde(default)]
pub cluster_operation: ClusterOperation,
// no doc string - See Role struct
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name_nodes: Option<Role<NameNodeConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
// no doc string - See Role struct
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_nodes: Option<Role<DataNodeConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
// no doc string - See Role struct
#[serde(default, skip_serializing_if = "Option::is_none")]
pub journal_nodes:
Option<Role<JournalNodeConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
}
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HdfsClusterConfig {
/// `dfsReplication` is the factor of how many times a file will be replicated to different data nodes.
/// The default is 3.
/// You need at least the same amount of data nodes so each file can be replicated correctly, otherwise a warning will be printed.
#[serde(default = "default_dfs_replication_factor")]
pub dfs_replication: u8,
/// Name of the Vector aggregator [discovery ConfigMap](DOCS_BASE_URL_PLACEHOLDER/concepts/service_discovery).
/// It must contain the key `ADDRESS` with the address of the Vector aggregator.
/// Follow the [logging tutorial](DOCS_BASE_URL_PLACEHOLDER/tutorials/logging-vector-aggregator)
/// to learn how to configure log aggregation with Vector.
#[serde(skip_serializing_if = "Option::is_none")]
pub vector_aggregator_config_map_name: Option<String>,
/// Name of the [discovery ConfigMap](DOCS_BASE_URL_PLACEHOLDER/concepts/service_discovery)
/// for a ZooKeeper cluster.
pub zookeeper_config_map_name: String,
/// Settings related to user [authentication](DOCS_BASE_URL_PLACEHOLDER/usage-guide/security).
pub authentication: Option<AuthenticationConfig>,
/// Authorization options for HDFS.
/// Learn more in the [HDFS authorization usage guide](DOCS_BASE_URL_PLACEHOLDER/hdfs/usage-guide/security#authorization).
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization: Option<AuthorizationConfig>,
// Scheduled for removal in v1alpha2, see https://github.com/stackabletech/issues/issues/504
/// Deprecated, please use `.spec.nameNodes.config.listenerClass` and `.spec.dataNodes.config.listenerClass` instead.
#[serde(default)]
pub listener_class: DeprecatedClusterListenerClass,
/// Configuration to control HDFS topology (rack) awareness feature
pub rack_awareness: Option<Vec<TopologyLabel>>,
}
}
impl HasStatusCondition for v1alpha1::HdfsCluster {
fn conditions(&self) -> Vec<ClusterCondition> {
match &self.status {
Some(status) => status.conditions.clone(),
None => vec![],
}
}
}
impl v1alpha1::HdfsCluster {
/// Return the namespace of the cluster or an error in case it is not set.
pub fn namespace_or_error(&self) -> Result<String, Error> {
self.namespace().context(NoNamespaceSnafu)
}
/// Kubernetes labels to attach to Pods within a role group.
///
/// The same labels are also used as selectors for Services and StatefulSets.
pub fn rolegroup_selector_labels(
&self,
rolegroup_ref: &RoleGroupRef<v1alpha1::HdfsCluster>,
) -> Result<Labels> {
let mut group_labels = Labels::role_group_selector(
self,
APP_NAME,
&rolegroup_ref.role,
&rolegroup_ref.role_group,
)
.context(BuildRoleGroupSelectorLabelSnafu)?;
group_labels
.parse_insert(("role", rolegroup_ref.role.deref()))
.context(BuildRoleGroupSelectorLabelSnafu)?;
group_labels
.parse_insert(("group", rolegroup_ref.role_group.deref()))
.context(BuildRoleGroupSelectorLabelSnafu)?;
Ok(group_labels)
}
/// Get a reference to the namenode [`RoleGroup`] struct if it exists.
pub fn namenode_rolegroup(
&self,
role_group: &str,
) -> Option<&RoleGroup<NameNodeConfigFragment, JavaCommonConfig>> {
self.spec.name_nodes.as_ref()?.role_groups.get(role_group)
}
/// Get a reference to the datanode [`RoleGroup`] struct if it exists.
pub fn datanode_rolegroup(
&self,
role_group: &str,
) -> Option<&RoleGroup<DataNodeConfigFragment, JavaCommonConfig>> {
self.spec.data_nodes.as_ref()?.role_groups.get(role_group)
}
/// Get a reference to the journalnode [`RoleGroup`] struct if it exists.
pub fn journalnode_rolegroup(
&self,
role_group: &str,
) -> Option<&RoleGroup<JournalNodeConfigFragment, JavaCommonConfig>> {
self.spec
.journal_nodes
.as_ref()?
.role_groups
.get(role_group)
}
pub fn role_config(&self, hdfs_role: &HdfsNodeRole) -> Option<&GenericRoleConfig> {
match hdfs_role {
HdfsNodeRole::Name => self.spec.name_nodes.as_ref().map(|nn| &nn.role_config),
HdfsNodeRole::Data => self.spec.data_nodes.as_ref().map(|dn| &dn.role_config),
HdfsNodeRole::Journal => self.spec.journal_nodes.as_ref().map(|jn| &jn.role_config),
}
}
pub fn get_merged_jvm_argument_overrides(
&self,
hdfs_role: &HdfsNodeRole,
role_group: &str,
operator_generated: &JvmArgumentOverrides,
) -> Result<JvmArgumentOverrides, Error> {
match hdfs_role {
HdfsNodeRole::Journal => self
.spec
.journal_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Journal.to_string(),
})?
.get_merged_jvm_argument_overrides(role_group, operator_generated),
HdfsNodeRole::Name => self
.spec
.name_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Name.to_string(),
})?
.get_merged_jvm_argument_overrides(role_group, operator_generated),
HdfsNodeRole::Data => self
.spec
.data_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Data.to_string(),
})?
.get_merged_jvm_argument_overrides(role_group, operator_generated),
}
.context(MergeJvmArgumentOverridesSnafu)
}
pub fn pod_overrides_for_role(&self, role: &HdfsNodeRole) -> Option<&PodTemplateSpec> {
match role {
HdfsNodeRole::Name => self
.spec
.name_nodes
.as_ref()
.map(|n| &n.config.pod_overrides),
HdfsNodeRole::Data => self
.spec
.data_nodes
.as_ref()
.map(|n| &n.config.pod_overrides),
HdfsNodeRole::Journal => self
.spec
.journal_nodes
.as_ref()
.map(|n| &n.config.pod_overrides),
}
}
pub fn pod_overrides_for_role_group(
&self,
role: &HdfsNodeRole,
role_group: &str,
) -> Option<&PodTemplateSpec> {
match role {
HdfsNodeRole::Name => self
.namenode_rolegroup(role_group)
.map(|r| &r.config.pod_overrides),
HdfsNodeRole::Data => self
.datanode_rolegroup(role_group)
.map(|r| &r.config.pod_overrides),
HdfsNodeRole::Journal => self
.journalnode_rolegroup(role_group)
.map(|r| &r.config.pod_overrides),
}
}
pub fn rolegroup_ref(
&self,
role_name: impl Into<String>,
group_name: impl Into<String>,
) -> RoleGroupRef<v1alpha1::HdfsCluster> {
RoleGroupRef {
cluster: ObjectRef::from_obj(self),
role: role_name.into(),
role_group: group_name.into(),
}
}
/// List all [`HdfsPodRef`]s expected for the given [`role`](HdfsNodeRole).
///
/// The `validated_config` is used to extract the ports exposed by the pods.
///
/// The pod refs returned by `pod_refs` will only be able to able to access HDFS
/// from inside the Kubernetes cluster. For configuring downstream clients,
/// consider using [`Self::namenode_listener_refs`] instead.
pub fn pod_refs(&self, role: &HdfsNodeRole) -> Result<Vec<HdfsPodRef>, Error> {
let ns = self.metadata.namespace.clone().context(NoNamespaceSnafu)?;
let rolegroup_ref_and_replicas = self.rolegroup_ref_and_replicas(role);
Ok(rolegroup_ref_and_replicas
.iter()
.flat_map(|(rolegroup_ref, replicas)| {
let ns = ns.clone();
(0..*replicas).map(move |i| HdfsPodRef {
namespace: ns.clone(),
role_group_service_name: rolegroup_ref.object_name(),
pod_name: format!("{}-{}", rolegroup_ref.object_name(), i),
ports: self
.ports(role)
.iter()
.map(|(n, p)| (n.clone(), *p))
.collect(),
fqdn_override: None,
})
})
.collect())
}
/// List all [`HdfsPodRef`]s for the running namenodes, configured to access the cluster via
/// [Listener] rather than direct [Pod] access.
///
/// This enables access from outside the Kubernetes cluster (if using a [ListenerClass] configured for this).
///
/// This method assumes that all [Listener]s have been created, and may fail while waiting for the cluster to come online.
/// If this is unacceptable (mainly for configuring the cluster itself), consider [`Self::pod_refs`] instead.
///
/// This method _only_ supports accessing namenodes, since journalnodes are considered internal, and datanodes are registered
/// dynamically with the namenodes.
pub async fn namenode_listener_refs(
&self,
client: &stackable_operator::client::Client,
) -> Result<Vec<HdfsPodRef>, Error> {
let pod_refs = self.pod_refs(&HdfsNodeRole::Name)?;
try_join_all(pod_refs.into_iter().map(|pod_ref| async {
let listener_name = format!("{LISTENER_VOLUME_NAME}-{}", pod_ref.pod_name);
let listener_ref =
|| ObjectRef::<Listener>::new(&listener_name).within(&pod_ref.namespace);
let pod_obj_ref =
|| ObjectRef::<Pod>::new(&pod_ref.pod_name).within(&pod_ref.namespace);
let listener = client
.get::<Listener>(&listener_name, &pod_ref.namespace)
.await
.context(GetPodListenerSnafu {
listener: listener_ref(),
pod: pod_obj_ref(),
})?;
let listener_address = listener
.status
.and_then(|s| s.ingress_addresses?.into_iter().next())
.context(PodListenerHasNoAddressSnafu {
listener: listener_ref(),
pod: pod_obj_ref(),
})?;
Ok(HdfsPodRef {
fqdn_override: Some(listener_address.address),
ports: listener_address
.ports
.into_iter()
.map(|(port_name, port)| {
let port = u16::try_from(port).context(PortOutOfBoundsSnafu {
port_name: &port_name,
port,
})?;
Ok((port_name, port))
})
.collect::<Result<_, _>>()?,
..pod_ref
})
}))
.await
}
pub fn rolegroup_ref_and_replicas(
&self,
role: &HdfsNodeRole,
) -> Vec<(RoleGroupRef<v1alpha1::HdfsCluster>, u16)> {
match role {
HdfsNodeRole::Name => self
.spec
.name_nodes
.iter()
.flat_map(|role| &role.role_groups)
// Order rolegroups consistently, to avoid spurious downstream rewrites
.collect::<BTreeMap<_, _>>()
.into_iter()
.map(|(rolegroup_name, role_group)| {
(
self.rolegroup_ref(HdfsNodeRole::Name.to_string(), rolegroup_name),
role_group.replicas.unwrap_or_default(),
)
})
.collect(),
HdfsNodeRole::Data => self
.spec
.data_nodes
.iter()
.flat_map(|role| &role.role_groups)
// Order rolegroups consistently, to avoid spurious downstream rewrites
.collect::<BTreeMap<_, _>>()
.into_iter()
.map(|(rolegroup_name, role_group)| {
(
self.rolegroup_ref(HdfsNodeRole::Data.to_string(), rolegroup_name),
role_group.replicas.unwrap_or_default(),
)
})
.collect(),
HdfsNodeRole::Journal => self
.spec
.journal_nodes
.iter()
.flat_map(|role| &role.role_groups)
// Order rolegroups consistently, to avoid spurious downstream rewrites
.collect::<BTreeMap<_, _>>()
.into_iter()
.map(|(rolegroup_name, role_group)| {
(
self.rolegroup_ref(HdfsNodeRole::Journal.to_string(), rolegroup_name),
role_group.replicas.unwrap_or_default(),
)
})
.collect(),
}
}
#[allow(clippy::type_complexity)]
pub fn build_role_properties(
&self,
) -> Result<
HashMap<
String,
(
Vec<PropertyNameKind>,
Role<
impl Configuration<Configurable = v1alpha1::HdfsCluster>,
GenericRoleConfig,
JavaCommonConfig,
>,
),
>,
Error,
> {
let mut result = HashMap::new();
let pnk = vec![
PropertyNameKind::File(HDFS_SITE_XML.to_string()),
PropertyNameKind::File(CORE_SITE_XML.to_string()),
PropertyNameKind::File(HADOOP_POLICY_XML.to_string()),
PropertyNameKind::File(SSL_SERVER_XML.to_string()),
PropertyNameKind::File(SSL_CLIENT_XML.to_string()),
PropertyNameKind::File(JVM_SECURITY_PROPERTIES_FILE.to_string()),
PropertyNameKind::Env,
];
if let Some(name_nodes) = &self.spec.name_nodes {
result.insert(
HdfsNodeRole::Name.to_string(),
(pnk.clone(), name_nodes.clone().erase()),
);
} else {
return Err(Error::MissingRole {
role: HdfsNodeRole::Name.to_string(),
});
}
if let Some(data_nodes) = &self.spec.data_nodes {
result.insert(
HdfsNodeRole::Data.to_string(),
(pnk.clone(), data_nodes.clone().erase()),
);
} else {
return Err(Error::MissingRole {
role: HdfsNodeRole::Data.to_string(),
});
}
if let Some(journal_nodes) = &self.spec.journal_nodes {
result.insert(
HdfsNodeRole::Journal.to_string(),
(pnk, journal_nodes.clone().erase()),
);
} else {
return Err(Error::MissingRole {
role: HdfsNodeRole::Journal.to_string(),
});
}
Ok(result)
}
pub fn upgrade_state(&self) -> Result<Option<UpgradeState>, UpgradeStateError> {
use upgrade_state_error::*;
let Some(status) = self.status.as_ref() else {
return Ok(None);
};
let requested_version = self.spec.image.product_version();
let Some(deployed_version) = status.deployed_product_version.as_deref() else {
// If no deployed version, fresh install -> no upgrade
return Ok(None);
};
let current_upgrade_target_version = status.upgrade_target_product_version.as_deref();
if requested_version != deployed_version {
// If we're requesting a different version than what is deployed, assume that we're upgrading.
// Could also be a downgrade to an older version, but we don't support downgrades after upgrade finalization.
match current_upgrade_target_version {
Some(upgrading_version) if requested_version != upgrading_version => {
// If we're in an upgrade, do not allow switching to a third version
InvalidCrossgradeSnafu {
requested_version,
deployed_version,
upgrading_version,
}
.fail()
}
_ => Ok(Some(UpgradeState::Upgrading)),
}
} else if current_upgrade_target_version.is_some_and(|x| requested_version != x) {
// If we're requesting the old version mid-upgrade, assume that we're downgrading.
// We only support downgrading to the exact previous version.
Ok(Some(UpgradeState::Downgrading))
} else {
// All three versions match, upgrade was completed without clearing `upgrading_product_version`.
Ok(None)
}
}
pub fn authentication_config(&self) -> Option<&AuthenticationConfig> {
self.spec.cluster_config.authentication.as_ref()
}
pub fn has_kerberos_enabled(&self) -> bool {
self.kerberos_config().is_some()
}
pub fn kerberos_config(&self) -> Option<&KerberosConfig> {
self.spec
.cluster_config
.authentication
.as_ref()
.map(|s| &s.kerberos)
}
pub fn has_https_enabled(&self) -> bool {
self.https_secret_class().is_some()
}
pub fn rackawareness_config(&self) -> Option<String> {
self.spec
.cluster_config
.rack_awareness
.as_ref()
.map(|label_list| {
label_list
.iter()
.map(TopologyLabel::to_config)
.collect::<Vec<_>>()
.join(";")
})
}
pub fn https_secret_class(&self) -> Option<&str> {
self.spec
.cluster_config
.authentication
.as_ref()
.map(|k| k.tls_secret_class.as_str())
}
pub fn has_authorization_enabled(&self) -> bool {
self.spec.cluster_config.authorization.is_some()
}
pub fn num_datanodes(&self) -> u16 {
self.spec
.data_nodes
.iter()
.flat_map(|dn| dn.role_groups.values())
.map(|rg| rg.replicas.unwrap_or(1))
.sum()
}
/// Returns required port name and port number tuples depending on the role.
pub fn ports(&self, role: &HdfsNodeRole) -> Vec<(String, u16)> {
match role {
HdfsNodeRole::Name => vec![
(
String::from(SERVICE_PORT_NAME_METRICS),
DEFAULT_NAME_NODE_METRICS_PORT,
),
(
String::from(SERVICE_PORT_NAME_RPC),
DEFAULT_NAME_NODE_RPC_PORT,
),
if self.has_https_enabled() {
(
String::from(SERVICE_PORT_NAME_HTTPS),
DEFAULT_NAME_NODE_HTTPS_PORT,
)
} else {
(
String::from(SERVICE_PORT_NAME_HTTP),
DEFAULT_NAME_NODE_HTTP_PORT,
)
},
],
HdfsNodeRole::Data => vec![
(
String::from(SERVICE_PORT_NAME_METRICS),
DEFAULT_DATA_NODE_METRICS_PORT,
),
(
String::from(SERVICE_PORT_NAME_DATA),
DEFAULT_DATA_NODE_DATA_PORT,
),
(
String::from(SERVICE_PORT_NAME_IPC),
DEFAULT_DATA_NODE_IPC_PORT,
),
if self.has_https_enabled() {
(
String::from(SERVICE_PORT_NAME_HTTPS),
DEFAULT_DATA_NODE_HTTPS_PORT,
)
} else {
(
String::from(SERVICE_PORT_NAME_HTTP),
DEFAULT_DATA_NODE_HTTP_PORT,
)
},
],
HdfsNodeRole::Journal => vec![
(
String::from(SERVICE_PORT_NAME_METRICS),
DEFAULT_JOURNAL_NODE_METRICS_PORT,
),
(
String::from(SERVICE_PORT_NAME_RPC),
DEFAULT_JOURNAL_NODE_RPC_PORT,
),
if self.has_https_enabled() {
(
String::from(SERVICE_PORT_NAME_HTTPS),
DEFAULT_JOURNAL_NODE_HTTPS_PORT,
)
} else {
(
String::from(SERVICE_PORT_NAME_HTTP),
DEFAULT_JOURNAL_NODE_HTTP_PORT,
)
},
],
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TopologyLabel {
/// Name of the label on the Kubernetes Node (where the Pod is placed on) used to resolve a datanode to a topology
/// zone.
NodeLabel(String),
/// Name of the label on the Kubernetes Pod used to resolve a datanode to a topology zone.
PodLabel(String),
}
impl TopologyLabel {
pub fn to_config(&self) -> String {
match &self {
TopologyLabel::NodeLabel(l) => format!("Node:{l}"),
TopologyLabel::PodLabel(l) => format!("Pod:{l}"),
}
}
}
fn default_dfs_replication_factor() -> u8 {
DEFAULT_DFS_REPLICATION_FACTOR
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum DeprecatedClusterListenerClass {
#[default]
ClusterInternal,
}
/// Configuration options that are available for all roles.
#[derive(Clone, Debug, Default, Fragment, JsonSchema, PartialEq)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct CommonNodeConfig {
#[fragment_attrs(serde(default))]
pub affinity: StackableAffinity,
/// Time period Pods have to gracefully shut down, e.g. `30m`, `1h` or `2d`. Consult the operator documentation for details.
#[fragment_attrs(serde(default))]
pub graceful_shutdown_timeout: Option<Duration>,
/// Request secret (currently only autoTls certificates) lifetime from the secret operator, e.g. `7d`, or `30d`.
/// This can be shortened by the `maxCertificateLifetime` setting on the SecretClass issuing the TLS certificate.
#[fragment_attrs(serde(default))]
pub requested_secret_lifetime: Option<Duration>,
}
/// Configuration for a rolegroup of an unknown type.
#[derive(Debug)]
pub enum AnyNodeConfig {
Name(NameNodeConfig),
Data(DataNodeConfig),
Journal(JournalNodeConfig),
}
impl Deref for AnyNodeConfig {
type Target = CommonNodeConfig;
fn deref(&self) -> &Self::Target {
match self {
AnyNodeConfig::Name(node) => &node.common,
AnyNodeConfig::Data(node) => &node.common,
AnyNodeConfig::Journal(node) => &node.common,
}
}
}
impl AnyNodeConfig {
// Downcasting helpers for each variant
pub fn as_namenode(&self) -> Option<&NameNodeConfig> {
if let Self::Name(node) = self {
Some(node)
} else {
None
}
}
pub fn as_datanode(&self) -> Option<&DataNodeConfig> {
if let Self::Data(node) = self {
Some(node)
} else {
None
}
}
pub fn as_journalnode(&self) -> Option<&JournalNodeConfig> {
if let Self::Journal(node) = self {
Some(node)
} else {
None
}
}
// Logging config is distinct between each role, due to the different enum types,
// so provide helpers for containers that are common between all roles.
pub fn hdfs_logging(&self) -> Cow<ContainerLogConfig> {
match self {
AnyNodeConfig::Name(node) => node.logging.for_container(&NameNodeContainer::Hdfs),
AnyNodeConfig::Data(node) => node.logging.for_container(&DataNodeContainer::Hdfs),
AnyNodeConfig::Journal(node) => node.logging.for_container(&JournalNodeContainer::Hdfs),
}
}
pub fn vector_logging(&self) -> Cow<ContainerLogConfig> {
match &self {
AnyNodeConfig::Name(node) => node.logging.for_container(&NameNodeContainer::Vector),
AnyNodeConfig::Data(node) => node.logging.for_container(&DataNodeContainer::Vector),
AnyNodeConfig::Journal(node) => {
node.logging.for_container(&JournalNodeContainer::Vector)
}
}
}
pub fn vector_logging_enabled(&self) -> bool {
match self {
AnyNodeConfig::Name(node) => node.logging.enable_vector_agent,
AnyNodeConfig::Data(node) => node.logging.enable_vector_agent,
AnyNodeConfig::Journal(node) => node.logging.enable_vector_agent,
}
}
pub fn requested_secret_lifetime(&self) -> Option<Duration> {
match self {
AnyNodeConfig::Name(node) => node.common.requested_secret_lifetime,
AnyNodeConfig::Data(node) => node.common.requested_secret_lifetime,
AnyNodeConfig::Journal(node) => node.common.requested_secret_lifetime,
}
}
}
#[derive(
Clone,
Copy,
Debug,
Deserialize,
Display,
EnumIter,
EnumString,
IntoStaticStr,
Eq,
Hash,
JsonSchema,
PartialEq,
Serialize,
)]
pub enum HdfsNodeRole {
#[serde(rename = "journalnode")]
#[strum(serialize = "journalnode")]
Journal,
#[serde(rename = "namenode")]
#[strum(serialize = "namenode")]
Name,
#[serde(rename = "datanode")]
#[strum(serialize = "datanode")]
Data,
}
impl HdfsNodeRole {
pub fn min_replicas(&self) -> u16 {
match self {
HdfsNodeRole::Name => 2,
HdfsNodeRole::Data => 1,
HdfsNodeRole::Journal => 3,
}
}
pub fn replicas_can_be_even(&self) -> bool {
match self {
HdfsNodeRole::Name => true,
HdfsNodeRole::Data => true,
HdfsNodeRole::Journal => false,
}
}
pub fn check_valid_dfs_replication(&self) -> bool {
match self {
HdfsNodeRole::Name => false,
HdfsNodeRole::Data => true,
HdfsNodeRole::Journal => false,
}
}
/// Merge the [Name|Data|Journal]NodeConfigFragment defaults, role and role group settings.
/// The priority is: default < role config < role_group config
pub fn merged_config(
&self,
hdfs: &v1alpha1::HdfsCluster,
role_group: &str,
) -> Result<AnyNodeConfig, Error> {
match self {
HdfsNodeRole::Name => {
let default_config = NameNodeConfigFragment::default_config(&hdfs.name_any(), self);
let role = hdfs
.spec
.name_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Name.to_string(),
})?;
let mut role_config = role.config.config.clone();
let mut role_group_config = hdfs
.namenode_rolegroup(role_group)
.with_context(|| MissingRoleGroupSnafu {
role: HdfsNodeRole::Name.to_string(),
role_group: role_group.to_string(),
})?
.config
.config
.clone();
role_config.merge(&default_config);
role_group_config.merge(&role_config);
Ok(AnyNodeConfig::Name(
fragment::validate::<NameNodeConfig>(role_group_config)
.context(FragmentValidationFailureSnafu)?,
))
}
HdfsNodeRole::Data => {
let default_config = DataNodeConfigFragment::default_config(&hdfs.name_any(), self);
let role = hdfs
.spec
.data_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Data.to_string(),
})?;
let mut role_config = role.config.config.clone();
let mut role_group_config = hdfs
.datanode_rolegroup(role_group)
.with_context(|| MissingRoleGroupSnafu {
role: HdfsNodeRole::Data.to_string(),
role_group: role_group.to_string(),
})?
.config
.config
.clone();
role_config.merge(&default_config);
role_group_config.merge(&role_config);
Ok(AnyNodeConfig::Data(
fragment::validate::<DataNodeConfig>(role_group_config)
.context(FragmentValidationFailureSnafu)?,
))
}
HdfsNodeRole::Journal => {
let default_config =
JournalNodeConfigFragment::default_config(&hdfs.name_any(), self);
let role = hdfs
.spec
.journal_nodes
.as_ref()
.with_context(|| MissingRoleSnafu {
role: HdfsNodeRole::Journal.to_string(),
})?;