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
use std::fmt::Debug;
use std::fmt::Display;
use std::io::Error as IoError;
use std::sync::Arc;

use async_trait::async_trait;
use futures_util::future::ready;
use futures_util::future::FutureExt;
use futures_util::stream::once;
use futures_util::stream::BoxStream;
use futures_util::stream::StreamExt;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json;
use serde_json::Error as SerdeJsonError;
use serde_json::Value;
use tracing::debug;
use tracing::trace;

use k8_diff::Changes;
use k8_diff::Diff;
use k8_diff::DiffError;
use k8_obj_metadata::InputK8Obj;
use k8_obj_metadata::K8List;
use k8_obj_metadata::K8Meta;
use k8_obj_metadata::K8Obj;
use k8_obj_metadata::K8Status;
use k8_obj_metadata::K8Watch;
use k8_obj_metadata::Spec;
use k8_obj_metadata::UpdateK8ObjStatus;

use crate::ApplyResult;
use crate::DiffSpec;

#[derive(Clone)]
pub enum NameSpace {
    All,
    Named(String),
}

impl NameSpace {
    pub fn is_all(&self) -> bool {
        match self {
            Self::All => true,
            _ => false,
        }
    }

    pub fn named(&self) -> &str {
        match self {
            Self::All => "all",
            Self::Named(name) => &name,
        }
    }
}

impl From<String> for NameSpace {
    fn from(namespace: String) -> Self {
        NameSpace::Named(namespace)
    }
}

impl From<&str> for NameSpace {
    fn from(namespace: &str) -> Self {
        NameSpace::Named(namespace.to_owned())
    }
}

#[derive(Default, Clone)]
pub struct ListArg {
    pub field_selector: Option<String>,
    pub include_uninitialized: Option<bool>,
    pub label_selector: Option<String>,
}

/// trait for metadata client
pub trait MetadataClientError: Debug + Display {
    /// is not founded
    fn not_founded(&self) -> bool;

    // create new patch error
    fn patch_error() -> Self;
}

// For error mapping: see: https://doc.rust-lang.org/nightly/core/convert/trait.From.html

pub type TokenStreamResult<S, E> = Result<Vec<Result<K8Watch<S>, E>>, E>;

pub fn as_token_stream_result<S, E>(events: Vec<K8Watch<S>>) -> TokenStreamResult<S, E>
where
    S: Spec,
    S::Status: Serialize + DeserializeOwned,
    S::Header: Serialize + DeserializeOwned,
{
    Ok(events.into_iter().map(|event| Ok(event)).collect())
}

#[async_trait]
pub trait MetadataClient: Send + Sync {
    type MetadataClientError: MetadataClientError
        + Send
        + Display
        + From<IoError>
        + From<DiffError>
        + From<SerdeJsonError>;

    /// retrieval a single item
    async fn retrieve_item<S, M>(
        &self,
        metadata: &M,
    ) -> Result<K8Obj<S>, Self::MetadataClientError>
    where
        S: Spec,
        M: K8Meta + Send + Sync;

    /// retrieve all items a single chunk
    /// this may cause client to hang if there are too many items
    async fn retrieve_items<S, N>(
        &self,
        namespace: N,
    ) -> Result<K8List<S>, Self::MetadataClientError>
    where
        S: Spec,
        N: Into<NameSpace> + Send + Sync,
    {
        self.retrieve_items_with_option(namespace, None).await
    }

    async fn retrieve_items_with_option<S, N>(
        &self,
        namespace: N,
        option: Option<ListArg>,
    ) -> Result<K8List<S>, Self::MetadataClientError>
    where
        S: Spec,
        N: Into<NameSpace> + Send + Sync;

    /// returns stream of items in chunks
    fn retrieve_items_in_chunks<'a, S, N>(
        self: Arc<Self>,
        namespace: N,
        limit: u32,
        option: Option<ListArg>,
    ) -> BoxStream<'a, K8List<S>>
    where
        S: Spec + 'static,
        N: Into<NameSpace> + Send + Sync + 'static;

    async fn delete_item<S, M>(&self, metadata: &M) -> Result<K8Status, Self::MetadataClientError>
    where
        S: Spec,
        M: K8Meta + Send + Sync;

    /// create new object
    async fn create_item<S>(
        &self,
        value: InputK8Obj<S>,
    ) -> Result<K8Obj<S>, Self::MetadataClientError>
    where
        S: Spec;

    /// apply object, this is similar to ```kubectl apply```
    /// for now, this doesn't do any optimization
    /// if object doesn't exist, it will be created
    /// if object exist, it will be patched by using strategic merge diff
    async fn apply<S>(
        &self,
        value: InputK8Obj<S>,
    ) -> Result<ApplyResult<S>, Self::MetadataClientError>
    where
        S: Spec,
        Self::MetadataClientError: From<serde_json::Error> + From<DiffError> + Send,
    {
        debug!("{}: applying '{}' changes", S::label(), value.metadata.name);
        trace!("{}: applying {:#?}", S::label(), value);
        match self.retrieve_item(&value.metadata).await {
            Ok(item) => {
                let mut old_spec: S = item.spec;
                old_spec.make_same(&value.spec);
                // we don't care about status
                let new_spec = serde_json::to_value(DiffSpec::from(value.spec.clone()))?;
                let old_spec = serde_json::to_value(DiffSpec::from(old_spec))?;
                let diff = old_spec.diff(&new_spec)?;
                match diff {
                    Diff::None => {
                        debug!("{}: no diff detected, doing nothing", S::label());
                        Ok(ApplyResult::None)
                    }
                    Diff::Patch(p) => {
                        let json_diff = serde_json::to_value(p)?;
                        debug!("{}: detected diff: old vs. new spec", S::label());
                        trace!("{}: new spec: {:#?}", S::label(), &new_spec);
                        trace!("{}: old spec: {:#?}", S::label(), &old_spec);
                        trace!("{}: new/old diff: {:#?}", S::label(), json_diff);
                        let patch_result = self.patch_spec(&value.metadata, &json_diff).await?;
                        Ok(ApplyResult::Patched(patch_result))
                    }
                    _ => Err(Self::MetadataClientError::patch_error()),
                }
            }
            Err(err) => {
                if err.not_founded() {
                    debug!(
                        "{}: item '{}' not found, creating ...",
                        S::label(),
                        value.metadata.name
                    );
                    let created_item = self.create_item(value.into()).await?;
                    Ok(ApplyResult::Created(created_item))
                } else {
                    Err(err)
                }
            }
        }
    }

    /// update status
    async fn update_status<S>(
        &self,
        value: &UpdateK8ObjStatus<S>,
    ) -> Result<K8Obj<S>, Self::MetadataClientError>
    where
        S: Spec;

    /// patch existing with spec
    async fn patch_spec<S, M>(
        &self,
        metadata: &M,
        patch: &Value,
    ) -> Result<K8Obj<S>, Self::MetadataClientError>
    where
        S: Spec,
        M: K8Meta + Display + Send + Sync;

    /// stream items since resource versions
    fn watch_stream_since<S, N>(
        &self,
        namespace: N,
        resource_version: Option<String>,
    ) -> BoxStream<'_, TokenStreamResult<S, Self::MetadataClientError>>
    where
        S: Spec + 'static,
        N: Into<NameSpace>;

    fn watch_stream_now<S>(
        &self,
        ns: String,
    ) -> BoxStream<'_, TokenStreamResult<S, Self::MetadataClientError>>
    where
        S: Spec + 'static,
    {
        let ft_stream = async move {
            let namespace = ns.as_ref();
            match self.retrieve_items_with_option(namespace, None).await {
                Ok(item_now_list) => {
                    let resource_version = item_now_list.metadata.resource_version;

                    let items_watch_stream =
                        self.watch_stream_since(namespace, Some(resource_version));

                    let items_list = item_now_list
                        .items
                        .into_iter()
                        .map(|item| Ok(K8Watch::ADDED(item)))
                        .collect();
                    let list_stream = once(ready(Ok(items_list)));

                    list_stream.chain(items_watch_stream).left_stream()
                    // list_stream
                }
                Err(err) => once(ready(Err(err))).right_stream(),
            }
        };

        ft_stream.flatten_stream().boxed()
    }

    /// Check if the object exists, return true or false.
    async fn exists<S, M>(&self, metadata: &M) -> Result<bool, Self::MetadataClientError>
    where
        S: Spec,
        M: K8Meta + Display + Send + Sync,
    {
        debug!("check if '{}' exists", metadata);
        match self.retrieve_item::<S, M>(metadata).await {
            Ok(_) => Ok(true),
            Err(err) => {
                if err.not_founded() {
                    Ok(false)
                } else {
                    Err(err)
                }
            }
        }
    }
}