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
use error::Error;
use std::time::Duration;
use tokio::time::timeout;
use url::Url;

// Hyper imports.
use hyper::body::Buf;
use hyper::header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE, USER_AGENT};
use hyper::{Method, Request};
#[cfg(feature = "rustls")]
type HttpsConnector = hyper_rustls::HttpsConnector<hyper::client::HttpConnector>;
#[cfg(feature = "rust-native-tls")]
use hyper_tls;
#[cfg(feature = "rust-native-tls")]
type HttpsConnector = hyper_tls::HttpsConnector<hyper::client::HttpConnector>;

pub mod error;
pub mod resource_url;

pub mod cluster;
pub mod kubeversion;
pub mod node;
pub mod nodegroup;
pub mod task;

// Environment variables from Cargo.
static PKG_NAME: &str = env!("CARGO_PKG_NAME");
static PKG_VERSION: &str = env!("CARGO_PKG_VERSION");

/// `Client` struct is used to make calls to the MKS API.
pub struct Client {
    client: hyper::Client<HttpsConnector>,
    token: String,
    base_endpoint: url::Url,
    user_agent: String,
    timeout: Duration,
}

impl Client {
    /// Construct the new Client struct with default configuration.
    ///
    /// Use `Builder` to configure the client.
    pub fn new(base_endpoint: &str, token: &str) -> Result<Client, Error> {
        Client::with_builder(base_endpoint, token, Client::builder())
    }

    fn with_builder(base_endpoint: &str, token: &str, builder: Builder) -> Result<Client, Error> {
        // Check token.
        if token.is_empty() {
            return Err(Error::EmptyTokenError);
        }
        let token = String::from(token);

        // Check base endpoint.
        let base_endpoint = Url::parse(base_endpoint).map_err(|_| Error::EndpointError)?;

        // Use the provided Hyper client or configure a new one.
        let client = match builder.client {
            Some(client) => client,
            None => {
                #[cfg(feature = "rustls")]
                let client = hyper::Client::builder().build(HttpsConnector::new());
                #[cfg(feature = "rust-native-tls")]
                let client = hyper::Client::builder().build(HttpsConnector::new()?);

                client
            }
        };

        Ok(Client {
            client,
            token,
            base_endpoint,
            user_agent: Client::user_agent(),
            timeout: builder.timeout,
        })
    }

    fn user_agent() -> String {
        format!("{}/{}", PKG_NAME, PKG_VERSION)
    }

    /// Get a default builder.
    pub fn builder() -> Builder {
        Builder::default()
    }

    // Prepare a new request.
    fn new_request(
        &self,
        method: Method,
        path: &str,
        body: Option<String>,
    ) -> Result<Request<hyper::Body>, Error> {
        // Build a final Hyper URI.
        let uri = self.make_uri(path)?;

        // Prepare a new Hyper request.
        let mut req = Request::new(hyper::Body::empty());
        *req.method_mut() = method;
        *req.uri_mut() = uri;

        // Add user-agent header.
        req.headers_mut().insert(
            USER_AGENT,
            HeaderValue::from_str(&self.user_agent).map_err(|_| Error::RequestError)?,
        );

        // Add x-auth-token header.
        req.headers_mut().insert(
            "x-auth-token",
            HeaderValue::from_str(&self.token).map_err(|_| Error::RequestError)?,
        );

        // Add body into the new request if it's provided.
        if let Some(body) = body {
            // Add content-length header if body is provided.
            let len =
                HeaderValue::from_str(&body.len().to_string()).map_err(|_| Error::RequestError)?;
            req.headers_mut().insert(CONTENT_LENGTH, len);

            // Add content-type header if body is provided.
            req.headers_mut().insert(
                CONTENT_TYPE,
                HeaderValue::from_str("application/json").map_err(|_| Error::RequestError)?,
            );

            *req.body_mut() = hyper::Body::from(body);
        }

        Ok(req)
    }

    #[tokio::main]
    async fn do_request(&self, req: hyper::Request<hyper::Body>) -> Result<String, Error> {
        let duration = self.timeout;
        let handle = async {
            let raw_resp = self.client.request(req).await?;

            let status = raw_resp.status();
            let body = hyper::body::aggregate(raw_resp).await?.to_bytes();
            let body = String::from_utf8_lossy(&body);

            Ok::<_, hyper::Error>((body.to_string(), status))
        };

        let raw_resp = timeout(duration, handle).await??;

        let (body, status) = raw_resp;

        if !status.is_success() {
            return Err(Error::HttpError(status.as_u16(), body));
        }

        Ok(body)
    }

    fn make_uri(&self, path: &str) -> Result<hyper::Uri, Error> {
        let url = self
            .base_endpoint
            .clone()
            .join(path)
            .map_err(|_| Error::UrlError)?;

        url.as_str()
            .parse::<hyper::Uri>()
            .map_err(|_| Error::UrlError)
    }
}

/// Methods to work with clusters.
impl Client {
    /// Get a cluster.
    pub fn get_cluster(&self, cluster_id: &str) -> Result<cluster::schemas::Cluster, Error> {
        cluster::api::get(self, cluster_id)
    }

    /// List clusters.
    pub fn list_clusters(&self) -> Result<Vec<cluster::schemas::Cluster>, Error> {
        cluster::api::list(self)
    }

    /// Create a cluster.
    pub fn create_cluster(
        &self,
        opts: &cluster::schemas::CreateOpts,
    ) -> Result<cluster::schemas::Cluster, Error> {
        cluster::api::create(self, opts)
    }

    /// Delete a cluster.
    pub fn delete_cluster(&self, cluster_id: &str) -> Result<(), Error> {
        cluster::api::delete(self, cluster_id)
    }
}

/// Methods to work with Kubernetes versions.
impl Client {
    /// List all Kubernetes versions.
    pub fn list_kube_versions(&self) -> Result<Vec<kubeversion::schemas::KubeVersion>, Error> {
        kubeversion::api::list(self)
    }
}

/// Methods to work with nodes.
impl Client {
    /// Get a cluster node.
    pub fn get_node(
        &self,
        cluster_id: &str,
        nodegroup_id: &str,
        node_id: &str,
    ) -> Result<node::schemas::Node, Error> {
        node::api::get(self, cluster_id, nodegroup_id, node_id)
    }

    /// Reinstall a cluster node.
    pub fn reinstall_node(
        &self,
        cluster_id: &str,
        nodegroup_id: &str,
        node_id: &str,
    ) -> Result<(), Error> {
        node::api::reinstall(self, cluster_id, nodegroup_id, node_id)
    }
}

/// Methods to work with nodegroups.
impl Client {
    /// Get a cluster nodegroup.
    pub fn get_nodegroup(
        &self,
        cluster_id: &str,
        nodegroup_id: &str,
    ) -> Result<nodegroup::schemas::Nodegroup, Error> {
        nodegroup::api::get(self, cluster_id, nodegroup_id)
    }

    /// List cluster nodegroups.
    pub fn list_nodegroups(
        &self,
        cluster_id: &str,
    ) -> Result<Vec<nodegroup::schemas::Nodegroup>, Error> {
        nodegroup::api::list(self, cluster_id)
    }

    /// Create a cluster nodegroup.
    pub fn create_nodegroup(
        &self,
        cluster_id: &str,
        opts: &nodegroup::schemas::CreateOpts,
    ) -> Result<(), Error> {
        nodegroup::api::create(self, cluster_id, opts)
    }

    /// Delete a cluster nodegroup.
    pub fn delete_nodegroup(&self, cluster_id: &str, nodegroup_id: &str) -> Result<(), Error> {
        nodegroup::api::delete(self, cluster_id, nodegroup_id)
    }

    /// Resize a cluster nodegroup.
    pub fn resize_nodegroup(
        &self,
        cluster_id: &str,
        nodegroup_id: &str,
        opts: &nodegroup::schemas::ResizeOpts,
    ) -> Result<(), Error> {
        nodegroup::api::resize(self, cluster_id, nodegroup_id, opts)
    }

    /// Update a cluster nodegroup.
    pub fn update_nodegroup(
        &self,
        cluster_id: &str,
        nodegroup_id: &str,
        opts: &nodegroup::schemas::UpdateOpts,
    ) -> Result<(), Error> {
        nodegroup::api::update(self, cluster_id, nodegroup_id, opts)
    }
}

/// Methods to work with tasks.
impl Client {
    /// Get a task.
    pub fn get_task(&self, cluster_id: &str, task_id: &str) -> Result<task::schemas::Task, Error> {
        task::api::get(self, cluster_id, task_id)
    }

    /// List tasks.
    pub fn list_tasks(&self, cluster_id: &str) -> Result<Vec<task::schemas::Task>, Error> {
        task::api::list(self, cluster_id)
    }
}

/// Builder for `Client`.
pub struct Builder {
    /// Hyper client to use for the connection.
    client: Option<hyper::Client<HttpsConnector>>,

    /// Request timeout.
    timeout: Duration,
}

// Default timeout for requests.
const DEFAULT_TIMEOUT: u64 = 30;

impl Default for Builder {
    fn default() -> Self {
        Self {
            client: None,
            timeout: Duration::from_secs(DEFAULT_TIMEOUT),
        }
    }
}

impl Builder {
    /// Set Hyper client.
    ///
    /// By default this library will instantiate a new HttpsConnector.
    /// It will use hyper_rustls or hyper_tls depending on selected library features.
    pub fn with_client(mut self, client: hyper::Client<HttpsConnector>) -> Self {
        self.client = Some(client);
        self
    }

    /// Set request timeout.
    ///
    /// Default is 30 seconds.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Create `Client` with the configuration in this builder.
    pub fn build(self, base_endpoint: &str, token: &str) -> Result<Client, Error> {
        Client::with_builder(base_endpoint, token, self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_client_default_builder() {
        let client = Client::new("https://example.org", "token_a").unwrap();

        assert_eq!(
            client.base_endpoint,
            Url::parse("https://example.org").unwrap()
        );
        assert_eq!(client.token, String::from("token_a"));
        assert_eq!(client.user_agent, format!("{}/{}", PKG_NAME, PKG_VERSION));
        assert_eq!(client.timeout, Duration::from_secs(DEFAULT_TIMEOUT));
    }

    #[test]
    fn new_client_with_builder() {
        let client = Client::builder()
            .with_timeout(Duration::from_secs(10))
            .build("https://example.com", "token_b")
            .unwrap();

        assert_eq!(
            client.base_endpoint,
            Url::parse("https://example.com").unwrap()
        );
        assert_eq!(client.token, String::from("token_b"));
        assert_eq!(client.user_agent, format!("{}/{}", PKG_NAME, PKG_VERSION));
        assert_eq!(client.timeout, Duration::from_secs(10));
    }
}