Skip to main content

openstack_cli_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//! Set Healthmonitor command
19//!
20//! Wraps invoking of the `v2/lbaas/healthmonitors/{healthmonitor_id}` with `PUT` method
21
22use clap::Args;
23use eyre::WrapErr;
24use tracing::info;
25
26use openstack_cli_core::cli::CliArgs;
27use openstack_cli_core::error::OpenStackCliError;
28use openstack_cli_core::output::OutputProcessor;
29use openstack_sdk::AsyncOpenStack;
30
31use clap::ValueEnum;
32use openstack_sdk::api::QueryAsync;
33use openstack_sdk::api::find;
34use openstack_sdk::api::load_balancer::v2::healthmonitor::find;
35use openstack_sdk::api::load_balancer::v2::healthmonitor::set;
36use openstack_types::load_balancer::v2::healthmonitor::response;
37
38/// Update an existing health monitor.
39///
40/// If the request is valid, the service returns the `Accepted (202)` response
41/// code. To confirm the update, check that the health monitor provisioning
42/// status is `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation
43/// to poll the health monitor object for changes.
44///
45/// This operation returns the updated health monitor object with the `ACTIVE`,
46/// `PENDING_UPDATE`, or `ERROR` provisioning status.
47#[derive(Args)]
48#[command(about = "Update a Health Monitor")]
49pub struct HealthmonitorCommand {
50    /// Request Query parameters
51    #[command(flatten)]
52    query: QueryParameters,
53
54    /// Path parameters
55    #[command(flatten)]
56    path: PathParameters,
57
58    /// Defines attributes that are acceptable of a PUT request.
59    #[command(flatten)]
60    healthmonitor: Healthmonitor,
61}
62
63/// Query parameters
64#[derive(Args)]
65struct QueryParameters {}
66
67/// Path parameters
68#[derive(Args)]
69struct PathParameters {
70    /// healthmonitor_id parameter for
71    /// /v2/lbaas/healthmonitors/{healthmonitor_id} API
72    #[arg(
73        help_heading = "Path parameters",
74        id = "path_param_id",
75        value_name = "ID"
76    )]
77    id: String,
78}
79
80#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
81enum HttpMethod {
82    Connect,
83    Delete,
84    Get,
85    Head,
86    Options,
87    Patch,
88    Post,
89    Put,
90    Trace,
91}
92
93/// Healthmonitor Body data
94#[derive(Args, Clone)]
95struct Healthmonitor {
96    /// The administrative state of the resource, which is up (`true`) or down
97    /// (`false`). Default is `true`.
98    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
99    admin_state_up: Option<bool>,
100
101    /// The time, in seconds, between sending probes to members.
102    #[arg(help_heading = "Body parameters", long)]
103    delay: Option<i32>,
104
105    /// The domain name, which be injected into the HTTP Host Header to the
106    /// backend server for HTTP health check.
107    ///
108    /// **New in version 2.10**
109    #[arg(help_heading = "Body parameters", long)]
110    domain_name: Option<String>,
111
112    /// The list of HTTP status codes expected in response from the member to
113    /// declare it healthy. Specify one of the following values:
114    ///
115    /// - A single value, such as `200`
116    /// - A list, such as `200, 202`
117    /// - A range, such as `200-204`
118    ///
119    /// The default is 200.
120    #[arg(help_heading = "Body parameters", long)]
121    expected_codes: Option<String>,
122
123    /// The HTTP method that the health monitor uses for requests. One of
124    /// `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT`,
125    /// or `TRACE`. The default is `GET`.
126    #[arg(help_heading = "Body parameters", long)]
127    http_method: Option<HttpMethod>,
128
129    /// The HTTP version. One of `1.0` or `1.1`. The default is `1.0`.
130    ///
131    /// **New in version 2.10**
132    #[arg(help_heading = "Body parameters", long)]
133    http_version: Option<f32>,
134
135    /// The number of successful checks before changing the `operating status`
136    /// of the member to `ONLINE`. A valid value is from `1` to `10`.
137    #[arg(help_heading = "Body parameters", long)]
138    max_retries: Option<i32>,
139
140    /// The number of allowed check failures before changing the
141    /// `operating status` of the member to `ERROR`. A valid value is from `1`
142    /// to `10`. The default is `3`.
143    #[arg(help_heading = "Body parameters", long)]
144    max_retries_down: Option<i32>,
145
146    /// Human-readable name of the resource.
147    #[arg(help_heading = "Body parameters", long)]
148    name: Option<String>,
149
150    /// A list of simple strings assigned to the resource.
151    ///
152    /// **New in version 2.5**
153    ///
154    /// Parameter is an array, may be provided multiple times.
155    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
156    tags: Option<Vec<String>>,
157
158    /// The maximum time, in seconds, that a monitor waits to connect before it
159    /// times out. This value must be less than the delay value.
160    #[arg(help_heading = "Body parameters", long)]
161    timeout: Option<i32>,
162
163    /// The HTTP URL path of the request sent by the monitor to test the health
164    /// of a backend member. Must be a string that begins with a forward slash
165    /// (`/`). The default URL path is `/`.
166    #[arg(help_heading = "Body parameters", long)]
167    url_path: Option<String>,
168}
169
170impl HealthmonitorCommand {
171    /// Perform command action
172    pub async fn take_action<C: CliArgs>(
173        &self,
174        parsed_args: &C,
175        client: &mut AsyncOpenStack,
176    ) -> Result<(), OpenStackCliError> {
177        info!("Set Healthmonitor");
178
179        let op = OutputProcessor::from_args(
180            parsed_args,
181            Some("load-balancer.healthmonitor"),
182            Some("set"),
183        );
184        op.validate_args(parsed_args)?;
185
186        let mut find_builder = find::Request::builder();
187
188        find_builder.id(&self.path.id);
189
190        let find_ep = find_builder
191            .build()
192            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
193        let find_data: serde_json::Value = find(find_ep).query_async(client).await?;
194
195        let mut ep_builder = set::Request::builder();
196
197        let resource_id = find_data["id"]
198            .as_str()
199            .ok_or_else(|| eyre::eyre!("resource ID must be a string"))?
200            .to_string();
201        ep_builder.id(resource_id.clone());
202
203        // Set body parameters
204        // Set Request.healthmonitor data
205        let args = &self.healthmonitor;
206        let mut healthmonitor_builder = set::HealthmonitorBuilder::default();
207        if let Some(val) = &args.admin_state_up {
208            healthmonitor_builder.admin_state_up(*val);
209        }
210
211        if let Some(val) = &args.delay {
212            healthmonitor_builder.delay(*val);
213        }
214
215        if let Some(val) = &args.domain_name {
216            healthmonitor_builder.domain_name(val);
217        }
218
219        if let Some(val) = &args.expected_codes {
220            healthmonitor_builder.expected_codes(val);
221        }
222
223        if let Some(val) = &args.http_method {
224            let tmp = match val {
225                HttpMethod::Connect => set::HttpMethod::Connect,
226                HttpMethod::Delete => set::HttpMethod::Delete,
227                HttpMethod::Get => set::HttpMethod::Get,
228                HttpMethod::Head => set::HttpMethod::Head,
229                HttpMethod::Options => set::HttpMethod::Options,
230                HttpMethod::Patch => set::HttpMethod::Patch,
231                HttpMethod::Post => set::HttpMethod::Post,
232                HttpMethod::Put => set::HttpMethod::Put,
233                HttpMethod::Trace => set::HttpMethod::Trace,
234            };
235            healthmonitor_builder.http_method(tmp);
236        }
237
238        if let Some(val) = &args.http_version {
239            healthmonitor_builder.http_version(*val);
240        }
241
242        if let Some(val) = &args.max_retries {
243            healthmonitor_builder.max_retries(*val);
244        }
245
246        if let Some(val) = &args.max_retries_down {
247            healthmonitor_builder.max_retries_down(*val);
248        }
249
250        if let Some(val) = &args.name {
251            healthmonitor_builder.name(val);
252        }
253
254        if let Some(val) = &args.tags {
255            healthmonitor_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
256        }
257
258        if let Some(val) = &args.timeout {
259            healthmonitor_builder.timeout(*val);
260        }
261
262        if let Some(val) = &args.url_path {
263            healthmonitor_builder.url_path(val);
264        }
265
266        ep_builder.healthmonitor(
267            healthmonitor_builder
268                .build()
269                .wrap_err("error preparing the request data")?,
270        );
271
272        let ep = ep_builder
273            .build()
274            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
275
276        let data: serde_json::Value = ep.query_async(client).await?;
277
278        op.output_single::<response::set::HealthmonitorResponse>(data.clone())?;
279        // Show command specific hints
280        op.show_command_hint()?;
281        Ok(())
282    }
283}