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
/**
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/

use std::fmt::Debug;
use std::str::FromStr;

use crate::error::{MetricsResult, StorageError};
use crate::ir::{TsPoint, TsValue};
use crate::IntoPoint;

use log::debug;
use reqwest::{header::HeaderName, header::HeaderValue, StatusCode};
use serde::de::DeserializeOwned;
use serde_json::json;

#[derive(Clone, Deserialize, Debug)]
pub struct OpenstackConfig {
    /// The openstack endpoint to use
    pub endpoint: String,
    pub port: Option<u16>,
    pub user: String,
    /// This gets replaced with the token at runtime
    pub password: String,
    /// Openstack domain to use
    pub domain: String,
    pub project_name: String,
    /// Optional certificate file to use against the server
    /// der encoded
    pub certificate: Option<String>,
    pub region: String,
}

#[derive(Deserialize, Debug)]
pub struct Domain {
    pub description: String,
    pub enabled: bool,
    pub id: String,
    pub name: String,
}

#[derive(Deserialize, Debug)]
pub struct Domains {
    pub domains: Vec<Domain>,
}

#[derive(Deserialize, Debug)]
pub struct Project {
    pub is_domain: Option<bool>,
    pub description: Option<String>,
    pub domain_id: String,
    pub enabled: bool,
    pub id: String,
    pub name: String,
    pub parent_id: Option<String>,
    pub tags: Option<Vec<String>>,
}

#[derive(Deserialize, Debug)]
pub struct Projects {
    pub projects: Vec<Project>,
}

#[derive(Deserialize, Debug)]
pub struct UserRoot {
    pub user: User,
}

#[derive(Deserialize, Debug)]
pub struct User {
    pub default_project_id: Option<String>,
    pub domain_id: String,
    pub enabled: Option<bool>,
    pub id: String,
    pub name: String,
    pub email: Option<String>,
    pub password_expires_at: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct VolumesAttachment {
    pub server_id: String,
    pub attachment_id: String,
    pub host_name: Option<String>,
    pub volume_id: String,
    pub device: String,
    pub id: String,
}

#[derive(Deserialize, Debug)]
pub struct VolumesMetadatum {
    pub readonly: Option<String>,
    pub attached_mode: Option<String>,
}

#[derive(Deserialize, Debug)]
pub struct VolumeImageMetadatum {
    pub kernel_id: Option<String>,
    pub checksum: Option<String>,
    pub min_ram: Option<String>,
    pub ramdisk_id: Option<String>,
    pub disk_format: Option<String>,
    pub image_name: Option<String>,
    pub image_id: Option<String>,
    pub container_format: Option<String>,
    pub min_disk: Option<String>,
    pub size: Option<String>,
}

#[derive(Deserialize, Debug, IntoPoint)]
pub struct Volume {
    pub migration_status: Option<String>,
    pub attachments: Vec<VolumesAttachment>,
    pub availability_zone: String,
    pub os_vol_host_attr_host: Option<String>,
    pub encrypted: bool,
    pub replication_status: String,
    pub snapshot_id: Option<String>,
    pub id: String,
    pub size: u64, // Size is in GB
    pub user_id: String,
    #[serde(rename = "os-vol-tenant-attr:tenant_id")]
    pub os_vol_tenant_attr_tenant_id: String,
    pub os_vol_mig_status_attr_migstat: Option<String>,
    pub metadata: VolumesMetadatum,
    pub status: String,
    pub description: Option<String>,
    pub multiattach: bool,
    pub source_volid: Option<String>,
    pub consistencygroup_id: Option<String>,
    pub os_vol_mig_status_attr_name_id: Option<String>,
    pub name: Option<String>,
    pub bootable: String,
    pub created_at: String,
    pub volume_type: Option<String>,
    pub volume_image_metadata: Option<VolumeImageMetadatum>,
}

#[derive(Deserialize, Debug)]
pub struct Volumes {
    pub volumes: Vec<Volume>,
    pub count: Option<u64>,
}

impl IntoPoint for Volumes {
    fn into_point(&self, name: Option<&str>, is_time_series: bool) -> Vec<TsPoint> {
        let mut points: Vec<TsPoint> = Vec::new();

        for v in &self.volumes {
            points.extend(v.into_point(name, is_time_series));
        }

        points
    }
}

fn get<T>(client: &reqwest::Client, config: &OpenstackConfig, api: &str) -> MetricsResult<T>
where
    T: DeserializeOwned + Debug,
{
    let url = match config.port {
        Some(port) => format!("https://{}:{}/{}", config.endpoint, port, api),
        None => format!("https://{}/{}", config.endpoint, api),
    };

    // This could be more efficient by deserializing immediately but when errors
    // occur it can be really difficult to debug.
    let res: Result<String, reqwest::Error> = client
        .get(&url)
        .header(
            HeaderName::from_str("X-Auth-Token")?,
            HeaderValue::from_str(&config.password)?,
        )
        .send()?
        .error_for_status()?
        .text();
    debug!("raw response: {:?}", res);
    let res = serde_json::from_str(&res?);
    Ok(res?)
}

// Connect to the metadata server and request a new api token
pub fn get_api_token(client: &reqwest::Client, config: &mut OpenstackConfig) -> MetricsResult<()> {
    let auth_json = json!({
        "auth": {
            "identity": {
                "methods": ["password"],
                "password": {
                    "user": {
                        "name": config.user,
                        "domain": {
                            "name": config.domain,
                        },
                        "password": config.password,
                    }
                }
            },
           "scope": {
               "project": {
                   "name": config.project_name,
                   "domain": {
                       "name": "comcast",
                   }
               }
           }
        }
    });
    let url = match config.port {
        Some(port) => format!("https://{}:{}/v3/auth/tokens", config.endpoint, port),
        None => format!("https://{}/v3/auth/tokens", config.endpoint),
    };
    let resp = client
        .post(&url)
        .json(&auth_json)
        .send()?
        .error_for_status()?;
    match resp.status() {
        StatusCode::OK | StatusCode::CREATED => {
            // ok we're good
            let h = resp.headers();

            let token = h.get("X-Subject-Token");
            if token.is_none() {
                return Err(StorageError::new(
                    "openstack token not found in header".to_string(),
                ));
            }
            config.password = token.unwrap().to_str()?.to_owned();
            Ok(())
        }
        StatusCode::UNAUTHORIZED => Err(StorageError::new(format!(
            "Invalid credentials for {}",
            config.user
        ))),
        _ => Err(StorageError::new(format!(
            "Unknown error: {}",
            resp.status()
        ))),
    }
}

pub fn list_domains(
    client: &reqwest::Client,
    config: &OpenstackConfig,
) -> MetricsResult<Vec<Domain>> {
    let domains: Domains = get(&client, &config, "v3/domains")?;

    Ok(domains.domains)
}

pub fn list_projects(
    client: &reqwest::Client,
    config: &OpenstackConfig,
) -> MetricsResult<Vec<Project>> {
    let projects: Projects = get(&client, &config, "v3/projects")?;

    Ok(projects.projects)
}

pub fn list_volumes(
    client: &reqwest::Client,
    config: &OpenstackConfig,
    project_id: &str,
) -> MetricsResult<Vec<TsPoint>> {
    let volumes: Volumes = get(
        &client,
        &config,
        &format!("v3/{}/volumes/detail?all_tenants=True", project_id),
    )?;

    Ok(volumes.into_point(Some("openstack_volume"), true))
}

#[test]
fn test_list_openstack_volumes() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/openstack/volumes.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: Volumes = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}

pub fn get_user(
    client: &reqwest::Client,
    config: &OpenstackConfig,
    user_id: &str,
) -> MetricsResult<User> {
    let user: UserRoot = get(&client, &config, &format!("/v3/users/{}", user_id))?;

    Ok(user.user)
}

#[test]
fn test_get_openstack_user() {
    use std::fs::File;
    use std::io::Read;

    let mut f = File::open("tests/openstack/user.json").unwrap();
    let mut buff = String::new();
    f.read_to_string(&mut buff).unwrap();

    let i: UserRoot = serde_json::from_str(&buff).unwrap();
    println!("result: {:#?}", i);
}