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
//! A basic API client with standard kube error handling

use serde_json::Value;
use either::{Right, Left};
use either::Either;
use http::StatusCode;
use http;
use serde::de::DeserializeOwned;
use serde_json;
use failure::ResultExt;
use crate::{ApiError, Error, ErrorKind, Result};
use crate::config::Configuration;


#[allow(non_snake_case)]
#[derive(Deserialize, Debug)]
pub struct StatusDetails {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub group: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub kind: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub uid: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub causes: Vec<StatusCause>,
    #[serde(default, skip_serializing_if = "num::Zero::is_zero")]
    pub retryAfterSeconds: u32
}

#[derive(Deserialize, Debug)]
pub struct StatusCause {
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub message: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub field: String,
}

#[derive(Deserialize, Debug)]
pub struct Status {
    // TODO: typemeta
    // TODO: metadata that can be completely empty (listmeta...)
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub status: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub message: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub reason: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub details: Option<StatusDetails>,
    #[serde(default, skip_serializing_if = "num::Zero::is_zero")]
    pub code: u16,
}

/// APIClient requires `config::Configuration` includes client to connect with kubernetes cluster.
#[derive(Clone)]
pub struct APIClient {
    configuration: Configuration,
}

impl APIClient {
    pub fn new(configuration: Configuration) -> Self {
        APIClient { configuration }
    }

    fn send(&self, request: http::Request<Vec<u8>>) -> Result<reqwest::Response>
    {
        let (parts, body) = request.into_parts();
        let uri_str = format!("{}{}", self.configuration.base_path, parts.uri);
        trace!("{} {}", parts.method, uri_str);
        //trace!("Request body: {:?}", String::from_utf8_lossy(&body));
        let req = match parts.method {
            http::Method::GET => self.configuration.client.get(&uri_str),
            http::Method::POST => self.configuration.client.post(&uri_str),
            http::Method::DELETE => self.configuration.client.delete(&uri_str),
            http::Method::PUT => self.configuration.client.put(&uri_str),
            http::Method::PATCH => self.configuration.client.patch(&uri_str),
            other => Err(ErrorKind::InvalidMethod(other.to_string()))?
        }.headers(parts.headers).body(body).build().context(ErrorKind::RequestBuild)?;
        //trace!("Request Headers: {:?}", req.headers());
        Ok(self.configuration.client.execute(req).context(ErrorKind::RequestSend)?)
    }


    pub fn request<T>(&self, request: http::Request<Vec<u8>>) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let mut res : reqwest::Response = self.send(request)?;
        trace!("{} {}", res.status().as_str(), res.url());
        //trace!("Response Headers: {:?}", res.headers());
        let s = res.status();
        let text = res.text().context(ErrorKind::RequestParse)?;
        res.error_for_status().map_err(|e| make_api_error(&text, e, &s))?;

        serde_json::from_str(&text).map_err(|e| {
            warn!("{}, {:?}", text, e);
            Error::from(ErrorKind::SerdeParse)
        })
    }

    pub fn request_text(&self, request: http::Request<Vec<u8>>) -> Result<String>
    {
        let mut res : reqwest::Response = self.send(request)?;
        trace!("{} {}", res.status().as_str(), res.url());
        //trace!("Response Headers: {:?}", res.headers());
        let s = res.status();
        let text = res.text().context(ErrorKind::RequestParse)?;
        res.error_for_status().map_err(|e| make_api_error(&text, e, &s))?;

        Ok(text)
    }

    pub fn request_status<T>(&self, request: http::Request<Vec<u8>>) -> Result<Either<T, Status>>
    where
        T: DeserializeOwned,
    {
        let mut res : reqwest::Response = self.send(request)?;
        trace!("{} {}", res.status().as_str(), res.url());
        //trace!("Response Headers: {:?}", res.headers());
        let s = res.status();
        let text = res.text().context(ErrorKind::RequestParse)?;
        res.error_for_status().map_err(|e| make_api_error(&text, e, &s))?;

        // It needs to be JSON:
        let v: Value = serde_json::from_str(&text).context(ErrorKind::SerdeParse)?;;
        if v["kind"] == "Status" {
            trace!("Status from {}", text);
            Ok(Right(serde_json::from_str::<Status>(&text).map_err(|e| {
                warn!("{}, {:?}", text, e);
                Error::from(ErrorKind::SerdeParse)
            })?))
        } else {
            Ok(Left(serde_json::from_str::<T>(&text).map_err(|e| {
                warn!("{}, {:?}", text, e);
                Error::from(ErrorKind::SerdeParse)
            })?))
        }
    }

    pub fn request_events<T>(&self, request: http::Request<Vec<u8>>) -> Result<Vec<T>>
    where
        T: DeserializeOwned,
    {
        let mut res : reqwest::Response = self.send(request)?;
        trace!("{} {}", res.status().as_str(), res.url());
        //trace!("Response Headers: {:?}", res.headers());
        let s = res.status();
        let text = res.text().context(ErrorKind::RequestParse)?;
        res.error_for_status().map_err(|e| make_api_error(&text, e, &s))?;

        // Should be able to coerce result into Vec<T> at this point
        let mut xs : Vec<T> = vec![];
        for l in text.lines() {
            let r = serde_json::from_str(&l).map_err(|e| {
                warn!("{} {:?}", l, e);
                Error::from(ErrorKind::SerdeParse)
            })?;
            xs.push(r);
        }
        Ok(xs)
    }
}

/// Kubernetes returned error handling
///
/// Either kube returned an explicit ApiError struct,
/// or it someohow returned something we couldn't parse as one.
///
/// In either case, present an ApiError upstream.
/// The latter is probably a bug if encountered.
fn make_api_error(text: &str, error: reqwest::Error, s: &StatusCode) -> ErrorKind {
    // Print better debug when things do fail
    //trace!("Parsing error: {}", text);
    if let Ok(errdata) = serde_json::from_str::<ApiError>(text) {
        debug!("Unsuccessful: {:?}", errdata);
        ErrorKind::Api(errdata)
    } else {
        warn!("Unsuccessful data error parse: {}", text);
        // Propagate errors properly via reqwest
        let ae = ApiError {
            status: s.to_string(),
            code: s.as_u16(),
            message: format!("{:?}", error),
            reason: format!("{}", error),
        };
        debug!("Unsuccessful: {:?} (reconstruct)", ae);
        ErrorKind::Api(ae)
    }
}