openstack_sdk/api/compute/v2/server/
get.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Shows details for a server.
19//!
20//! Includes server details including configuration drive, extended status, and
21//! server usage information.
22//!
23//! The extended status information appears in the `OS-EXT-STS:vm_state`,
24//! `OS-EXT-STS:power_state`, and `OS-EXT-STS:task_state` attributes.
25//!
26//! The server usage information appears in the `OS-SRV-USG:launched_at` and
27//! `OS-SRV-USG:terminated_at` attributes.
28//!
29//! HostId is unique per account and is not globally unique.
30//!
31//! **Preconditions**
32//!
33//! The server must exist.
34//!
35//! Normal response codes: 200
36//!
37//! Error response codes: unauthorized(401), forbidden(403), itemNotFound(404)
38//!
39use derive_builder::Builder;
40use http::{HeaderMap, HeaderName, HeaderValue};
41
42use crate::api::rest_endpoint_prelude::*;
43
44use std::borrow::Cow;
45
46#[derive(Builder, Debug, Clone)]
47#[builder(setter(strip_option))]
48pub struct Request<'a> {
49    /// id parameter for /v2.1/servers/{id} API
50    #[builder(default, setter(into))]
51    id: Cow<'a, str>,
52
53    #[builder(setter(name = "_headers"), default, private)]
54    _headers: Option<HeaderMap>,
55}
56impl<'a> Request<'a> {
57    /// Create a builder for the endpoint.
58    pub fn builder() -> RequestBuilder<'a> {
59        RequestBuilder::default()
60    }
61}
62
63impl RequestBuilder<'_> {
64    /// Add a single header to the Server.
65    pub fn header(&mut self, header_name: &'static str, header_value: &'static str) -> &mut Self
66where {
67        self._headers
68            .get_or_insert(None)
69            .get_or_insert_with(HeaderMap::new)
70            .insert(header_name, HeaderValue::from_static(header_value));
71        self
72    }
73
74    /// Add multiple headers.
75    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
76    where
77        I: Iterator<Item = T>,
78        T: Into<(Option<HeaderName>, HeaderValue)>,
79    {
80        self._headers
81            .get_or_insert(None)
82            .get_or_insert_with(HeaderMap::new)
83            .extend(iter.map(Into::into));
84        self
85    }
86}
87
88impl RestEndpoint for Request<'_> {
89    fn method(&self) -> http::Method {
90        http::Method::GET
91    }
92
93    fn endpoint(&self) -> Cow<'static, str> {
94        format!("servers/{id}", id = self.id.as_ref(),).into()
95    }
96
97    fn parameters(&self) -> QueryParams {
98        QueryParams::default()
99    }
100
101    fn service_type(&self) -> ServiceType {
102        ServiceType::Compute
103    }
104
105    fn response_key(&self) -> Option<Cow<'static, str>> {
106        Some("server".into())
107    }
108
109    /// Returns headers to be set into the request
110    fn request_headers(&self) -> Option<&HeaderMap> {
111        self._headers.as_ref()
112    }
113
114    /// Returns required API version
115    fn api_version(&self) -> Option<ApiVersion> {
116        Some(ApiVersion::new(2, 1))
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    #[cfg(feature = "sync")]
124    use crate::api::Query;
125    use crate::test::client::FakeOpenStackClient;
126    use crate::types::ServiceType;
127    use http::{HeaderName, HeaderValue};
128    use httpmock::MockServer;
129    use serde_json::json;
130
131    #[test]
132    fn test_service_type() {
133        assert_eq!(
134            Request::builder().build().unwrap().service_type(),
135            ServiceType::Compute
136        );
137    }
138
139    #[test]
140    fn test_response_key() {
141        assert_eq!(
142            Request::builder().build().unwrap().response_key().unwrap(),
143            "server"
144        );
145    }
146
147    #[cfg(feature = "sync")]
148    #[test]
149    fn endpoint() {
150        let server = MockServer::start();
151        let client = FakeOpenStackClient::new(server.base_url());
152        let mock = server.mock(|when, then| {
153            when.method(httpmock::Method::GET)
154                .path(format!("/servers/{id}", id = "id",));
155
156            then.status(200)
157                .header("content-type", "application/json")
158                .json_body(json!({ "server": {} }));
159        });
160
161        let endpoint = Request::builder().id("id").build().unwrap();
162        let _: serde_json::Value = endpoint.query(&client).unwrap();
163        mock.assert();
164    }
165
166    #[cfg(feature = "sync")]
167    #[test]
168    fn endpoint_headers() {
169        let server = MockServer::start();
170        let client = FakeOpenStackClient::new(server.base_url());
171        let mock = server.mock(|when, then| {
172            when.method(httpmock::Method::GET)
173                .path(format!("/servers/{id}", id = "id",))
174                .header("foo", "bar")
175                .header("not_foo", "not_bar");
176            then.status(200)
177                .header("content-type", "application/json")
178                .json_body(json!({ "server": {} }));
179        });
180
181        let endpoint = Request::builder()
182            .id("id")
183            .headers(
184                [(
185                    Some(HeaderName::from_static("foo")),
186                    HeaderValue::from_static("bar"),
187                )]
188                .into_iter(),
189            )
190            .header("not_foo", "not_bar")
191            .build()
192            .unwrap();
193        let _: serde_json::Value = endpoint.query(&client).unwrap();
194        mock.assert();
195    }
196}