-
Notifications
You must be signed in to change notification settings - Fork 15
/
kubernetes.rs
1515 lines (1311 loc) · 45 KB
/
kubernetes.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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::error;
use bottlerocket_scalar_derive::Scalar;
use bottlerocket_string_impls_for::string_impls_for;
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
// Just need serde's Error in scope to get its trait methods
use bottlerocket_model_derive::model;
use serde::de::Error as _;
use serde_json::Value;
use snafu::{ensure, ResultExt};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
use std::net::IpAddr;
use crate::SingleLineString;
// Declare constant values usable by any type
const IMAGE_GC_THRESHOLD_MAX: i32 = 100;
const IMAGE_GC_THRESHOLD_MIN: i32 = 0;
/// KubernetesName represents a string that contains a valid Kubernetes resource name. It stores
/// the original string and makes it accessible through standard traits.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesName {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_NAME: Regex = Regex::new(r"^[0-9a-z.-]{1,253}$").unwrap();
}
impl TryFrom<&str> for KubernetesName {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_NAME.is_match(input),
error::PatternSnafu {
thing: "Kubernetes name",
pattern: KUBERNETES_NAME.clone(),
input
}
);
Ok(KubernetesName {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesName, "KubernetesName");
#[cfg(test)]
mod test_kubernetes_name {
use super::KubernetesName;
use std::convert::TryFrom;
#[test]
fn good_names() {
for ok in &["howdy", "42", "18-eighteen."] {
KubernetesName::try_from(*ok).unwrap();
}
}
#[test]
fn bad_names() {
for err in &["", "HOWDY", "@", "hi/there", &"a".repeat(254)] {
KubernetesName::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesLabelKey represents a string that contains a valid Kubernetes label key. It stores
/// the original string and makes it accessible through standard traits.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesLabelKey {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_LABEL_KEY: Regex = Regex::new(
r"(?x)^
( # optional prefix
[[:alnum:].-]{1,253}/ # DNS label characters followed by slash
)?
[[:alnum:]] # at least one alphanumeric
(
([[:alnum:]._-]{0,61})? # more characters allowed in middle
[[:alnum:]] # have to end with alphanumeric
)?
$"
)
.unwrap();
}
impl TryFrom<&str> for KubernetesLabelKey {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_LABEL_KEY.is_match(input),
error::BigPatternSnafu {
thing: "Kubernetes label key",
input
}
);
Ok(KubernetesLabelKey {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesLabelKey, "KubernetesLabelKey");
#[cfg(test)]
mod test_kubernetes_label_key {
use super::KubernetesLabelKey;
use std::convert::TryFrom;
#[test]
fn good_keys() {
for ok in &[
"no-prefix",
"have.a/prefix",
"more-chars_here.now",
&"a".repeat(63),
&format!("{}/{}", "a".repeat(253), "name"),
] {
KubernetesLabelKey::try_from(*ok).unwrap();
}
}
#[test]
fn bad_keys() {
for err in &[
".bad",
"bad.",
&"a".repeat(64),
&format!("{}/{}", "a".repeat(254), "name"),
] {
KubernetesLabelKey::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesLabelValue represents a string that contains a valid Kubernetes label value. It
/// stores the original string and makes it accessible through standard traits.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesLabelValue {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_LABEL_VALUE: Regex = Regex::new(
r"(?x)
^$ | # may be empty, or:
^
[[:alnum:]] # at least one alphanumeric
(
([[:alnum:]._-]{0,61})? # more characters allowed in middle
[[:alnum:]] # have to end with alphanumeric
)?
$
"
)
.unwrap();
}
impl TryFrom<&str> for KubernetesLabelValue {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_LABEL_VALUE.is_match(input),
error::BigPatternSnafu {
thing: "Kubernetes label value",
input
}
);
Ok(KubernetesLabelValue {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesLabelValue, "KubernetesLabelValue");
#[cfg(test)]
mod test_kubernetes_label_value {
use super::KubernetesLabelValue;
use std::convert::TryFrom;
#[test]
fn good_values() {
for ok in &["", "more-chars_here.now", &"a".repeat(63)] {
KubernetesLabelValue::try_from(*ok).unwrap();
}
}
#[test]
fn bad_values() {
for err in &[".bad", "bad.", &"a".repeat(64)] {
KubernetesLabelValue::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesTaintValue represents a string that contains a valid Kubernetes taint value, which is
/// like a label value, plus a colon, plus an "effect". It stores the original string and makes it
/// accessible through standard traits.
///
/// Note: Kubelet won't launch if you specify an effect it doesn't know about, but we don't want to
/// gatekeep all possible values, so be careful.
// Note: couldn't find an exact spec for this. Cobbling things together, and guessing a bit as to
// the syntax of the effect.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set
// https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesTaintValue {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_TAINT_VALUE: Regex = Regex::new(
r"(?x)^
(
[[:alnum:]] # values have to start with alphanumeric if they're specified
(
([[:alnum:]._-]{0,61})? # more characters allowed in middle
[[:alnum:]] # values have to end with alphanumeric
)? # only the first alphanumeric is required, further chars optional
)? # the taint value is optional
: # separate the taint value from the effect
[[:alnum:]]{1,253} # effect
$"
)
.unwrap();
}
impl TryFrom<&str> for KubernetesTaintValue {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_TAINT_VALUE.is_match(input),
error::BigPatternSnafu {
thing: "Kubernetes taint value",
input
}
);
Ok(KubernetesTaintValue {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesTaintValue, "KubernetesTaintValue");
#[cfg(test)]
mod test_kubernetes_taint_value {
use super::KubernetesTaintValue;
use std::convert::TryFrom;
#[test]
fn good_values() {
// All the examples from the docs linked above
for ok in &[
"value:NoSchedule",
"value:PreferNoSchedule",
"value:NoExecute",
":NoSchedule",
"a:NoSchedule",
"a-b:NoSchedule",
] {
KubernetesTaintValue::try_from(*ok).unwrap();
}
}
#[test]
fn bad_values() {
for err in &[
".bad",
"bad.",
&"a".repeat(254),
"value:",
":",
"-a:NoSchedule",
"a-:NoSchedule",
] {
KubernetesTaintValue::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesClusterName represents a string that contains a valid Kubernetes cluster name. It
/// stores the original string and makes it accessible through standard traits.
// Note: I was unable to find the rules for cluster naming. We know they have to fit into label
// values, because of the common cluster-name label, but they also can't be empty. This combines
// those two characteristics into a new type, until we find an explicit syntax.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesClusterName {
inner: String,
}
impl TryFrom<&str> for KubernetesClusterName {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
!input.is_empty(),
error::InvalidClusterNameSnafu {
name: input,
msg: "must not be empty"
}
);
ensure!(
KubernetesLabelValue::try_from(input).is_ok(),
error::InvalidClusterNameSnafu {
name: input,
msg: "cluster names must be valid Kubernetes label values"
}
);
Ok(KubernetesClusterName {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesClusterName, "KubernetesClusterName");
#[cfg(test)]
mod test_kubernetes_cluster_name {
use super::KubernetesClusterName;
use std::convert::TryFrom;
#[test]
fn good_cluster_names() {
for ok in &["more-chars_here.now", &"a".repeat(63)] {
KubernetesClusterName::try_from(*ok).unwrap();
}
}
#[test]
fn bad_values() {
for err in &["", ".bad", "bad.", &"a".repeat(64)] {
KubernetesClusterName::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesAuthenticationMode represents a string that is a valid authentication mode for the
/// kubelet. It stores the original string and makes it accessible through standard traits.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesAuthenticationMode {
inner: String,
}
impl TryFrom<&str> for KubernetesAuthenticationMode {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, error::Error> {
ensure!(
matches!(input, "aws" | "tls"),
error::InvalidAuthenticationModeSnafu { input }
);
Ok(KubernetesAuthenticationMode {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesAuthenticationMode, "KubernetesAuthenticationMode");
#[cfg(test)]
mod test_kubernetes_authentication_mode {
use super::KubernetesAuthenticationMode;
use std::convert::TryFrom;
#[test]
fn good_modes() {
for ok in &["aws", "tls"] {
KubernetesAuthenticationMode::try_from(*ok).unwrap();
}
}
#[test]
fn bad_modes() {
for err in &["", "anonymous"] {
KubernetesAuthenticationMode::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesBootstrapToken represents a string that is a valid bootstrap token for Kubernetes.
/// It stores the original string and makes it accessible through standard traits.
// https://kubernetes.io/docs/reference/access-authn-authz/bootstrap-tokens/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesBootstrapToken {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_BOOTSTRAP_TOKEN: Regex =
Regex::new(r"^[a-z0-9]{6}\.[a-z0-9]{16}$").unwrap();
}
impl TryFrom<&str> for KubernetesBootstrapToken {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_BOOTSTRAP_TOKEN.is_match(input),
error::PatternSnafu {
thing: "Kubernetes bootstrap token",
pattern: KUBERNETES_BOOTSTRAP_TOKEN.clone(),
input
}
);
Ok(KubernetesBootstrapToken {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesBootstrapToken, "KubernetesBootstrapToken");
#[cfg(test)]
mod test_kubernetes_bootstrap_token {
use super::KubernetesBootstrapToken;
use std::convert::TryFrom;
#[test]
fn good_tokens() {
for ok in &["abcdef.0123456789abcdef", "07401b.f395accd246ae52d"] {
KubernetesBootstrapToken::try_from(*ok).unwrap();
}
}
#[test]
fn bad_names() {
for err in &["", "ABCDEF.0123456789ABCDEF", "secret", &"a".repeat(23)] {
KubernetesBootstrapToken::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesEvictionKey represents a string that contains a valid Kubernetes eviction key.
/// https://kubernetes.io/docs/tasks/administer-cluster/out-of-resource/
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, Scalar)]
#[serde(rename_all = "lowercase")]
pub enum KubernetesEvictionKey {
#[serde(rename = "memory.available")]
MemoryAvailable,
#[serde(rename = "nodefs.available")]
NodefsAvailable,
#[serde(rename = "nodefs.inodesFree")]
NodefsInodesFree,
#[serde(rename = "imagefs.available")]
ImagefsAvailable,
#[serde(rename = "imagefs.inodesFree")]
ImagefsInodesFree,
#[serde(rename = "pid.available")]
PidAvailable,
}
#[cfg(test)]
mod test_kubernetes_eviction_key {
use super::KubernetesEvictionKey;
use std::convert::TryFrom;
#[test]
fn good_eviction_key() {
for ok in &[
"memory.available",
"nodefs.available",
"nodefs.inodesFree",
"imagefs.available",
"imagefs.inodesFree",
"pid.available",
] {
KubernetesEvictionKey::try_from(*ok).unwrap();
}
}
#[test]
fn bad_eviction_key() {
for err in &["", "storage.available", ".bad", "bad.", &"a".repeat(64)] {
KubernetesEvictionKey::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesThresholdValue represents a string that contains a valid kubernetes threshold value.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesThresholdValue {
inner: String,
}
// Regular expression of Kubernetes quantity. i.e. 128974848, 129e6, 129M, 123Mi
lazy_static! {
pub(crate) static ref KUBERNETES_QUANTITY: Regex = Regex::new(
r"(?x)
# format1 for scientific notations (e.g. 123e4) or:
^([+-]?[0-9.]+)((e)?[0-9]*)$ |
# format2 for values with unit suffixes [EPTGMK] and [EiPiTiGiMiKi] (e.g. 100K or 100Ki),
# or no units (e.g. 100) or:
^([+-]?[0-9.]+)((E|P|T|G|M|K)i?)?$ |
# format3 for values with unit suffixes [numk] (e.g. 100n 1000k)
^([+-]?[0-9.]+)(n|u|m|k)?$
"
)
.unwrap();
}
impl TryFrom<&str> for KubernetesThresholdValue {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
if let Some(stripped) = input.strip_suffix('%') {
let input_f32 = stripped
.parse::<f32>()
.context(error::InvalidPercentageSnafu { input })?;
ensure!(
(0.0..100.0).contains(&input_f32),
error::InvalidThresholdPercentageSnafu { input }
);
} else {
ensure!(
KUBERNETES_QUANTITY.is_match(input),
error::PatternSnafu {
thing: "Kubernetes quantity",
pattern: KUBERNETES_QUANTITY.clone(),
input
}
);
}
Ok(KubernetesThresholdValue {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesThresholdValue, "KubernetesThresholdValue");
#[cfg(test)]
mod test_kubernetes_threshold_value {
use super::KubernetesThresholdValue;
use std::convert::TryFrom;
#[test]
fn good_kubernetes_threshold_value() {
for ok in &[
"10%", "129e6", "10Mi", "1024M", "1Gi", "120Ki", "1Ti", "1000n", "100m",
] {
KubernetesThresholdValue::try_from(*ok).unwrap();
}
}
#[test]
fn bad_kubernetes_threshold_value() {
for err in &[
"",
"anything%",
"12ki",
"100e23m",
"1100KTi",
"100Kiii",
"1000i",
&"a".repeat(64),
] {
KubernetesThresholdValue::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesReservedResourceKey represents a string that contains a valid Kubernetes kubeReserved
/// and systemReserved resources i.e. cpu, memory.
/// https://kubernetes.io/docs/tasks/administer-cluster/reserve-compute-resources/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesReservedResourceKey {
inner: String,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ReservedResources {
Cpu,
Memory,
#[serde(rename = "ephemeral-storage")]
EphemeralStorage,
}
impl TryFrom<&str> for KubernetesReservedResourceKey {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
serde_plain::from_str::<ReservedResources>(input).context(
error::InvalidPlainValueSnafu {
field: "Reserved sources key",
},
)?;
Ok(KubernetesReservedResourceKey {
inner: input.to_string(),
})
}
}
string_impls_for!(
KubernetesReservedResourceKey,
"KubernetesReservedResourceKey"
);
#[cfg(test)]
mod test_reserved_resources_key {
use super::KubernetesReservedResourceKey;
use std::convert::TryFrom;
#[test]
fn good_reserved_resources_key() {
for ok in &["cpu", "memory", "ephemeral-storage"] {
KubernetesReservedResourceKey::try_from(*ok).unwrap();
}
}
#[test]
fn bad_reserved_resources_key() {
for err in &["", "cpa", ".bad", "bad.", &"a".repeat(64)] {
KubernetesReservedResourceKey::try_from(*err).unwrap_err();
}
}
}
/// // =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesQuantityValue represents a string that contains a valid kubernetes quantity value.
/// https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesQuantityValue {
inner: String,
}
impl TryFrom<&str> for KubernetesQuantityValue {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
KUBERNETES_QUANTITY.is_match(input),
error::PatternSnafu {
thing: "Kubernetes quantity",
pattern: KUBERNETES_QUANTITY.clone(),
input
}
);
Ok(KubernetesQuantityValue {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesQuantityValue, "KubernetesQuantityValue");
#[cfg(test)]
mod test_kubernetes_quantity_value {
use super::KubernetesQuantityValue;
use std::convert::TryFrom;
#[test]
fn good_kubernetes_quantity_value() {
for ok in &[
"129e6", "10Mi", "1024M", "1Gi", "120Ki", "1Ti", "1000n", "100m",
] {
KubernetesQuantityValue::try_from(*ok).unwrap();
}
}
#[test]
fn bad_kubernetes_quantity_value() {
for err in &[
"",
"12%",
"anything%",
"12ki",
"100e23m",
"1100KTi",
"100Kiii",
"1000i",
&"a".repeat(64),
] {
KubernetesQuantityValue::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesCloudProvider represents a string that is a valid cloud provider for the
/// kubelet. It stores the original string and makes it accessible through standard traits.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesCloudProvider {
inner: String,
}
impl TryFrom<&str> for KubernetesCloudProvider {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, error::Error> {
// Kubelet expects the empty string to be double-quoted when be passed to `--cloud-provider`
let cloud_provider = if input.is_empty() { "\"\"" } else { input };
ensure!(
matches!(cloud_provider, "aws" | "external" | "\"\""),
error::InvalidCloudProviderSnafu {
input: cloud_provider
}
);
Ok(KubernetesCloudProvider {
inner: cloud_provider.to_string(),
})
}
}
string_impls_for!(KubernetesCloudProvider, "KubernetesCloudProvider");
#[cfg(test)]
mod test_kubernetes_cloud_provider {
use super::KubernetesCloudProvider;
use std::convert::TryFrom;
#[test]
fn allowed_providers() {
for ok in &["aws", "external", "\"\"", ""] {
KubernetesCloudProvider::try_from(*ok).unwrap();
}
}
#[test]
fn disallowed_providers() {
for err in &["internal"] {
KubernetesCloudProvider::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// CpuManagerPolicy represents a string that contains a valid cpu management policy. Default: none
/// https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct CpuManagerPolicy {
inner: String,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ValidCpuManagerPolicy {
#[serde(alias = "Static")]
Static,
#[serde(alias = "None")]
None,
}
impl TryFrom<&str> for CpuManagerPolicy {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
serde_plain::from_str::<ValidCpuManagerPolicy>(input)
.context(error::InvalidCpuManagerPolicySnafu { input })?;
Ok(CpuManagerPolicy {
inner: input.to_string(),
})
}
}
string_impls_for!(CpuManagerPolicy, "CpuManagerPolicy");
#[cfg(test)]
mod test_cpu_manager_policy {
use super::CpuManagerPolicy;
use std::convert::TryFrom;
#[test]
fn good_cpu_manager_policy() {
for ok in &["Static", "static", "None", "none"] {
CpuManagerPolicy::try_from(*ok).unwrap();
}
}
#[test]
fn bad_cpu_manager_policy() {
for err in &["", "bad", "100", &"a".repeat(64)] {
CpuManagerPolicy::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// KubernetesDurationValue represents a string that contains a valid Kubernetes duration value.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KubernetesDurationValue {
inner: String,
}
lazy_static! {
pub(crate) static ref KUBERNETES_DURATION_VALUE: Regex = Regex::new(
r"^(([0-9]+\.)?[0-9]+h)?(([0-9]+\.)?[0-9]+m)?(([0-9]+\.)?[0-9]+s)?(([0-9]+\.)?[0-9]+ms)?$"
)
.unwrap();
}
impl TryFrom<&str> for KubernetesDurationValue {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
ensure!(
!input.is_empty(),
error::InvalidKubernetesDurationValueSnafu { input }
);
ensure!(
KUBERNETES_DURATION_VALUE.is_match(input),
error::InvalidKubernetesDurationValueSnafu { input }
);
Ok(KubernetesDurationValue {
inner: input.to_string(),
})
}
}
string_impls_for!(KubernetesDurationValue, "KubernetesDurationValue");
#[cfg(test)]
mod test_kubernetes_duration_value {
use super::KubernetesDurationValue;
use std::convert::TryFrom;
#[test]
fn good_tokens() {
for ok in &[
"9ms",
"99s",
"20m",
"1h",
"1h2m3s10ms",
"4m5s10ms",
"2h3s10ms",
"1.5h3.5m",
] {
KubernetesDurationValue::try_from(*ok).unwrap();
}
}
#[test]
fn bad_names() {
for err in &[
"",
"100",
"...3ms",
"1..5s",
"ten second",
"1m2h",
"9ns",
&"a".repeat(23),
] {
KubernetesDurationValue::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// TopologyManagerScope represents a string that contains a valid topology management scope. Default: container
/// https://kubernetes.io/docs/tasks/administer-cluster/topology-manager/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct TopologyManagerScope {
inner: String,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ValidTopologyManagerScope {
Container,
Pod,
}
impl TryFrom<&str> for TopologyManagerScope {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
serde_plain::from_str::<ValidTopologyManagerScope>(input)
.context(error::InvalidTopologyManagerScopeSnafu { input })?;
Ok(TopologyManagerScope {
inner: input.to_string(),
})
}
}
string_impls_for!(TopologyManagerScope, "TopologyManagerScope");
#[cfg(test)]
mod test_topology_manager_scope {
use super::TopologyManagerScope;
use std::convert::TryFrom;
#[test]
fn good_topology_manager_scope() {
for ok in &["container", "pod"] {
TopologyManagerScope::try_from(*ok).unwrap();
}
}
#[test]
fn bad_topology_manager_scope() {
for err in &["", "bad", "100", &"a".repeat(64)] {
TopologyManagerScope::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// TopologyManagerPolicy represents a string that contains a valid topology management policy. Default: none
/// https://kubernetes.io/docs/tasks/administer-cluster/topology-manager/
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct TopologyManagerPolicy {
inner: String,
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Deserialize)]
#[serde(rename_all = "lowercase")]
enum ValidTopologyManagerPolicy {
None,
Restricted,
#[serde(rename = "best-effort")]
BestEffort,
#[serde(rename = "single-numa-node")]
SingleNumaNode,
}
impl TryFrom<&str> for TopologyManagerPolicy {
type Error = error::Error;
fn try_from(input: &str) -> Result<Self, Self::Error> {
serde_plain::from_str::<ValidTopologyManagerPolicy>(input)
.context(error::InvalidTopologyManagerPolicySnafu { input })?;
Ok(TopologyManagerPolicy {
inner: input.to_string(),
})
}
}
string_impls_for!(TopologyManagerPolicy, "TopologyManagerPolicy");
#[cfg(test)]
mod test_topology_manager_policy {
use super::TopologyManagerPolicy;
use std::convert::TryFrom;
#[test]
fn good_topology_manager_policy() {
for ok in &["none", "restricted", "best-effort", "single-numa-node"] {
TopologyManagerPolicy::try_from(*ok).unwrap();
}
}
#[test]
fn bad_topology_manager_policy() {
for err in &["", "bad", "100", &"a".repeat(64)] {
TopologyManagerPolicy::try_from(*err).unwrap_err();
}
}
}
// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^=
/// This enum is used by `IntegerPercent` to "remember" how the number was deserialized.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
enum IntegerPercentMode {
Number,
String,