Skip to main content

openstack_cli_load_balancer/v2/quota/
show.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//! Show Quota command
19//!
20//! Wraps invoking of the `v2/lbaas/quotas/{project_id}` 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 eyre::eyre;
32use openstack_sdk::api::QueryAsync;
33use openstack_sdk::api::find_by_name;
34use openstack_sdk::api::identity::v3::project::find as find_project;
35use openstack_sdk::api::load_balancer::v2::quota::get;
36use openstack_types::load_balancer::v2::quota::response;
37use tracing::warn;
38
39/// Show the quota 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 show quota for other projects.
48///
49/// A quota of `-1` means the quota is unlimited.
50#[derive(Args)]
51#[command(about = "Show Project Quota")]
52pub struct QuotaCommand {
53    /// Request Query parameters
54    #[command(flatten)]
55    query: QueryParameters,
56
57    /// Path parameters
58    #[command(flatten)]
59    path: PathParameters,
60}
61
62/// Query parameters
63#[derive(Args)]
64struct QueryParameters {}
65
66/// Path parameters
67#[derive(Args)]
68struct PathParameters {
69    /// Project resource for which the operation should be performed.
70    #[command(flatten)]
71    project: ProjectInput,
72}
73
74/// Project input select group
75#[derive(Args)]
76#[group(required = true, multiple = false)]
77struct ProjectInput {
78    /// Project Name.
79    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
80    project_name: Option<String>,
81    /// Project ID.
82    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
83    project_id: Option<String>,
84    /// Current project.
85    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
86    current_project: bool,
87}
88
89impl QuotaCommand {
90    /// Perform command action
91    pub async fn take_action<C: CliArgs>(
92        &self,
93        parsed_args: &C,
94        client: &mut AsyncOpenStack,
95    ) -> Result<(), OpenStackCliError> {
96        info!("Show Quota");
97
98        let op = OutputProcessor::from_args(parsed_args, Some("load-balancer.quota"), Some("show"));
99        op.validate_args(parsed_args)?;
100
101        let mut ep_builder = get::Request::builder();
102
103        // Process path parameter `project_id`
104        if let Some(id) = &self.path.project.project_id {
105            // project_id is passed. No need to lookup
106            ep_builder.project_id(id);
107        } else if let Some(name) = &self.path.project.project_name {
108            // project_name is passed. Need to lookup resource
109            let mut sub_find_builder = find_project::Request::builder();
110            warn!(
111                "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."
112            );
113
114            sub_find_builder.id(name);
115            let find_ep = sub_find_builder
116                .build()
117                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
118            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
119            // Try to extract resource id
120            match find_data.get("id") {
121                Some(val) => match val.as_str() {
122                    Some(id_str) => {
123                        ep_builder.project_id(id_str.to_owned());
124                    }
125                    None => {
126                        return Err(OpenStackCliError::ResourceAttributeNotString(
127                            serde_json::to_string(&val)?,
128                        ));
129                    }
130                },
131                None => {
132                    return Err(OpenStackCliError::ResourceAttributeMissing(
133                        "id".to_string(),
134                    ));
135                }
136            };
137        } else if self.path.project.current_project {
138            let token = client
139                .get_auth_info()
140                .ok_or_eyre("Cannot determine current authentication information")?
141                .token;
142            if let Some(project) = token.project {
143                ep_builder.project_id(
144                    project
145                        .id
146                        .ok_or_eyre("Project ID is missing in the project auth info")?,
147                );
148            } else {
149                return Err(eyre!("Current project information can not be identified").into());
150            }
151        }
152
153        let ep = ep_builder
154            .build()
155            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
156
157        let data: serde_json::Value = ep.query_async(client).await?;
158
159        op.output_single::<response::get::QuotaResponse>(data.clone())?;
160        // Show command specific hints
161        op.show_command_hint()?;
162        Ok(())
163    }
164}