Skip to main content

openstack_sdk_load_balancer/v2/loadbalancer/
set.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//! Updates a load balancer.
19//!
20//! If the request is valid, the service returns the `Accepted (202)` response
21//! code. To confirm the update, check that the load balancer provisioning
22//! status is `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation
23//! to poll the load balancer object for changes.
24//!
25//! This operation returns the updated load balancer object with the `ACTIVE`,
26//! `PENDING_UPDATE`, or `ERROR` provisioning status.
27//!
28use derive_builder::Builder;
29use http::{HeaderMap, HeaderName, HeaderValue};
30
31use openstack_sdk_core::api::rest_endpoint_prelude::*;
32
33use serde::Deserialize;
34use serde::Serialize;
35use std::borrow::Cow;
36
37/// A load balancer object.
38#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
39#[builder(setter(strip_option))]
40pub struct Loadbalancer<'a> {
41    /// The administrative state of the resource, which is up (`true`) or down
42    /// (`false`).
43    #[serde(skip_serializing_if = "Option::is_none")]
44    #[builder(default, setter(into))]
45    pub(crate) admin_state_up: Option<bool>,
46
47    /// A human-readable description for the resource.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    #[builder(default, setter(into))]
50    pub(crate) description: Option<Cow<'a, str>>,
51
52    /// Human-readable name of the resource.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    #[builder(default, setter(into))]
55    pub(crate) name: Option<Cow<'a, str>>,
56
57    /// A list of simple strings assigned to the resource.
58    ///
59    /// **New in version 2.5**
60    #[serde(skip_serializing_if = "Option::is_none")]
61    #[builder(default, setter(into))]
62    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
63
64    /// The ID of the QoS Policy which will apply to the Virtual IP (VIP).
65    #[serde(skip_serializing_if = "Option::is_none")]
66    #[builder(default, setter(into))]
67    pub(crate) vip_qos_policy_id: Option<Cow<'a, str>>,
68
69    #[serde(skip_serializing_if = "Option::is_none")]
70    #[builder(default, setter(into))]
71    pub(crate) vip_sg_ids: Option<Vec<Cow<'a, str>>>,
72}
73
74#[derive(Builder, Debug, Clone)]
75#[builder(setter(strip_option))]
76pub struct Request<'a> {
77    /// A load balancer object.
78    #[builder(setter(into))]
79    pub(crate) loadbalancer: Loadbalancer<'a>,
80
81    /// loadbalancer_id parameter for /v2/lbaas/loadbalancers/{loadbalancer_id}
82    /// API
83    #[builder(default, setter(into))]
84    id: Cow<'a, str>,
85
86    #[builder(setter(name = "_headers"), default, private)]
87    _headers: Option<HeaderMap>,
88}
89impl<'a> Request<'a> {
90    /// Create a builder for the endpoint.
91    pub fn builder() -> RequestBuilder<'a> {
92        RequestBuilder::default()
93    }
94}
95
96impl<'a> RequestBuilder<'a> {
97    /// Add a single header to the Loadbalancer.
98    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
99    where
100        K: Into<HeaderName>,
101        V: Into<HeaderValue>,
102    {
103        self._headers
104            .get_or_insert(None)
105            .get_or_insert_with(HeaderMap::new)
106            .insert(header_name.into(), header_value.into());
107        self
108    }
109
110    /// Add multiple headers.
111    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
112    where
113        I: Iterator<Item = T>,
114        T: Into<(Option<HeaderName>, HeaderValue)>,
115    {
116        self._headers
117            .get_or_insert(None)
118            .get_or_insert_with(HeaderMap::new)
119            .extend(iter.map(Into::into));
120        self
121    }
122}
123
124impl RestEndpoint for Request<'_> {
125    fn method(&self) -> http::Method {
126        http::Method::PUT
127    }
128
129    fn endpoint(&self) -> Cow<'static, str> {
130        format!("lbaas/loadbalancers/{id}", id = self.id.as_ref(),).into()
131    }
132
133    fn parameters(&self) -> QueryParams<'_> {
134        QueryParams::default()
135    }
136
137    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
138        let mut params = JsonBodyParams::default();
139
140        params.push("loadbalancer", serde_json::to_value(&self.loadbalancer)?);
141
142        params.into_body()
143    }
144
145    fn service_type(&self) -> ServiceType {
146        ServiceType::LoadBalancer
147    }
148
149    fn response_key(&self) -> Option<Cow<'static, str>> {
150        Some("loadbalancer".into())
151    }
152
153    /// Returns headers to be set into the request
154    fn request_headers(&self) -> Option<&HeaderMap> {
155        self._headers.as_ref()
156    }
157
158    /// Returns required API version
159    fn api_version(&self) -> Option<ApiVersion> {
160        Some(ApiVersion::new(2, 0))
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use http::{HeaderName, HeaderValue};
168    use httpmock::MockServer;
169    #[cfg(feature = "sync")]
170    use openstack_sdk_core::api::Query;
171    use openstack_sdk_core::test::client::FakeOpenStackClient;
172    use openstack_sdk_core::types::ServiceType;
173    use serde_json::json;
174
175    #[test]
176    fn test_service_type() {
177        assert_eq!(
178            Request::builder()
179                .loadbalancer(LoadbalancerBuilder::default().build().unwrap())
180                .build()
181                .unwrap()
182                .service_type(),
183            ServiceType::LoadBalancer
184        );
185    }
186
187    #[test]
188    fn test_response_key() {
189        assert_eq!(
190            Request::builder()
191                .loadbalancer(LoadbalancerBuilder::default().build().unwrap())
192                .build()
193                .unwrap()
194                .response_key()
195                .unwrap(),
196            "loadbalancer"
197        );
198    }
199
200    #[cfg(feature = "sync")]
201    #[test]
202    fn endpoint() {
203        let server = MockServer::start();
204        let client = FakeOpenStackClient::new(server.base_url());
205        let mock = server.mock(|when, then| {
206            when.method(httpmock::Method::PUT)
207                .path(format!("/lbaas/loadbalancers/{id}", id = "id",));
208
209            then.status(200)
210                .header("content-type", "application/json")
211                .json_body(json!({ "loadbalancer": {} }));
212        });
213
214        let endpoint = Request::builder()
215            .id("id")
216            .loadbalancer(LoadbalancerBuilder::default().build().unwrap())
217            .build()
218            .unwrap();
219        let _: serde_json::Value = endpoint.query(&client).unwrap();
220        mock.assert();
221    }
222
223    #[cfg(feature = "sync")]
224    #[test]
225    fn endpoint_headers() {
226        let server = MockServer::start();
227        let client = FakeOpenStackClient::new(server.base_url());
228        let mock = server.mock(|when, then| {
229            when.method(httpmock::Method::PUT)
230                .path(format!("/lbaas/loadbalancers/{id}", id = "id",))
231                .header("foo", "bar")
232                .header("not_foo", "not_bar");
233            then.status(200)
234                .header("content-type", "application/json")
235                .json_body(json!({ "loadbalancer": {} }));
236        });
237
238        let endpoint = Request::builder()
239            .id("id")
240            .loadbalancer(LoadbalancerBuilder::default().build().unwrap())
241            .headers(
242                [(
243                    Some(HeaderName::from_static("foo")),
244                    HeaderValue::from_static("bar"),
245                )]
246                .into_iter(),
247            )
248            .header(
249                HeaderName::from_static("not_foo"),
250                HeaderValue::from_static("not_bar"),
251            )
252            .build()
253            .unwrap();
254        let _: serde_json::Value = endpoint.query(&client).unwrap();
255        mock.assert();
256    }
257}