Skip to main content

openstack_cli_dns/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/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::dns::v2::quota::get;
34use openstack_sdk::api::find_by_name;
35use openstack_sdk::api::identity::v3::project::find as find_project;
36use openstack_types::dns::v2::quota::response;
37use tracing::warn;
38
39/// View a projects quotas
40///
41/// This returns a key:value set of quotas on the system.
42#[derive(Args)]
43#[command(about = "View Quotas")]
44pub struct QuotaCommand {
45    /// Request Query parameters
46    #[command(flatten)]
47    query: QueryParameters,
48
49    /// Request Headers parameters
50    #[command(flatten)]
51    headers: HeaderParameters,
52
53    /// Path parameters
54    #[command(flatten)]
55    path: PathParameters,
56}
57
58/// Query parameters
59#[derive(Args)]
60struct QueryParameters {}
61
62/// Header parameters
63#[derive(Args)]
64struct HeaderParameters {
65    /// If enabled this will show results from all projects in Designate
66    #[arg(long)]
67    x_auth_all_projects: Option<bool>,
68
69    /// This allows a user to impersonate another project
70    #[arg(long)]
71    x_auth_sudo_project_id: Option<String>,
72}
73
74/// Path parameters
75#[derive(Args)]
76struct PathParameters {
77    /// Project resource for which the operation should be performed.
78    #[command(flatten)]
79    project: ProjectInput,
80}
81
82/// Project input select group
83#[derive(Args)]
84#[group(required = true, multiple = false)]
85struct ProjectInput {
86    /// Project Name.
87    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
88    project_name: Option<String>,
89    /// Project ID.
90    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
91    project_id: Option<String>,
92    /// Current project.
93    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
94    current_project: bool,
95}
96
97impl QuotaCommand {
98    /// Perform command action
99    pub async fn take_action<C: CliArgs>(
100        &self,
101        parsed_args: &C,
102        client: &mut AsyncOpenStack,
103    ) -> Result<(), OpenStackCliError> {
104        info!("Show Quota");
105
106        let op = OutputProcessor::from_args(parsed_args, Some("dns.quota"), Some("show"));
107        op.validate_args(parsed_args)?;
108
109        let mut ep_builder = get::Request::builder();
110        // Set path parameters
111
112        // Process path parameter `project_id`
113        if let Some(id) = &self.path.project.project_id {
114            // project_id is passed. No need to lookup
115            ep_builder.project_id(id);
116        } else if let Some(name) = &self.path.project.project_name {
117            // project_name is passed. Need to lookup resource
118            let mut sub_find_builder = find_project::Request::builder();
119            warn!(
120                "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."
121            );
122
123            sub_find_builder.id(name);
124            let find_ep = sub_find_builder
125                .build()
126                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
127            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
128            // Try to extract resource id
129            match find_data.get("id") {
130                Some(val) => match val.as_str() {
131                    Some(id_str) => {
132                        ep_builder.project_id(id_str.to_owned());
133                    }
134                    None => {
135                        return Err(OpenStackCliError::ResourceAttributeNotString(
136                            serde_json::to_string(&val)?,
137                        ));
138                    }
139                },
140                None => {
141                    return Err(OpenStackCliError::ResourceAttributeMissing(
142                        "id".to_string(),
143                    ));
144                }
145            };
146        } else if self.path.project.current_project {
147            let token = client
148                .get_auth_info()
149                .ok_or_eyre("Cannot determine current authentication information")?
150                .token;
151            if let Some(project) = token.project {
152                ep_builder.project_id(
153                    project
154                        .id
155                        .ok_or_eyre("Project ID is missing in the project auth info")?,
156                );
157            } else {
158                return Err(eyre!("Current project information can not be identified").into());
159            }
160        }
161
162        // Set header parameters
163        if let Some(val) = &self.headers.x_auth_all_projects {
164            ep_builder.header(
165                http::header::HeaderName::from_static("x-auth-all-projects"),
166                http::header::HeaderValue::from_static(if *val { "true" } else { "false" }),
167            );
168        }
169        if let Some(val) = &self.headers.x_auth_sudo_project_id {
170            ep_builder.header(
171                http::header::HeaderName::from_static("x-auth-sudo-project-id"),
172                http::header::HeaderValue::from_str(val)?,
173            );
174        }
175
176        let ep = ep_builder
177            .build()
178            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
179
180        let data: serde_json::Value = ep.query_async(client).await?;
181
182        op.output_single::<response::get::QuotaResponse>(data.clone())?;
183        // Show command specific hints
184        op.show_command_hint()?;
185        Ok(())
186    }
187}