-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpdb.rs
344 lines (319 loc) · 13.2 KB
/
pdb.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
use k8s_openapi::{
api::policy::v1::{PodDisruptionBudget, PodDisruptionBudgetSpec},
apimachinery::pkg::{
apis::meta::v1::{LabelSelector, ObjectMeta},
util::intstr::IntOrString,
},
};
use kube::{Resource, ResourceExt};
use snafu::{ResultExt, Snafu};
use crate::{
builder::meta::ObjectMetaBuilder,
kvp::{label, KeyValuePairsExt},
};
type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, PartialEq, Snafu)]
pub enum Error {
#[snafu(display("failed to create role selector labels"))]
RoleSelectorLabels { source: crate::kvp::LabelError },
#[snafu(display("failed to set owner reference from resource"))]
OwnerReferenceFromResource { source: crate::builder::meta::Error },
#[snafu(display("failed to create app.kubernetes.io/managed-by label"))]
ManagedByLabel { source: crate::kvp::LabelError },
}
/// This builder is used to construct [`PodDisruptionBudget`]s.
/// If you are using this to create [`PodDisruptionBudget`]s according to [ADR 30 on Allowed Pod disruptions][adr],
/// the use of [`PodDisruptionBudgetBuilder::new_with_role`] is recommended.
///
/// The following attributes on a [`PodDisruptionBudget`] are considered mandatory and must be specified
/// before being able to construct the [`PodDisruptionBudget`]:
///
/// 1. [`PodDisruptionBudget::metadata`]
/// 2. [`PodDisruptionBudgetSpec::selector`]
/// 3. Either [`PodDisruptionBudgetSpec::min_available`] or [`PodDisruptionBudgetSpec::max_unavailable`]
///
/// Both [`PodDisruptionBudget::metadata`] and [`PodDisruptionBudgetSpec::selector`] will be set by [`PodDisruptionBudgetBuilder::new_with_role`].
///
/// [adr]: https://docs.stackable.tech/home/stable/contributor/adr/adr030-allowed-pod-disruptions
#[derive(Debug, Default)]
pub struct PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, PodDisruptionBudgetConstraint> {
metadata: ObjectMeta,
selector: LabelSelector,
/// Tracks wether either `maxUnavailable` or `minAvailable` is set.
constraint: Option<PodDisruptionBudgetConstraint>,
}
/// We intentionally only support fixed numbers, no percentage, see ADR 30 on Pod disruptions for details.
/// We use u16, as [`IntOrString`] takes an i32 and we don't want to allow negative numbers. u16 will always fit in i32.
#[derive(Debug)]
pub enum PodDisruptionBudgetConstraint {
MaxUnavailable(u16),
MinAvailable(u16),
}
impl PodDisruptionBudgetBuilder<(), (), ()> {
pub fn new() -> Self {
PodDisruptionBudgetBuilder::default()
}
/// This method populates [`PodDisruptionBudget::metadata`] and
/// [`PodDisruptionBudgetSpec::selector`] from the give role (not roleGroup!).
///
/// The parameters are the same as the fields from
/// [`ObjectLabels`][crate::kvp::ObjectLabels]:
///
/// * `owner` - Reference to the k8s object owning the created resource,
/// such as `HdfsCluster` or `TrinoCluster`.
/// * `app_name` - The name of the app being managed, such as `hdfs` or
/// `trino`.
/// * `role` - The role that this object belongs to, e.g. `datanode` or
/// `worker`.
/// * `operator_name` - The DNS-style name of the operator managing the
/// object (such as `hdfs.stackable.tech`).
/// * `controller_name` - The name of the controller inside of the operator
/// managing the object (such as `hdfscluster`)
pub fn new_with_role<T: Resource<DynamicType = ()>>(
owner: &T,
app_name: &str,
role: &str,
operator_name: &str,
controller_name: &str,
) -> Result<PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, ()>> {
let role_selector_labels = label::well_known::sets::role_selector(owner, app_name, role)
.context(RoleSelectorLabelsSnafu)?;
let managed_by_label = label::well_known::managed_by(operator_name, controller_name)
.context(ManagedByLabelSnafu)?;
let metadata = ObjectMetaBuilder::new()
.namespace_opt(owner.namespace())
.name(format!("{}-{}", owner.name_any(), role))
.ownerreference_from_resource(owner, None, Some(true))
.context(OwnerReferenceFromResourceSnafu)?
.with_labels(role_selector_labels.clone())
.with_label(managed_by_label)
.build();
Ok(PodDisruptionBudgetBuilder {
metadata,
selector: LabelSelector {
match_expressions: None,
match_labels: Some(role_selector_labels.to_unvalidated()),
},
..PodDisruptionBudgetBuilder::default()
})
}
/// Sets the mandatory [`PodDisruptionBudget::metadata`].
pub fn new_with_metadata(
self,
metadata: impl Into<ObjectMeta>,
) -> PodDisruptionBudgetBuilder<ObjectMeta, (), ()> {
PodDisruptionBudgetBuilder {
metadata: metadata.into(),
..PodDisruptionBudgetBuilder::default()
}
}
}
impl PodDisruptionBudgetBuilder<ObjectMeta, (), ()> {
/// Sets the mandatory [`PodDisruptionBudgetSpec::selector`].
pub fn with_selector(
self,
selector: LabelSelector,
) -> PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, ()> {
PodDisruptionBudgetBuilder {
metadata: self.metadata,
selector,
constraint: self.constraint,
}
}
}
impl PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, ()> {
/// Sets the mandatory [`PodDisruptionBudgetSpec::max_unavailable`].
/// Mutually exclusive with [`PodDisruptionBudgetBuilder::with_min_available`].
pub fn with_max_unavailable(
self,
max_unavailable: u16,
) -> PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, PodDisruptionBudgetConstraint> {
PodDisruptionBudgetBuilder {
metadata: self.metadata,
selector: self.selector,
constraint: Some(PodDisruptionBudgetConstraint::MaxUnavailable(
max_unavailable,
)),
}
}
/// Sets the mandatory [`PodDisruptionBudgetSpec::min_available`].
/// Mutually exclusive with [`PodDisruptionBudgetBuilder::with_max_unavailable`].
#[deprecated(
since = "0.51.0",
note = "It is strongly recommended to use [`max_unavailable`]. Please read the ADR on Pod disruptions before using this function."
)]
pub fn with_min_available(
self,
min_available: u16,
) -> PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, PodDisruptionBudgetConstraint> {
PodDisruptionBudgetBuilder {
metadata: self.metadata,
selector: self.selector,
constraint: Some(PodDisruptionBudgetConstraint::MinAvailable(min_available)),
}
}
}
impl PodDisruptionBudgetBuilder<ObjectMeta, LabelSelector, PodDisruptionBudgetConstraint> {
/// This function can be called after [`PodDisruptionBudget::metadata`], [`PodDisruptionBudgetSpec::selector`]
/// and either [`PodDisruptionBudgetSpec::min_available`] or [`PodDisruptionBudgetSpec::max_unavailable`] are set.
pub fn build(self) -> PodDisruptionBudget {
let (max_unavailable, min_available) = match self.constraint {
Some(PodDisruptionBudgetConstraint::MaxUnavailable(max_unavailable)) => {
(Some(max_unavailable), None)
}
Some(PodDisruptionBudgetConstraint::MinAvailable(min_unavailable)) => {
(None, Some(min_unavailable))
}
None => {
unreachable!("Either minUnavailable or maxUnavailable must be set at this point!")
}
};
PodDisruptionBudget {
metadata: self.metadata,
spec: Some(PodDisruptionBudgetSpec {
max_unavailable: max_unavailable.map(i32::from).map(IntOrString::Int),
min_available: min_available.map(i32::from).map(IntOrString::Int),
selector: Some(self.selector),
// Because this feature is still in beta in k8s version 1.27, the builder currently does not offer this attribute.
unhealthy_pod_eviction_policy: Default::default(),
}),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use k8s_openapi::{
api::policy::v1::{PodDisruptionBudget, PodDisruptionBudgetSpec},
apimachinery::pkg::{apis::meta::v1::LabelSelector, util::intstr::IntOrString},
};
use kube::{core::ObjectMeta, CustomResource};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::builder::meta::{ObjectMetaBuilder, OwnerReferenceBuilder};
use super::PodDisruptionBudgetBuilder;
#[test]
pub fn normal_build() {
#[allow(deprecated)]
let pdb = PodDisruptionBudgetBuilder::new()
.new_with_metadata(
ObjectMetaBuilder::new()
.namespace("default")
.name("trino")
.build(),
)
.with_selector(LabelSelector {
match_expressions: None,
match_labels: Some(BTreeMap::from([("foo".to_string(), "bar".to_string())])),
})
.with_min_available(42)
.build();
assert_eq!(
pdb,
PodDisruptionBudget {
metadata: ObjectMeta {
name: Some("trino".to_string()),
namespace: Some("default".to_string()),
..Default::default()
},
spec: Some(PodDisruptionBudgetSpec {
min_available: Some(IntOrString::Int(42)),
selector: Some(LabelSelector {
match_expressions: None,
match_labels: Some(BTreeMap::from([(
"foo".to_string(),
"bar".to_string()
)])),
}),
..Default::default()
}),
..Default::default()
}
)
}
#[test]
pub fn build_from_role() {
#[derive(
Clone, CustomResource, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize,
)]
#[kube(group = "test", version = "v1", kind = "TrinoCluster", namespaced)]
pub struct TrinoClusterSpec {}
let trino: TrinoCluster = serde_yaml::from_str(
"
apiVersion: test/v1
kind: TrinoCluster
metadata:
name: simple-trino
namespace: default
uid: 123 # Needed for the ownerreference
spec: {}
",
)
.unwrap();
let app_name = "trino";
let role = "worker";
let operator_name = "trino.stackable.tech";
let controller_name = "trino-operator-trino-controller";
let pdb = PodDisruptionBudgetBuilder::new_with_role(
&trino,
app_name,
role,
operator_name,
controller_name,
)
.unwrap()
.with_max_unavailable(2)
.build();
assert_eq!(
pdb,
PodDisruptionBudget {
metadata: ObjectMeta {
name: Some("simple-trino-worker".to_string()),
namespace: Some("default".to_string()),
labels: Some(BTreeMap::from([
("app.kubernetes.io/name".to_string(), "trino".to_string()),
(
"app.kubernetes.io/instance".to_string(),
"simple-trino".to_string()
),
(
"app.kubernetes.io/managed-by".to_string(),
"trino.stackable.tech_trino-operator-trino-controller".to_string()
),
(
"app.kubernetes.io/component".to_string(),
"worker".to_string()
)
])),
owner_references: Some(vec![OwnerReferenceBuilder::new()
.initialize_from_resource(&trino)
.block_owner_deletion_opt(None)
.controller_opt(Some(true))
.build()
.unwrap()]),
..Default::default()
},
spec: Some(PodDisruptionBudgetSpec {
max_unavailable: Some(IntOrString::Int(2)),
selector: Some(LabelSelector {
match_expressions: None,
match_labels: Some(BTreeMap::from([
("app.kubernetes.io/name".to_string(), "trino".to_string()),
(
"app.kubernetes.io/instance".to_string(),
"simple-trino".to_string()
),
(
"app.kubernetes.io/component".to_string(),
"worker".to_string()
)
])),
}),
..Default::default()
}),
..Default::default()
}
)
}
}