Skip to main content

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