Skip to main content

openstack_cli_load_balancer/v2/healthmonitor/
list.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//! List Healthmonitors command
19//!
20//! Wraps invoking of the `v2/lbaas/healthmonitors` with `GET` method
21
22use clap::Args;
23use eyre::OptionExt;
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 openstack_sdk::api::QueryAsync;
32use openstack_sdk::api::find_by_name;
33use openstack_sdk::api::identity::v3::project::find as find_project;
34use openstack_sdk::api::load_balancer::v2::healthmonitor::list;
35use openstack_sdk::api::{Pagination, paged};
36use openstack_types::load_balancer::v2::healthmonitor::response;
37use tracing::warn;
38
39/// Lists all health monitors for the project.
40///
41/// Use the `fields` query parameter to control which fields are returned in
42/// the response body. Additionally, you can filter results by using query
43/// string parameters. For information, see
44/// [Filtering and column selection](#filtering).
45///
46/// Administrative users can specify a project ID that is different than their
47/// own to list health monitors for other projects.
48///
49/// The list might be empty.
50#[derive(Args)]
51#[command(about = "List Health Monitors")]
52pub struct HealthmonitorsCommand {
53    /// Request Query parameters
54    #[command(flatten)]
55    query: QueryParameters,
56
57    /// Path parameters
58    #[command(flatten)]
59    path: PathParameters,
60
61    /// Total limit of entities count to return. Use this when there are too many entries.
62    #[arg(long, default_value_t = 10000)]
63    max_items: usize,
64}
65
66/// Query parameters
67#[derive(Args)]
68struct QueryParameters {
69    /// The type of health monitor.
70    #[arg(help_heading = "Query parameters", long, value_parser = ["HTTP","HTTPS","PING","SCTP","TCP","TLS-HELLO","UDP-CONNECT"])]
71    _type: Option<String>,
72
73    /// The administrative state of the resource
74    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
75    admin_state_up: Option<bool>,
76
77    /// The UTC date and timestamp when the resource was created.
78    #[arg(help_heading = "Query parameters", long)]
79    created_at: Option<String>,
80
81    /// The time, in seconds, between sending probes to members.
82    #[arg(help_heading = "Query parameters", long)]
83    delay: Option<i32>,
84
85    /// A human-readable description for the resource.
86    #[arg(help_heading = "Query parameters", long)]
87    description: Option<String>,
88
89    /// The list of HTTP status codes expected in response from the member to
90    /// declare it healthy.
91    #[arg(help_heading = "Query parameters", long)]
92    expected_codes: Option<String>,
93
94    /// The HTTP method that the health monitor uses for requests.
95    #[arg(help_heading = "Query parameters", long, value_parser = ["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"])]
96    http_method: Option<String>,
97
98    /// The ID of the resource
99    #[arg(help_heading = "Query parameters", long)]
100    id: Option<String>,
101
102    /// Page size
103    #[arg(
104        help_heading = "Query parameters",
105        long("page-size"),
106        visible_alias("limit")
107    )]
108    limit: Option<i32>,
109
110    /// ID of the last item in the previous list
111    #[arg(help_heading = "Query parameters", long)]
112    marker: Option<String>,
113
114    /// The number of successful checks before changing the operating status of
115    /// the member to ONLINE. A valid value is from 1 to 10.
116    #[arg(help_heading = "Query parameters", long)]
117    max_retries: Option<i32>,
118
119    /// The number of allowed check failures before changing the operating
120    /// status of the member to ERROR. A valid value is from 1 to 10.
121    #[arg(help_heading = "Query parameters", long)]
122    max_retries_down: Option<i32>,
123
124    /// Human-readable name of the resource.
125    #[arg(help_heading = "Query parameters", long)]
126    name: Option<String>,
127
128    /// Return the list of entities that do not have one or more of the given
129    /// tags.
130    #[arg(help_heading = "Query parameters", long)]
131    not_tags: Option<String>,
132
133    /// Return the list of entities that do not have at least one of the given
134    /// tags.
135    #[arg(help_heading = "Query parameters", long)]
136    not_tags_any: Option<String>,
137
138    /// The operating status of the resource.
139    #[arg(help_heading = "Query parameters", long, value_parser = ["DEGRADED","DRAINING","ERROR","NO_MONITOR","OFFLINE","ONLINE"])]
140    operating_status: Option<String>,
141
142    /// The page direction.
143    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
144    page_reverse: Option<bool>,
145
146    /// The ID of the pool.
147    #[arg(help_heading = "Query parameters", long)]
148    pool_id: Option<String>,
149
150    /// Project resource for which the operation should be performed.
151    #[command(flatten)]
152    project: ProjectInput,
153
154    /// The provisioning status of the resource.
155    #[arg(help_heading = "Query parameters", long, value_parser = ["ACTIVE","DELETED","ERROR","PENDING_CREATE","PENDING_DELETE","PENDING_UPDATE"])]
156    provisioning_status: Option<String>,
157
158    /// Return the list of entities that have this tag or tags.
159    #[arg(help_heading = "Query parameters", long)]
160    tags: Option<String>,
161
162    /// Return the list of entities that have one or more of the given tags.
163    #[arg(help_heading = "Query parameters", long)]
164    tags_any: Option<String>,
165
166    /// The maximum time, in seconds, that a monitor waits to connect before it
167    /// times out.
168    #[arg(help_heading = "Query parameters", long)]
169    timeout: Option<i32>,
170
171    /// The UTC date and timestamp when the resource was last updated.
172    #[arg(help_heading = "Query parameters", long)]
173    updated_at: Option<String>,
174
175    /// The HTTP URL path of the request sent by the monitor to test the health
176    /// of a backend member. Must be a string that begins with a forward slash
177    /// (/).
178    #[arg(help_heading = "Query parameters", long)]
179    url_path: Option<String>,
180}
181
182/// Project input select group
183#[derive(Args)]
184#[group(required = false, multiple = false)]
185struct ProjectInput {
186    /// Project Name.
187    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
188    project_name: Option<String>,
189    /// Project ID.
190    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
191    project_id: Option<String>,
192    /// Current project.
193    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
194    current_project: bool,
195}
196
197/// Path parameters
198#[derive(Args)]
199struct PathParameters {}
200
201impl HealthmonitorsCommand {
202    /// Perform command action
203    pub async fn take_action<C: CliArgs>(
204        &self,
205        parsed_args: &C,
206        client: &mut AsyncOpenStack,
207    ) -> Result<(), OpenStackCliError> {
208        info!("List Healthmonitors");
209
210        let op = OutputProcessor::from_args(
211            parsed_args,
212            Some("load-balancer.healthmonitor"),
213            Some("list"),
214        );
215        op.validate_args(parsed_args)?;
216
217        let mut ep_builder = list::Request::builder();
218
219        // Set query parameters
220        if let Some(val) = &self.query.admin_state_up {
221            ep_builder.admin_state_up(*val);
222        }
223        if let Some(val) = &self.query.created_at {
224            ep_builder.created_at(val);
225        }
226        if let Some(val) = &self.query.delay {
227            ep_builder.delay(*val);
228        }
229        if let Some(val) = &self.query.description {
230            ep_builder.description(val);
231        }
232        if let Some(val) = &self.query.expected_codes {
233            ep_builder.expected_codes(val);
234        }
235        if let Some(val) = &self.query.http_method {
236            ep_builder.http_method(val);
237        }
238        if let Some(val) = &self.query.id {
239            ep_builder.id(val);
240        }
241        if let Some(val) = &self.query.limit {
242            ep_builder.limit(*val);
243        }
244        if let Some(val) = &self.query.marker {
245            ep_builder.marker(val);
246        }
247        if let Some(val) = &self.query.max_retries {
248            ep_builder.max_retries(*val);
249        }
250        if let Some(val) = &self.query.max_retries_down {
251            ep_builder.max_retries_down(*val);
252        }
253        if let Some(val) = &self.query.name {
254            ep_builder.name(val);
255        }
256        if let Some(val) = &self.query.not_tags {
257            ep_builder.not_tags(val);
258        }
259        if let Some(val) = &self.query.not_tags_any {
260            ep_builder.not_tags_any(val);
261        }
262        if let Some(val) = &self.query.operating_status {
263            ep_builder.operating_status(val);
264        }
265        if let Some(val) = &self.query.page_reverse {
266            ep_builder.page_reverse(*val);
267        }
268        if let Some(val) = &self.query.pool_id {
269            ep_builder.pool_id(val);
270        }
271        if let Some(id) = &self.query.project.project_id {
272            // project_id is passed. No need to lookup
273            ep_builder.project_id(id);
274        } else if let Some(name) = &self.query.project.project_name {
275            // project_name is passed. Need to lookup resource
276            let mut sub_find_builder = find_project::Request::builder();
277            warn!(
278                "Querying project by name (because of `--project-name` parameter passed) may not be definite. This may fail in which case parameter `--project-id` should be used instead."
279            );
280
281            sub_find_builder.id(name);
282            let find_ep = sub_find_builder
283                .build()
284                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
285            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
286            // Try to extract resource id
287            match find_data.get("id") {
288                Some(val) => match val.as_str() {
289                    Some(id_str) => {
290                        ep_builder.project_id(id_str.to_owned());
291                    }
292                    None => {
293                        return Err(OpenStackCliError::ResourceAttributeNotString(
294                            serde_json::to_string(&val)?,
295                        ));
296                    }
297                },
298                None => {
299                    return Err(OpenStackCliError::ResourceAttributeMissing(
300                        "id".to_string(),
301                    ));
302                }
303            };
304        } else if self.query.project.current_project {
305            ep_builder.project_id(
306                client
307                    .get_auth_info()
308                    .ok_or_eyre("Cannot determine current authentication information")?
309                    .token
310                    .user
311                    .id,
312            );
313        }
314        if let Some(val) = &self.query.provisioning_status {
315            ep_builder.provisioning_status(val);
316        }
317        if let Some(val) = &self.query.tags {
318            ep_builder.tags(val);
319        }
320        if let Some(val) = &self.query.tags_any {
321            ep_builder.tags_any(val);
322        }
323        if let Some(val) = &self.query.timeout {
324            ep_builder.timeout(*val);
325        }
326        if let Some(val) = &self.query._type {
327            ep_builder._type(val);
328        }
329        if let Some(val) = &self.query.updated_at {
330            ep_builder.updated_at(val);
331        }
332        if let Some(val) = &self.query.url_path {
333            ep_builder.url_path(val);
334        }
335
336        let ep = ep_builder
337            .build()
338            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
339
340        let data: Vec<serde_json::Value> = paged(ep, Pagination::Limit(self.max_items))
341            .query_async(client)
342            .await?;
343
344        op.output_list::<response::list::HealthmonitorResponse>(data.clone())?;
345        // Show command specific hints
346        op.show_command_hint()?;
347        Ok(())
348    }
349}