-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmod.rs
More file actions
1423 lines (1284 loc) · 49.6 KB
/
mod.rs
File metadata and controls
1423 lines (1284 loc) · 49.6 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
use std::collections::{BTreeMap, HashMap};
use product_config::types::PropertyNameKind;
use security::AuthenticationConfig;
use serde::{Deserialize, Serialize};
use shell_escape::escape;
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
commons::{
affinity::StackableAffinity,
cluster_operation::ClusterOperation,
product_image_selection::ProductImage,
resources::{
CpuLimitsFragment, MemoryLimitsFragment, NoRuntimeLimits, NoRuntimeLimitsFragment,
Resources, ResourcesFragment,
},
},
config::{
fragment::{self, Fragment, ValidationError},
merge::{Atomic, Merge},
},
k8s_openapi::{
DeepMerge,
api::core::v1::{EnvVar, PodTemplateSpec},
apimachinery::pkg::api::resource::Quantity,
},
kube::{CustomResource, ResourceExt, runtime::reflector::ObjectRef},
product_config_utils::Configuration,
product_logging::{self, spec::Logging},
role_utils::{GenericRoleConfig, JavaCommonConfig, Role, RoleGroupRef},
schemars::{self, JsonSchema},
status::condition::{ClusterCondition, HasStatusCondition},
time::Duration,
versioned::versioned,
};
use strum::{Display, EnumIter, EnumString};
use crate::crd::{affinity::get_affinity, security::AuthorizationConfig};
pub mod affinity;
pub mod security;
pub const APP_NAME: &str = "hbase";
// This constant is hard coded in hbase-entrypoint.sh
// You need to change it there too.
pub const CONFIG_DIR_NAME: &str = "/stackable/conf";
pub const TLS_STORE_DIR: &str = "/stackable/tls";
pub const TLS_STORE_VOLUME_NAME: &str = "tls";
pub const TLS_STORE_PASSWORD: &str = "changeit";
pub const JVM_SECURITY_PROPERTIES_FILE: &str = "security.properties";
pub const HBASE_ENV_SH: &str = "hbase-env.sh";
pub const HBASE_SITE_XML: &str = "hbase-site.xml";
pub const SSL_SERVER_XML: &str = "ssl-server.xml";
pub const SSL_CLIENT_XML: &str = "ssl-client.xml";
pub const HBASE_CLUSTER_DISTRIBUTED: &str = "hbase.cluster.distributed";
pub const HBASE_ROOTDIR: &str = "hbase.rootdir";
pub const HBASE_UNSAFE_REGIONSERVER_HOSTNAME_DISABLE_MASTER_REVERSEDNS: &str =
"hbase.unsafe.regionserver.hostname.disable.master.reversedns";
pub const HBASE_UI_PORT_NAME_HTTP: &str = "ui-http";
pub const HBASE_UI_PORT_NAME_HTTPS: &str = "ui-https";
pub const HBASE_REST_PORT_NAME_HTTP: &str = "rest-http";
pub const HBASE_REST_PORT_NAME_HTTPS: &str = "rest-https";
pub const METRICS_PORT_NAME: &str = "metrics";
pub const HBASE_MASTER_PORT: u16 = 16000;
// HBase always uses 16010, regardless of http or https. On 2024-01-17 we decided in Arch-meeting that we want to stick
// the port numbers to what the product is doing, so we get the least surprise for users - even when this means we have
// inconsistency between Stackable products.
pub const HBASE_MASTER_UI_PORT: u16 = 16010;
pub const HBASE_REGIONSERVER_PORT: u16 = 16020;
pub const HBASE_REGIONSERVER_UI_PORT: u16 = 16030;
pub const HBASE_REST_PORT: u16 = 8080;
pub const HBASE_REST_UI_PORT: u16 = 8085;
// This port is only used by Hbase prior to version 2.6 with a third-party JMX exporter.
// Newer versions use the same port as the UI because Hbase provides it's own metrics API
pub const METRICS_PORT: u16 = 9100;
const DEFAULT_REGION_MOVER_TIMEOUT: Duration = Duration::from_minutes_unchecked(59);
const DEFAULT_REGION_MOVER_DELTA_TO_SHUTDOWN: Duration = Duration::from_minutes_unchecked(1);
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("the role [{role}] is invalid and does not exist in HBase"))]
InvalidRole {
source: strum::ParseError,
role: String,
},
#[snafu(display("the HBase role [{role}] is missing from spec"))]
MissingHbaseRole { role: String },
#[snafu(display("fragment validation failure"))]
FragmentValidationFailure { source: ValidationError },
#[snafu(display("object defines no master role"))]
NoMasterRole,
#[snafu(display("object defines no regionserver role"))]
NoRegionServerRole,
#[snafu(display("incompatible merge types"))]
IncompatibleMergeTypes,
}
#[versioned(version(name = "v1alpha1"))]
pub mod versioned {
/// An HBase cluster stacklet. This resource is managed by the Stackable operator for Apache HBase.
/// Find more information on how to use it and the resources that the operator generates in the
/// [operator documentation](DOCS_BASE_URL_PLACEHOLDER/hbase/).
///
/// The CRD contains three roles: `masters`, `regionServers` and `restServers`.
#[versioned(k8s(
group = "hbase.stackable.tech",
kind = "HbaseCluster",
plural = "hbaseclusters",
shortname = "hbase",
status = "HbaseClusterStatus",
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 HbaseClusterSpec {
// no doc string - See ProductImage struct
pub image: ProductImage,
/// Configuration that applies to all roles and role groups.
/// This includes settings for logging, ZooKeeper and HDFS connection, among other things.
pub cluster_config: v1alpha1::HbaseClusterConfig,
// no doc string - See ClusterOperation struct
#[serde(default)]
pub cluster_operation: ClusterOperation,
/// The HBase master process is responsible for assigning regions to region servers and
/// manages the cluster.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub masters: Option<Role<HbaseConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
/// Region servers hold the data and handle requests from clients for their region.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region_servers:
Option<Role<RegionServerConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
/// Rest servers provide a REST API to interact with.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rest_servers: Option<Role<HbaseConfigFragment, GenericRoleConfig, JavaCommonConfig>>,
}
#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HbaseClusterConfig {
/// Name of the [discovery ConfigMap](DOCS_BASE_URL_PLACEHOLDER/concepts/service_discovery)
/// for an HDFS cluster.
pub hdfs_config_map_name: String,
/// 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,
/// This field controls which type of Service the Operator creates for this HbaseCluster:
///
/// * cluster-internal: Use a ClusterIP service
///
/// * external-unstable: Use a NodePort service
///
/// This is a temporary solution with the goal to keep yaml manifests forward compatible.
/// In the future, this setting will control which [ListenerClass](DOCS_BASE_URL_PLACEHOLDER/listener-operator/listenerclass.html)
/// will be used to expose the service, and ListenerClass names will stay the same, allowing for a non-breaking change.
#[serde(default)]
pub listener_class: CurrentlySupportedListenerClasses,
/// Settings related to user [authentication](DOCS_BASE_URL_PLACEHOLDER/usage-guide/security).
pub authentication: Option<AuthenticationConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization: Option<AuthorizationConfig>,
}
}
impl HasStatusCondition for v1alpha1::HbaseCluster {
fn conditions(&self) -> Vec<ClusterCondition> {
match &self.status {
Some(status) => status.conditions.clone(),
None => vec![],
}
}
}
impl v1alpha1::HbaseCluster {
/// Retrieve and merge resource configs for role and role groups
pub fn merged_config(
&self,
role: &HbaseRole,
role_group: &str,
hdfs_discovery_cm_name: &str,
) -> Result<AnyServiceConfig, Error> {
// Initialize the result with all default values as baseline
let defaults =
AnyConfigFragment::default_for(role, &self.name_any(), hdfs_discovery_cm_name);
let (mut role_config, mut role_group_config) = match role {
HbaseRole::RegionServer => {
let role = self
.spec
.region_servers
.clone()
.context(MissingHbaseRoleSnafu {
role: role.to_string(),
})?;
let role_config = role.config.config.to_owned();
let role_group_config = role
.role_groups
.get(role_group)
.map(|rg| rg.config.config.clone())
.unwrap_or_default();
(
AnyConfigFragment::RegionServer(role_config),
AnyConfigFragment::RegionServer(role_group_config),
)
}
HbaseRole::RestServer => {
let role = self
.spec
.rest_servers
.clone()
.context(MissingHbaseRoleSnafu {
role: role.to_string(),
})?;
let role_config = role.config.config.to_owned();
let role_group_config = role
.role_groups
.get(role_group)
.map(|rg| rg.config.config.clone())
.unwrap_or_default();
// Retrieve role resource config
(
AnyConfigFragment::RestServer(role_config),
AnyConfigFragment::RestServer(role_group_config),
)
}
HbaseRole::Master => {
let role = self.spec.masters.clone().context(MissingHbaseRoleSnafu {
role: role.to_string(),
})?;
let role_config = role.config.config.to_owned();
// Retrieve rolegroup specific resource config
let role_group_config = role
.role_groups
.get(role_group)
.map(|rg| rg.config.config.clone())
.unwrap_or_default();
// Retrieve role resource config
(
AnyConfigFragment::Master(role_config),
AnyConfigFragment::Master(role_group_config),
)
}
};
// Merge more specific configs into default config
// Hierarchy is:
// 1. RoleGroup
// 2. Role
// 3. Default
role_config = role_config.merge(&defaults)?;
role_group_config = role_group_config.merge(&role_config)?;
tracing::debug!("Merged config: {:?}", role_group_config);
Ok(match role_group_config {
AnyConfigFragment::RegionServer(conf) => AnyServiceConfig::RegionServer(
fragment::validate(conf).context(FragmentValidationFailureSnafu)?,
),
AnyConfigFragment::RestServer(conf) => AnyServiceConfig::RestServer(
fragment::validate(conf).context(FragmentValidationFailureSnafu)?,
),
AnyConfigFragment::Master(conf) => AnyServiceConfig::Master(
fragment::validate(conf).context(FragmentValidationFailureSnafu)?,
),
})
}
// The result type is only defined once, there is no value in extracting it into a type definition.
#[allow(clippy::type_complexity)]
pub fn build_role_properties(
&self,
) -> Result<
HashMap<
String,
(
Vec<PropertyNameKind>,
Role<impl Configuration<Configurable = Self>, GenericRoleConfig, JavaCommonConfig>,
),
>,
Error,
> {
let config_types = vec![
PropertyNameKind::Env,
PropertyNameKind::File(HBASE_ENV_SH.to_string()),
PropertyNameKind::File(HBASE_SITE_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()),
];
let mut roles = HashMap::from([(
HbaseRole::Master.to_string(),
(
config_types.to_owned(),
self.spec
.masters
.clone()
.context(NoMasterRoleSnafu)?
.erase(),
),
)]);
roles.insert(
HbaseRole::RegionServer.to_string(),
(
config_types.to_owned(),
self.spec
.region_servers
.clone()
.context(NoRegionServerRoleSnafu)?
.erase(),
),
);
if let Some(rest_servers) = self.spec.rest_servers.as_ref() {
roles.insert(
HbaseRole::RestServer.to_string(),
(config_types, rest_servers.to_owned().erase()),
);
}
Ok(roles)
}
pub fn merge_pod_overrides(
&self,
pod_template: &mut PodTemplateSpec,
role: &HbaseRole,
role_group_ref: &RoleGroupRef<Self>,
) {
let (role_pod_overrides, role_group_pod_overrides) = match role {
HbaseRole::Master => (
self.spec
.masters
.as_ref()
.map(|r| r.config.pod_overrides.clone()),
self.spec
.masters
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.map(|r| r.config.pod_overrides.clone()),
),
HbaseRole::RegionServer => (
self.spec
.region_servers
.as_ref()
.map(|r| r.config.pod_overrides.clone()),
self.spec
.region_servers
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.map(|r| r.config.pod_overrides.clone()),
),
HbaseRole::RestServer => (
self.spec
.rest_servers
.as_ref()
.map(|r| r.config.pod_overrides.clone()),
self.spec
.rest_servers
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.map(|r| r.config.pod_overrides.clone()),
),
};
if let Some(rpo) = role_pod_overrides {
pod_template.merge_from(rpo);
}
if let Some(rgpo) = role_group_pod_overrides {
pod_template.merge_from(rgpo);
}
}
pub fn replicas(
&self,
hbase_role: &HbaseRole,
role_group_ref: &RoleGroupRef<Self>,
) -> Option<i32> {
match hbase_role {
HbaseRole::Master => self
.spec
.masters
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.and_then(|rg| rg.replicas)
.map(i32::from),
HbaseRole::RegionServer => self
.spec
.region_servers
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.and_then(|rg| rg.replicas)
.map(i32::from),
HbaseRole::RestServer => self
.spec
.rest_servers
.as_ref()
.and_then(|r| r.role_groups.get(&role_group_ref.role_group))
.and_then(|rg| rg.replicas)
.map(i32::from),
}
}
/// The name of the role-level load-balanced Kubernetes `Service`
pub fn server_role_service_name(&self) -> Option<String> {
self.metadata.name.clone()
}
/// Metadata about a server rolegroup
pub fn server_rolegroup_ref(
&self,
role_name: impl Into<String>,
group_name: impl Into<String>,
) -> RoleGroupRef<Self> {
RoleGroupRef {
cluster: ObjectRef::from_obj(self),
role: role_name.into(),
role_group: group_name.into(),
}
}
pub fn role_config(&self, role: &HbaseRole) -> Option<&GenericRoleConfig> {
match role {
HbaseRole::Master => self.spec.masters.as_ref().map(|m| &m.role_config),
HbaseRole::RegionServer => self.spec.region_servers.as_ref().map(|rs| &rs.role_config),
HbaseRole::RestServer => self.spec.rest_servers.as_ref().map(|rs| &rs.role_config),
}
}
pub fn has_kerberos_enabled(&self) -> bool {
self.kerberos_secret_class().is_some()
}
pub fn kerberos_secret_class(&self) -> Option<String> {
self.spec
.cluster_config
.authentication
.as_ref()
.map(|a| &a.kerberos)
.map(|k| k.secret_class.clone())
}
pub fn has_https_enabled(&self) -> bool {
self.https_secret_class().is_some()
}
pub fn https_secret_class(&self) -> Option<String> {
self.spec
.cluster_config
.authentication
.as_ref()
.map(|a| a.tls_secret_class.clone())
}
/// Returns required port name and port number tuples depending on the role.
/// Hbase versions 2.4.* will have three ports for each role
/// Hbase versions 2.6.* will have two ports for each role. The metrics are available over the
/// UI port.
pub fn ports(&self, role: &HbaseRole, hbase_version: &str) -> Vec<(String, u16)> {
let result_without_metric_port: Vec<(String, u16)> = match role {
HbaseRole::Master => vec![
("master".to_string(), HBASE_MASTER_PORT),
(self.ui_port_name(), HBASE_MASTER_UI_PORT),
],
HbaseRole::RegionServer => vec![
("regionserver".to_string(), HBASE_REGIONSERVER_PORT),
(self.ui_port_name(), HBASE_REGIONSERVER_UI_PORT),
],
HbaseRole::RestServer => vec![
(
if self.has_https_enabled() {
HBASE_REST_PORT_NAME_HTTPS
} else {
HBASE_REST_PORT_NAME_HTTP
}
.to_string(),
HBASE_REST_PORT,
),
(self.ui_port_name(), HBASE_REST_UI_PORT),
],
};
if hbase_version.starts_with(r"2.4") {
result_without_metric_port
.into_iter()
.chain(vec![(METRICS_PORT_NAME.to_string(), METRICS_PORT)])
.collect()
} else {
result_without_metric_port
}
}
pub fn service_port(&self, role: &HbaseRole) -> u16 {
match role {
HbaseRole::Master => HBASE_MASTER_PORT,
HbaseRole::RegionServer => HBASE_REGIONSERVER_PORT,
HbaseRole::RestServer => HBASE_REST_PORT,
}
}
/// Name of the port used by the Web UI, which depends on HTTPS usage
fn ui_port_name(&self) -> String {
if self.has_https_enabled() {
HBASE_UI_PORT_NAME_HTTPS
} else {
HBASE_UI_PORT_NAME_HTTP
}
.to_string()
}
}
pub fn merged_env(rolegroup_config: Option<&BTreeMap<String, String>>) -> Vec<EnvVar> {
let merged_env: Vec<EnvVar> = if let Some(rolegroup_config) = rolegroup_config {
rolegroup_config
.iter()
.map(|(env_name, env_value)| EnvVar {
name: env_name.clone(),
value: Some(env_value.to_owned()),
value_from: None,
})
.collect()
} else {
vec![]
};
merged_env
}
// TODO: Temporary solution until listener-operator is finished
#[derive(Clone, Debug, Default, Display, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "PascalCase")]
pub enum CurrentlySupportedListenerClasses {
#[default]
#[serde(rename = "cluster-internal")]
ClusterInternal,
#[serde(rename = "external-unstable")]
ExternalUnstable,
}
impl CurrentlySupportedListenerClasses {
pub fn k8s_service_type(&self) -> String {
match self {
CurrentlySupportedListenerClasses::ClusterInternal => "ClusterIP".to_string(),
CurrentlySupportedListenerClasses::ExternalUnstable => "NodePort".to_string(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KerberosConfig {
/// Name of the SecretClass providing the keytab for the HDFS services.
#[serde(default = "default_kerberos_kerberos_secret_class")]
kerberos_secret_class: String,
/// Name of the SecretClass providing the tls certificates for the WebUIs.
#[serde(default = "default_kerberos_tls_secret_class")]
tls_secret_class: String,
/// Wether a principal including the Kubernetes node name should be requested.
/// The principal could e.g. be `HTTP/my-k8s-worker-0.mycorp.lan`.
/// This feature is disabled by default, as the resulting principals can already by existent
/// e.g. in Active Directory which can cause problems.
#[serde(default)]
request_node_principals: bool,
}
fn default_kerberos_tls_secret_class() -> String {
"tls".to_string()
}
fn default_kerberos_kerberos_secret_class() -> String {
"kerberos".to_string()
}
#[derive(
Clone,
Debug,
Deserialize,
Display,
EnumIter,
Eq,
Hash,
JsonSchema,
PartialEq,
Serialize,
EnumString,
)]
pub enum HbaseRole {
#[serde(rename = "master")]
#[strum(serialize = "master")]
Master,
#[serde(rename = "regionserver")]
#[strum(serialize = "regionserver")]
RegionServer,
#[serde(rename = "restserver")]
#[strum(serialize = "restserver")]
RestServer,
}
impl HbaseRole {
const DEFAULT_MASTER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_minutes_unchecked(20);
// Auto TLS certificate lifetime
const DEFAULT_MASTER_SECRET_LIFETIME: Duration = Duration::from_days_unchecked(1);
const DEFAULT_REGION_SECRET_LIFETIME: Duration = Duration::from_days_unchecked(1);
const DEFAULT_REGION_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration =
Duration::from_minutes_unchecked(60);
const DEFAULT_REST_SECRET_LIFETIME: Duration = Duration::from_days_unchecked(1);
const DEFAULT_REST_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration =
Duration::from_minutes_unchecked(5);
pub fn default_config(
&self,
cluster_name: &str,
hdfs_discovery_cm_name: &str,
) -> HbaseConfigFragment {
let resources = match &self {
HbaseRole::Master => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("250m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
HbaseRole::RegionServer => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("250m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
HbaseRole::RestServer => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("100m".to_owned())),
max: Some(Quantity("400m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("512Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
};
let graceful_shutdown_timeout = match &self {
HbaseRole::Master => Self::DEFAULT_MASTER_GRACEFUL_SHUTDOWN_TIMEOUT,
HbaseRole::RegionServer => Self::DEFAULT_REGION_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
HbaseRole::RestServer => Self::DEFAULT_REST_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
};
let requested_secret_lifetime = match &self {
HbaseRole::Master => Self::DEFAULT_MASTER_SECRET_LIFETIME,
HbaseRole::RegionServer => Self::DEFAULT_REGION_SECRET_LIFETIME,
HbaseRole::RestServer => Self::DEFAULT_REST_SECRET_LIFETIME,
};
HbaseConfigFragment {
hbase_rootdir: None,
resources,
logging: product_logging::spec::default_logging(),
affinity: get_affinity(cluster_name, self, hdfs_discovery_cm_name),
graceful_shutdown_timeout: Some(graceful_shutdown_timeout),
requested_secret_lifetime: Some(requested_secret_lifetime),
}
}
/// Returns the name of the role as it is needed by the `bin/hbase {cli_role_name} start` command.
pub fn cli_role_name(&self) -> String {
match self {
HbaseRole::Master | HbaseRole::RegionServer => self.to_string(),
// Of course it is not called "restserver", so we need to have this match
// instead of just letting the Display impl do it's thing ;P
HbaseRole::RestServer => "rest".to_string(),
}
}
}
fn default_resources(role: &HbaseRole) -> ResourcesFragment<HbaseStorageConfig, NoRuntimeLimits> {
match role {
HbaseRole::RegionServer => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("250m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
HbaseRole::RestServer => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("100m".to_owned())),
max: Some(Quantity("400m".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("512Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
HbaseRole::Master => ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("250m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1Gi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: HbaseStorageConfigFragment {},
},
}
}
#[derive(Debug, Clone)]
enum AnyConfigFragment {
RegionServer(RegionServerConfigFragment),
RestServer(HbaseConfigFragment),
Master(HbaseConfigFragment),
}
impl AnyConfigFragment {
fn merge(self, other: &AnyConfigFragment) -> Result<Self, Error> {
match (self, other) {
(AnyConfigFragment::RegionServer(mut me), AnyConfigFragment::RegionServer(you)) => {
me.merge(you);
Ok(AnyConfigFragment::RegionServer(me.clone()))
}
(AnyConfigFragment::RestServer(mut me), AnyConfigFragment::RestServer(you)) => {
me.merge(you);
Ok(AnyConfigFragment::RestServer(me.clone()))
}
(AnyConfigFragment::Master(mut me), AnyConfigFragment::Master(you)) => {
me.merge(you);
Ok(AnyConfigFragment::Master(me.clone()))
}
(_, _) => Err(Error::IncompatibleMergeTypes),
}
}
fn default_for(
role: &HbaseRole,
cluster_name: &str,
hdfs_discovery_cm_name: &str,
) -> AnyConfigFragment {
match role {
HbaseRole::RegionServer => {
AnyConfigFragment::RegionServer(RegionServerConfigFragment {
hbase_rootdir: None,
resources: default_resources(role),
logging: product_logging::spec::default_logging(),
affinity: get_affinity(cluster_name, role, hdfs_discovery_cm_name),
graceful_shutdown_timeout: Some(
HbaseRole::DEFAULT_REGION_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
),
region_mover: RegionMoverFragment {
run_before_shutdown: Some(false),
max_threads: Some(1),
ack: Some(true),
cli_opts: None,
},
requested_secret_lifetime: Some(HbaseRole::DEFAULT_REGION_SECRET_LIFETIME),
})
}
HbaseRole::RestServer => AnyConfigFragment::RestServer(HbaseConfigFragment {
hbase_rootdir: None,
resources: default_resources(role),
logging: product_logging::spec::default_logging(),
affinity: get_affinity(cluster_name, role, hdfs_discovery_cm_name),
graceful_shutdown_timeout: Some(
HbaseRole::DEFAULT_REST_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
),
requested_secret_lifetime: Some(HbaseRole::DEFAULT_REST_SECRET_LIFETIME),
}),
HbaseRole::Master => AnyConfigFragment::Master(HbaseConfigFragment {
hbase_rootdir: None,
resources: default_resources(role),
logging: product_logging::spec::default_logging(),
affinity: get_affinity(cluster_name, role, hdfs_discovery_cm_name),
graceful_shutdown_timeout: Some(
HbaseRole::DEFAULT_MASTER_GRACEFUL_SHUTDOWN_TIMEOUT,
),
requested_secret_lifetime: Some(HbaseRole::DEFAULT_MASTER_SECRET_LIFETIME),
}),
}
}
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, Debug, Default, JsonSchema, PartialEq, Fragment)]
#[fragment_attrs(
allow(clippy::derive_partial_eq_without_eq),
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct HbaseStorageConfig {}
#[derive(
Clone,
Debug,
Deserialize,
Display,
Eq,
EnumIter,
JsonSchema,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[serde(rename_all = "camelCase")]
pub enum Container {
Hbase,
Vector,
}
#[derive(Clone, Debug, Default, Fragment, JsonSchema, PartialEq)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct HbaseConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hbase_rootdir: Option<String>,
#[fragment_attrs(serde(default))]
pub resources: Resources<HbaseStorageConfig, NoRuntimeLimits>,
#[fragment_attrs(serde(default))]
pub logging: Logging<Container>,
#[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`.
/// Please note that 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>,
}
impl Configuration for HbaseConfigFragment {
type Configurable = v1alpha1::HbaseCluster;
fn compute_env(
&self,
_resource: &Self::Configurable,
_role_name: &str,
) -> Result<BTreeMap<String, Option<String>>, stackable_operator::product_config_utils::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 vars: BTreeMap<String, Option<String>> = BTreeMap::new();
vars.insert(
"HBASE_CONF_DIR".to_string(),
Some(CONFIG_DIR_NAME.to_string()),
);
// required by phoenix (for cases where Kerberos is enabled): see https://issues.apache.org/jira/browse/PHOENIX-2369
vars.insert(
"HADOOP_CONF_DIR".to_string(),
Some(CONFIG_DIR_NAME.to_string()),
);
Ok(vars)
}
fn compute_cli(
&self,
_resource: &Self::Configurable,
_role_name: &str,
) -> Result<BTreeMap<String, Option<String>>, stackable_operator::product_config_utils::Error>
{
Ok(BTreeMap::new())
}
fn compute_files(
&self,
_resource: &Self::Configurable,
_role_name: &str,
file: &str,
) -> Result<BTreeMap<String, Option<String>>, stackable_operator::product_config_utils::Error>
{
let mut result = BTreeMap::new();
match file {
HBASE_ENV_SH => {
// The contents of this file cannot be built entirely here because we don't have
// access to the clusterConfig or product version.
// These are needed to set up Kerberos and JMX exporter settings.
// To avoid fragmentation of the code needed to build this file, we moved the
// implementation to the hbase_controller::build_hbase_env_sh() function.
}
HBASE_SITE_XML => {
result.insert(
HBASE_CLUSTER_DISTRIBUTED.to_string(),
Some("true".to_string()),
);
result.insert(
HBASE_UNSAFE_REGIONSERVER_HOSTNAME_DISABLE_MASTER_REVERSEDNS.to_string(),
Some("true".to_string()),
);
result.insert(HBASE_ROOTDIR.to_string(), self.hbase_rootdir.clone());
}
_ => {}
}
result.retain(|_, maybe_value| maybe_value.is_some());
Ok(result)
}
}
#[derive(Fragment, Clone, Debug, JsonSchema, PartialEq, Serialize, Deserialize)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct RegionMover {
/// Move local regions to other servers before terminating a region server's pod.
run_before_shutdown: bool,