-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcrd.rs
More file actions
565 lines (512 loc) · 18.9 KB
/
Copy pathcrd.rs
File metadata and controls
565 lines (512 loc) · 18.9 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
use const_format::concatcp;
use serde::{Deserialize, Serialize};
use snafu::{ResultExt, Snafu};
use stackable_operator::{
commons::{
affinity::{StackableAffinity, StackableAffinityFragment, affinity_between_role_pods},
cluster_operation::ClusterOperation,
product_image_selection::ProductImage,
resources::{
CpuLimitsFragment, MemoryLimitsFragment, NoRuntimeLimits, NoRuntimeLimitsFragment,
Resources, ResourcesFragment,
},
},
config::{
fragment::{self, Fragment, ValidationError},
merge::Merge,
},
config_overrides::KeyValueConfigOverrides,
crd::s3,
deep_merger::ObjectOverrides,
k8s_openapi::{api::core::v1::PodAntiAffinity, apimachinery::pkg::api::resource::Quantity},
kube::{CustomResource, ResourceExt},
product_logging::{
self,
spec::{
ConfigMapLogConfig, ContainerLogConfig, ContainerLogConfigChoice,
CustomContainerLogConfig, Logging,
},
},
role_utils::{CommonConfiguration, JavaCommonConfig},
schemars::{self, JsonSchema},
shared::time::Duration,
status::condition::{ClusterCondition, HasStatusCondition},
versioned::versioned,
};
use strum::{Display, EnumIter};
use super::common::SparkConnectRole;
pub const CONNECT_CONTROLLER_NAME: &str = "connect";
pub const CONNECT_FULL_CONTROLLER_NAME: &str = concatcp!(
CONNECT_CONTROLLER_NAME,
'.',
crate::crd::constants::OPERATOR_NAME
);
pub const CONNECT_SERVER_ROLE_NAME: &str = "server";
pub const CONNECT_EXECUTOR_ROLE_NAME: &str = "executor";
pub const CONNECT_GRPC_PORT: i32 = 15002;
pub const CONNECT_UI_PORT: i32 = 4040;
pub const DEFAULT_SPARK_CONNECT_GROUP_NAME: &str = "default";
pub const CONNECT_APP_NAME: &str = "spark-connect";
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("fragment validation failure"))]
FragmentValidationFailure { source: ValidationError },
}
type SparkConnectServerRoleType = CommonConfiguration<
v1alpha1::ServerConfigFragment,
JavaCommonConfig,
v1alpha1::ConfigOverrides,
>;
type SparkConnectExecutorRoleType = CommonConfiguration<
v1alpha1::ExecutorConfigFragment,
JavaCommonConfig,
v1alpha1::ConfigOverrides,
>;
#[versioned(
version(name = "v1alpha1"),
crates(
kube_core = "stackable_operator::kube::core",
kube_client = "stackable_operator::kube::client",
k8s_openapi = "stackable_operator::k8s_openapi",
schemars = "stackable_operator::schemars",
versioned = "stackable_operator::versioned"
)
)]
pub mod versioned {
/// An Apache Spark Connect server component. This resource is managed by the Stackable operator
/// for Apache Spark. Find more information on how to use it in the
/// [operator documentation](DOCS_BASE_URL_PLACEHOLDER/spark-k8s/usage-guide/connect-server).
#[versioned(crd(
group = "spark.stackable.tech",
plural = "sparkconnectservers",
shortname = "sparkconnect",
status = "SparkConnectServerStatus",
namespaced,
))]
#[derive(Clone, CustomResource, Debug, Deserialize, JsonSchema, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SparkConnectServerSpec {
pub image: ProductImage,
// no doc string - See ClusterOperation struct
#[serde(default)]
pub cluster_operation: ClusterOperation,
/// One or more S3 connections to be used by the Spark Connect server.
#[serde(default)]
connectors: Connectors,
// Docs are on the ObjectOverrides struct
#[serde(default)]
pub object_overrides: ObjectOverrides,
/// User provided command line arguments appended to the server entry point.
#[serde(default)]
pub args: Vec<String>,
/// Name of the Vector aggregator discovery ConfigMap.
/// It must contain the key `ADDRESS` with the address of the Vector aggregator.
#[serde(skip_serializing_if = "Option::is_none")]
pub vector_aggregator_config_map_name: Option<String>,
/// A Spark Connect server definition.
#[serde(default)]
pub server: SparkConnectServerConfigWrapper,
/// Spark Connect executor properties.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub executor: Option<SparkConnectExecutorRoleType>,
}
/// This struct is a wrapper for the `ServerConfig` in order to keep the `spec.server.roleConfig` setting consistent.
/// It is required since Spark Connect does not utilize the Stackable `Role` and therefore does not offer a `roleConfig`.
#[derive(Clone, Debug, Default, JsonSchema, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SparkConnectServerConfigWrapper {
#[serde(flatten)]
pub config: Option<SparkConnectServerRoleType>,
#[serde(default)]
pub role_config: SparkConnectServerRoleConfig,
}
/// Global role config settings for the Spark Connect Server.
#[derive(Clone, Debug, JsonSchema, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SparkConnectServerRoleConfig {
/// This field controls which [ListenerClass](DOCS_BASE_URL_PLACEHOLDER/listener-operator/listenerclass.html)
/// is used to expose the Spark Connect services.
#[serde(default = "default_listener_class")]
pub listener_class: String,
}
#[derive(Clone, Debug, Default, JsonSchema, PartialEq, Fragment)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct ServerConfig {
#[fragment_attrs(serde(default))]
pub resources: Resources<crate::connect::crd::ConnectStorageConfig, NoRuntimeLimits>,
#[fragment_attrs(serde(default))]
pub logging: Logging<SparkConnectContainer>,
/// Request secret (currently only autoTls certificates) lifetime from the secret operator, e.g. `7d`, or `30d`.
/// This can be shortened by the `maxCertificateLifetime` setting on the SecretClass issuing the TLS certificate.
#[fragment_attrs(serde(default))]
pub requested_secret_lifetime: Option<Duration>,
}
#[derive(Clone, Debug, Default, JsonSchema, PartialEq, Fragment)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct ExecutorConfig {
#[fragment_attrs(serde(default))]
pub resources: Resources<crate::connect::crd::ConnectStorageConfig, NoRuntimeLimits>,
#[fragment_attrs(serde(default))]
pub logging: Logging<crate::connect::crd::SparkConnectContainer>,
#[fragment_attrs(serde(default))]
pub affinity: StackableAffinity,
/// Request secret (currently only autoTls certificates) lifetime from the secret operator, e.g. `7d`, or `30d`.
/// This can be shortened by the `maxCertificateLifetime` setting on the SecretClass issuing the TLS certificate.
#[fragment_attrs(serde(default))]
pub requested_secret_lifetime: Option<Duration>,
}
#[derive(Clone, Debug, Default, JsonSchema, PartialEq, Deserialize, Serialize)]
struct Connectors {
#[serde(default)]
pub s3buckets: Vec<s3::v1alpha1::InlineBucketOrReference>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub s3connection: Option<s3::v1alpha1::InlineConnectionOrReference>,
}
#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Serialize)]
pub struct ConfigOverrides {
#[serde(
default,
rename = "spark-defaults.conf",
skip_serializing_if = "Option::is_none"
)]
pub spark_defaults_conf: Option<KeyValueConfigOverrides>,
#[serde(
default,
rename = "metrics.properties",
skip_serializing_if = "Option::is_none"
)]
pub metrics_properties: Option<KeyValueConfigOverrides>,
#[serde(
default,
rename = "security.properties",
skip_serializing_if = "Option::is_none"
)]
pub security_properties: Option<KeyValueConfigOverrides>,
}
}
#[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(crate) struct ConnectStorageConfig {}
#[derive(
Clone,
Debug,
Deserialize,
Display,
EnumIter,
Eq,
JsonSchema,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub(crate) enum SparkConnectContainer {
Spark,
Vector,
}
impl v1alpha1::ServerConfig {
// Auto TLS certificate lifetime
const DEFAULT_CONNECT_SECRET_LIFETIME: Duration = Duration::from_days_unchecked(1);
fn default_config() -> v1alpha1::ServerConfigFragment {
v1alpha1::ServerConfigFragment {
resources: ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("250m".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1024Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: ConnectStorageConfigFragment {},
},
logging: product_logging::spec::default_logging(),
requested_secret_lifetime: Some(Self::DEFAULT_CONNECT_SECRET_LIFETIME),
}
}
pub fn log_config_map(&self) -> Option<String> {
let container_log_config = self
.logging
.containers
.get(&SparkConnectContainer::Spark)
.cloned();
match container_log_config {
Some(ContainerLogConfig {
choice:
Some(ContainerLogConfigChoice::Custom(CustomContainerLogConfig {
custom: ConfigMapLogConfig { config_map },
})),
}) => Some(config_map.clone()),
_ => None,
}
}
}
// This is the equivalent to merged_config() in other ops
// only here we only need to merge operator defaults with
// user configuration.
impl v1alpha1::SparkConnectServer {
pub fn server_config(&self) -> Result<v1alpha1::ServerConfig, Error> {
let defaults = v1alpha1::ServerConfig::default_config();
fragment::validate(
match self.spec.server.config.as_ref().map(|cc| cc.config.clone()) {
Some(fragment) => {
let mut fc = fragment.clone();
fc.merge(&defaults);
fc
}
_ => defaults,
},
)
.context(FragmentValidationFailureSnafu)
}
pub fn executor_config(&self) -> Result<v1alpha1::ExecutorConfig, Error> {
let defaults = v1alpha1::ExecutorConfig::default_config(&self.name_unchecked());
fragment::validate(
match self.spec.executor.as_ref().map(|cc| cc.config.clone()) {
Some(fragment) => {
let mut fc = fragment.clone();
fc.merge(&defaults);
fc
}
_ => defaults,
},
)
.context(FragmentValidationFailureSnafu)
}
}
impl Default for v1alpha1::SparkConnectServerRoleConfig {
fn default() -> Self {
v1alpha1::SparkConnectServerRoleConfig {
listener_class: default_listener_class(),
}
}
}
pub fn default_listener_class() -> String {
"cluster-internal".to_string()
}
#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SparkConnectServerStatus {
#[serde(default)]
pub conditions: Vec<ClusterCondition>,
}
impl HasStatusCondition for v1alpha1::SparkConnectServer {
fn conditions(&self) -> Vec<ClusterCondition> {
match &self.status {
Some(status) => status.conditions.clone(),
None => vec![],
}
}
}
impl v1alpha1::ExecutorConfig {
// Auto TLS certificate lifetime
const DEFAULT_CONNECT_SECRET_LIFETIME: Duration = Duration::from_days_unchecked(1);
fn default_config(cluster_name: &str) -> v1alpha1::ExecutorConfigFragment {
v1alpha1::ExecutorConfigFragment {
resources: ResourcesFragment {
cpu: CpuLimitsFragment {
min: Some(Quantity("1".to_owned())),
max: Some(Quantity("1".to_owned())),
},
memory: MemoryLimitsFragment {
limit: Some(Quantity("1024M".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
storage: ConnectStorageConfigFragment {},
},
logging: product_logging::spec::default_logging(),
affinity: v1alpha1::ExecutorConfig::affinity(cluster_name),
requested_secret_lifetime: Some(Self::DEFAULT_CONNECT_SECRET_LIFETIME),
}
}
pub fn log_config_map(&self) -> Option<String> {
let container_log_config = self
.logging
.containers
.get(&SparkConnectContainer::Spark)
.cloned();
match container_log_config {
Some(ContainerLogConfig {
choice:
Some(ContainerLogConfigChoice::Custom(CustomContainerLogConfig {
custom: ConfigMapLogConfig { config_map },
})),
}) => Some(config_map.clone()),
_ => None,
}
}
fn affinity(cluster_name: &str) -> StackableAffinityFragment {
let affinity_between_role_pods = affinity_between_role_pods(
CONNECT_APP_NAME,
cluster_name,
&SparkConnectRole::Executor.to_string(),
70,
);
StackableAffinityFragment {
pod_affinity: None,
pod_anti_affinity: Some(PodAntiAffinity {
preferred_during_scheduling_ignored_during_execution: Some(vec![
affinity_between_role_pods,
]),
required_during_scheduling_ignored_during_execution: None,
}),
node_affinity: None,
node_selector: None,
}
}
}
#[cfg(test)]
mod tests {
use indoc::indoc;
use stackable_operator::versioned::test_utils::RoundtripTestData;
use super::*;
#[test]
fn test_cr_minimal_deserialization() {
let _spark_connect_cr = serde_yaml::from_str::<v1alpha1::SparkConnectServer>(indoc! { r#"
apiVersion: spark.stackable.tech/v1alpha1
kind: SparkConnectServer
metadata:
name: spark-connect
spec:
image:
productVersion: 4.1.2
"# })
.expect("Failed to deserialize minimal SparkConnectServer CR");
}
#[test]
fn test_cr_s3_ref_deserialization() {
let input = indoc! { r#"
---
apiVersion: spark.stackable.tech/v1alpha1
kind: SparkConnectServer
metadata:
name: spark-connect
spec:
image:
productVersion: 4.1.2
connectors:
s3:
- reference: my-s3-bucket
"# };
let deserializer = serde_yaml::Deserializer::from_str(input);
let _spark_connect_cr: v1alpha1::SparkConnectServer =
serde_yaml::with::singleton_map_recursive::deserialize(deserializer)
.expect("Failed to deserialize SparkConnectServer with S3 connectors CR");
}
#[test]
fn test_cr_s3_inline_deserialization() {
let input = indoc! { r#"
---
apiVersion: spark.stackable.tech/v1alpha1
kind: SparkConnectServer
metadata:
name: spark-connect
spec:
image:
productVersion: 4.1.2
connectors:
s3:
- inline:
bucketName: mybucket
connection:
inline:
host: minio
port: 9000
accessStyle: Path
credentials:
secretClass: minio-credentials-class
tls:
verification:
server:
caCert:
secretClass: minio-tls-ca
"# };
let deserializer = serde_yaml::Deserializer::from_str(input);
let _spark_connect_cr: v1alpha1::SparkConnectServer =
serde_yaml::with::singleton_map_recursive::deserialize(deserializer)
.expect("Failed to deserialize SparkConnectServer with S3 connectors CR");
}
impl RoundtripTestData for v1alpha1::SparkConnectServerSpec {
fn roundtrip_test_data() -> Vec<Self> {
stackable_operator::utils::yaml_from_str_singleton_map(indoc! {r#"
- image:
productVersion: 4.1.2
pullPolicy: IfNotPresent
connectors:
s3buckets:
- reference: ingest-bucket
s3connection:
reference: s3-connection
server:
jvmArgumentOverrides:
add:
- -Dmy.custom.jvm.arg=customValue
roleConfig:
listenerClass: external-unstable
config:
logging:
enableVectorAgent: false
containers:
spark:
custom:
configMap: spark-connect-log-config
configOverrides:
spark-defaults.conf:
spark.jars.ivy: /tmp/ivy2
executor:
configOverrides:
spark-defaults.conf:
spark.executor.instances: "1"
spark.executor.memoryOverhead: 1m
config:
logging:
enableVectorAgent: false
containers:
spark:
custom:
configMap: spark-connect-log-config
"#})
.expect("Failed to parse SparkConnectServerSpec YAML")
}
}
}