-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmeta.rs
354 lines (308 loc) · 11.6 KB
/
meta.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
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference};
use kube::{Resource, ResourceExt};
use snafu::{ResultExt, Snafu};
use tracing::warn;
use crate::{
error::{Error, OperatorResult},
kvp::{Annotation, Annotations, Label, LabelError, Labels, ObjectLabels},
};
// NOTE (Techassi): Think about that name
#[derive(Debug, Snafu)]
pub enum ObjectMetaBuilderError {
#[snafu(display("failed to set recommended labels"))]
RecommendedLabels { source: LabelError },
}
/// A builder to build [`ObjectMeta`] objects.
///
/// Of special interest is the [`Self::ownerreference_from_resource()`] function.
/// Note: This builder only supports a single `OwnerReference`.
///
/// It is strongly recommended to always call [`Self::with_recommended_labels()`]!
#[derive(Clone, Default)]
pub struct ObjectMetaBuilder {
ownerreference: Option<OwnerReference>,
annotations: Option<Annotations>,
generate_name: Option<String>,
namespace: Option<String>,
labels: Option<Labels>,
name: Option<String>,
}
impl ObjectMetaBuilder {
pub fn new() -> ObjectMetaBuilder {
ObjectMetaBuilder::default()
}
/// This sets the name and namespace from a given resource
pub fn name_and_namespace<T: Resource>(&mut self, resource: &T) -> &mut Self {
self.name = Some(resource.name_any());
self.namespace = resource.namespace();
self
}
pub fn name_opt(&mut self, name: impl Into<Option<String>>) -> &mut Self {
self.name = name.into();
self
}
pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
self.name = Some(name.into());
self
}
pub fn generate_name(&mut self, generate_name: impl Into<String>) -> &mut Self {
self.generate_name = Some(generate_name.into());
self
}
pub fn generate_name_opt(&mut self, generate_name: impl Into<Option<String>>) -> &mut Self {
self.generate_name = generate_name.into();
self
}
pub fn namespace_opt(&mut self, namespace: impl Into<Option<String>>) -> &mut Self {
self.namespace = namespace.into();
self
}
pub fn namespace(&mut self, namespace: impl Into<String>) -> &mut Self {
self.namespace = Some(namespace.into());
self
}
pub fn ownerreference(&mut self, ownerreference: OwnerReference) -> &mut Self {
self.ownerreference = Some(ownerreference);
self
}
pub fn ownerreference_opt(&mut self, ownerreference: Option<OwnerReference>) -> &mut Self {
self.ownerreference = ownerreference;
self
}
/// This can be used to set the `OwnerReference` to the provided resource.
pub fn ownerreference_from_resource<T: Resource<DynamicType = ()>>(
&mut self,
resource: &T,
block_owner_deletion: Option<bool>,
controller: Option<bool>,
) -> OperatorResult<&mut Self> {
self.ownerreference = Some(
OwnerReferenceBuilder::new()
.initialize_from_resource(resource)
.block_owner_deletion_opt(block_owner_deletion)
.controller_opt(controller)
.build()?,
);
Ok(self)
}
/// This adds a single annotation to the existing annotations.
/// It'll override an annotation with the same key.
pub fn with_annotation(&mut self, annotation: Annotation) -> &mut Self {
self.annotations
.get_or_insert(Annotations::new())
.insert(annotation);
self
}
/// This adds multiple annotations to the existing annotations.
/// Any existing annotation with a key that is contained in `annotations` will be overwritten
pub fn with_annotations(&mut self, annotations: Annotations) -> &mut Self {
self.annotations
.get_or_insert(Annotations::new())
.extend(annotations);
self
}
/// This will replace all existing annotations
pub fn annotations(&mut self, annotations: Annotations) -> &mut Self {
self.annotations = Some(annotations);
self
}
/// This adds a single label to the existing labels.
/// It'll override a label with the same key.
pub fn with_label(&mut self, label: Label) -> &mut Self {
self.labels.get_or_insert(Labels::new()).insert(label);
self
}
/// This adds multiple labels to the existing labels.
/// Any existing label with a key that is contained in `labels` will be overwritten
pub fn with_labels(&mut self, labels: Labels) -> &mut Self {
self.labels.get_or_insert(Labels::new()).extend(labels);
self
}
/// This will replace all existing labels
pub fn labels(&mut self, labels: Labels) -> &mut Self {
self.labels = Some(labels);
self
}
/// This sets the common recommended labels (in the `app.kubernetes.io`
/// namespace). It is recommended to always call this method. The only
/// reasons it is not _required_ is to make testing easier and to allow
/// for more flexibility if needed.
pub fn with_recommended_labels<T: Resource>(
&mut self,
object_labels: ObjectLabels<T>,
) -> Result<&mut Self, ObjectMetaBuilderError> {
let recommended_labels =
Labels::recommended(object_labels).context(RecommendedLabelsSnafu)?;
self.labels
.get_or_insert(Labels::new())
.extend(recommended_labels);
Ok(self)
}
pub fn build(&self) -> ObjectMeta {
// NOTE (Techassi): Shouldn't this take self instead of &self to consume
// the builder and build ObjectMeta without cloning?
// if 'generate_name' and 'name' are set, Kubernetes will prioritize the 'name' field and
// 'generate_name' has no impact.
if let (Some(name), Some(generate_name)) = (&self.name, &self.generate_name) {
warn!(
"ObjectMeta has a 'name' [{}] and 'generate_name' [{}] field set. Kubernetes \
will prioritize the 'name' field over 'generate_name'.",
name, generate_name
);
}
ObjectMeta {
generate_name: self.generate_name.clone(),
name: self.name.clone(),
namespace: self.namespace.clone(),
owner_references: self
.ownerreference
.as_ref()
.map(|ownerreference| vec![ownerreference.clone()]),
labels: self.labels.clone().map(|l| l.into()),
annotations: self.annotations.clone().map(|a| a.into()),
..ObjectMeta::default()
}
}
}
/// A builder to build [`OwnerReference`] objects.
///
/// Of special interest is the [`Self::initialize_from_resource()`] function.
#[derive(Clone, Default)]
pub struct OwnerReferenceBuilder {
api_version: Option<String>,
block_owner_deletion: Option<bool>,
controller: Option<bool>,
kind: Option<String>,
name: Option<String>,
uid: Option<String>,
}
impl OwnerReferenceBuilder {
pub fn new() -> OwnerReferenceBuilder {
OwnerReferenceBuilder::default()
}
pub fn api_version(&mut self, api_version: impl Into<String>) -> &mut Self {
self.api_version = Some(api_version.into());
self
}
pub fn api_version_opt(&mut self, api_version: impl Into<Option<String>>) -> &mut Self {
self.api_version = api_version.into();
self
}
pub fn block_owner_deletion(&mut self, block_owner_deletion: bool) -> &mut Self {
self.block_owner_deletion = Some(block_owner_deletion);
self
}
pub fn block_owner_deletion_opt(&mut self, block_owner_deletion: Option<bool>) -> &mut Self {
self.block_owner_deletion = block_owner_deletion;
self
}
pub fn controller(&mut self, controller: bool) -> &mut Self {
self.controller = Some(controller);
self
}
pub fn controller_opt(&mut self, controller: Option<bool>) -> &mut Self {
self.controller = controller;
self
}
pub fn kind(&mut self, kind: impl Into<String>) -> &mut Self {
self.kind = Some(kind.into());
self
}
pub fn kind_opt(&mut self, kind: impl Into<Option<String>>) -> &mut Self {
self.kind = kind.into();
self
}
pub fn name(&mut self, name: impl Into<String>) -> &mut Self {
self.name = Some(name.into());
self
}
pub fn name_opt(&mut self, name: impl Into<Option<String>>) -> &mut Self {
self.name = name.into();
self
}
pub fn uid(&mut self, uid: impl Into<String>) -> &mut Self {
self.uid = Some(uid.into());
self
}
pub fn uid_opt(&mut self, uid: impl Into<Option<String>>) -> &mut Self {
self.uid = uid.into();
self
}
/// Can be used to initialize a builder with settings from an existing resource.
/// The builder will create an `OwnerReference` that points to the passed resource.
///
/// This will _not_ set `controller` or `block_owner_deletion`.
pub fn initialize_from_resource<T: Resource<DynamicType = ()>>(
&mut self,
resource: &T,
) -> &mut Self {
self.api_version(T::api_version(&()))
.kind(T::kind(&()))
.name(resource.name_any())
.uid_opt(resource.meta().uid.clone());
self
}
pub fn build(&self) -> OperatorResult<OwnerReference> {
Ok(OwnerReference {
api_version: match self.api_version {
None => return Err(Error::MissingObjectKey { key: "api_version" }),
Some(ref api_version) => api_version.clone(),
},
block_owner_deletion: self.block_owner_deletion,
controller: self.controller,
kind: match self.kind {
None => return Err(Error::MissingObjectKey { key: "kind" }),
Some(ref kind) => kind.clone(),
},
name: match self.name {
None => return Err(Error::MissingObjectKey { key: "name" }),
Some(ref name) => name.clone(),
},
uid: match self.uid {
None => return Err(Error::MissingObjectKey { key: "uid" }),
Some(ref uid) => uid.clone(),
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::builder::meta::ObjectMetaBuilder;
use k8s_openapi::api::core::v1::Pod;
#[test]
fn test_objectmeta_builder() {
let mut pod = Pod::default();
pod.metadata.name = Some("pod".to_string());
pod.metadata.uid = Some("uid".to_string());
let meta = ObjectMetaBuilder::new()
.generate_name("generate_foo")
.name("foo")
.namespace("bar")
.ownerreference_from_resource(&pod, Some(true), Some(false))
.unwrap()
.with_recommended_labels(ObjectLabels {
owner: &pod,
app_name: "test_app",
app_version: "1.0",
operator_name: "app.stackable.tech",
controller_name: "appcluster",
role: "role",
role_group: "rolegroup",
})
.unwrap()
.with_annotation(("foo", "bar").try_into().unwrap())
.build();
assert_eq!(meta.generate_name, Some("generate_foo".to_string()));
assert_eq!(meta.name, Some("foo".to_string()));
assert_eq!(meta.owner_references.as_ref().unwrap().len(), 1);
assert!(
matches!(meta.owner_references.unwrap().first(), Some(OwnerReference { uid, ..}) if uid == "uid")
);
assert_eq!(meta.annotations.as_ref().unwrap().len(), 1);
assert_eq!(
meta.annotations.as_ref().unwrap().get(&"foo".to_string()),
Some(&"bar".to_string())
);
}
}