-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
789 lines (711 loc) · 26.2 KB
/
lib.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
use git_sync::GitSync;
use product_config::flask_app_config_writer::{FlaskAppConfigOptions, PythonType};
use serde::{Deserialize, Serialize};
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, fragment::Fragment, fragment::ValidationError, merge::Merge},
k8s_openapi::{
api::core::v1::{Volume, VolumeMount},
apimachinery::pkg::api::resource::Quantity,
},
kube::{CustomResource, ResourceExt},
labels::ObjectLabels,
memory::{BinaryMultiple, MemoryQuantity},
product_config_utils::{ConfigError, Configuration},
product_logging::{
self,
framework::{create_vector_shutdown_file_command, remove_vector_shutdown_file_command},
spec::Logging,
},
role_utils::{CommonConfiguration, GenericRoleConfig, Role, RoleGroup, RoleGroupRef},
schemars::{self, JsonSchema},
status::condition::{ClusterCondition, HasStatusCondition},
time::Duration,
utils::COMMON_BASH_TRAP_FUNCTIONS,
};
use std::collections::BTreeMap;
use strum::{Display, EnumIter, EnumString, IntoEnumIterator};
pub mod affinity;
pub mod authentication;
mod git_sync;
use crate::{affinity::get_affinity, authentication::AirflowAuthentication};
pub const AIRFLOW_UID: i64 = 1000;
pub const APP_NAME: &str = "airflow";
pub const OPERATOR_NAME: &str = "airflow.stackable.tech";
pub const CONFIG_PATH: &str = "/stackable/app/config";
pub const STACKABLE_LOG_DIR: &str = "/stackable/log";
pub const LOG_CONFIG_DIR: &str = "/stackable/app/log_config";
pub const AIRFLOW_HOME: &str = "/stackable/airflow";
pub const AIRFLOW_CONFIG_FILENAME: &str = "webserver_config.py";
pub const GIT_SYNC_DIR: &str = "/stackable/app/git";
pub const GIT_CONTENT: &str = "content-from-git";
pub const GIT_ROOT: &str = "/tmp/git";
pub const GIT_LINK: &str = "current";
pub const GIT_SYNC_NAME: &str = "gitsync";
pub const GIT_SAFE_DIR: &str = "safe.directory";
pub const TEMPLATE_VOLUME_NAME: &str = "airflow-executor-pod-template";
pub const TEMPLATE_CONFIGMAP_NAME: &str = "airflow-executor-pod-template";
pub const TEMPLATE_LOCATION: &str = "/templates";
pub const TEMPLATE_NAME: &str = "airflow_executor_pod_template.yaml";
const GIT_SYNC_DEPTH: u8 = 1u8;
const GIT_SYNC_WAIT: u16 = 20u16;
const DEFAULT_AIRFLOW_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_minutes_unchecked(2);
const DEFAULT_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT: Duration = Duration::from_minutes_unchecked(5);
pub const MAX_LOG_FILES_SIZE: MemoryQuantity = MemoryQuantity {
value: 10.0,
unit: BinaryMultiple::Mebi,
};
#[derive(Snafu, Debug)]
pub enum Error {
#[snafu(display("Unknown Airflow role found {role}. Should be one of {roles:?}"))]
UnknownAirflowRole { role: String, roles: Vec<String> },
#[snafu(display("fragment validation failure"))]
FragmentValidationFailure { source: ValidationError },
#[snafu(display("Configuration/Executor conflict!"))]
NoRoleForExecutorFailure,
}
#[derive(Display, EnumIter, EnumString)]
#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]
pub enum AirflowConfigOptions {
AuthType,
AuthLdapSearch,
AuthLdapSearchFilter,
AuthLdapServer,
AuthLdapUidField,
AuthLdapBindUser,
AuthLdapBindPassword,
AuthUserRegistration,
AuthUserRegistrationRole,
AuthLdapFirstnameField,
AuthLdapLastnameField,
AuthLdapEmailField,
AuthLdapGroupField,
AuthRolesSyncAtLogin,
AuthLdapTlsDemand,
AuthLdapTlsCertfile,
AuthLdapTlsKeyfile,
AuthLdapTlsCacertfile,
AuthLdapAllowSelfSigned,
}
impl FlaskAppConfigOptions for AirflowConfigOptions {
fn python_type(&self) -> PythonType {
match self {
AirflowConfigOptions::AuthType => PythonType::Expression,
AirflowConfigOptions::AuthUserRegistration => PythonType::BoolLiteral,
AirflowConfigOptions::AuthUserRegistrationRole => PythonType::StringLiteral,
AirflowConfigOptions::AuthRolesSyncAtLogin => PythonType::BoolLiteral,
AirflowConfigOptions::AuthLdapServer => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapBindUser => PythonType::Expression,
AirflowConfigOptions::AuthLdapBindPassword => PythonType::Expression,
AirflowConfigOptions::AuthLdapSearch => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapSearchFilter => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapUidField => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapGroupField => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapFirstnameField => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapLastnameField => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapEmailField => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapTlsDemand => PythonType::BoolLiteral,
AirflowConfigOptions::AuthLdapTlsCertfile => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapTlsKeyfile => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapTlsCacertfile => PythonType::StringLiteral,
AirflowConfigOptions::AuthLdapAllowSelfSigned => PythonType::BoolLiteral,
}
}
}
#[derive(Clone, CustomResource, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
#[kube(
group = "airflow.stackable.tech",
version = "v1alpha1",
kind = "AirflowCluster",
plural = "airflowclusters",
shortname = "airflow",
status = "AirflowClusterStatus",
namespaced,
crates(
kube_core = "stackable_operator::kube::core",
k8s_openapi = "stackable_operator::k8s_openapi",
schemars = "stackable_operator::schemars"
)
)]
#[serde(rename_all = "camelCase")]
pub struct AirflowClusterSpec {
/// The Airflow image to use
pub image: ProductImage,
/// Global cluster configuration that applies to all roles and role groups
pub cluster_config: AirflowClusterConfig,
/// Cluster operations like pause reconciliation or cluster stop.
#[serde(default)]
pub cluster_operation: ClusterOperation,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub webservers: Option<Role<AirflowConfigFragment>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedulers: Option<Role<AirflowConfigFragment>>,
#[serde(flatten)]
pub executor: AirflowExecutor,
}
#[derive(Clone, Deserialize, Debug, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AirflowClusterConfig {
#[serde(flatten)]
pub authentication: AirflowAuthentication,
pub credentials_secret: String,
#[serde(default)]
pub dags_git_sync: Vec<GitSync>,
#[serde(default)]
pub expose_config: bool,
#[serde(default)]
pub load_examples: bool,
/// This field controls which type of Service the Operator creates for this AirflowCluster:
///
/// * cluster-internal: Use a ClusterIP service
///
/// * external-unstable: Use a NodePort service
///
/// * external-stable: Use a LoadBalancer service
///
/// This is a temporary solution with the goal to keep yaml manifests forward compatible.
/// In the future, this setting will control which ListenerClass <https://docs.stackable.tech/home/stable/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,
/// 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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub volumes: Option<Vec<Volume>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub volume_mounts: Option<Vec<VolumeMount>>,
}
// 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,
#[serde(rename = "external-stable")]
ExternalStable,
}
impl CurrentlySupportedListenerClasses {
pub fn k8s_service_type(&self) -> String {
match self {
CurrentlySupportedListenerClasses::ClusterInternal => "ClusterIP".to_string(),
CurrentlySupportedListenerClasses::ExternalUnstable => "NodePort".to_string(),
CurrentlySupportedListenerClasses::ExternalStable => "LoadBalancer".to_string(),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AirflowCredentials {
pub admin_user: AdminUserCredentials,
pub connections: Connections,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdminUserCredentials {
pub username: String,
pub firstname: String,
pub lastname: String,
pub email: String,
pub password: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Connections {
pub secret_key: String,
pub sqlalchemy_database_uri: String,
}
#[derive(
Clone,
Debug,
Deserialize,
Display,
EnumIter,
Eq,
Hash,
JsonSchema,
PartialEq,
Serialize,
EnumString,
)]
pub enum AirflowRole {
#[strum(serialize = "webserver")]
Webserver,
#[strum(serialize = "scheduler")]
Scheduler,
#[strum(serialize = "worker")]
Worker,
}
impl AirflowRole {
/// Returns the start commands for the different airflow components. Airflow expects all
/// components to have the same image/configuration (e.g. DAG folder location), even if not all
/// configuration settings are used everywhere. For this reason we ensure that the webserver
/// config file is in the Airflow home directory on all pods.
pub fn get_commands(&self) -> Vec<String> {
let mut command = vec![
format!("cp -RL {CONFIG_PATH}/{AIRFLOW_CONFIG_FILENAME} {AIRFLOW_HOME}/{AIRFLOW_CONFIG_FILENAME}"),
// graceful shutdown part
COMMON_BASH_TRAP_FUNCTIONS.to_string(),
remove_vector_shutdown_file_command(STACKABLE_LOG_DIR),
];
match &self {
AirflowRole::Webserver => command.extend(vec![
"prepare_signal_handlers".to_string(),
"airflow webserver &".to_string(),
]),
AirflowRole::Scheduler => command.extend(vec![
// Database initialization is limited to the scheduler, see https://github.com/stackabletech/airflow-operator/issues/259
"airflow db init".to_string(),
"airflow db upgrade".to_string(),
"airflow users create \
--username \"$ADMIN_USERNAME\" \
--firstname \"$ADMIN_FIRSTNAME\" \
--lastname \"$ADMIN_LASTNAME\" \
--email \"$ADMIN_EMAIL\" \
--password \"$ADMIN_PASSWORD\" \
--role \"Admin\""
.to_string(),
"prepare_signal_handlers".to_string(),
"airflow scheduler &".to_string(),
]),
AirflowRole::Worker => command.extend(vec![
"prepare_signal_handlers".to_string(),
"airflow celery worker &".to_string(),
]),
}
// graceful shutdown part
command.extend(vec![
"wait_for_termination $!".to_string(),
create_vector_shutdown_file_command(STACKABLE_LOG_DIR),
]);
command
}
/// Will be used to expose service ports and - by extension - which roles should be
/// created as services.
pub fn get_http_port(&self) -> Option<u16> {
match &self {
AirflowRole::Webserver => Some(8080),
AirflowRole::Scheduler => None,
AirflowRole::Worker => None,
}
}
pub fn roles() -> Vec<String> {
let mut roles = vec![];
for role in Self::iter() {
roles.push(role.to_string())
}
roles
}
}
#[derive(Clone, Debug, Deserialize, Display, JsonSchema, PartialEq, Serialize)]
pub enum AirflowExecutor {
#[serde(rename = "celeryExecutors")]
CeleryExecutor {
#[serde(flatten)]
config: Role<AirflowConfigFragment>,
},
#[serde(rename = "kubernetesExecutors")]
KubernetesExecutor {
#[serde(flatten)]
common_configuration: CommonConfiguration<ExecutorConfigFragment>,
},
}
impl AirflowCluster {
/// the worker role will not be returned if airflow provisions pods as needed (i.e. when
/// the kubernetes executor is specified)
pub fn get_role(&self, role: &AirflowRole) -> Option<&Role<AirflowConfigFragment>> {
match role {
AirflowRole::Webserver => self.spec.webservers.as_ref(),
AirflowRole::Scheduler => self.spec.schedulers.as_ref(),
AirflowRole::Worker => {
if let AirflowExecutor::CeleryExecutor { config } = &self.spec.executor {
Some(config)
} else {
None
}
}
}
}
pub fn role_config(&self, role: &AirflowRole) -> Option<&GenericRoleConfig> {
self.get_role(role).map(|r| &r.role_config)
}
/// this will extract a `Vec<Volume>` from `Option<Vec<Volume>>`
pub fn volumes(&self) -> Vec<Volume> {
let tmp = self.spec.cluster_config.volumes.as_ref();
tmp.iter().flat_map(|v| (*v).clone()).collect()
}
pub fn volume_mounts(&self) -> Vec<VolumeMount> {
let tmp = self.spec.cluster_config.volume_mounts.as_ref();
let mut mounts: Vec<VolumeMount> = tmp.iter().flat_map(|v| (*v).clone()).collect();
if self.git_sync().is_some() {
mounts.push(VolumeMount {
name: GIT_CONTENT.into(),
mount_path: GIT_SYNC_DIR.into(),
..VolumeMount::default()
});
}
mounts
}
pub fn git_sync(&self) -> Option<&GitSync> {
let dags_git_sync = &self.spec.cluster_config.dags_git_sync;
// dags_git_sync is a list but only the first element is considered
// (this avoids a later breaking change when all list elements are processed)
if dags_git_sync.len() > 1 {
tracing::warn!(
"{:?} git-sync elements: only first will be considered...",
dags_git_sync.len()
);
}
dags_git_sync.first()
}
/// The name of the role-level load-balanced Kubernetes `Service`
pub fn node_role_service_name(&self) -> Option<String> {
self.metadata.name.clone()
}
/// Retrieve and merge resource configs for role and role groups
pub fn merged_config(
&self,
role: &AirflowRole,
rolegroup_ref: &RoleGroupRef<AirflowCluster>,
) -> Result<AirflowConfig, Error> {
// Initialize the result with all default values as baseline
let conf_defaults = AirflowConfig::default_config(&self.name_any(), role);
let role = match role {
AirflowRole::Webserver => {
self.spec
.webservers
.as_ref()
.context(UnknownAirflowRoleSnafu {
role: role.to_string(),
roles: AirflowRole::roles(),
})?
}
AirflowRole::Worker => {
if let AirflowExecutor::CeleryExecutor { config } = &self.spec.executor {
config
} else {
return Err(Error::NoRoleForExecutorFailure);
}
}
AirflowRole::Scheduler => {
self.spec
.schedulers
.as_ref()
.context(UnknownAirflowRoleSnafu {
role: role.to_string(),
roles: AirflowRole::roles(),
})?
}
};
// Retrieve role resource config
let mut conf_role = role.config.config.to_owned();
// Retrieve rolegroup specific resource config
let mut conf_rolegroup = role
.role_groups
.get(&rolegroup_ref.role_group)
.map(|rg| rg.config.config.clone())
.unwrap_or_default();
if let Some(RoleGroup {
selector: Some(selector),
..
}) = role.role_groups.get(&rolegroup_ref.role_group)
{
// Migrate old `selector` attribute, see ADR 26 affinities.
// TODO Can be removed after support for the old `selector` field is dropped.
#[allow(deprecated)]
conf_rolegroup.affinity.add_legacy_selector(selector);
}
// Merge more specific configs into default config
// Hierarchy is:
// 1. RoleGroup
// 2. Role
// 3. Default
conf_role.merge(&conf_defaults);
conf_rolegroup.merge(&conf_role);
tracing::debug!("Merged config: {:?}", conf_rolegroup);
fragment::validate(conf_rolegroup).context(FragmentValidationFailureSnafu)
}
/// Retrieve and merge resource configs for the executor template
pub fn merged_executor_config(
&self,
config: &ExecutorConfigFragment,
) -> Result<ExecutorConfig, Error> {
// use the worker defaults for executor pods
let resources = default_resources(&AirflowRole::Worker);
let logging = product_logging::spec::default_logging();
let graceful_shutdown_timeout = Some(DEFAULT_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT);
let executor_defaults = ExecutorConfigFragment {
resources,
logging,
graceful_shutdown_timeout,
};
let mut conf_executor = config.to_owned();
conf_executor.merge(&executor_defaults);
tracing::debug!("Merged executor config: {:?}", conf_executor);
fragment::validate(conf_executor).context(FragmentValidationFailureSnafu)
}
}
#[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 AirflowStorageConfig {}
#[derive(
Clone,
Debug,
Deserialize,
Display,
Eq,
EnumIter,
JsonSchema,
Ord,
PartialEq,
PartialOrd,
Serialize,
)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum Container {
Airflow,
Vector,
Base,
}
#[derive(Clone, Debug, Default, Fragment, JsonSchema, PartialEq)]
#[fragment_attrs(
derive(
Clone,
Debug,
Default,
Deserialize,
Merge,
JsonSchema,
PartialEq,
Serialize
),
serde(rename_all = "camelCase")
)]
pub struct AirflowConfig {
#[fragment_attrs(serde(default))]
pub resources: Resources<AirflowStorageConfig, 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>,
}
#[derive(Clone, Debug, Default, Fragment, JsonSchema, PartialEq)]
#[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<AirflowStorageConfig, NoRuntimeLimits>,
#[fragment_attrs(serde(default))]
pub logging: Logging<Container>,
/// 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>,
}
impl AirflowConfig {
pub const CREDENTIALS_SECRET_PROPERTY: &'static str = "credentialsSecret";
pub const GIT_CREDENTIALS_SECRET_PROPERTY: &'static str = "gitCredentialsSecret";
fn default_config(cluster_name: &str, role: &AirflowRole) -> AirflowConfigFragment {
AirflowConfigFragment {
resources: default_resources(role),
logging: product_logging::spec::default_logging(),
affinity: get_affinity(cluster_name, role),
graceful_shutdown_timeout: Some(match role {
AirflowRole::Webserver | AirflowRole::Scheduler => {
DEFAULT_AIRFLOW_GRACEFUL_SHUTDOWN_TIMEOUT
}
AirflowRole::Worker => DEFAULT_WORKER_GRACEFUL_SHUTDOWN_TIMEOUT,
}),
}
}
}
fn default_resources(role: &AirflowRole) -> ResourcesFragment<AirflowStorageConfig> {
let (cpu, memory) = match role {
AirflowRole::Worker => (
CpuLimitsFragment {
min: Some(Quantity("200m".into())),
max: Some(Quantity("800m".into())),
},
MemoryLimitsFragment {
limit: Some(Quantity("1750Mi".into())),
runtime_limits: NoRuntimeLimitsFragment {},
},
),
AirflowRole::Webserver => (
CpuLimitsFragment {
min: Some(Quantity("100m".into())),
max: Some(Quantity("400m".into())),
},
MemoryLimitsFragment {
limit: Some(Quantity("2Gi".into())),
runtime_limits: NoRuntimeLimitsFragment {},
},
),
AirflowRole::Scheduler => (
CpuLimitsFragment {
min: Some(Quantity("100m".to_owned())),
max: Some(Quantity("400m".to_owned())),
},
MemoryLimitsFragment {
limit: Some(Quantity("512Mi".to_owned())),
runtime_limits: NoRuntimeLimitsFragment {},
},
),
};
ResourcesFragment {
cpu,
memory,
storage: AirflowStorageConfigFragment {},
}
}
impl Configuration for AirflowConfigFragment {
type Configurable = AirflowCluster;
fn compute_env(
&self,
cluster: &Self::Configurable,
_role_name: &str,
) -> Result<BTreeMap<String, Option<String>>, ConfigError> {
let mut env: BTreeMap<String, Option<String>> = BTreeMap::new();
env.insert(
AirflowConfig::CREDENTIALS_SECRET_PROPERTY.to_string(),
Some(cluster.spec.cluster_config.credentials_secret.clone()),
);
if let Some(git_sync) = &cluster.git_sync() {
if let Some(credentials_secret) = &git_sync.credentials_secret {
env.insert(
AirflowConfig::GIT_CREDENTIALS_SECRET_PROPERTY.to_string(),
Some(credentials_secret.to_string()),
);
}
}
Ok(env)
}
fn compute_cli(
&self,
_cluster: &Self::Configurable,
_role_name: &str,
) -> Result<BTreeMap<String, Option<String>>, ConfigError> {
Ok(BTreeMap::new())
}
fn compute_files(
&self,
_cluster: &Self::Configurable,
_role_name: &str,
_file: &str,
) -> Result<BTreeMap<String, Option<String>>, ConfigError> {
Ok(BTreeMap::new())
}
}
#[derive(Clone, Debug, Default, Deserialize, JsonSchema, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AirflowClusterStatus {
#[serde(default)]
pub conditions: Vec<ClusterCondition>,
}
impl HasStatusCondition for AirflowCluster {
fn conditions(&self) -> Vec<ClusterCondition> {
match &self.status {
Some(status) => status.conditions.clone(),
None => vec![],
}
}
}
/// Creates recommended `ObjectLabels` to be used in deployed resources
pub fn build_recommended_labels<'a, T>(
owner: &'a T,
controller_name: &'a str,
app_version: &'a str,
role: &'a str,
role_group: &'a str,
) -> ObjectLabels<'a, T> {
ObjectLabels {
owner,
app_name: APP_NAME,
app_version,
operator_name: OPERATOR_NAME,
controller_name,
role,
role_group,
}
}
#[cfg(test)]
mod tests {
use crate::AirflowCluster;
use stackable_operator::commons::product_image_selection::ResolvedProductImage;
#[test]
fn test_cluster_config() {
let cluster = "
apiVersion: airflow.stackable.tech/v1alpha1
kind: AirflowCluster
metadata:
name: airflow
spec:
image:
productVersion: 2.7.2
clusterConfig:
loadExamples: true
exposeConfig: true
credentialsSecret: simple-airflow-credentials
webservers:
roleGroups:
default:
config: {}
kubernetesExecutors:
config: {}
schedulers:
roleGroups:
default:
config: {}
";
let deserializer = serde_yaml::Deserializer::from_str(cluster);
let cluster: AirflowCluster =
serde_yaml::with::singleton_map_recursive::deserialize(deserializer).unwrap();
let resolved_airflow_image: ResolvedProductImage =
cluster.spec.image.resolve("airflow", "0.0.0-dev");
assert_eq!("2.7.2", &resolved_airflow_image.product_version);
assert_eq!("KubernetesExecutor", cluster.spec.executor.to_string());
assert!(cluster.spec.cluster_config.load_examples);
assert!(cluster.spec.cluster_config.expose_config);
}
}