Skip to main content

openstack_sdk_load_balancer/v2/healthmonitor/
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 health monitor.
19//!
20//! If the request is valid, the service returns the `Accepted (202)` response
21//! code. To confirm the update, check that the health monitor provisioning
22//! status is `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation
23//! to poll the health monitor object for changes.
24//!
25//! This operation returns the updated health monitor 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#[derive(Debug, Deserialize, Clone, Serialize)]
38pub enum HttpMethod {
39    #[serde(rename = "CONNECT")]
40    Connect,
41    #[serde(rename = "DELETE")]
42    Delete,
43    #[serde(rename = "GET")]
44    Get,
45    #[serde(rename = "HEAD")]
46    Head,
47    #[serde(rename = "OPTIONS")]
48    Options,
49    #[serde(rename = "PATCH")]
50    Patch,
51    #[serde(rename = "POST")]
52    Post,
53    #[serde(rename = "PUT")]
54    Put,
55    #[serde(rename = "TRACE")]
56    Trace,
57}
58
59/// Defines attributes that are acceptable of a PUT request.
60#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
61#[builder(setter(strip_option))]
62pub struct Healthmonitor<'a> {
63    /// The administrative state of the resource, which is up (`true`) or down
64    /// (`false`). Default is `true`.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    #[builder(default, setter(into))]
67    pub(crate) admin_state_up: Option<bool>,
68
69    /// The time, in seconds, between sending probes to members.
70    #[serde(skip_serializing_if = "Option::is_none")]
71    #[builder(default, setter(into))]
72    pub(crate) delay: Option<i32>,
73
74    /// The domain name, which be injected into the HTTP Host Header to the
75    /// backend server for HTTP health check.
76    ///
77    /// **New in version 2.10**
78    #[serde(skip_serializing_if = "Option::is_none")]
79    #[builder(default, setter(into))]
80    pub(crate) domain_name: Option<Cow<'a, str>>,
81
82    /// The list of HTTP status codes expected in response from the member to
83    /// declare it healthy. Specify one of the following values:
84    ///
85    /// - A single value, such as `200`
86    /// - A list, such as `200, 202`
87    /// - A range, such as `200-204`
88    ///
89    /// The default is 200.
90    #[serde(skip_serializing_if = "Option::is_none")]
91    #[builder(default, setter(into))]
92    pub(crate) expected_codes: Option<Cow<'a, str>>,
93
94    /// The HTTP method that the health monitor uses for requests. One of
95    /// `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT`,
96    /// or `TRACE`. The default is `GET`.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    #[builder(default)]
99    pub(crate) http_method: Option<HttpMethod>,
100
101    /// The HTTP version. One of `1.0` or `1.1`. The default is `1.0`.
102    ///
103    /// **New in version 2.10**
104    #[serde(skip_serializing_if = "Option::is_none")]
105    #[builder(default, setter(into))]
106    pub(crate) http_version: Option<f32>,
107
108    /// The number of successful checks before changing the `operating status`
109    /// of the member to `ONLINE`. A valid value is from `1` to `10`.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    #[builder(default, setter(into))]
112    pub(crate) max_retries: Option<i32>,
113
114    /// The number of allowed check failures before changing the
115    /// `operating status` of the member to `ERROR`. A valid value is from `1`
116    /// to `10`. The default is `3`.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    #[builder(default, setter(into))]
119    pub(crate) max_retries_down: Option<i32>,
120
121    /// Human-readable name of the resource.
122    #[serde(skip_serializing_if = "Option::is_none")]
123    #[builder(default, setter(into))]
124    pub(crate) name: Option<Cow<'a, str>>,
125
126    /// A list of simple strings assigned to the resource.
127    ///
128    /// **New in version 2.5**
129    #[serde(skip_serializing_if = "Option::is_none")]
130    #[builder(default, setter(into))]
131    pub(crate) tags: Option<Vec<Cow<'a, str>>>,
132
133    /// The maximum time, in seconds, that a monitor waits to connect before it
134    /// times out. This value must be less than the delay value.
135    #[serde(skip_serializing_if = "Option::is_none")]
136    #[builder(default, setter(into))]
137    pub(crate) timeout: Option<i32>,
138
139    /// The HTTP URL path of the request sent by the monitor to test the health
140    /// of a backend member. Must be a string that begins with a forward slash
141    /// (`/`). The default URL path is `/`.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    #[builder(default, setter(into))]
144    pub(crate) url_path: Option<Cow<'a, str>>,
145}
146
147#[derive(Builder, Debug, Clone)]
148#[builder(setter(strip_option))]
149pub struct Request<'a> {
150    /// Defines attributes that are acceptable of a PUT request.
151    #[builder(setter(into))]
152    pub(crate) healthmonitor: Healthmonitor<'a>,
153
154    /// healthmonitor_id parameter for
155    /// /v2/lbaas/healthmonitors/{healthmonitor_id} API
156    #[builder(default, setter(into))]
157    id: Cow<'a, str>,
158
159    #[builder(setter(name = "_headers"), default, private)]
160    _headers: Option<HeaderMap>,
161}
162impl<'a> Request<'a> {
163    /// Create a builder for the endpoint.
164    pub fn builder() -> RequestBuilder<'a> {
165        RequestBuilder::default()
166    }
167}
168
169impl<'a> RequestBuilder<'a> {
170    /// Add a single header to the Healthmonitor.
171    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
172    where
173        K: Into<HeaderName>,
174        V: Into<HeaderValue>,
175    {
176        self._headers
177            .get_or_insert(None)
178            .get_or_insert_with(HeaderMap::new)
179            .insert(header_name.into(), header_value.into());
180        self
181    }
182
183    /// Add multiple headers.
184    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
185    where
186        I: Iterator<Item = T>,
187        T: Into<(Option<HeaderName>, HeaderValue)>,
188    {
189        self._headers
190            .get_or_insert(None)
191            .get_or_insert_with(HeaderMap::new)
192            .extend(iter.map(Into::into));
193        self
194    }
195}
196
197impl RestEndpoint for Request<'_> {
198    fn method(&self) -> http::Method {
199        http::Method::PUT
200    }
201
202    fn endpoint(&self) -> Cow<'static, str> {
203        format!("lbaas/healthmonitors/{id}", id = self.id.as_ref(),).into()
204    }
205
206    fn parameters(&self) -> QueryParams<'_> {
207        QueryParams::default()
208    }
209
210    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
211        let mut params = JsonBodyParams::default();
212
213        params.push("healthmonitor", serde_json::to_value(&self.healthmonitor)?);
214
215        params.into_body()
216    }
217
218    fn service_type(&self) -> ServiceType {
219        ServiceType::LoadBalancer
220    }
221
222    fn response_key(&self) -> Option<Cow<'static, str>> {
223        Some("healthmonitor".into())
224    }
225
226    /// Returns headers to be set into the request
227    fn request_headers(&self) -> Option<&HeaderMap> {
228        self._headers.as_ref()
229    }
230
231    /// Returns required API version
232    fn api_version(&self) -> Option<ApiVersion> {
233        Some(ApiVersion::new(2, 0))
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use http::{HeaderName, HeaderValue};
241    use httpmock::MockServer;
242    #[cfg(feature = "sync")]
243    use openstack_sdk_core::api::Query;
244    use openstack_sdk_core::test::client::FakeOpenStackClient;
245    use openstack_sdk_core::types::ServiceType;
246    use serde_json::json;
247
248    #[test]
249    fn test_service_type() {
250        assert_eq!(
251            Request::builder()
252                .healthmonitor(HealthmonitorBuilder::default().build().unwrap())
253                .build()
254                .unwrap()
255                .service_type(),
256            ServiceType::LoadBalancer
257        );
258    }
259
260    #[test]
261    fn test_response_key() {
262        assert_eq!(
263            Request::builder()
264                .healthmonitor(HealthmonitorBuilder::default().build().unwrap())
265                .build()
266                .unwrap()
267                .response_key()
268                .unwrap(),
269            "healthmonitor"
270        );
271    }
272
273    #[cfg(feature = "sync")]
274    #[test]
275    fn endpoint() {
276        let server = MockServer::start();
277        let client = FakeOpenStackClient::new(server.base_url());
278        let mock = server.mock(|when, then| {
279            when.method(httpmock::Method::PUT)
280                .path(format!("/lbaas/healthmonitors/{id}", id = "id",));
281
282            then.status(200)
283                .header("content-type", "application/json")
284                .json_body(json!({ "healthmonitor": {} }));
285        });
286
287        let endpoint = Request::builder()
288            .id("id")
289            .healthmonitor(HealthmonitorBuilder::default().build().unwrap())
290            .build()
291            .unwrap();
292        let _: serde_json::Value = endpoint.query(&client).unwrap();
293        mock.assert();
294    }
295
296    #[cfg(feature = "sync")]
297    #[test]
298    fn endpoint_headers() {
299        let server = MockServer::start();
300        let client = FakeOpenStackClient::new(server.base_url());
301        let mock = server.mock(|when, then| {
302            when.method(httpmock::Method::PUT)
303                .path(format!("/lbaas/healthmonitors/{id}", id = "id",))
304                .header("foo", "bar")
305                .header("not_foo", "not_bar");
306            then.status(200)
307                .header("content-type", "application/json")
308                .json_body(json!({ "healthmonitor": {} }));
309        });
310
311        let endpoint = Request::builder()
312            .id("id")
313            .healthmonitor(HealthmonitorBuilder::default().build().unwrap())
314            .headers(
315                [(
316                    Some(HeaderName::from_static("foo")),
317                    HeaderValue::from_static("bar"),
318                )]
319                .into_iter(),
320            )
321            .header(
322                HeaderName::from_static("not_foo"),
323                HeaderValue::from_static("not_bar"),
324            )
325            .build()
326            .unwrap();
327        let _: serde_json::Value = endpoint.query(&client).unwrap();
328        mock.assert();
329    }
330}