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
use client::{Client, GoogleAPIResponse};
use std::error::Error;



#[derive(Deserialize, Debug, Clone)]
pub enum InstanceStatus {
    PROVISIONING,
    STAGING,
    RUNNING,
    STOPPING,
    STOPPED,
    SUSPENDING,
    SUSPENDED,
    TERMINATED,
}


#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct InstanceItem {
    pub id: String,
    pub name: String,
    pub status: InstanceStatus,
}

impl InstanceItem {
    pub fn start(&self, client: &Client) -> Result<GoogleAPIResponse, Box<Error>> {
        client.post(&format!("/instances/{}/start", self.name), vec![])
    }

    pub fn stop(&self, client: &Client) -> Result<GoogleAPIResponse, Box<Error>> {
        client.post(&format!("/instances/{}/stop", self.name), vec![])
    }
}

pub type InstanceItems = Vec<InstanceItem>;


pub fn empty_instance_items() -> InstanceItems {
    vec![]
}

#[derive(Debug)]
pub struct InstanceOp<'a> {
    pub client: &'a Client<'a>,
}

impl<'a> InstanceOp<'a> {
    /// Get Google Cloud compute instance list
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use std::env;
    /// use gcloud::{Client, InstanceOp};
    ///
    /// fn env_var(key: &str) -> String {
    ///     env::var(key).expect(&format!("{} environment variable is required", key))
    /// }
    ///
    /// let client = Client {
    ///     project: &env_var("PROJECT"),
    ///     zone: &env_var("ZONE"),
    ///     client_secret: &env_var("CLIENT_SECRET"),
    ///     client_id: &env_var("CLIENT_ID"),
    ///     refresh_token: &env_var("REFRESH_TOKEN"),
    /// };

    /// let instances = InstanceOp { client: &client }.list().unwrap();
    /// println!("{:#?}", instances);
    /// assert!(
    ///     instances.len() > 0,
    ///     "instances.len() > 0 ==> {} is not higher than 0",
    ///     instances.len()
    /// );
    /// ```
    pub fn list(&self) -> Result<InstanceItems, Box<Error>> {
        self.client.get("/instances", vec![]).and_then(|response| {
            match response {
                GoogleAPIResponse::GoogleAPISuccessResponse(resp) => Ok(resp.items),
                _ => Err(From::from("Invalid response from GoogleAPI")),
            }
        })
    }
}