Skip to main content

k8_metadata_core/
metadata.rs

1use std::collections::HashMap;
2use std::collections::BTreeMap;
3use std::marker::PhantomData;
4use std::fmt;
5
6use http::Uri;
7use serde::de::Deserializer;
8use serde::Deserialize;
9use serde::Serialize;
10
11use crate::options::prefix_uri;
12use crate::options::ListOptions;
13use crate::Spec;
14
15pub const DEFAULT_NS: &'static str = "default";
16pub const TYPE_OPAQUE: &'static str = "Opaque";
17
18pub trait K8Meta<S> where S: Spec {
19
20    // return uri for given host name
21    fn item_uri(&self,host_name: &str) -> Uri;
22}
23
24pub trait LabelProvider: Sized {
25
26
27    fn set_label_map(self, labels: HashMap<String,String>) -> Self;
28
29    /// helper for setting list of labels
30    fn set_labels<T: ToString>(self, labels: Vec<(T, T)>) -> Self {
31        let mut label_map = HashMap::new();
32        for (key, value) in labels {
33            label_map.insert(key.to_string(), value.to_string());
34        }
35        self.set_label_map(label_map)
36    }
37
38}
39
40/// metadata associated with object when returned
41/// here name and namespace must be populated
42#[derive(Deserialize, Serialize, PartialEq, Debug, Default, Clone)]
43#[serde(rename_all = "camelCase",default)]
44pub struct ObjectMeta {
45    // mandatory fields
46    pub name: String,
47    pub namespace: String,
48    pub uid: String,
49    pub self_link: String,
50    pub creation_timestamp: String,
51    pub generation: Option<i32>,
52    pub resource_version: String,
53    // optional
54    pub cluster_name: Option<String>,
55    pub deletion_timestamp: Option<String>,
56    pub deletion_grace_period_seconds: Option<u32>,
57    pub labels: HashMap<String, String>,
58    pub owner_references: Vec<OwnerReferences>,
59}
60
61impl LabelProvider for ObjectMeta {
62
63    fn set_label_map(mut self, labels: HashMap<String,String>) -> Self {
64        self.labels = labels;
65        self
66    }
67}
68
69
70impl ObjectMeta {
71
72    pub fn new<S>(name: S,name_space: S) -> Self 
73    where S: Into<String> {
74        Self {
75            name: name.into(),
76            namespace: name_space.into(),
77            ..Default::default()
78        }
79    }
80
81    /// provide builder pattern setter
82    pub fn set_labels<T: Into<String>>(mut self, labels: Vec<(T, T)>) -> Self {
83        let mut label_map = HashMap::new();
84        for (key, value) in labels {
85            label_map.insert(key.into(), value.into());
86        }
87        self.labels = label_map;
88        self
89    }
90
91    /// create with name and default namespace
92    pub fn named<S>(name: S) -> Self where S: Into<String>{
93        Self {
94            name: name.into(),
95            ..Default::default()
96        }
97    }
98
99    /// create owner references point to this metadata
100    /// if name or uid doesn't exists return none
101    pub fn make_owner_reference<S: Spec>(&self) -> OwnerReferences {
102           
103        OwnerReferences {
104            api_version: S::api_version(),
105            kind: S::kind(),
106            name: self.name.clone(),
107            uid: self.uid.clone(),
108            controller: Some(true),
109            ..Default::default()
110        }
111
112    }
113
114    pub fn namespace(&self) -> &str {
115        &self.namespace
116    }
117
118    /// create child references that points to this
119    pub fn make_child_input_metadata<S: Spec>(&self,childname: String) -> InputObjectMeta {
120
121        let mut owner_refs: Vec<OwnerReferences> = vec![];
122        owner_refs.push(self.make_owner_reference::<S>());
123
124        InputObjectMeta {
125            name: childname,
126            namespace: self.namespace().to_owned(),
127            owner_references: owner_refs,
128            ..Default::default()
129        }
130
131    }
132
133
134    pub fn as_input(&self) -> InputObjectMeta {
135        
136        InputObjectMeta {
137            name: self.name.clone(),
138            namespace: self.namespace.clone(),
139            ..Default::default()
140        }
141    }
142
143    pub fn as_item(&self) -> ItemMeta {
144        ItemMeta {
145            name: self.name.clone(),
146            namespace: self.namespace.clone(),
147        }
148    }
149
150    pub fn as_update(&self) -> UpdateItemMeta {
151        UpdateItemMeta {
152            name: self.name.clone(),
153            namespace: self.namespace.clone(),
154            resource_version: self.resource_version.clone()
155        }
156    }
157}
158
159
160
161#[derive(Deserialize, Serialize, Debug, Default, Clone)]
162#[serde(rename_all = "camelCase")]
163pub struct InputObjectMeta {
164    pub name: String,
165    pub labels: HashMap<String, String>,
166    pub namespace: String,
167    pub owner_references: Vec<OwnerReferences>,
168}
169
170impl LabelProvider for InputObjectMeta {
171
172    fn set_label_map(mut self, labels: HashMap<String,String>) -> Self {
173        self.labels = labels;
174        self
175    }
176}
177
178
179impl fmt::Display for InputObjectMeta {
180    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181        write!(f, "{}:{}",self.name,self.namespace)
182    }
183}
184
185impl <S>K8Meta<S> for InputObjectMeta where S: Spec {
186
187     fn item_uri(&self,host_name: &str) -> Uri {
188         
189         item_uri::<S>(
190            host_name,
191            &self.name,
192            &self.namespace,
193            None,
194        )
195     }
196}
197
198
199
200impl InputObjectMeta {
201    // shorthand to create just with name and metadata
202    pub fn named<S: Into<String>>(name: S, namespace: S) -> Self {
203        InputObjectMeta {
204            name: name.into(),
205            namespace: namespace.into(),
206            ..Default::default()
207        }
208    }
209}
210
211impl From<ObjectMeta> for InputObjectMeta {
212    fn from(meta: ObjectMeta) -> Self {
213        Self {
214            name: meta.name,
215            namespace: meta.namespace,
216            ..Default::default()
217        }
218    }
219}
220
221
222/// used for retrieving,updating and deleting item
223#[derive(Deserialize, Serialize, Debug, Default, Clone)]
224#[serde(rename_all = "camelCase")]
225pub struct ItemMeta {
226    pub name: String,
227    pub namespace: String,
228}
229
230
231impl From<ObjectMeta> for ItemMeta {
232    fn from(meta: ObjectMeta) -> Self {
233        Self {
234            name: meta.name,
235            namespace: meta.namespace
236        }
237    }
238}
239
240/// used for updating item
241#[derive(Deserialize, Serialize, Debug, Default, Clone)]
242#[serde(rename_all = "camelCase")]
243pub struct UpdateItemMeta {
244    pub name: String,
245    pub namespace: String,
246    pub resource_version: String,
247}
248
249
250impl From<ObjectMeta> for UpdateItemMeta {
251    fn from(meta: ObjectMeta) -> Self {
252        Self {
253            name: meta.name,
254            namespace: meta.namespace,
255            resource_version: meta.resource_version
256        }
257    }
258}
259
260
261
262#[derive(Deserialize, Serialize, Debug, Default, Clone, PartialEq)]
263#[serde(rename_all = "camelCase")]
264pub struct OwnerReferences {
265    pub api_version: String,
266    pub block_owner_deletion: Option<bool>,
267    pub controller: Option<bool>,
268    pub kind: String,
269    pub name: String,
270    pub uid: String,
271}
272
273/// items uri
274pub fn item_uri<S>(host: &str, name: &str, namespace: &str, sub_resource: Option<&str>) -> Uri
275where
276    S: Spec + Sized,
277{
278    let crd = S::metadata();
279    let prefix = prefix_uri(crd, host, namespace, None);
280    let uri_value = format!("{}/{}{}", prefix, name, sub_resource.unwrap_or(""));
281    let uri: Uri = uri_value.parse().unwrap();
282    uri
283}
284
285/// items uri
286pub fn items_uri<S>(host: &str, namespace: &str, list_options: Option<&ListOptions>) -> Uri
287where
288    S: Spec,
289{
290    let crd = S::metadata();
291    let uri_value = prefix_uri(crd, host, namespace, list_options);
292    let uri: Uri = uri_value.parse().unwrap();
293    uri
294}
295
296#[derive(Deserialize, Debug, Eq, PartialEq, Clone)]
297pub enum StatusEnum {
298    SUCCESS,
299    FAILURE,
300}
301
302impl DeserializeWith for StatusEnum {
303    fn deserialize_with<'de, D>(de: D) -> Result<Self, D::Error>
304    where
305        D: Deserializer<'de>,
306    {
307        let s = String::deserialize(de)?;
308
309        match s.as_ref() {
310            "Success" => Ok(StatusEnum::SUCCESS),
311            "Failure" => Ok(StatusEnum::FAILURE),
312            _ => Err(serde::de::Error::custom(
313                "error trying to deserialize status type",
314            )),
315        }
316    }
317}
318
319#[derive(Deserialize, Debug, Clone)]
320#[serde(rename_all = "camelCase")]
321pub struct K8Status {
322    pub api_version: String,
323    pub code: Option<u16>,
324    pub details: Option<StatusDetails>,
325    pub kind: String,
326    pub message: Option<String>,
327    pub reason: Option<String>,
328    #[serde(deserialize_with = "StatusEnum::deserialize_with")]
329    pub status: StatusEnum,
330}
331
332#[derive(Deserialize, Serialize, Debug, Clone)]
333pub struct StatusDetails {
334    pub name: String,
335    pub group: Option<String>,
336    pub kind: String,
337    pub uid: String,
338}
339
340#[derive(Deserialize, Serialize, Debug, Default, Clone)]
341#[serde(rename_all = "camelCase")]
342pub struct K8Obj<S,P> {
343    pub api_version: String,
344    pub kind: String,
345    pub metadata: ObjectMeta,
346    pub spec: S,
347    pub status: Option<P>,
348    #[serde(default)]
349    pub data: Option<BTreeMap<String, String>>,
350}
351
352
353
354
355
356impl <S> K8Obj<S,S::Status>
357    where S: Spec + Default,
358        S::Status: Default
359{
360
361    #[allow(dead_code)]
362    pub fn new<N>(name: N,spec: S) -> Self where N: Into<String> {
363        Self {
364            api_version: S::api_version(),
365            kind: S::kind(),
366            metadata: ObjectMeta::named(name),
367            spec,
368            status: None,
369            ..Default::default()
370        }
371    }
372
373    #[allow(dead_code)]
374    pub fn set_status(mut self,status: S::Status) -> Self {
375        self.status = Some(status);
376        self
377    }
378
379    pub fn as_status_update(&self,status: S::Status) -> UpdateK8ObjStatus<S,S::Status>  {
380
381        UpdateK8ObjStatus {
382            api_version: S::api_version(),
383            kind: S::kind(),
384            metadata: self.metadata.as_update(),
385            status,
386            ..Default::default()
387        }
388    }
389}
390
391impl <S> K8Obj<S,S::Status>
392    where S: Spec + Default + Clone,
393{
394
395    pub fn as_input(&self) -> InputK8Obj<S> {
396        K8SpecObj {
397            api_version: self.api_version.clone(),
398            kind: self.kind.clone(),
399            metadata: self.metadata.as_input(),
400            spec: self.spec.clone(),
401            ..Default::default()
402        }
403    }
404
405}
406
407/// For creating, only need spec
408#[derive(Deserialize, Serialize, Debug, Default, Clone)]
409#[serde(rename_all = "camelCase")]
410pub struct K8SpecObj<S,M> {
411    pub api_version: String,
412    pub kind: String,
413    pub metadata: M,
414    pub spec: S,
415    #[serde(default)]
416    pub data: BTreeMap<String, String>,
417}
418
419impl <S,M> K8SpecObj<S,M> 
420    where S: Spec + Default
421{
422    pub fn new(spec: S,metadata: M) -> Self where M: Default {
423        Self {
424            api_version: S::api_version(),
425            kind: S::kind(),
426            metadata,
427            spec,
428            ..Default::default()
429        }
430    }
431}
432
433pub type InputK8Obj<S> = K8SpecObj<S,InputObjectMeta>;
434pub type UpdateK8Obj<S> = K8SpecObj<S,ItemMeta>;
435
436
437/// Used for updating k8obj
438#[derive(Deserialize, Serialize, Debug, Default, Clone)]
439#[serde(rename_all = "camelCase")]
440pub struct UpdateK8ObjStatus<S,P> {
441    pub api_version: String,
442    pub kind: String,
443    pub metadata: UpdateItemMeta,
444    pub status: P,
445    pub data: PhantomData<S>
446}
447
448
449impl <S>UpdateK8ObjStatus<S,S::Status> 
450    where S: Spec + Default,
451        S::Status: Default
452{
453
454    pub fn new(status: S::Status, metadata: UpdateItemMeta) -> Self {
455        Self {
456            api_version: S::api_version(),
457            kind: S::kind(),
458            metadata,
459            status,
460            ..Default::default()
461        }
462    }
463}
464
465
466impl <S>From<UpdateK8Obj<S>> for InputK8Obj<S> where S: Default {
467    fn from(update: UpdateK8Obj<S>) -> Self {
468        Self {
469            api_version: update.api_version,
470            kind: update.kind,
471            metadata: update.metadata.into(),
472            spec: update.spec,
473            ..Default::default()
474        }
475    }
476}
477
478
479
480impl From<ItemMeta> for InputObjectMeta {
481    fn from(update: ItemMeta) -> Self {
482        Self {
483            name: update.name,
484            namespace: update.namespace,
485            ..Default::default()
486        }
487    }
488}
489
490/// name is optional for template
491#[derive(Deserialize, Serialize, Debug, Default, Clone)]
492#[serde(rename_all = "camelCase",default)]
493pub struct TemplateMeta {
494    pub name:   Option<String>,
495    pub creation_timestamp: Option<String>,
496    pub labels: HashMap<String, String>,
497}
498
499
500impl LabelProvider for TemplateMeta {
501
502    fn set_label_map(mut self, labels: HashMap<String,String>) -> Self {
503        self.labels = labels;
504        self
505    }
506}
507
508impl TemplateMeta {
509
510    /// create with name and default namespace
511    pub fn named<S>(name: S) -> Self where S: Into<String>{
512        Self {
513            name: Some(name.into()),
514            ..Default::default()
515        }
516    }
517}
518
519
520
521#[derive(Deserialize, Serialize, Debug, Default, Clone)]
522#[serde(rename_all = "camelCase")]
523pub struct TemplateSpec<S> {
524    pub metadata: Option<TemplateMeta>,
525    pub spec: S,
526}
527
528impl <S>TemplateSpec<S> {
529    pub fn new(spec: S) -> Self {
530        TemplateSpec {
531            metadata: None,
532            spec
533        }
534    }
535}
536
537#[derive(Deserialize, Serialize, Debug, Clone)]
538#[serde(rename_all = "camelCase")]
539pub struct K8List<S, P> {
540    pub api_version: String,
541    pub items: Vec<K8Obj<S, P>>,
542    pub kind: String,
543    pub metadata: ListMetadata 
544}
545
546impl <S> K8List<S,S::Status> where S: Spec {
547
548    #[allow(dead_code)]
549    pub fn new() -> Self {
550        K8List {
551            api_version: S::api_version(),
552            items: vec![],
553            kind: S::kind(),
554            metadata: ListMetadata {
555                _continue: None,
556                resource_version: S::api_version(),
557                self_link: "".to_owned()
558            }
559        }
560    }
561}
562
563
564
565pub trait DeserializeWith: Sized {
566    fn deserialize_with<'de, D>(de: D) -> Result<Self, D::Error>
567    where
568        D: Deserializer<'de>;
569}
570
571#[derive(Deserialize, Debug, Clone)]
572#[serde(tag = "type", content = "object")]
573pub enum K8Watch<Spec, Status> {
574    ADDED(K8Obj<Spec, Status>),
575    MODIFIED(K8Obj<Spec, Status>),
576    DELETED(K8Obj<Spec, Status>),
577}
578
579
580
581#[derive(Deserialize, Serialize, Debug, Clone)]
582#[serde(rename_all = "camelCase")]
583pub struct ListMetadata {
584    pub _continue: Option<String>,
585    pub resource_version: String,
586    pub self_link: String,
587}
588
589#[derive(Deserialize, Serialize, Default, Debug, PartialEq, Clone)]
590#[serde(rename_all = "camelCase")]
591pub struct LabelSelector {
592    pub match_labels: HashMap<String, String>,
593}
594
595impl LabelSelector {
596    pub fn new_labels<T: Into<String>>(labels: Vec<(T, T)>) -> Self {
597        let mut match_labels = HashMap::new();
598        for (key, value) in labels {
599            match_labels.insert(key.into(), value.into());
600        }
601        LabelSelector { match_labels }
602    }
603}
604
605#[derive(Deserialize, Serialize, Default, Debug, Clone)]
606#[serde(rename_all = "camelCase")]
607pub struct Env {
608    pub name: String,
609    pub value: Option<String>,
610    pub value_from: Option<EnvVarSource>
611}
612
613impl Env {
614    pub fn key_value<T: Into<String>>(name: T, value: T) -> Self {
615        Env {
616            name: name.into(),
617            value: Some(value.into()),
618            value_from: None
619        }
620    }
621
622    pub fn key_field_ref<T: Into<String>>(name: T,field_path: T) -> Self {
623        Env {
624            name: name.into(),
625            value: None,
626            value_from: Some(EnvVarSource{
627                field_ref: Some(ObjectFieldSelector{ field_path: field_path.into()})
628            })
629        }
630    }
631}
632
633#[derive(Deserialize, Serialize, Default, Debug, Clone)]
634#[serde(rename_all = "camelCase")]
635pub struct EnvVarSource {
636    field_ref: Option<ObjectFieldSelector>
637}
638
639#[derive(Deserialize, Serialize, Default, Debug, Clone)]
640#[serde(rename_all = "camelCase")]
641pub struct ObjectFieldSelector {
642    pub field_path: String
643}
644
645#[cfg(test)]
646mod test {
647
648    use super::Env;
649    use super::ObjectMeta;
650
651    #[test]
652    fn test_metadata_label() {
653        let metadata = ObjectMeta::default().set_labels(vec![("app".to_owned(), "test".to_owned())]);
654
655        let maps = metadata.labels;
656        assert_eq!(maps.len(), 1);
657        assert_eq!(maps.get("app").unwrap(), "test");
658    }
659
660    #[test]
661    fn test_env() {
662        let env = Env::key_value("lang", "english");
663        assert_eq!(env.name, "lang");
664        assert_eq!(env.value, Some("english".to_owned()));
665    }
666
667}