Skip to main content

openstack_cli_load_balancer/v2/quota/
set.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//! Set Quota command
19//!
20//! Wraps invoking of the `v2/lbaas/quotas/{project_id}` with `PUT` method
21
22use clap::Args;
23use eyre::{OptionExt, WrapErr};
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::set;
36use openstack_types::load_balancer::v2::quota::response;
37use tracing::warn;
38
39/// Updates a quota for a project.
40///
41/// If the request is valid, the service returns the `Accepted (202)` response
42/// code.
43///
44/// This operation returns the updated quota object.
45///
46/// If the quota is specified as `null` the quota will use the deployment
47/// default quota settings.
48///
49/// Specifying a quota of `-1` means the quota is unlimited.
50///
51/// Specifying a quota of `0` means the project cannot create any of the
52/// resource.
53#[derive(Args)]
54#[command(about = "Update a Quota")]
55pub struct QuotaCommand {
56    /// Request Query parameters
57    #[command(flatten)]
58    query: QueryParameters,
59
60    /// Path parameters
61    #[command(flatten)]
62    path: PathParameters,
63
64    /// Base type for complex types
65    #[command(flatten)]
66    quota: Quota,
67}
68
69/// Query parameters
70#[derive(Args)]
71struct QueryParameters {}
72
73/// Path parameters
74#[derive(Args)]
75struct PathParameters {
76    /// Project resource for which the operation should be performed.
77    #[command(flatten)]
78    project: ProjectInput,
79}
80
81/// Project input select group
82#[derive(Args)]
83#[group(required = true, multiple = false)]
84struct ProjectInput {
85    /// Project Name.
86    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
87    project_name: Option<String>,
88    /// Project ID.
89    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
90    project_id: Option<String>,
91    /// Current project.
92    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
93    current_project: bool,
94}
95/// Quota Body data
96#[derive(Args, Clone)]
97struct Quota {
98    #[arg(help_heading = "Body parameters", long)]
99    health_monitor: Option<i32>,
100
101    /// The configured health monitor quota limit. A setting of `null` means it
102    /// is using the deployment default quota. A setting of `-1` means
103    /// unlimited.
104    #[arg(help_heading = "Body parameters", long)]
105    healthmonitor: Option<i32>,
106
107    /// The configured l7policy quota limit. A setting of `null` means it is
108    /// using the deployment default quota. A setting of `-1` means unlimited.
109    #[arg(help_heading = "Body parameters", long)]
110    l7policy: Option<i32>,
111
112    /// The configured l7rule quota limit. A setting of `null` means it is
113    /// using the deployment default quota. A setting of `-1` means unlimited.
114    #[arg(help_heading = "Body parameters", long)]
115    l7rule: Option<i32>,
116
117    /// The configured listener quota limit. A setting of `null` means it is
118    /// using the deployment default quota. A setting of `-1` means unlimited.
119    #[arg(help_heading = "Body parameters", long)]
120    listener: Option<i32>,
121
122    #[arg(help_heading = "Body parameters", long)]
123    load_balancer: Option<i32>,
124
125    /// The configured load balancer quota limit. A setting of `null` means it
126    /// is using the deployment default quota. A setting of `-1` means
127    /// unlimited.
128    #[arg(help_heading = "Body parameters", long)]
129    loadbalancer: Option<i32>,
130
131    /// The configured member quota limit. A setting of `null` means it is
132    /// using the deployment default quota. A setting of `-1` means unlimited.
133    #[arg(help_heading = "Body parameters", long)]
134    member: Option<i32>,
135
136    /// The configured pool quota limit. A setting of `null` means it is using
137    /// the deployment default quota. A setting of `-1` means unlimited.
138    #[arg(help_heading = "Body parameters", long)]
139    pool: Option<i32>,
140}
141
142impl QuotaCommand {
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!("Set Quota");
150
151        let op = OutputProcessor::from_args(parsed_args, Some("load-balancer.quota"), Some("set"));
152        op.validate_args(parsed_args)?;
153
154        let mut ep_builder = set::Request::builder();
155
156        // Process path parameter `project_id`
157        if let Some(id) = &self.path.project.project_id {
158            // project_id is passed. No need to lookup
159            ep_builder.project_id(id);
160        } else if let Some(name) = &self.path.project.project_name {
161            // project_name is passed. Need to lookup resource
162            let mut sub_find_builder = find_project::Request::builder();
163            warn!(
164                "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."
165            );
166
167            sub_find_builder.id(name);
168            let find_ep = sub_find_builder
169                .build()
170                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
171            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
172            // Try to extract resource id
173            match find_data.get("id") {
174                Some(val) => match val.as_str() {
175                    Some(id_str) => {
176                        ep_builder.project_id(id_str.to_owned());
177                    }
178                    None => {
179                        return Err(OpenStackCliError::ResourceAttributeNotString(
180                            serde_json::to_string(&val)?,
181                        ));
182                    }
183                },
184                None => {
185                    return Err(OpenStackCliError::ResourceAttributeMissing(
186                        "id".to_string(),
187                    ));
188                }
189            };
190        } else if self.path.project.current_project {
191            let token = client
192                .get_auth_info()
193                .ok_or_eyre("Cannot determine current authentication information")?
194                .token;
195            if let Some(project) = token.project {
196                ep_builder.project_id(
197                    project
198                        .id
199                        .ok_or_eyre("Project ID is missing in the project auth info")?,
200                );
201            } else {
202                return Err(eyre!("Current project information can not be identified").into());
203            }
204        }
205
206        // Set body parameters
207        // Set Request.quota data
208        let args = &self.quota;
209        let mut quota_builder = set::QuotaBuilder::default();
210        if let Some(val) = &args.health_monitor {
211            quota_builder.health_monitor(*val);
212        }
213
214        if let Some(val) = &args.healthmonitor {
215            quota_builder.healthmonitor(*val);
216        }
217
218        if let Some(val) = &args.l7policy {
219            quota_builder.l7policy(*val);
220        }
221
222        if let Some(val) = &args.l7rule {
223            quota_builder.l7rule(*val);
224        }
225
226        if let Some(val) = &args.listener {
227            quota_builder.listener(*val);
228        }
229
230        if let Some(val) = &args.load_balancer {
231            quota_builder.load_balancer(*val);
232        }
233
234        if let Some(val) = &args.loadbalancer {
235            quota_builder.loadbalancer(*val);
236        }
237
238        if let Some(val) = &args.member {
239            quota_builder.member(*val);
240        }
241
242        if let Some(val) = &args.pool {
243            quota_builder.pool(*val);
244        }
245
246        ep_builder.quota(
247            quota_builder
248                .build()
249                .wrap_err("error preparing the request data")?,
250        );
251
252        let ep = ep_builder
253            .build()
254            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
255
256        let data: serde_json::Value = ep.query_async(client).await?;
257
258        op.output_single::<response::set::QuotaResponse>(data.clone())?;
259        // Show command specific hints
260        op.show_command_hint()?;
261        Ok(())
262    }
263}