Skip to main content

openstack_sdk_load_balancer/v2/pool/member/
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//! Update an existing member.
19//!
20//! If the request is valid, the service returns the `Accepted (202)` response
21//! code. To confirm the update, check that the member provisioning status is
22//! `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation to poll
23//! the member object for changes.
24//!
25//! Setting the member weight to `0` means that the member will not receive new
26//! requests but will finish any existing connections. This “drains” the
27//! backend member of active connections.
28//!
29//! This operation returns the updated member object with the `ACTIVE`,
30//! `PENDING_UPDATE`, or `ERROR` provisioning status.
31//!
32use derive_builder::Builder;
33use http::{HeaderMap, HeaderName, HeaderValue};
34
35use openstack_sdk_core::api::rest_endpoint_prelude::*;
36
37use serde::Deserialize;
38use serde::Serialize;
39use std::borrow::Cow;
40
41/// Defines attributes that are acceptable of a PUT request.
42#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
43#[builder(setter(strip_option))]
44pub struct Member<'a> {
45    /// The administrative state of the resource, which is up (`true`) or down
46    /// (`false`). Default is `true`.
47    #[serde(skip_serializing_if = "Option::is_none")]
48    #[builder(default, setter(into))]
49    pub(crate) admin_state_up: Option<bool>,
50
51    /// Is the member a backup? Backup members only receive traffic when all
52    /// non-backup members are down.
53    ///
54    /// **New in version 2.1**
55    #[serde(skip_serializing_if = "Option::is_none")]
56    #[builder(default, setter(into))]
57    pub(crate) backup: Option<bool>,
58
59    /// An alternate IP address used for health monitoring a backend member.
60    /// Default is `null` which monitors the member `address`.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    #[builder(default, setter(into))]
63    pub(crate) monitor_address: Option<Cow<'a, str>>,
64
65    /// An alternate protocol port used for health monitoring a backend member.
66    /// Default is `null` which monitors the member `protocol_port`.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    #[builder(default, setter(into))]
69    pub(crate) monitor_port: Option<i32>,
70
71    /// Human-readable name of the resource.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    #[builder(default, setter(into))]
74    pub(crate) name: Option<Cow<'a, str>>,
75
76    /// A list of simple strings assigned to the resource.
77    ///
78    /// **New in version 2.5**
79    #[serde(skip_serializing_if = "Option::is_none")]
80    #[builder(default, setter(into))]
81    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
82
83    /// The weight of a member determines the portion of requests or
84    /// connections it services compared to the other members of the pool. For
85    /// example, a member with a weight of 10 receives five times as many
86    /// requests as a member with a weight of 2. A value of 0 means the member
87    /// does not receive new connections but continues to service existing
88    /// connections. A valid value is from `0` to `256`. Default is `1`.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    #[builder(default, setter(into))]
91    pub(crate) weight: Option<i32>,
92}
93
94#[derive(Builder, Debug, Clone)]
95#[builder(setter(strip_option))]
96pub struct Request<'a> {
97    /// Defines attributes that are acceptable of a PUT request.
98    #[builder(setter(into))]
99    pub(crate) member: Member<'a>,
100
101    /// member_id parameter for /v2/lbaas/pools/{pool_id}/members/{member_id}
102    /// API
103    #[builder(default, setter(into))]
104    id: Cow<'a, str>,
105
106    /// pool_id parameter for /v2/lbaas/pools/{pool_id}/members/{member_id} API
107    #[builder(default, setter(into))]
108    pool_id: Cow<'a, str>,
109
110    #[builder(setter(name = "_headers"), default, private)]
111    _headers: Option<HeaderMap>,
112}
113impl<'a> Request<'a> {
114    /// Create a builder for the endpoint.
115    pub fn builder() -> RequestBuilder<'a> {
116        RequestBuilder::default()
117    }
118}
119
120impl<'a> RequestBuilder<'a> {
121    /// Add a single header to the Member.
122    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
123    where
124        K: Into<HeaderName>,
125        V: Into<HeaderValue>,
126    {
127        self._headers
128            .get_or_insert(None)
129            .get_or_insert_with(HeaderMap::new)
130            .insert(header_name.into(), header_value.into());
131        self
132    }
133
134    /// Add multiple headers.
135    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
136    where
137        I: Iterator<Item = T>,
138        T: Into<(Option<HeaderName>, HeaderValue)>,
139    {
140        self._headers
141            .get_or_insert(None)
142            .get_or_insert_with(HeaderMap::new)
143            .extend(iter.map(Into::into));
144        self
145    }
146}
147
148impl RestEndpoint for Request<'_> {
149    fn method(&self) -> http::Method {
150        http::Method::PUT
151    }
152
153    fn endpoint(&self) -> Cow<'static, str> {
154        format!(
155            "lbaas/pools/{pool_id}/members/{id}",
156            id = self.id.as_ref(),
157            pool_id = self.pool_id.as_ref(),
158        )
159        .into()
160    }
161
162    fn parameters(&self) -> QueryParams<'_> {
163        QueryParams::default()
164    }
165
166    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
167        let mut params = JsonBodyParams::default();
168
169        params.push("member", serde_json::to_value(&self.member)?);
170
171        params.into_body()
172    }
173
174    fn service_type(&self) -> ServiceType {
175        ServiceType::LoadBalancer
176    }
177
178    fn response_key(&self) -> Option<Cow<'static, str>> {
179        Some("member".into())
180    }
181
182    /// Returns headers to be set into the request
183    fn request_headers(&self) -> Option<&HeaderMap> {
184        self._headers.as_ref()
185    }
186
187    /// Returns required API version
188    fn api_version(&self) -> Option<ApiVersion> {
189        Some(ApiVersion::new(2, 0))
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use http::{HeaderName, HeaderValue};
197    use httpmock::MockServer;
198    #[cfg(feature = "sync")]
199    use openstack_sdk_core::api::Query;
200    use openstack_sdk_core::test::client::FakeOpenStackClient;
201    use openstack_sdk_core::types::ServiceType;
202    use serde_json::json;
203
204    #[test]
205    fn test_service_type() {
206        assert_eq!(
207            Request::builder()
208                .member(MemberBuilder::default().build().unwrap())
209                .build()
210                .unwrap()
211                .service_type(),
212            ServiceType::LoadBalancer
213        );
214    }
215
216    #[test]
217    fn test_response_key() {
218        assert_eq!(
219            Request::builder()
220                .member(MemberBuilder::default().build().unwrap())
221                .build()
222                .unwrap()
223                .response_key()
224                .unwrap(),
225            "member"
226        );
227    }
228
229    #[cfg(feature = "sync")]
230    #[test]
231    fn endpoint() {
232        let server = MockServer::start();
233        let client = FakeOpenStackClient::new(server.base_url());
234        let mock = server.mock(|when, then| {
235            when.method(httpmock::Method::PUT).path(format!(
236                "/lbaas/pools/{pool_id}/members/{id}",
237                id = "id",
238                pool_id = "pool_id",
239            ));
240
241            then.status(200)
242                .header("content-type", "application/json")
243                .json_body(json!({ "member": {} }));
244        });
245
246        let endpoint = Request::builder()
247            .id("id")
248            .pool_id("pool_id")
249            .member(MemberBuilder::default().build().unwrap())
250            .build()
251            .unwrap();
252        let _: serde_json::Value = endpoint.query(&client).unwrap();
253        mock.assert();
254    }
255
256    #[cfg(feature = "sync")]
257    #[test]
258    fn endpoint_headers() {
259        let server = MockServer::start();
260        let client = FakeOpenStackClient::new(server.base_url());
261        let mock = server.mock(|when, then| {
262            when.method(httpmock::Method::PUT)
263                .path(format!(
264                    "/lbaas/pools/{pool_id}/members/{id}",
265                    id = "id",
266                    pool_id = "pool_id",
267                ))
268                .header("foo", "bar")
269                .header("not_foo", "not_bar");
270            then.status(200)
271                .header("content-type", "application/json")
272                .json_body(json!({ "member": {} }));
273        });
274
275        let endpoint = Request::builder()
276            .id("id")
277            .pool_id("pool_id")
278            .member(MemberBuilder::default().build().unwrap())
279            .headers(
280                [(
281                    Some(HeaderName::from_static("foo")),
282                    HeaderValue::from_static("bar"),
283                )]
284                .into_iter(),
285            )
286            .header(
287                HeaderName::from_static("not_foo"),
288                HeaderValue::from_static("not_bar"),
289            )
290            .build()
291            .unwrap();
292        let _: serde_json::Value = endpoint.query(&client).unwrap();
293        mock.assert();
294    }
295}