-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkafka_controller.rs
1242 lines (1121 loc) · 43.3 KB
/
kafka_controller.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
//! Ensures that `Pod`s are configured and running for each [`v1alpha1::KafkaCluster`].
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap},
sync::Arc,
};
use const_format::concatcp;
use product_config::{
types::PropertyNameKind,
writer::{to_java_properties_string, PropertiesWriterError},
ProductConfigManager,
};
use snafu::{OptionExt, ResultExt, Snafu};
use stackable_operator::{
builder::{
self,
configmap::ConfigMapBuilder,
meta::ObjectMetaBuilder,
pod::{
container::ContainerBuilder,
resources::ResourceRequirementsBuilder,
security::PodSecurityContextBuilder,
volume::{ListenerOperatorVolumeSourceBuilder, ListenerReference, VolumeBuilder},
PodBuilder,
},
},
cluster_resources::{ClusterResourceApplyStrategy, ClusterResources},
commons::{
authentication::AuthenticationClass,
listener::{Listener, ListenerPort, ListenerSpec},
opa::OpaApiVersion,
product_image_selection::ResolvedProductImage,
rbac::build_rbac_resources,
},
k8s_openapi::{
api::{
apps::v1::{StatefulSet, StatefulSetSpec},
core::v1::{
ConfigMap, ConfigMapKeySelector, ConfigMapVolumeSource, ContainerPort, EnvVar,
EnvVarSource, ExecAction, ObjectFieldSelector, PodSpec, Probe, Service,
ServiceAccount, ServiceSpec, Volume,
},
},
apimachinery::pkg::apis::meta::v1::LabelSelector,
DeepMerge,
},
kube::{
api::DynamicObject,
core::{error_boundary, DeserializeGuard},
runtime::{controller::Action, reflector::ObjectRef},
Resource, ResourceExt,
},
kvp::{Label, Labels},
logging::controller::ReconcilerError,
product_config_utils::{transform_all_roles_to_config, validate_all_roles_and_groups_config},
product_logging::{
self,
framework::LoggingError,
spec::{
ConfigMapLogConfig, ContainerLogConfig, ContainerLogConfigChoice,
CustomContainerLogConfig,
},
},
role_utils::{GenericRoleConfig, RoleGroupRef},
status::condition::{
compute_conditions, operations::ClusterOperationsConditionBuilder,
statefulset::StatefulSetConditionBuilder,
},
time::Duration,
utils::cluster_info::KubernetesClusterInfo,
};
use strum::{EnumDiscriminants, IntoStaticStr};
use crate::{
config::jvm::{construct_heap_jvm_args, construct_non_heap_jvm_args},
crd::{
listener::{get_kafka_listener_config, KafkaListenerError},
security::KafkaTlsSecurity,
v1alpha1, Container, KafkaClusterStatus, KafkaConfig, KafkaRole, APP_NAME,
DOCKER_IMAGE_BASE_NAME, JVM_SECURITY_PROPERTIES_FILE, KAFKA_HEAP_OPTS,
LISTENER_BOOTSTRAP_VOLUME_NAME, LISTENER_BROKER_VOLUME_NAME, LOG_DIRS_VOLUME_NAME,
METRICS_PORT, METRICS_PORT_NAME, OPERATOR_NAME, SERVER_PROPERTIES_FILE,
STACKABLE_CONFIG_DIR, STACKABLE_DATA_DIR, STACKABLE_LISTENER_BOOTSTRAP_DIR,
STACKABLE_LISTENER_BROKER_DIR, STACKABLE_LOG_CONFIG_DIR, STACKABLE_LOG_DIR,
},
discovery::{self, build_discovery_configmaps},
kerberos::{self, add_kerberos_pod_config},
operations::{
graceful_shutdown::{add_graceful_shutdown_config, graceful_shutdown_config_properties},
pdb::add_pdbs,
},
product_logging::{
extend_role_group_config_map, resolve_vector_aggregator_address, LOG4J_CONFIG_FILE,
MAX_KAFKA_LOG_FILES_SIZE,
},
utils::build_recommended_labels,
};
pub const KAFKA_CONTROLLER_NAME: &str = "kafkacluster";
pub const KAFKA_FULL_CONTROLLER_NAME: &str = concatcp!(KAFKA_CONTROLLER_NAME, '.', OPERATOR_NAME);
/// Used as runAsUser in the pod security context. This is specified in the kafka image file
pub const KAFKA_UID: i64 = 1000;
pub struct Ctx {
pub client: stackable_operator::client::Client,
pub product_config: ProductConfigManager,
}
#[derive(Snafu, Debug, EnumDiscriminants)]
#[strum_discriminants(derive(IntoStaticStr))]
#[allow(clippy::enum_variant_names)]
pub enum Error {
#[snafu(display("missing secret lifetime"))]
MissingSecretLifetime,
#[snafu(display("object has no name"))]
ObjectHasNoName,
#[snafu(display("object has no namespace"))]
ObjectHasNoNamespace,
#[snafu(display("object defines no broker role"))]
NoBrokerRole,
#[snafu(display("failed to apply role Service"))]
ApplyRoleService {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to apply role ServiceAccount"))]
ApplyRoleServiceAccount {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to apply global RoleBinding"))]
ApplyRoleRoleBinding {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to apply Service for {}", rolegroup))]
ApplyRoleGroupService {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("failed to build ConfigMap for {}", rolegroup))]
BuildRoleGroupConfig {
source: stackable_operator::builder::configmap::Error,
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("failed to apply ConfigMap for {}", rolegroup))]
ApplyRoleGroupConfig {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("failed to apply StatefulSet for {}", rolegroup))]
ApplyRoleGroupStatefulSet {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("failed to generate product config"))]
GenerateProductConfig {
source: stackable_operator::product_config_utils::Error,
},
#[snafu(display("invalid product config"))]
InvalidProductConfig {
source: stackable_operator::product_config_utils::Error,
},
#[snafu(display("failed to serialize zoo.cfg for {}", rolegroup))]
SerializeZooCfg {
source: PropertiesWriterError,
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("object is missing metadata to build owner reference"))]
ObjectMissingMetadataForOwnerRef {
source: stackable_operator::builder::meta::Error,
},
#[snafu(display("failed to build discovery ConfigMap"))]
BuildDiscoveryConfig { source: discovery::Error },
#[snafu(display("failed to apply discovery ConfigMap"))]
ApplyDiscoveryConfig {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to find rolegroup {}", rolegroup))]
RoleGroupNotFound {
rolegroup: RoleGroupRef<v1alpha1::KafkaCluster>,
},
#[snafu(display("invalid OpaConfig"))]
InvalidOpaConfig {
source: stackable_operator::commons::opa::Error,
},
#[snafu(display("failed to retrieve {}", authentication_class))]
AuthenticationClassRetrieval {
source: stackable_operator::commons::opa::Error,
authentication_class: ObjectRef<AuthenticationClass>,
},
#[snafu(display(
"failed to use authentication provider {} - supported methods: {:?}",
provider,
supported
))]
AuthenticationProviderNotSupported {
authentication_class: ObjectRef<AuthenticationClass>,
supported: Vec<String>,
provider: String,
},
#[snafu(display("invalid kafka listeners"))]
InvalidKafkaListeners {
source: crate::crd::listener::KafkaListenerError,
},
#[snafu(display("failed to add listener volume"))]
AddListenerVolume {
source: stackable_operator::builder::pod::Error,
},
#[snafu(display("invalid container name [{name}]"))]
InvalidContainerName {
name: String,
source: stackable_operator::builder::pod::container::Error,
},
#[snafu(display("failed to delete orphaned resources"))]
DeleteOrphans {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to initialize security context"))]
FailedToInitializeSecurityContext { source: crate::crd::security::Error },
#[snafu(display("failed to create cluster resources"))]
CreateClusterResources {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to resolve and merge config for role and role group"))]
FailedToResolveConfig { source: crate::crd::Error },
#[snafu(display("failed to resolve the Vector aggregator address"))]
ResolveVectorAggregatorAddress {
source: crate::product_logging::Error,
},
#[snafu(display("failed to add the logging configuration to the ConfigMap [{cm_name}]"))]
InvalidLoggingConfig {
source: crate::product_logging::Error,
cm_name: String,
},
#[snafu(display("failed to patch service account"))]
ApplyServiceAccount {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to patch role binding"))]
ApplyRoleBinding {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to update status"))]
ApplyStatus {
source: stackable_operator::client::Error,
},
#[snafu(display("failed to build RBAC resources"))]
BuildRbacResources {
source: stackable_operator::commons::rbac::Error,
},
#[snafu(display("internal operator failure"))]
InternalOperatorError { source: crate::crd::Error },
#[snafu(display(
"failed to serialize [{JVM_SECURITY_PROPERTIES_FILE}] for {}",
rolegroup
))]
JvmSecurityPoperties {
source: PropertiesWriterError,
rolegroup: String,
},
#[snafu(display("failed to create PodDisruptionBudget"))]
FailedToCreatePdb {
source: crate::operations::pdb::Error,
},
#[snafu(display("failed to configure graceful shutdown"))]
GracefulShutdown {
source: crate::operations::graceful_shutdown::Error,
},
#[snafu(display("failed to get required Labels"))]
GetRequiredLabels {
source:
stackable_operator::kvp::KeyValuePairError<stackable_operator::kvp::LabelValueError>,
},
#[snafu(display("failed to build Metadata"))]
MetadataBuild {
source: stackable_operator::builder::meta::Error,
},
#[snafu(display("failed to build Labels"))]
LabelBuild {
source: stackable_operator::kvp::LabelError,
},
#[snafu(display("failed to add Secret Volumes and VolumeMounts"))]
AddVolumesAndVolumeMounts { source: crate::crd::security::Error },
#[snafu(display("failed to resolve the fully-qualified pod name"))]
ResolveNamespace { source: KafkaListenerError },
#[snafu(display("failed to add kerberos config"))]
AddKerberosConfig { source: kerberos::Error },
#[snafu(display("failed to validate authentication method"))]
FailedToValidateAuthenticationMethod { source: crate::crd::security::Error },
#[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("failed to configure logging"))]
ConfigureLogging { source: LoggingError },
#[snafu(display("KafkaCluster object is invalid"))]
InvalidKafkaCluster {
source: error_boundary::InvalidObject,
},
#[snafu(display("failed to construct JVM arguments"))]
ConstructJvmArguments { source: crate::config::jvm::Error },
}
type Result<T, E = Error> = std::result::Result<T, E>;
impl ReconcilerError for Error {
fn category(&self) -> &'static str {
ErrorDiscriminants::from(self).into()
}
fn secondary_object(&self) -> Option<ObjectRef<DynamicObject>> {
match self {
Error::MissingSecretLifetime => None,
Error::ObjectHasNoName => None,
Error::ObjectHasNoNamespace => None,
Error::NoBrokerRole => None,
Error::ApplyRoleService { .. } => None,
Error::ApplyRoleServiceAccount { .. } => None,
Error::ApplyRoleRoleBinding { .. } => None,
Error::ApplyRoleGroupService { .. } => None,
Error::BuildRoleGroupConfig { .. } => None,
Error::ApplyRoleGroupConfig { .. } => None,
Error::ApplyRoleGroupStatefulSet { .. } => None,
Error::GenerateProductConfig { .. } => None,
Error::InvalidProductConfig { .. } => None,
Error::SerializeZooCfg { .. } => None,
Error::ObjectMissingMetadataForOwnerRef { .. } => None,
Error::BuildDiscoveryConfig { .. } => None,
Error::ApplyDiscoveryConfig { .. } => None,
Error::RoleGroupNotFound { .. } => None,
Error::InvalidOpaConfig { .. } => None,
Error::AuthenticationClassRetrieval {
authentication_class,
..
} => Some(authentication_class.clone().erase()),
Error::AuthenticationProviderNotSupported {
authentication_class,
..
} => Some(authentication_class.clone().erase()),
Error::InvalidKafkaListeners { .. } => None,
Error::AddListenerVolume { .. } => None,
Error::InvalidContainerName { .. } => None,
Error::DeleteOrphans { .. } => None,
Error::FailedToInitializeSecurityContext { .. } => None,
Error::CreateClusterResources { .. } => None,
Error::FailedToResolveConfig { .. } => None,
Error::ResolveVectorAggregatorAddress { .. } => None,
Error::InvalidLoggingConfig { .. } => None,
Error::ApplyServiceAccount { .. } => None,
Error::ApplyRoleBinding { .. } => None,
Error::ApplyStatus { .. } => None,
Error::BuildRbacResources { .. } => None,
Error::InternalOperatorError { .. } => None,
Error::JvmSecurityPoperties { .. } => None,
Error::FailedToCreatePdb { .. } => None,
Error::GracefulShutdown { .. } => None,
Error::GetRequiredLabels { .. } => None,
Error::MetadataBuild { .. } => None,
Error::LabelBuild { .. } => None,
Error::AddVolumesAndVolumeMounts { .. } => None,
Error::ConfigureLogging { .. } => None,
Error::AddVolume { .. } => None,
Error::AddVolumeMount { .. } => None,
Error::ResolveNamespace { .. } => None,
Error::AddKerberosConfig { .. } => None,
Error::FailedToValidateAuthenticationMethod { .. } => None,
Error::InvalidKafkaCluster { .. } => None,
Error::ConstructJvmArguments { .. } => None,
}
}
}
pub async fn reconcile_kafka(
kafka: Arc<DeserializeGuard<v1alpha1::KafkaCluster>>,
ctx: Arc<Ctx>,
) -> Result<Action> {
tracing::info!("Starting reconcile");
let kafka = kafka
.0
.as_ref()
.map_err(error_boundary::InvalidObject::clone)
.context(InvalidKafkaClusterSnafu)?;
let client = &ctx.client;
let kafka_role = KafkaRole::Broker;
let resolved_product_image = kafka
.spec
.image
.resolve(DOCKER_IMAGE_BASE_NAME, crate::built_info::PKG_VERSION);
let mut cluster_resources = ClusterResources::new(
APP_NAME,
OPERATOR_NAME,
KAFKA_CONTROLLER_NAME,
&kafka.object_ref(&()),
ClusterResourceApplyStrategy::from(&kafka.spec.cluster_operation),
)
.context(CreateClusterResourcesSnafu)?;
let validated_config = validate_all_roles_and_groups_config(
&resolved_product_image.product_version,
&transform_all_roles_to_config(
kafka,
[(
KafkaRole::Broker.to_string(),
(
vec![
PropertyNameKind::File(SERVER_PROPERTIES_FILE.to_string()),
PropertyNameKind::File(JVM_SECURITY_PROPERTIES_FILE.to_string()),
PropertyNameKind::Env,
],
kafka.spec.brokers.clone().context(NoBrokerRoleSnafu)?,
),
)]
.into(),
)
.context(GenerateProductConfigSnafu)?,
&ctx.product_config,
false,
false,
)
.context(InvalidProductConfigSnafu)?;
let role_broker_config = validated_config
.get(&KafkaRole::Broker.to_string())
.map(Cow::Borrowed)
.unwrap_or_default();
let kafka_security = KafkaTlsSecurity::new_from_kafka_cluster(client, kafka)
.await
.context(FailedToInitializeSecurityContextSnafu)?;
tracing::debug!(
kerberos_enabled = kafka_security.has_kerberos_enabled(),
kerberos_secret_class = ?kafka_security.kerberos_secret_class(),
tls_enabled = kafka_security.tls_enabled(),
tls_client_authentication_class = ?kafka_security.tls_client_authentication_class(),
"The following security settings are used"
);
kafka_security
.validate_authentication_methods()
.context(FailedToValidateAuthenticationMethodSnafu)?;
// Assemble the OPA connection string from the discovery and the given path if provided
// Will be passed as --override parameter in the cli in the state ful set
let opa_connect = if let Some(opa_spec) = &kafka.spec.cluster_config.authorization.opa {
Some(
opa_spec
.full_document_url_from_config_map(client, kafka, Some("allow"), OpaApiVersion::V1)
.await
.context(InvalidOpaConfigSnafu)?,
)
} else {
None
};
let vector_aggregator_address = resolve_vector_aggregator_address(kafka, client)
.await
.context(ResolveVectorAggregatorAddressSnafu)?;
let mut ss_cond_builder = StatefulSetConditionBuilder::default();
let (rbac_sa, rbac_rolebinding) = build_rbac_resources(
kafka,
APP_NAME,
cluster_resources
.get_required_labels()
.context(GetRequiredLabelsSnafu)?,
)
.context(BuildRbacResourcesSnafu)?;
let rbac_sa = cluster_resources
.add(client, rbac_sa.clone())
.await
.context(ApplyServiceAccountSnafu)?;
cluster_resources
.add(client, rbac_rolebinding)
.await
.context(ApplyRoleBindingSnafu)?;
let mut bootstrap_listeners = Vec::<Listener>::new();
for (rolegroup_name, rolegroup_config) in role_broker_config.iter() {
let rolegroup_ref = kafka.broker_rolegroup_ref(rolegroup_name);
let merged_config = kafka
.merged_config(&KafkaRole::Broker, &rolegroup_ref)
.context(FailedToResolveConfigSnafu)?;
let rg_service =
build_broker_rolegroup_service(kafka, &resolved_product_image, &rolegroup_ref)?;
let rg_configmap = build_broker_rolegroup_config_map(
kafka,
&resolved_product_image,
&kafka_security,
&rolegroup_ref,
rolegroup_config,
&merged_config,
vector_aggregator_address.as_deref(),
)?;
let rg_statefulset = build_broker_rolegroup_statefulset(
kafka,
&kafka_role,
&resolved_product_image,
&rolegroup_ref,
rolegroup_config,
opa_connect.as_deref(),
&kafka_security,
&merged_config,
&rbac_sa,
&client.kubernetes_cluster_info,
)?;
let rg_bootstrap_listener = build_broker_rolegroup_bootstrap_listener(
kafka,
&resolved_product_image,
&kafka_security,
&rolegroup_ref,
&merged_config,
)?;
bootstrap_listeners.push(
cluster_resources
.add(client, rg_bootstrap_listener)
.await
.context(ApplyRoleServiceSnafu)?,
);
cluster_resources
.add(client, rg_service)
.await
.with_context(|_| ApplyRoleGroupServiceSnafu {
rolegroup: rolegroup_ref.clone(),
})?;
cluster_resources
.add(client, rg_configmap)
.await
.with_context(|_| ApplyRoleGroupConfigSnafu {
rolegroup: rolegroup_ref.clone(),
})?;
ss_cond_builder.add(
cluster_resources
.add(client, rg_statefulset)
.await
.with_context(|_| ApplyRoleGroupStatefulSetSnafu {
rolegroup: rolegroup_ref.clone(),
})?,
);
}
let role_config = kafka.role_config(&kafka_role);
if let Some(GenericRoleConfig {
pod_disruption_budget: pdb,
}) = role_config
{
add_pdbs(pdb, kafka, &kafka_role, client, &mut cluster_resources)
.await
.context(FailedToCreatePdbSnafu)?;
}
for discovery_cm in build_discovery_configmaps(
kafka,
kafka,
&resolved_product_image,
&kafka_security,
&bootstrap_listeners,
)
.await
.context(BuildDiscoveryConfigSnafu)?
{
cluster_resources
.add(client, discovery_cm)
.await
.context(ApplyDiscoveryConfigSnafu)?;
}
let cluster_operation_cond_builder =
ClusterOperationsConditionBuilder::new(&kafka.spec.cluster_operation);
let status = KafkaClusterStatus {
conditions: compute_conditions(kafka, &[&ss_cond_builder, &cluster_operation_cond_builder]),
};
cluster_resources
.delete_orphaned_resources(client)
.await
.context(DeleteOrphansSnafu)?;
client
.apply_patch_status(OPERATOR_NAME, kafka, &status)
.await
.context(ApplyStatusSnafu)?;
Ok(Action::await_change())
}
/// Kafka clients will use the load-balanced bootstrap listener to get a list of broker addresses and will use those to
/// transmit data to the correct broker.
pub fn build_broker_rolegroup_bootstrap_listener(
kafka: &v1alpha1::KafkaCluster,
resolved_product_image: &ResolvedProductImage,
kafka_security: &KafkaTlsSecurity,
rolegroup: &RoleGroupRef<v1alpha1::KafkaCluster>,
merged_config: &KafkaConfig,
) -> Result<Listener> {
Ok(Listener {
metadata: ObjectMetaBuilder::new()
.name_and_namespace(kafka)
.name(kafka.bootstrap_service_name(rolegroup))
.ownerreference_from_resource(kafka, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
kafka,
KAFKA_CONTROLLER_NAME,
&resolved_product_image.app_version_label,
&rolegroup.role,
&rolegroup.role_group,
))
.context(MetadataBuildSnafu)?
.build(),
spec: ListenerSpec {
class_name: Some(merged_config.bootstrap_listener_class.clone()),
ports: Some(listener_ports(kafka_security)),
..ListenerSpec::default()
},
status: None,
})
}
/// The rolegroup [`ConfigMap`] configures the rolegroup based on the configuration given by the administrator
fn build_broker_rolegroup_config_map(
kafka: &v1alpha1::KafkaCluster,
resolved_product_image: &ResolvedProductImage,
kafka_security: &KafkaTlsSecurity,
rolegroup: &RoleGroupRef<v1alpha1::KafkaCluster>,
broker_config: &HashMap<PropertyNameKind, BTreeMap<String, String>>,
merged_config: &KafkaConfig,
vector_aggregator_address: Option<&str>,
) -> Result<ConfigMap> {
let mut server_cfg = broker_config
.get(&PropertyNameKind::File(SERVER_PROPERTIES_FILE.to_string()))
.cloned()
.unwrap_or_default();
server_cfg.extend(kafka_security.config_settings());
server_cfg.extend(graceful_shutdown_config_properties());
let server_cfg = server_cfg
.into_iter()
.map(|(k, v)| (k, Some(v)))
.collect::<Vec<_>>();
let jvm_sec_props: BTreeMap<String, Option<String>> = broker_config
.get(&PropertyNameKind::File(
JVM_SECURITY_PROPERTIES_FILE.to_string(),
))
.cloned()
.unwrap_or_default()
.into_iter()
.map(|(k, v)| (k, Some(v)))
.collect();
let mut cm_builder = ConfigMapBuilder::new();
cm_builder
.metadata(
ObjectMetaBuilder::new()
.name_and_namespace(kafka)
.name(rolegroup.object_name())
.ownerreference_from_resource(kafka, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
kafka,
KAFKA_CONTROLLER_NAME,
&resolved_product_image.app_version_label,
&rolegroup.role,
&rolegroup.role_group,
))
.context(MetadataBuildSnafu)?
.build(),
)
.add_data(
SERVER_PROPERTIES_FILE,
to_java_properties_string(server_cfg.iter().map(|(k, v)| (k, v))).with_context(
|_| SerializeZooCfgSnafu {
rolegroup: rolegroup.clone(),
},
)?,
)
.add_data(
JVM_SECURITY_PROPERTIES_FILE,
to_java_properties_string(jvm_sec_props.iter()).with_context(|_| {
JvmSecurityPopertiesSnafu {
rolegroup: rolegroup.role_group.clone(),
}
})?,
);
tracing::debug!(?server_cfg, "Applied server config");
tracing::debug!(?jvm_sec_props, "Applied JVM config");
extend_role_group_config_map(
rolegroup,
vector_aggregator_address,
&merged_config.logging,
&mut cm_builder,
)
.context(InvalidLoggingConfigSnafu {
cm_name: rolegroup.object_name(),
})?;
cm_builder
.build()
.with_context(|_| BuildRoleGroupConfigSnafu {
rolegroup: rolegroup.clone(),
})
}
/// The rolegroup [`Service`] is a headless service that allows direct access to the instances of a certain rolegroup
///
/// This is mostly useful for internal communication between peers, or for clients that perform client-side load balancing.
fn build_broker_rolegroup_service(
kafka: &v1alpha1::KafkaCluster,
resolved_product_image: &ResolvedProductImage,
rolegroup: &RoleGroupRef<v1alpha1::KafkaCluster>,
) -> Result<Service> {
Ok(Service {
metadata: ObjectMetaBuilder::new()
.name_and_namespace(kafka)
.name(rolegroup.object_name())
.ownerreference_from_resource(kafka, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
kafka,
KAFKA_CONTROLLER_NAME,
&resolved_product_image.app_version_label,
&rolegroup.role,
&rolegroup.role_group,
))
.context(MetadataBuildSnafu)?
.with_label(Label::try_from(("prometheus.io/scrape", "true")).context(LabelBuildSnafu)?)
.build(),
spec: Some(ServiceSpec {
cluster_ip: Some("None".to_string()),
selector: Some(
Labels::role_group_selector(
kafka,
APP_NAME,
&rolegroup.role,
&rolegroup.role_group,
)
.context(LabelBuildSnafu)?
.into(),
),
publish_not_ready_addresses: Some(true),
..ServiceSpec::default()
}),
status: None,
})
}
/// The rolegroup [`StatefulSet`] runs the rolegroup, as configured by the administrator.
///
/// The [`Pod`](`stackable_operator::k8s_openapi::api::core::v1::Pod`)s are accessible through the corresponding [`Service`] (from [`build_broker_rolegroup_service`]).
#[allow(clippy::too_many_arguments)]
fn build_broker_rolegroup_statefulset(
kafka: &v1alpha1::KafkaCluster,
kafka_role: &KafkaRole,
resolved_product_image: &ResolvedProductImage,
rolegroup_ref: &RoleGroupRef<v1alpha1::KafkaCluster>,
broker_config: &HashMap<PropertyNameKind, BTreeMap<String, String>>,
opa_connect_string: Option<&str>,
kafka_security: &KafkaTlsSecurity,
merged_config: &KafkaConfig,
service_account: &ServiceAccount,
cluster_info: &KubernetesClusterInfo,
) -> Result<StatefulSet> {
let role = kafka.role(kafka_role).context(InternalOperatorSnafu)?;
let rolegroup = kafka
.rolegroup(rolegroup_ref)
.context(InternalOperatorSnafu)?;
let recommended_object_labels = build_recommended_labels(
kafka,
KAFKA_CONTROLLER_NAME,
&resolved_product_image.app_version_label,
&rolegroup_ref.role,
&rolegroup_ref.role_group,
);
let recommended_labels =
Labels::recommended(recommended_object_labels.clone()).context(LabelBuildSnafu)?;
// Used for PVC templates that cannot be modified once they are deployed
let unversioned_recommended_labels = Labels::recommended(build_recommended_labels(
kafka,
KAFKA_CONTROLLER_NAME,
// A version value is required, and we do want to use the "recommended" format for the other desired labels
"none",
&rolegroup_ref.role,
&rolegroup_ref.role_group,
))
.context(LabelBuildSnafu)?;
let kcat_prober_container_name = Container::KcatProber.to_string();
let mut cb_kcat_prober =
ContainerBuilder::new(&kcat_prober_container_name).context(InvalidContainerNameSnafu {
name: kcat_prober_container_name.clone(),
})?;
let kafka_container_name = Container::Kafka.to_string();
let mut cb_kafka =
ContainerBuilder::new(&kafka_container_name).context(InvalidContainerNameSnafu {
name: kafka_container_name.clone(),
})?;
let mut pod_builder = PodBuilder::new();
// Add TLS related volumes and volume mounts
let requested_secret_lifetime = merged_config
.requested_secret_lifetime
.context(MissingSecretLifetimeSnafu)?;
kafka_security
.add_volume_and_volume_mounts(
&mut pod_builder,
&mut cb_kcat_prober,
&mut cb_kafka,
&requested_secret_lifetime,
)
.context(AddVolumesAndVolumeMountsSnafu)?;
let mut pvcs = merged_config.resources.storage.build_pvcs();
// bootstrap listener should be persistent,
// main broker listener is an ephemeral PVC instead
pvcs.push(
ListenerOperatorVolumeSourceBuilder::new(
&ListenerReference::ListenerName(kafka.bootstrap_service_name(rolegroup_ref)),
&unversioned_recommended_labels,
)
.and_then(|builder| builder.build_pvc(LISTENER_BOOTSTRAP_VOLUME_NAME))
.unwrap(),
);
if kafka_security.has_kerberos_enabled() {
add_kerberos_pod_config(
kafka_security,
kafka_role,
&mut cb_kcat_prober,
&mut cb_kafka,
&mut pod_builder,
)
.context(AddKerberosConfigSnafu)?;
}
let mut env = broker_config
.get(&PropertyNameKind::Env)
.into_iter()
.flatten()
.map(|(k, v)| EnvVar {
name: k.clone(),
value: Some(v.clone()),
..EnvVar::default()
})
.collect::<Vec<_>>();
env.push(EnvVar {
name: "ZOOKEEPER".to_string(),
value_from: Some(EnvVarSource {
config_map_key_ref: Some(ConfigMapKeySelector {
name: kafka.spec.cluster_config.zookeeper_config_map_name.clone(),
key: "ZOOKEEPER".to_string(),
..ConfigMapKeySelector::default()
}),
..EnvVarSource::default()
}),
..EnvVar::default()
});
env.push(EnvVar {
name: "POD_NAME".to_string(),
value_from: Some(EnvVarSource {
field_ref: Some(ObjectFieldSelector {
api_version: Some("v1".to_string()),
field_path: "metadata.name".to_string(),
}),
..EnvVarSource::default()
}),
..EnvVar::default()
});
let kafka_listeners = get_kafka_listener_config(
kafka,
kafka_security,
&rolegroup_ref.object_name(),
cluster_info,
)
.context(InvalidKafkaListenersSnafu)?;
cb_kafka
.image_from_product_image(resolved_product_image)
.command(vec![
"/bin/bash".to_string(),
"-x".to_string(),
"-euo".to_string(),
"pipefail".to_string(),
"-c".to_string(),
])
.args(vec![kafka_security
.kafka_container_commands(
&kafka_listeners,
opa_connect_string,
kafka_security.has_kerberos_enabled(),
)
.join("\n")])
.add_env_var(
"EXTRA_ARGS",
construct_non_heap_jvm_args(merged_config, role, &rolegroup_ref.role_group)
.context(ConstructJvmArgumentsSnafu)?,
)
.add_env_var(
KAFKA_HEAP_OPTS,
construct_heap_jvm_args(merged_config, role, &rolegroup_ref.role_group)
.context(ConstructJvmArgumentsSnafu)?,
)
.add_env_var(
"KAFKA_LOG4J_OPTS",
format!("-Dlog4j.configuration=file:{STACKABLE_LOG_CONFIG_DIR}/{LOG4J_CONFIG_FILE}"),
)
// Needed for the `containerdebug` process to log it's tracing information to.
.add_env_var(
"CONTAINERDEBUG_LOG_DIRECTORY",
format!("{STACKABLE_LOG_DIR}/containerdebug"),
)
.add_env_vars(env)
.add_container_ports(container_ports(kafka_security))
.add_volume_mount(LOG_DIRS_VOLUME_NAME, STACKABLE_DATA_DIR)
.context(AddVolumeMountSnafu)?
.add_volume_mount("config", STACKABLE_CONFIG_DIR)
.context(AddVolumeMountSnafu)?
.add_volume_mount(
LISTENER_BOOTSTRAP_VOLUME_NAME,
STACKABLE_LISTENER_BOOTSTRAP_DIR,
)
.context(AddVolumeMountSnafu)?
.add_volume_mount(LISTENER_BROKER_VOLUME_NAME, STACKABLE_LISTENER_BROKER_DIR)
.context(AddVolumeMountSnafu)?
.add_volume_mount("log-config", STACKABLE_LOG_CONFIG_DIR)
.context(AddVolumeMountSnafu)?
.add_volume_mount("log", STACKABLE_LOG_DIR)
.context(AddVolumeMountSnafu)?
.resources(merged_config.resources.clone().into());