-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmod.rs
More file actions
423 lines (366 loc) · 13.7 KB
/
Copy pathmod.rs
File metadata and controls
423 lines (366 loc) · 13.7 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
//! This module provides various types and functions to construct valid
//! Kubernetes labels. Labels are key/value pairs, where the key must meet
//! certain requirementens regarding length and character set. The value can
//! contain a limited set of ASCII characters.
//!
//! Additionally, the [`Label`] struct provides various helper functions to
//! construct commonly used labels across the Stackable Data Platform, like
//! the role_group or component.
//!
//! See <https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/>
//! for more information on Kubernetes labels.
use std::{
collections::{BTreeMap, BTreeSet},
fmt::Display,
};
use delegate::delegate;
use kube::{Resource, ResourceExt};
use crate::{
iter::TryFromIterator,
kvp::{
consts::{
K8S_APP_COMPONENT_KEY, K8S_APP_INSTANCE_KEY, K8S_APP_MANAGED_BY_KEY, K8S_APP_NAME_KEY,
K8S_APP_ROLE_GROUP_KEY, K8S_APP_VERSION_KEY, STACKABLE_VENDOR_KEY,
STACKABLE_VENDOR_VALUE,
},
Key, KeyValuePair, KeyValuePairError, KeyValuePairs, KeyValuePairsError, ObjectLabels,
},
utils::format_full_controller_name,
};
mod selector;
mod value;
pub use selector::*;
pub use value::*;
pub type LabelsError = KeyValuePairsError;
/// A type alias for errors returned when construction or manipulation of a set
/// of labels fails.
pub type LabelError = KeyValuePairError<LabelValueError>;
/// A specialized implementation of a key/value pair representing Kubernetes
/// labels.
///
/// ```
/// # use stackable_operator::kvp::Label;
/// let label = Label::try_from(("stackable.tech/vendor", "Stackable")).unwrap();
/// assert_eq!(label.to_string(), "stackable.tech/vendor=Stackable");
/// ```
///
/// The validation of the label value can fail due to multiple reasons. It can
/// only contain a limited set and combination of ASCII characters. See
/// <https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/>
/// for more information on Kubernetes labels.
#[derive(Clone, Debug)]
pub struct Label(KeyValuePair<LabelValue>);
impl<K, V> TryFrom<(K, V)> for Label
where
K: AsRef<str>,
V: AsRef<str>,
{
type Error = LabelError;
fn try_from(value: (K, V)) -> Result<Self, Self::Error> {
let kvp = KeyValuePair::try_from(value)?;
Ok(Self(kvp))
}
}
impl Display for Label {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl Label {
/// Returns an immutable reference to the label's [`Key`].
///
/// ```
/// # use stackable_operator::kvp::Label;
/// let label = Label::try_from(("stackable.tech/vendor", "Stackable")).unwrap();
/// assert_eq!(label.key().to_string(), "stackable.tech/vendor");
/// ```
pub fn key(&self) -> &Key {
self.0.key()
}
/// Returns an immutable reference to the label's value.
pub fn value(&self) -> &LabelValue {
self.0.value()
}
/// Consumes self and returns the inner [`KeyValuePair<LabelValue>`].
pub fn into_inner(self) -> KeyValuePair<LabelValue> {
self.0
}
/// Creates the `app.kubernetes.io/component` label with `role` as the
/// value. This function will return an error if `role` violates the required
/// Kubernetes restrictions.
pub fn component(component: &str) -> Result<Self, LabelError> {
let kvp = KeyValuePair::try_from((K8S_APP_COMPONENT_KEY, component))?;
Ok(Self(kvp))
}
/// Creates the `app.kubernetes.io/role-group` label with `role_group` as
/// the value. This function will return an error if `role_group` violates
/// the required Kubernetes restrictions.
pub fn role_group(role_group: &str) -> Result<Self, LabelError> {
let kvp = KeyValuePair::try_from((K8S_APP_ROLE_GROUP_KEY, role_group))?;
Ok(Self(kvp))
}
/// Creates the `app.kubernetes.io/managed-by` label with the formated
/// full controller name based on `operator_name` and `controller_name` as
/// the value. This function will return an error if the formatted controller
/// name violates the required Kubernetes restrictions.
pub fn managed_by(operator_name: &str, controller_name: &str) -> Result<Self, LabelError> {
let kvp = KeyValuePair::try_from((
K8S_APP_MANAGED_BY_KEY,
format_full_controller_name(operator_name, controller_name).as_str(),
))?;
Ok(Self(kvp))
}
/// Creates the `app.kubernetes.io/version` label with `version` as the
/// value. This function will return an error if `role_group` violates the
/// required Kubernetes restrictions.
pub fn version(version: &str) -> Result<Self, LabelError> {
// NOTE (Techassi): Maybe use semver::Version
let kvp = KeyValuePair::try_from((K8S_APP_VERSION_KEY, version))?;
Ok(Self(kvp))
}
}
/// A validated set/list of Kubernetes labels.
///
/// It provides selected associated functions to manipulate the set of labels,
/// like inserting or extending.
///
/// ## Examples
///
/// ### Converting a BTreeMap into a list of labels
///
/// ```
/// # use std::collections::BTreeMap;
/// # use stackable_operator::kvp::Labels;
/// let map = BTreeMap::from([
/// ("stackable.tech/managed-by", "stackablectl"),
/// ("stackable.tech/vendor", "Stackable"),
/// ]);
///
/// let labels = Labels::try_from(map).unwrap();
/// ```
///
/// ### Creating a list of labels from an array
///
/// ```
/// # use stackable_operator::kvp::Labels;
/// let labels = Labels::try_from([
/// ("stackable.tech/managed-by", "stackablectl"),
/// ("stackable.tech/vendor", "Stackable"),
/// ]).unwrap();
/// ```
#[derive(Clone, Debug, Default)]
pub struct Labels(KeyValuePairs<LabelValue>);
impl<K, V> TryFrom<BTreeMap<K, V>> for Labels
where
K: AsRef<str>,
V: AsRef<str>,
{
type Error = LabelError;
fn try_from(map: BTreeMap<K, V>) -> Result<Self, Self::Error> {
Self::try_from_iter(map)
}
}
impl<K, V> TryFrom<&BTreeMap<K, V>> for Labels
where
K: AsRef<str>,
V: AsRef<str>,
{
type Error = LabelError;
fn try_from(map: &BTreeMap<K, V>) -> Result<Self, Self::Error> {
Self::try_from_iter(map)
}
}
impl<const N: usize, K, V> TryFrom<[(K, V); N]> for Labels
where
K: AsRef<str>,
V: AsRef<str>,
{
type Error = LabelError;
fn try_from(array: [(K, V); N]) -> Result<Self, Self::Error> {
Self::try_from_iter(array)
}
}
impl FromIterator<KeyValuePair<LabelValue>> for Labels {
fn from_iter<T: IntoIterator<Item = KeyValuePair<LabelValue>>>(iter: T) -> Self {
let kvps = KeyValuePairs::from_iter(iter);
Self(kvps)
}
}
impl<K, V> TryFromIterator<(K, V)> for Labels
where
K: AsRef<str>,
V: AsRef<str>,
{
type Error = LabelError;
fn try_from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Result<Self, Self::Error> {
let kvps = KeyValuePairs::try_from_iter(iter)?;
Ok(Self(kvps))
}
}
impl From<Labels> for BTreeMap<String, String> {
fn from(value: Labels) -> Self {
value.0.into()
}
}
impl Labels {
/// Creates a new empty list of [`Labels`].
pub fn new() -> Self {
Self::default()
}
/// Creates a new list of [`Labels`] from `pairs`.
pub fn new_with(pairs: BTreeSet<KeyValuePair<LabelValue>>) -> Self {
Self(KeyValuePairs::new_with(pairs))
}
/// Tries to insert a new label by first parsing `label` as a [`Label`]
/// and then inserting it into the list. This function will overwrite any
/// existing label already present.
pub fn parse_insert(
&mut self,
label: impl TryInto<Label, Error = LabelError>,
) -> Result<(), LabelError> {
self.0.insert(label.try_into()?.0);
Ok(())
}
/// Inserts a new [`Label`]. This function will overwrite any existing label
/// already present.
pub fn insert(&mut self, label: Label) -> &mut Self {
self.0.insert(label.0);
self
}
/// Returns the recommended set of labels. The set includes these well-known
/// Kubernetes labels:
///
/// - `app.kubernetes.io/role-group`
/// - `app.kubernetes.io/managed-by`
/// - `app.kubernetes.io/component`
/// - `app.kubernetes.io/instance`
/// - `app.kubernetes.io/version`
/// - `app.kubernetes.io/name`
///
/// Additionally, it includes Stackable-specific labels. These are:
///
/// - `stackable.tech/vendor`
///
/// This function returns a result, because the parameter `object_labels`
/// can contain invalid data or can exceed the maximum allowed number of
/// characters.
pub fn recommended<R>(object_labels: ObjectLabels<R>) -> Result<Self, LabelError>
where
R: Resource,
{
// Well-known Kubernetes labels
let mut labels = Self::role_group_selector(
object_labels.owner,
object_labels.app_name,
object_labels.role,
object_labels.role_group,
)?;
let managed_by =
Label::managed_by(object_labels.operator_name, object_labels.controller_name)?;
let version = Label::version(object_labels.app_version)?;
labels.insert(managed_by);
labels.insert(version);
// Stackable-specific labels
labels.parse_insert((STACKABLE_VENDOR_KEY, STACKABLE_VENDOR_VALUE))?;
Ok(labels)
}
/// Returns the set of labels required to select the resource based on the
/// role group. The set contains role selector labels, see
/// [`Labels::role_selector`] for more details. Additionally, it contains
/// the `app.kubernetes.io/role-group` label with `role_group` as the value.
pub fn role_group_selector<R>(
owner: &R,
app_name: &str,
role: &str,
role_group: &str,
) -> Result<Self, LabelError>
where
R: Resource,
{
let mut labels = Self::role_selector(owner, app_name, role)?;
labels.insert(Label::role_group(role_group)?);
Ok(labels)
}
/// Returns the set of labels required to select the resource based on the
/// role. The set contains the common labels, see [`Labels::common`] for
/// more details. Additionally, it contains the `app.kubernetes.io/component`
/// label with `role` as the value.
///
/// This function returns a result, because the parameters `owner`, `app_name`,
/// and `role` can contain invalid data or can exceed the maximum allowed
/// number fo characters.
pub fn role_selector<R>(owner: &R, app_name: &str, role: &str) -> Result<Self, LabelError>
where
R: Resource,
{
let mut labels = Self::common(app_name, owner.name_any().as_str())?;
labels.insert(Label::component(role)?);
Ok(labels)
}
/// Returns a common set of labels, which are required to identify resources
/// that belong to a certain owner object, for example a `ZookeeperCluster`.
/// The set contains these well-known labels:
///
/// - `app.kubernetes.io/instance` and
/// - `app.kubernetes.io/name`
///
/// This function returns a result, because the parameters `app_name` and
/// `app_instance` can contain invalid data or can exceed the maximum
/// allowed number of characters.
pub fn common(app_name: &str, app_instance: &str) -> Result<Self, LabelError> {
let mut labels = Self::new();
labels.insert((K8S_APP_INSTANCE_KEY, app_instance).try_into()?);
labels.insert((K8S_APP_NAME_KEY, app_name).try_into()?);
Ok(labels)
}
// This forwards / delegates associated functions to the inner field. In
// this case self.0 which is of type KeyValuePairs<T>. So calling
// Labels::len() will be delegated to KeyValuePair<T>::len() without the
// need to write boilerplate code.
delegate! {
to self.0 {
/// Tries to insert a new [`Label`]. It ensures there are no duplicate
/// entries. Trying to insert duplicated data returns an error. If no such
/// check is required, use [`Labels::insert`] instead.
pub fn try_insert(&mut self, #[newtype] label: Label) -> Result<(), LabelsError>;
/// Extends `self` with `other`.
pub fn extend(&mut self, #[newtype] other: Self);
/// Returns the number of labels.
pub fn len(&self) -> usize;
/// Returns if the set of labels is empty.
pub fn is_empty(&self) -> bool;
/// Returns if the set of labels contains the provided `label`. Failure to
/// parse/validate the [`KeyValuePair`] will return `false`.
pub fn contains(&self, label: impl TryInto<KeyValuePair<LabelValue>>) -> bool;
/// Returns if the set of labels contains a label with the provided `key`.
/// Failure to parse/validate the [`Key`] will return `false`.
pub fn contains_key(&self, key: impl TryInto<Key>) -> bool;
/// Returns an [`Iterator`] over [`Labels`] yielding a reference to every [`Label`] contained within.
pub fn iter(&self) -> impl Iterator<Item = KeyValuePair<LabelValue>> + '_;
}
}
}
impl IntoIterator for Labels {
type Item = KeyValuePair<LabelValue>;
type IntoIter = <KeyValuePairs<LabelValue> as IntoIterator>::IntoIter;
/// Returns a consuming [`Iterator`] over [`Labels`] moving every [`Label`] out.
/// The [`Labels`] cannot be used again after calling this.
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn parse_insert() {
let mut labels = Labels::new();
labels
.parse_insert(("stackable.tech/managed-by", "stackablectl"))
.unwrap();
labels
.parse_insert(("stackable.tech/vendor", "Stackable"))
.unwrap();
assert_eq!(labels.len(), 2);
}
}