avina-api 1.1.2

Rust API server for the LRZ-specific features of the Openstack-based LRZ Compute Cloud.
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use std::{collections::HashMap, time::Instant};

use anyhow::Context;
use jzon::object;
use reqwest::{
    ClientBuilder,
    header::{CONTENT_TYPE, HeaderMap, HeaderValue},
};
use tokio::sync::RwLock;
use uuid::Uuid;

use crate::configuration::OpenStackSettings;

struct Token {
    settings: OpenStackSettings,
    token: String,
    renewed_at: Instant,
}

impl Token {
    async fn new(settings: &OpenStackSettings) -> Result<Self, anyhow::Error> {
        Ok(Self {
            settings: settings.clone(),
            token: issue_token(settings).await?,
            renewed_at: Instant::now(),
        })
    }

    async fn renew(&mut self) -> Result<(), anyhow::Error> {
        self.token = issue_token(&self.settings).await?;
        self.renewed_at = Instant::now();
        Ok(())
    }

    fn is_expired(&self) -> bool {
        self.renewed_at.elapsed().as_secs() > 3600
    }

    fn get(&self) -> String {
        self.token.clone()
    }
}

struct TokenHandler {
    token: RwLock<Token>,
}

impl TokenHandler {
    async fn new(settings: &OpenStackSettings) -> Result<Self, anyhow::Error> {
        Ok(TokenHandler {
            token: RwLock::new(Token::new(settings).await?),
        })
    }

    async fn get(&self) -> String {
        if self.token.read().await.is_expired() {
            self.token.write().await.renew().await.unwrap();
        }
        self.token.read().await.get()
    }
}

// TODO: maybe we could also use rust-openstack at some point.
pub struct OpenStack {
    settings: OpenStackSettings,
    token: TokenHandler,
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct ProjectMinimal {
    pub id: String,
    pub name: String,
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct Link {
    pub href: String,
    pub rel: String,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct FlavorDetailed {
    #[serde(rename = "OS-FLV-DISABLED:disabled")]
    pub disabled: bool,
    pub disk: u32,
    // TODO: this does not work, why?
    // #[serde(rename = "OS-FLV-EXT-DATA:ephemeral")]
    // pub ephemeral: bool,
    #[serde(rename = "os-flavor-access:is_public")]
    pub is_public: bool,
    pub id: String,
    pub links: Vec<Link>,
    pub name: String,
    pub ram: u32,
    // TODO: this does not work, why?
    // pub swap: u32,
    pub vcpus: u32,
    pub rxtx_factor: f32,
    pub description: Option<String>,
    // TODO: this is a more complicated field.
    // "extra_specs": {}
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct FlavorDetailedList {
    flavors: Vec<FlavorDetailed>,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct ServerDetailedFlavor {
    pub id: String,
    pub links: Vec<Link>,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct ServerDetailedSecurityGroup {
    pub name: String,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct ServerDetailedVolumesAttached {
    pub id: String,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct ServerDetailedAddress {
    pub version: usize,
    pub addr: String,
    #[serde(rename = "OS-EXT-IPS:type")]
    pub addr_type: String,
    #[serde(rename = "OS-EXT-IPS-MAC:mac_addr")]
    pub mac_addr: String,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
#[serde(untagged)]
pub enum ServerDetailedImage {
    Some { id: String, links: Vec<Link> },
    None(String),
}

// TODO: there are many missing fields here.
#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct ServerDetailed {
    pub id: Uuid,
    pub name: String,
    pub description: Option<String>,
    pub status: String,
    pub tenant_id: String,
    pub user_id: String,
    pub metadata: HashMap<String, String>,
    #[serde(rename = "hostId")]
    pub host_id: String,
    pub image: ServerDetailedImage,
    pub flavor: ServerDetailedFlavor,
    // TODO: this is actually a datetime
    pub created: String,
    // TODO: this is actually a datetime
    pub updated: String,
    pub addresses: HashMap<String, Vec<ServerDetailedAddress>>,
    #[serde(rename = "accessIPv4")]
    pub access_ipv4: String,
    #[serde(rename = "accessIPv6")]
    pub access_ipv6: String,
    pub links: Vec<Link>,
    #[serde(rename = "OS-DCF:diskConfig")]
    pub disk_config: String,
    #[serde(rename = "OS-EXT-AZ:availability_zone")]
    pub availability_zone: String,
    pub config_drive: String,
    pub key_name: Option<String>,
    // TODO: this is actually a datetime
    #[serde(rename = "OS-SRV-USG:launched_at")]
    pub launched_at: Option<String>,
    // TODO: this is actually a datetime
    #[serde(rename = "OS-SRV-USG:terminated_at")]
    pub terminated_at: Option<String>,
    #[serde(rename = "OS-EXT-SRV-ATTR:host")]
    pub host: Option<String>,
    #[serde(rename = "OS-EXT-SRV-ATTR:instance_name")]
    pub instance_name: String,
    #[serde(rename = "OS-EXT-SRV-ATTR:hypervisor_hostname")]
    pub hypervisor_hostname: Option<String>,
    #[serde(rename = "OS-EXT-STS:task_state")]
    pub task_state: Option<String>,
    #[serde(rename = "OS-EXT-STS:vm_state")]
    pub vm_state: String,
    #[serde(rename = "OS-EXT-STS:power_state")]
    pub power_state: usize,
    #[serde(rename = "os-extended-volumes:volumes_attached")]
    pub volumes_attached: Vec<ServerDetailedVolumesAttached>,
    pub security_groups: Option<Vec<ServerDetailedSecurityGroup>>,
}

#[derive(Clone, Debug, serde::Deserialize)]
pub struct ServerDetailedList {
    servers: Vec<ServerDetailed>,
}

#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct Domain {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub enabled: bool,
}

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

// TODO: the are fields missing here
#[derive(Clone, Debug, serde::Deserialize)]
#[allow(unused)]
pub struct Project {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub enabled: bool,
    pub is_domain: bool,
    pub domain_id: String,
    pub parent_id: String,
    pub tags: Vec<String>,
}

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

impl OpenStack {
    pub async fn new(
        settings: OpenStackSettings,
    ) -> Result<Self, anyhow::Error> {
        Ok(OpenStack {
            token: TokenHandler::new(&settings).await?,
            settings,
        })
    }

    async fn client(&self) -> Result<reqwest::Client, anyhow::Error> {
        let mut headers = HeaderMap::new();
        headers
            .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
        headers.insert(
            "X-Auth-Token",
            HeaderValue::from_str(self.token.get().await.as_str())
                .context("Could not create token header")?,
        );
        ClientBuilder::new()
            .default_headers(headers)
            .build()
            .context("Could not create client")
    }

    pub async fn validate_user_token(
        &self,
        token: &str,
    ) -> Result<ProjectMinimal, anyhow::Error> {
        #[derive(Debug, serde::Deserialize)]
        struct ValidateResponseToken {
            project: ProjectMinimal,
        }
        #[derive(Debug, serde::Deserialize)]
        struct ValidateResponse {
            token: ValidateResponseToken,
        }

        let client = self.client().await?;
        let url = format!("{}/auth/tokens/", self.settings.keystone_endpoint);
        let response = client
            .get(url.as_str())
            .header("X-Subject-Token", token)
            .send()
            .await
            .context("Could not validate user token")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let project: ValidateResponse = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(project.token.project)
    }

    pub async fn get_flavors(
        &self,
    ) -> Result<Vec<FlavorDetailed>, anyhow::Error> {
        let client = self.client().await?;
        let url = format!(
            "{}/v2.1/flavors/detail?is_public=False",
            self.settings.nova_endpoint
        );
        let response = client
            .get(url.as_str())
            .send()
            .await
            .context("Could not retrieve flavor list")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let flavors: FlavorDetailedList = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(flavors.flavors)
    }

    pub async fn get_servers(
        &self,
    ) -> Result<Vec<ServerDetailed>, anyhow::Error> {
        let client = self.client().await?;
        let url = format!(
            "{}/v2.1/servers/detail?all_tenants=True",
            self.settings.nova_endpoint
        );
        let response = client
            .get(url.as_str())
            .send()
            .await
            .context("Could not retrieve server list")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let servers: ServerDetailedList = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(servers.servers)
    }

    pub async fn get_servers_of_project(
        &self,
        project_id: String,
    ) -> Result<Vec<ServerDetailed>, anyhow::Error> {
        let client = self.client().await?;
        let url = format!(
            "{}/v2.1/servers/detail?all_tenants=True&tenant_id={}",
            self.settings.nova_endpoint, project_id,
        );
        let response = client
            .get(url.as_str())
            .send()
            .await
            .context("Could not retrieve server list")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let servers: ServerDetailedList = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(servers.servers)
    }

    pub async fn get_domains(&self) -> Result<Vec<Domain>, anyhow::Error> {
        let client = self.client().await?;
        let url = format!("{}/domains", self.settings.keystone_endpoint);
        let response = client
            .get(url.as_str())
            .send()
            .await
            .context("Could not retrieve domain list")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let domains: DomainList = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(domains.domains)
    }

    pub async fn get_projects(&self) -> Result<Vec<Project>, anyhow::Error> {
        let client = self.client().await?;
        let url = format!("{}/projects", self.settings.keystone_endpoint);
        let response = client
            .get(url.as_str())
            .send()
            .await
            .context("Could not retrieve project list")?;
        if !response.status().is_success() {
            return Err(anyhow::anyhow!(
                "Failed to validate user token, returned code {}",
                response.status().as_u16()
            ));
        }
        let projects: ProjectList = serde_json::from_str(
            response
                .text()
                .await
                .context("Could not read response text")?
                .as_str(),
        )
        .context("Could not parse response")?;
        Ok(projects.projects)
    }
}

#[tracing::instrument(name = "Issue an OpenStack token", skip(settings))]
pub async fn issue_token(
    settings: &OpenStackSettings,
) -> Result<String, anyhow::Error> {
    let mut headers = HeaderMap::new();
    headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
    let client = ClientBuilder::new()
        .default_headers(headers)
        .build()
        .unwrap();
    let url = format!("{}/auth/tokens/", settings.keystone_endpoint);
    let data = object! {
        "auth": {
            "identity": {
                "methods": ["password"],
                "password": {
                    "user": {
                        "name": settings.username.clone(),
                        "domain": {"name": settings.domain.clone()},
                        "password": settings.password.clone(),
                    }
                }
            },
            "scope": {
                "project": {
                    "name": settings.project.clone(),
                    "domain": {"id": settings.domain_id.clone()}
                }
            }
        }
    };
    let response = match client
        .post(url.as_str())
        .body(data.to_string())
        .send()
        .await
        .context("")
    {
        Ok(response) => response,
        Err(error) => {
            return Err(anyhow::anyhow!(
                "Could not complete authentication request: {}",
                error.root_cause()
            ));
        }
    };
    if !response.status().is_success() {
        return Err(anyhow::anyhow!(
            "Failed to authenticate, returned code {}",
            response.status().as_u16()
        ));
    }
    let token = match response.headers().get("X-Subject-Token") {
        Some(token) => token.to_str().unwrap().to_string(),
        None => {
            return Err(anyhow::anyhow!(
                "No token in authentication response header"
            ));
        }
    }
    .trim()
    .to_string();
    Ok(token)
}