Skip to main content

openstack_cli_compute/v2/quota_set/
set_257.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 QuotaSet command [microversion = 2.57]
19//!
20//! Wraps invoking of the `v2.1/os-quota-sets/{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 openstack_sdk::api::QueryAsync;
32use openstack_sdk::api::compute::v2::quota_set::set_257;
33use openstack_sdk::api::find_by_name;
34use openstack_sdk::api::identity::v3::user::find as find_user;
35use openstack_types::compute::v2::quota_set::response;
36use tracing::warn;
37
38/// Update the quotas for a project or a project and a user.
39///
40/// Users can force the update even if the quota has already been used and the
41/// reserved quota exceeds the new quota. To force the update, specify the
42/// `"force": True` attribute in the request body, the default value is
43/// `false`.
44///
45/// Normal response codes: 200
46///
47/// Error response codes: badRequest(400), unauthorized(401), forbidden(403)
48#[derive(Args)]
49#[command(about = "Update Quotas (microversion = 2.57)")]
50pub struct QuotaSetCommand {
51    /// Request Query parameters
52    #[command(flatten)]
53    query: QueryParameters,
54
55    /// Path parameters
56    #[command(flatten)]
57    path: PathParameters,
58
59    /// A `quota_set` object.
60    #[command(flatten)]
61    quota_set: QuotaSet,
62}
63
64/// Query parameters
65#[derive(Args)]
66struct QueryParameters {
67    /// User resource for which the operation should be performed.
68    #[command(flatten)]
69    user: UserInput,
70}
71
72/// User input select group
73#[derive(Args)]
74#[group(required = false, multiple = false)]
75struct UserInput {
76    /// User Name.
77    #[arg(long, help_heading = "Path parameters", value_name = "USER_NAME")]
78    user_name: Option<String>,
79    /// User ID.
80    #[arg(long, help_heading = "Path parameters", value_name = "USER_ID")]
81    user_id: Option<String>,
82    /// Current authenticated user.
83    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
84    current_user: bool,
85}
86
87/// Path parameters
88#[derive(Args)]
89struct PathParameters {
90    /// id parameter for /v2.1/os-quota-sets/{id} API
91    #[arg(
92        help_heading = "Path parameters",
93        id = "path_param_id",
94        value_name = "ID"
95    )]
96    id: String,
97}
98/// QuotaSet Body data
99#[derive(Args, Clone)]
100struct QuotaSet {
101    /// The number of allowed members for each server group.
102    #[arg(help_heading = "Body parameters", long)]
103    cores: Option<i32>,
104
105    /// You can force the update even if the quota has already been used and
106    /// the reserved quota exceeds the new quota. To force the update, specify
107    /// the `"force": "True"`. Default is `False`.
108    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
109    force: Option<bool>,
110
111    /// The number of allowed members for each server group.
112    #[arg(help_heading = "Body parameters", long)]
113    instances: Option<i32>,
114
115    /// The number of allowed members for each server group.
116    #[arg(help_heading = "Body parameters", long)]
117    key_pairs: Option<i32>,
118
119    /// The number of allowed members for each server group.
120    #[arg(help_heading = "Body parameters", long)]
121    metadata_items: Option<i32>,
122
123    /// The number of allowed members for each server group.
124    #[arg(help_heading = "Body parameters", long)]
125    ram: Option<i32>,
126
127    /// The number of allowed members for each server group.
128    #[arg(help_heading = "Body parameters", long)]
129    server_group_members: Option<i32>,
130
131    /// The number of allowed members for each server group.
132    #[arg(help_heading = "Body parameters", long)]
133    server_groups: Option<i32>,
134}
135
136impl QuotaSetCommand {
137    /// Perform command action
138    pub async fn take_action<C: CliArgs>(
139        &self,
140        parsed_args: &C,
141        client: &mut AsyncOpenStack,
142    ) -> Result<(), OpenStackCliError> {
143        info!("Set QuotaSet");
144
145        let op = OutputProcessor::from_args(parsed_args, Some("compute.quota_set"), Some("set"));
146        op.validate_args(parsed_args)?;
147
148        let mut ep_builder = set_257::Request::builder();
149        ep_builder.header(
150            http::header::HeaderName::from_static("openstack-api-version"),
151            http::header::HeaderValue::from_static("compute 2.57"),
152        );
153
154        ep_builder.id(&self.path.id);
155        // Set query parameters
156        if let Some(id) = &self.query.user.user_id {
157            // user_id is passed. No need to lookup
158            ep_builder.user_id(id);
159        } else if let Some(name) = &self.query.user.user_name {
160            // user_name is passed. Need to lookup resource
161            let mut sub_find_builder = find_user::Request::builder();
162            warn!(
163                "Querying user by name (because of `--user-name` parameter passed) may not be definite. This may fail in which case parameter `--user-id` should be used instead."
164            );
165
166            sub_find_builder.id(name);
167            let find_ep = sub_find_builder
168                .build()
169                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
170            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
171            // Try to extract resource id
172            match find_data.get("id") {
173                Some(val) => match val.as_str() {
174                    Some(id_str) => {
175                        ep_builder.user_id(id_str.to_owned());
176                    }
177                    None => {
178                        return Err(OpenStackCliError::ResourceAttributeNotString(
179                            serde_json::to_string(&val)?,
180                        ));
181                    }
182                },
183                None => {
184                    return Err(OpenStackCliError::ResourceAttributeMissing(
185                        "id".to_string(),
186                    ));
187                }
188            };
189        } else if self.query.user.current_user {
190            ep_builder.user_id(
191                client
192                    .get_auth_info()
193                    .ok_or_eyre("Cannot determine current authentication information")?
194                    .token
195                    .user
196                    .id,
197            );
198        }
199
200        // Set body parameters
201        // Set Request.quota_set data
202        let args = &self.quota_set;
203        let mut quota_set_builder = set_257::QuotaSetBuilder::default();
204        if let Some(val) = &args.cores {
205            quota_set_builder.cores(*val);
206        }
207
208        if let Some(val) = &args.force {
209            quota_set_builder.force(*val);
210        }
211
212        if let Some(val) = &args.instances {
213            quota_set_builder.instances(*val);
214        }
215
216        if let Some(val) = &args.key_pairs {
217            quota_set_builder.key_pairs(*val);
218        }
219
220        if let Some(val) = &args.metadata_items {
221            quota_set_builder.metadata_items(*val);
222        }
223
224        if let Some(val) = &args.ram {
225            quota_set_builder.ram(*val);
226        }
227
228        if let Some(val) = &args.server_group_members {
229            quota_set_builder.server_group_members(*val);
230        }
231
232        if let Some(val) = &args.server_groups {
233            quota_set_builder.server_groups(*val);
234        }
235
236        ep_builder.quota_set(
237            quota_set_builder
238                .build()
239                .wrap_err("error preparing the request data")?,
240        );
241
242        let ep = ep_builder
243            .build()
244            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
245
246        let data: serde_json::Value = ep.query_async(client).await?;
247
248        op.output_single::<response::set_257::QuotaSetResponse>(data.clone())?;
249        // Show command specific hints
250        op.show_command_hint()?;
251        Ok(())
252    }
253}