-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcontroller.rs
More file actions
1811 lines (1629 loc) · 62.1 KB
/
controller.rs
File metadata and controls
1811 lines (1629 loc) · 62.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Ensures that `Pod`s are configured and running for each [`TrinoCluster`]
use std::{
collections::{BTreeMap, HashMap},
convert::Infallible,
fmt::Write,
ops::Div,
str::FromStr,
sync::Arc,
};
use const_format::concatcp;
use product_config::{
self,
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::{SecretFormat, SecretOperatorVolumeSourceBuilder, VolumeBuilder},
PodBuilder,
},
},
client::Client,
cluster_resources::{ClusterResourceApplyStrategy, ClusterResources},
commons::{product_image_selection::ResolvedProductImage, rbac::build_rbac_resources},
k8s_openapi::{
api::{
apps::v1::{StatefulSet, StatefulSetSpec},
core::v1::{
ConfigMap, ConfigMapVolumeSource, ContainerPort, EnvVar, EnvVarSource, Probe,
Secret, SecretKeySelector, Service, ServicePort, ServiceSpec, TCPSocketAction,
Volume,
},
},
apimachinery::pkg::{apis::meta::v1::LabelSelector, util::intstr::IntOrString},
DeepMerge,
},
kube::{
core::{error_boundary, DeserializeGuard},
runtime::{controller::Action, reflector::ObjectRef},
Resource, ResourceExt,
},
kvp::{Annotation, Label, Labels, ObjectLabels},
logging::controller::ReconcilerError,
memory::{BinaryMultiple, MemoryQuantity},
product_config_utils::{
transform_all_roles_to_config, validate_all_roles_and_groups_config,
ValidatedRoleConfigByPropertyKind,
},
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 stackable_trino_crd::{
authentication::resolve_authentication_classes,
catalog::TrinoCatalog,
discovery::{TrinoDiscovery, TrinoDiscoveryProtocol, TrinoPodRef},
Container, TrinoCluster, TrinoClusterStatus, TrinoConfig, TrinoRole, ACCESS_CONTROL_PROPERTIES,
APP_NAME, CONFIG_DIR_NAME, CONFIG_PROPERTIES, DATA_DIR_NAME, DISCOVERY_URI,
ENV_INTERNAL_SECRET, HTTPS_PORT, HTTPS_PORT_NAME, HTTP_PORT, HTTP_PORT_NAME, JVM_CONFIG,
JVM_SECURITY_PROPERTIES, LOG_COMPRESSION, LOG_FORMAT, LOG_MAX_SIZE, LOG_MAX_TOTAL_SIZE,
LOG_PATH, LOG_PROPERTIES, METRICS_PORT, METRICS_PORT_NAME, NODE_PROPERTIES, RW_CONFIG_DIR_NAME,
STACKABLE_CLIENT_TLS_DIR, STACKABLE_INTERNAL_TLS_DIR, STACKABLE_MOUNT_INTERNAL_TLS_DIR,
STACKABLE_MOUNT_SERVER_TLS_DIR, STACKABLE_SERVER_TLS_DIR,
};
use strum::{EnumDiscriminants, IntoStaticStr};
use crate::{
authentication::{TrinoAuthenticationConfig, TrinoAuthenticationTypes},
authorization::opa::TrinoOpaConfig,
catalog::{config::CatalogConfig, FromTrinoCatalogError},
command, config,
operations::{
add_graceful_shutdown_config, graceful_shutdown_config_properties, pdb::add_pdbs,
},
product_logging::{get_log_properties, get_vector_toml, resolve_vector_aggregator_address},
};
pub struct Ctx {
pub client: stackable_operator::client::Client,
pub product_config: ProductConfigManager,
}
pub const OPERATOR_NAME: &str = "trino.stackable.tech";
pub const CONTROLLER_NAME: &str = "trinocluster";
pub const FULL_CONTROLLER_NAME: &str = concatcp!(CONTROLLER_NAME, '.', OPERATOR_NAME);
pub const TRINO_UID: i64 = 1000;
pub const STACKABLE_LOG_DIR: &str = "/stackable/log";
pub const STACKABLE_LOG_CONFIG_DIR: &str = "/stackable/log_config";
const LOG_FILE_COUNT: u32 = 2;
pub const MAX_TRINO_LOG_FILES_SIZE: MemoryQuantity = MemoryQuantity {
value: 10.0,
unit: BinaryMultiple::Mebi,
};
pub const MAX_PREPARE_LOG_FILE_SIZE: MemoryQuantity = MemoryQuantity {
value: 1.0,
unit: BinaryMultiple::Mebi,
};
const DOCKER_IMAGE_BASE_NAME: &str = "trino";
#[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 defines no namespace"))]
ObjectHasNoNamespace,
#[snafu(display("object defines no {} role", role))]
MissingTrinoRole { role: String },
#[snafu(display("failed to create cluster resources"))]
CreateClusterResources {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to delete orphaned resources"))]
DeleteOrphanedResources {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to apply global Service"))]
ApplyRoleService {
source: stackable_operator::cluster_resources::Error,
},
#[snafu(display("failed to apply Service for {}", rolegroup))]
ApplyRoleGroupService {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<TrinoCluster>,
},
#[snafu(display("failed to build ConfigMap for {}", rolegroup))]
BuildRoleGroupConfig {
source: stackable_operator::builder::configmap::Error,
rolegroup: RoleGroupRef<TrinoCluster>,
},
#[snafu(display("failed to apply ConfigMap for {}", rolegroup))]
ApplyRoleGroupConfig {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<TrinoCluster>,
},
#[snafu(display("failed to apply StatefulSet for {}", rolegroup))]
ApplyRoleGroupStatefulSet {
source: stackable_operator::cluster_resources::Error,
rolegroup: RoleGroupRef<TrinoCluster>,
},
#[snafu(display("failed to apply internal secret"))]
ApplyInternalSecret {
source: stackable_operator::client::Error,
},
#[snafu(display("invalid product config"))]
InvalidProductConfig {
source: stackable_operator::product_config_utils::Error,
},
#[snafu(display("object is missing metadata to build owner reference"))]
ObjectMissingMetadataForOwnerRef {
source: stackable_operator::builder::meta::Error,
},
#[snafu(display("failed to transform configs"))]
ProductConfigTransform {
source: stackable_operator::product_config_utils::Error,
},
#[snafu(display("failed to format runtime properties"))]
FailedToWriteJavaProperties { source: PropertiesWriterError },
#[snafu(display("failed to parse role: {source}"))]
FailedToParseRole { source: strum::ParseError },
#[snafu(display("internal operator failure: {source}"))]
InternalOperatorFailure { source: stackable_trino_crd::Error },
#[snafu(display("no coordinator pods found for discovery"))]
MissingCoordinatorPods,
#[snafu(display("invalid OpaConfig"))]
InvalidOpaConfig {
source: stackable_operator::commons::opa::Error,
},
#[snafu(display("failed to get associated TrinoCatalogs"))]
GetCatalogs {
source: stackable_operator::client::Error,
},
#[snafu(display("failed to parse {catalog}"))]
ParseCatalog {
source: FromTrinoCatalogError,
catalog: ObjectRef<TrinoCatalog>,
},
#[snafu(display("illegal container name: [{container_name}]"))]
IllegalContainerName {
source: stackable_operator::builder::pod::container::Error,
container_name: String,
},
#[snafu(display("failed to retrieve secret for internal communications"))]
FailedToRetrieveInternalSecret {
source: stackable_operator::client::Error,
},
#[snafu(display("failed to resolve and merge config for role and role group"))]
FailedToResolveConfig { source: stackable_trino_crd::Error },
#[snafu(display("failed to resolve the Vector aggregator address"))]
ResolveVectorAggregatorAddress {
source: crate::product_logging::Error,
},
#[snafu(display("failed to build vector container"))]
BuildVectorContainer { source: LoggingError },
#[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("Failed to retrieve AuthenticationClass"))]
AuthenticationClassRetrieval {
source: stackable_trino_crd::authentication::Error,
},
#[snafu(display("Unsupported Trino authentication"))]
UnsupportedAuthenticationConfig {
source: crate::authentication::Error,
},
#[snafu(display("Invalid Trino authentication"))]
InvalidAuthenticationConfig {
source: crate::authentication::Error,
},
#[snafu(display("failed to serialize [{JVM_SECURITY_PROPERTIES}] for {}", rolegroup))]
JvmSecurityProperties {
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 Labels"))]
LabelBuild {
source: stackable_operator::kvp::LabelError,
},
#[snafu(display("failed to build Annotation"))]
AnnotationBuild {
source: stackable_operator::kvp::KeyValuePairError<Infallible>,
},
#[snafu(display("failed to build Metadata"))]
MetadataBuild {
source: stackable_operator::builder::meta::Error,
},
#[snafu(display("failed to build TLS certificate SecretClass Volume"))]
TlsCertSecretClassVolumeBuild {
source: stackable_operator::builder::pod::volume::SecretOperatorVolumeSourceBuilderError,
},
#[snafu(display("failed to build JVM config"))]
FailedToCreateJvmConfig { source: crate::config::jvm::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("invalid TrinoCluster object"))]
InvalidTrinoCluster {
source: error_boundary::InvalidObject,
},
}
type Result<T, E = Error> = std::result::Result<T, E>;
impl ReconcilerError for Error {
fn category(&self) -> &'static str {
ErrorDiscriminants::from(self).into()
}
}
pub async fn reconcile_trino(
trino: Arc<DeserializeGuard<TrinoCluster>>,
ctx: Arc<Ctx>,
) -> Result<Action> {
tracing::info!("Starting reconcile");
let trino = trino
.0
.as_ref()
.map_err(error_boundary::InvalidObject::clone)
.context(InvalidTrinoClusterSnafu)?;
let client = &ctx.client;
let resolved_product_image: ResolvedProductImage = trino
.spec
.image
.resolve(DOCKER_IMAGE_BASE_NAME, crate::built_info::PKG_VERSION);
let resolved_authentication_classes =
resolve_authentication_classes(client, trino.get_authentication())
.await
.context(AuthenticationClassRetrievalSnafu)?;
let trino_authentication_config = TrinoAuthenticationConfig::new(
&resolved_product_image,
TrinoAuthenticationTypes::try_from(resolved_authentication_classes)
.context(UnsupportedAuthenticationConfigSnafu)?,
)
.context(InvalidAuthenticationConfigSnafu)?;
let catalog_definitions = client
.list_with_label_selector::<TrinoCatalog>(
trino
.metadata
.namespace
.as_deref()
.context(ObjectHasNoNamespaceSnafu)?,
&trino.spec.cluster_config.catalog_label_selector,
)
.await
.context(GetCatalogsSnafu)?;
let mut catalogs = vec![];
for catalog in &catalog_definitions {
let catalog_ref = ObjectRef::from_obj(catalog);
let catalog_config =
CatalogConfig::from_catalog(catalog, client)
.await
.context(ParseCatalogSnafu {
catalog: catalog_ref,
})?;
catalogs.push(catalog_config);
}
let validated_config = validated_product_config(
trino,
// The Trino version is a single number like 396.
// The product config expects semver formatted version strings.
// That is why we just add minor and patch version 0 here.
&format!("{}.0.0", resolved_product_image.product_version),
&ctx.product_config,
)?;
let mut cluster_resources = ClusterResources::new(
APP_NAME,
OPERATOR_NAME,
CONTROLLER_NAME,
&trino.object_ref(&()),
ClusterResourceApplyStrategy::from(&trino.spec.cluster_operation),
)
.context(CreateClusterResourcesSnafu)?;
let (rbac_sa, rbac_rolebinding) = build_rbac_resources(
trino,
APP_NAME,
cluster_resources
.get_required_labels()
.context(GetRequiredLabelsSnafu)?,
)
.context(BuildRbacResourcesSnafu)?;
let rbac_sa = cluster_resources
.add(client, rbac_sa)
.await
.context(ApplyServiceAccountSnafu)?;
cluster_resources
.add(client, rbac_rolebinding)
.await
.context(ApplyRoleBindingSnafu)?;
let trino_opa_config = match trino.get_opa_config() {
Some(opa_config) => Some(
TrinoOpaConfig::from_opa_config(client, trino, opa_config)
.await
.context(InvalidOpaConfigSnafu)?,
),
None => None,
};
let coordinator_role_service = build_coordinator_role_service(trino, &resolved_product_image)?;
cluster_resources
.add(client, coordinator_role_service)
.await
.context(ApplyRoleServiceSnafu)?;
create_shared_internal_secret(trino, client).await?;
let vector_aggregator_address = resolve_vector_aggregator_address(trino, client)
.await
.context(ResolveVectorAggregatorAddressSnafu)?;
let mut sts_cond_builder = StatefulSetConditionBuilder::default();
for (role, role_config) in validated_config {
let trino_role = TrinoRole::from_str(&role).context(FailedToParseRoleSnafu)?;
for (role_group, config) in role_config {
let rolegroup = trino_role.rolegroup_ref(trino, role_group);
let merged_config = trino
.merged_config(&trino_role, &rolegroup, &catalog_definitions)
.context(FailedToResolveConfigSnafu)?;
let rg_service = build_rolegroup_service(trino, &resolved_product_image, &rolegroup)?;
let rg_configmap = build_rolegroup_config_map(
trino,
&resolved_product_image,
&trino_role,
&rolegroup,
&config,
&merged_config,
&trino_authentication_config,
&trino_opa_config,
vector_aggregator_address.as_deref(),
&client.kubernetes_cluster_info,
)?;
let rg_catalog_configmap = build_rolegroup_catalog_config_map(
trino,
&resolved_product_image,
&rolegroup,
&catalogs,
)?;
let rg_stateful_set = build_rolegroup_statefulset(
trino,
&trino_role,
&resolved_product_image,
&rolegroup,
&config,
&merged_config,
&trino_authentication_config,
&catalogs,
&rbac_sa.name_any(),
)?;
cluster_resources
.add(client, rg_service)
.await
.with_context(|_| ApplyRoleGroupServiceSnafu {
rolegroup: rolegroup.clone(),
})?;
cluster_resources
.add(client, rg_configmap)
.await
.with_context(|_| ApplyRoleGroupConfigSnafu {
rolegroup: rolegroup.clone(),
})?;
cluster_resources
.add(client, rg_catalog_configmap)
.await
.with_context(|_| ApplyRoleGroupConfigSnafu {
rolegroup: rolegroup.clone(),
})?;
sts_cond_builder.add(
cluster_resources
.add(client, rg_stateful_set)
.await
.with_context(|_| ApplyRoleGroupStatefulSetSnafu {
rolegroup: rolegroup.clone(),
})?,
);
}
let role_config = trino.role_config(&trino_role);
if let Some(GenericRoleConfig {
pod_disruption_budget: pdb,
}) = role_config
{
add_pdbs(pdb, trino, &trino_role, client, &mut cluster_resources)
.await
.context(FailedToCreatePdbSnafu)?;
}
}
let cluster_operation_cond_builder =
ClusterOperationsConditionBuilder::new(&trino.spec.cluster_operation);
let status = TrinoClusterStatus {
conditions: compute_conditions(
trino,
&[&sts_cond_builder, &cluster_operation_cond_builder],
),
};
cluster_resources
.delete_orphaned_resources(client)
.await
.context(DeleteOrphanedResourcesSnafu)?;
client
.apply_patch_status(OPERATOR_NAME, trino, &status)
.await
.context(ApplyStatusSnafu)?;
Ok(Action::await_change())
}
/// The coordinator-role service is the primary endpoint that should be used by clients that do not
/// perform internal load balancing, including targets outside of the cluster.
pub fn build_coordinator_role_service(
trino: &TrinoCluster,
resolved_product_image: &ResolvedProductImage,
) -> Result<Service> {
let role = TrinoRole::Coordinator;
let role_name = role.to_string();
let role_svc_name = trino
.role_service_name(&role)
.context(InternalOperatorFailureSnafu)?;
Ok(Service {
metadata: ObjectMetaBuilder::new()
.name_and_namespace(trino)
.name(&role_svc_name)
.ownerreference_from_resource(trino, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
trino,
&resolved_product_image.app_version_label,
&role_name,
"global",
))
.context(MetadataBuildSnafu)?
.build(),
spec: Some(ServiceSpec {
ports: Some(service_ports(trino)),
selector: Some(
Labels::role_selector(trino, APP_NAME, &role_name)
.context(LabelBuildSnafu)?
.into(),
),
type_: Some(trino.spec.cluster_config.listener_class.k8s_service_type()),
..ServiceSpec::default()
}),
status: None,
})
}
/// The rolegroup [`ConfigMap`] configures the rolegroup based on the configuration given by the administrator
#[allow(clippy::too_many_arguments)]
fn build_rolegroup_config_map(
trino: &TrinoCluster,
resolved_product_image: &ResolvedProductImage,
role: &TrinoRole,
rolegroup_ref: &RoleGroupRef<TrinoCluster>,
config: &HashMap<PropertyNameKind, BTreeMap<String, String>>,
merged_config: &TrinoConfig,
trino_authentication_config: &TrinoAuthenticationConfig,
trino_opa_config: &Option<TrinoOpaConfig>,
vector_aggregator_address: Option<&str>,
cluster_info: &KubernetesClusterInfo,
) -> Result<ConfigMap> {
let mut cm_conf_data = BTreeMap::new();
// retrieve JVM config - TODO: currently not overridable
let mut jvm_config = config::jvm::jvm_config(resolved_product_image, role, merged_config)
.context(FailedToCreateJvmConfigSnafu)?;
// TODO: we support only one coordinator for now
let coordinator_ref: TrinoPodRef = trino
.coordinator_pods()
.context(InternalOperatorFailureSnafu)?
.next()
.context(MissingCoordinatorPodsSnafu)?;
// Add additional config files fore authentication
cm_conf_data.extend(trino_authentication_config.config_files(role));
for (property_name_kind, config) in config {
// We used this temporary map to add all dynamically resolved (e.g. discovery config maps)
// properties. This will be extended with the merged role group properties (transformed_config)
// to respect all possible override settings.
let mut dynamic_resolved_config = BTreeMap::<String, Option<String>>::new();
let transformed_config: BTreeMap<String, Option<String>> = config
.iter()
.map(|(k, v)| (k.clone(), Some(v.clone())))
.collect();
match property_name_kind {
PropertyNameKind::File(file_name) if file_name == CONFIG_PROPERTIES => {
// Add authentication properties (only required for the Coordinator)
dynamic_resolved_config.extend(
trino_authentication_config
.config_properties(role)
.into_iter()
.map(|(k, v)| (k, Some(v)))
.collect::<BTreeMap<String, Option<String>>>(),
);
let protocol = if trino.get_internal_tls().is_some() {
TrinoDiscoveryProtocol::Https
} else {
TrinoDiscoveryProtocol::Http
};
let discovery = TrinoDiscovery::new(&coordinator_ref, protocol);
dynamic_resolved_config.insert(
DISCOVERY_URI.to_string(),
Some(discovery.discovery_uri(cluster_info)),
);
dynamic_resolved_config.extend(graceful_shutdown_config_properties(trino, role));
// The log format used by Trino
dynamic_resolved_config.insert(LOG_FORMAT.to_string(), Some("json".to_string()));
// The path to the log file used by Trino
dynamic_resolved_config.insert(
LOG_PATH.to_string(),
Some(format!(
"{STACKABLE_LOG_DIR}/{container}/server.airlift.json",
container = Container::Trino
)),
);
// We do not compress. This will result in LOG_MAX_TOTAL_SIZE / LOG_MAX_SIZE files.
dynamic_resolved_config
.insert(LOG_COMPRESSION.to_string(), Some("none".to_string()));
// The size of one log file
dynamic_resolved_config.insert(
LOG_MAX_SIZE.to_string(),
Some(format!(
// Trino uses the unit "MB" for MiB.
"{}MB",
MAX_TRINO_LOG_FILES_SIZE
.scale_to(BinaryMultiple::Mebi)
.div(LOG_FILE_COUNT as f32)
.ceil()
.value,
)),
);
// The maximum size of all logfiles combined
dynamic_resolved_config.insert(
LOG_MAX_TOTAL_SIZE.to_string(),
Some(format!(
// Trino uses the unit "MB" for MiB.
"{}MB",
MAX_TRINO_LOG_FILES_SIZE
.scale_to(BinaryMultiple::Mebi)
.ceil()
.value,
)),
);
// Add static properties and overrides
dynamic_resolved_config.extend(transformed_config);
let config_properties = product_config::writer::to_java_properties_string(
dynamic_resolved_config.iter(),
)
.context(FailedToWriteJavaPropertiesSnafu)?;
cm_conf_data.insert(file_name.to_string(), config_properties);
}
PropertyNameKind::File(file_name) if file_name == NODE_PROPERTIES => {
// Add static properties and overrides
dynamic_resolved_config.extend(transformed_config);
let node_properties = product_config::writer::to_java_properties_string(
dynamic_resolved_config.iter(),
)
.context(FailedToWriteJavaPropertiesSnafu)?;
cm_conf_data.insert(file_name.to_string(), node_properties);
}
PropertyNameKind::File(file_name) if file_name == LOG_PROPERTIES => {
// No overrides required here, all settings can be set via logging options
if let Some(log_properties) = get_log_properties(&merged_config.logging) {
cm_conf_data.insert(file_name.to_string(), log_properties);
}
if let Some(vector_toml) = get_vector_toml(
rolegroup_ref,
vector_aggregator_address,
&merged_config.logging,
)
.context(InvalidLoggingConfigSnafu {
cm_name: rolegroup_ref.object_name(),
})? {
cm_conf_data.insert(
product_logging::framework::VECTOR_CONFIG_FILE.to_string(),
vector_toml,
);
}
}
PropertyNameKind::File(file_name) if file_name == JVM_CONFIG => {
let _ = writeln!(jvm_config, "-javaagent:/stackable/jmx/jmx_prometheus_javaagent.jar={}:/stackable/jmx/config.yaml", METRICS_PORT);
}
_ => {}
}
}
if let Some(trino_opa_config) = trino_opa_config {
let config = trino_opa_config.as_config();
let config_properties = product_config::writer::to_java_properties_string(config.iter())
.context(FailedToWriteJavaPropertiesSnafu)?;
cm_conf_data.insert(ACCESS_CONTROL_PROPERTIES.to_string(), config_properties);
}
cm_conf_data.insert(JVM_CONFIG.to_string(), jvm_config.to_string());
let jvm_sec_props: BTreeMap<String, Option<String>> = config
.get(&PropertyNameKind::File(JVM_SECURITY_PROPERTIES.to_string()))
.cloned()
.unwrap_or_default()
.into_iter()
.map(|(k, v)| (k, Some(v)))
.collect();
cm_conf_data.insert(
JVM_SECURITY_PROPERTIES.to_string(),
to_java_properties_string(jvm_sec_props.iter()).with_context(|_| {
JvmSecurityPropertiesSnafu {
rolegroup: rolegroup_ref.role_group.clone(),
}
})?,
);
ConfigMapBuilder::new()
.metadata(
ObjectMetaBuilder::new()
.name_and_namespace(trino)
.name(rolegroup_ref.object_name())
.ownerreference_from_resource(trino, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
trino,
&resolved_product_image.app_version_label,
&rolegroup_ref.role,
&rolegroup_ref.role_group,
))
.context(MetadataBuildSnafu)?
.build(),
)
.data(cm_conf_data)
.build()
.with_context(|_| BuildRoleGroupConfigSnafu {
rolegroup: rolegroup_ref.clone(),
})
}
/// The rolegroup catalog [`ConfigMap`] configures the rolegroup catalog based on the configuration
/// given by the administrator
fn build_rolegroup_catalog_config_map(
trino: &TrinoCluster,
resolved_product_image: &ResolvedProductImage,
rolegroup_ref: &RoleGroupRef<TrinoCluster>,
catalogs: &[CatalogConfig],
) -> Result<ConfigMap> {
ConfigMapBuilder::new()
.metadata(
ObjectMetaBuilder::new()
.name_and_namespace(trino)
.name(format!("{}-catalog", rolegroup_ref.object_name()))
.ownerreference_from_resource(trino, None, Some(true))
.context(ObjectMissingMetadataForOwnerRefSnafu)?
.with_recommended_labels(build_recommended_labels(
trino,
&resolved_product_image.app_version_label,
&rolegroup_ref.role,
&rolegroup_ref.role_group,
))
.context(MetadataBuildSnafu)?
.build(),
)
.data(
catalogs
.iter()
.map(|catalog| {
let catalog_props = catalog
.properties
.iter()
.map(|(k, v)| (k.to_string(), Some(v.to_string())))
.collect::<Vec<_>>();
Ok((
format!("{}.properties", catalog.name),
// false positive https://github.com/rust-lang/rust-clippy/issues/9280
// we need the tuple (&String, &Option<String>) which the extra map is doing.
// Removing the map changes the type to &(String, Option<String>)
#[allow(clippy::map_identity)]
product_config::writer::to_java_properties_string(
catalog_props.iter().map(|(k, v)| (k, v)),
)
.context(FailedToWriteJavaPropertiesSnafu)?,
))
})
.collect::<Result<_>>()?,
)
.build()
.with_context(|_| BuildRoleGroupConfigSnafu {
rolegroup: rolegroup_ref.clone(),
})
}
/// 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_rolegroup_service`]).
#[allow(clippy::too_many_arguments)]
fn build_rolegroup_statefulset(
trino: &TrinoCluster,
trino_role: &TrinoRole,
resolved_product_image: &ResolvedProductImage,
rolegroup_ref: &RoleGroupRef<TrinoCluster>,
config: &HashMap<PropertyNameKind, BTreeMap<String, String>>,
merged_config: &TrinoConfig,
trino_authentication_config: &TrinoAuthenticationConfig,
catalogs: &[CatalogConfig],
sa_name: &str,
) -> Result<StatefulSet> {
let role = trino
.role(trino_role)
.context(InternalOperatorFailureSnafu)?;
let rolegroup = trino
.rolegroup(rolegroup_ref)
.context(InternalOperatorFailureSnafu)?;
let mut pod_builder = PodBuilder::new();
let prepare_container_name = Container::Prepare.to_string();
let mut cb_prepare = ContainerBuilder::new(&prepare_container_name).with_context(|_| {
IllegalContainerNameSnafu {
container_name: prepare_container_name.clone(),
}
})?;
let trino_container_name = Container::Trino.to_string();
let mut cb_trino = ContainerBuilder::new(&trino_container_name).with_context(|_| {
IllegalContainerNameSnafu {
container_name: trino_container_name.clone(),
}
})?;
// additional authentication env vars
let mut env = trino_authentication_config.env_vars(trino_role, &Container::Trino);
let secret_name = build_shared_internal_secret_name(trino);
env.push(env_var_from_secret(&secret_name, None, ENV_INTERNAL_SECRET));
trino_authentication_config
.add_authentication_pod_and_volume_config(
trino_role,
&mut pod_builder,
&mut cb_prepare,
&mut cb_trino,
)
.context(InvalidAuthenticationConfigSnafu)?;
add_graceful_shutdown_config(
trino,
trino_role,
merged_config,
&mut pod_builder,
&mut cb_trino,
)
.context(GracefulShutdownSnafu)?;
// Add the needed stuff for catalogs
env.extend(
catalogs
.iter()
.flat_map(|catalog| &catalog.env_bindings)
.cloned(),
);
// Needed by the `containerdebug` process to log it's tracing information to.
// This process runs in the background of the `trino` container.
// See command::container_trino_args() for how it's called.
env.push(EnvVar {
name: "CONTAINERDEBUG_LOG_DIRECTORY".into(),
value: Some(format!("{STACKABLE_LOG_DIR}/containerdebug")),
..EnvVar::default()
});
// Finally add the user defined envOverrides properties.
env.extend(
config
.get(&PropertyNameKind::Env)
.into_iter()
.flatten()
.map(|(k, v)| EnvVar {
name: k.clone(),
value: Some(v.clone()),
..EnvVar::default()
}),
);
let requested_secret_lifetime = merged_config
.requested_secret_lifetime
.context(MissingSecretLifetimeSnafu)?;
// add volume mounts depending on the client tls, internal tls, catalogs and authentication
tls_volume_mounts(
trino,
&mut pod_builder,
&mut cb_prepare,
&mut cb_trino,
catalogs,
&requested_secret_lifetime,
)?;
let mut prepare_args = vec![];
if let Some(ContainerLogConfig {
choice: Some(ContainerLogConfigChoice::Automatic(log_config)),
}) = merged_config.logging.containers.get(&Container::Prepare)
{
prepare_args.push(product_logging::framework::capture_shell_output(
STACKABLE_LOG_DIR,
&prepare_container_name,
log_config,
));
}
prepare_args.extend(command::container_prepare_args(
trino,
catalogs,
merged_config,
));
prepare_args
.extend(trino_authentication_config.commands(&TrinoRole::Coordinator, &Container::Prepare));
let container_prepare = cb_prepare
.image_from_product_image(resolved_product_image)
.command(vec![
"/bin/bash".to_string(),
"-x".to_string(),
"-euo".to_string(),