Skip to main content

openstack_cli_load_balancer/v2/l7policy/
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 L7Policies command
19//!
20//! Wraps invoking of the `v2/lbaas/l7policies` 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::l7policy::list;
35use openstack_sdk::api::{Pagination, paged};
36use openstack_types::load_balancer::v2::l7policy::response;
37use tracing::warn;
38
39/// Lists all L7 policies 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 L7 policies for other projects.
48///
49/// The list might be empty.
50#[derive(Args)]
51#[command(about = "List L7 Policies")]
52pub struct L7PoliciesCommand {
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    #[arg(help_heading = "Query parameters", long)]
70    action: Option<String>,
71
72    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
73    admin_state_up: Option<bool>,
74
75    #[arg(help_heading = "Query parameters", long)]
76    description: Option<String>,
77
78    /// Page size
79    #[arg(
80        help_heading = "Query parameters",
81        long("page-size"),
82        visible_alias("limit")
83    )]
84    limit: Option<i32>,
85
86    #[arg(help_heading = "Query parameters", long)]
87    listener_id: Option<String>,
88
89    /// ID of the last item in the previous list
90    #[arg(help_heading = "Query parameters", long)]
91    marker: Option<String>,
92
93    #[arg(help_heading = "Query parameters", long)]
94    name: Option<String>,
95
96    #[arg(help_heading = "Query parameters", long)]
97    operating_status: Option<String>,
98
99    /// The page direction.
100    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
101    page_reverse: Option<bool>,
102
103    #[arg(help_heading = "Query parameters", long)]
104    position: Option<String>,
105
106    /// Project resource for which the operation should be performed.
107    #[command(flatten)]
108    project: ProjectInput,
109
110    #[arg(help_heading = "Query parameters", long)]
111    provisioning_status: Option<String>,
112
113    #[arg(help_heading = "Query parameters", long)]
114    redirect_pool_id: Option<String>,
115
116    #[arg(help_heading = "Query parameters", long)]
117    redirect_prefix: Option<String>,
118
119    #[arg(help_heading = "Query parameters", long)]
120    redirect_url: Option<String>,
121}
122
123/// Project input select group
124#[derive(Args)]
125#[group(required = false, multiple = false)]
126struct ProjectInput {
127    /// Project Name.
128    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
129    project_name: Option<String>,
130    /// Project ID.
131    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
132    project_id: Option<String>,
133    /// Current project.
134    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
135    current_project: bool,
136}
137
138/// Path parameters
139#[derive(Args)]
140struct PathParameters {}
141
142impl L7PoliciesCommand {
143    /// Perform command action
144    pub async fn take_action<C: CliArgs>(
145        &self,
146        parsed_args: &C,
147        client: &mut AsyncOpenStack,
148    ) -> Result<(), OpenStackCliError> {
149        info!("List L7Policies");
150
151        let op =
152            OutputProcessor::from_args(parsed_args, Some("load-balancer.l7policy"), Some("list"));
153        op.validate_args(parsed_args)?;
154
155        let mut ep_builder = list::Request::builder();
156
157        // Set query parameters
158        if let Some(val) = &self.query.action {
159            ep_builder.action(val);
160        }
161        if let Some(val) = &self.query.admin_state_up {
162            ep_builder.admin_state_up(*val);
163        }
164        if let Some(val) = &self.query.description {
165            ep_builder.description(val);
166        }
167        if let Some(val) = &self.query.limit {
168            ep_builder.limit(*val);
169        }
170        if let Some(val) = &self.query.listener_id {
171            ep_builder.listener_id(val);
172        }
173        if let Some(val) = &self.query.marker {
174            ep_builder.marker(val);
175        }
176        if let Some(val) = &self.query.name {
177            ep_builder.name(val);
178        }
179        if let Some(val) = &self.query.operating_status {
180            ep_builder.operating_status(val);
181        }
182        if let Some(val) = &self.query.page_reverse {
183            ep_builder.page_reverse(*val);
184        }
185        if let Some(val) = &self.query.position {
186            ep_builder.position(val);
187        }
188        if let Some(id) = &self.query.project.project_id {
189            // project_id is passed. No need to lookup
190            ep_builder.project_id(id);
191        } else if let Some(name) = &self.query.project.project_name {
192            // project_name is passed. Need to lookup resource
193            let mut sub_find_builder = find_project::Request::builder();
194            warn!(
195                "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."
196            );
197
198            sub_find_builder.id(name);
199            let find_ep = sub_find_builder
200                .build()
201                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
202            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
203            // Try to extract resource id
204            match find_data.get("id") {
205                Some(val) => match val.as_str() {
206                    Some(id_str) => {
207                        ep_builder.project_id(id_str.to_owned());
208                    }
209                    None => {
210                        return Err(OpenStackCliError::ResourceAttributeNotString(
211                            serde_json::to_string(&val)?,
212                        ));
213                    }
214                },
215                None => {
216                    return Err(OpenStackCliError::ResourceAttributeMissing(
217                        "id".to_string(),
218                    ));
219                }
220            };
221        } else if self.query.project.current_project {
222            ep_builder.project_id(
223                client
224                    .get_auth_info()
225                    .ok_or_eyre("Cannot determine current authentication information")?
226                    .token
227                    .user
228                    .id,
229            );
230        }
231        if let Some(val) = &self.query.provisioning_status {
232            ep_builder.provisioning_status(val);
233        }
234        if let Some(val) = &self.query.redirect_pool_id {
235            ep_builder.redirect_pool_id(val);
236        }
237        if let Some(val) = &self.query.redirect_prefix {
238            ep_builder.redirect_prefix(val);
239        }
240        if let Some(val) = &self.query.redirect_url {
241            ep_builder.redirect_url(val);
242        }
243
244        let ep = ep_builder
245            .build()
246            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
247
248        let data: Vec<serde_json::Value> = paged(ep, Pagination::Limit(self.max_items))
249            .query_async(client)
250            .await?;
251
252        op.output_list::<response::list::L7policyResponse>(data.clone())?;
253        // Show command specific hints
254        op.show_command_hint()?;
255        Ok(())
256    }
257}