Skip to main content

openstack_cli_compute/v2/quota_set/
set_236.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.36]
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_236;
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.36)")]
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 injected files for each tenant.
102    ///
103    /// **Available until version 2.56**
104    #[arg(help_heading = "Body parameters", long)]
105    cores: Option<i32>,
106
107    /// You can force the update even if the quota has already been used and
108    /// the reserved quota exceeds the new quota. To force the update, specify
109    /// the `"force": "True"`. Default is `False`.
110    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
111    force: Option<bool>,
112
113    /// The number of allowed injected files for each tenant.
114    ///
115    /// **Available until version 2.56**
116    #[arg(help_heading = "Body parameters", long)]
117    injected_file_content_bytes: Option<i32>,
118
119    /// The number of allowed injected files for each tenant.
120    ///
121    /// **Available until version 2.56**
122    #[arg(help_heading = "Body parameters", long)]
123    injected_file_path_bytes: Option<i32>,
124
125    /// The number of allowed injected files for each tenant.
126    ///
127    /// **Available until version 2.56**
128    #[arg(help_heading = "Body parameters", long)]
129    injected_files: Option<i32>,
130
131    /// The number of allowed injected files for each tenant.
132    ///
133    /// **Available until version 2.56**
134    #[arg(help_heading = "Body parameters", long)]
135    instances: Option<i32>,
136
137    /// The number of allowed injected files for each tenant.
138    ///
139    /// **Available until version 2.56**
140    #[arg(help_heading = "Body parameters", long)]
141    key_pairs: Option<i32>,
142
143    /// The number of allowed injected files for each tenant.
144    ///
145    /// **Available until version 2.56**
146    #[arg(help_heading = "Body parameters", long)]
147    metadata_items: Option<i32>,
148
149    /// The number of allowed injected files for each tenant.
150    ///
151    /// **Available until version 2.56**
152    #[arg(help_heading = "Body parameters", long)]
153    ram: Option<i32>,
154
155    /// The number of allowed injected files for each tenant.
156    ///
157    /// **Available until version 2.56**
158    #[arg(help_heading = "Body parameters", long)]
159    server_group_members: Option<i32>,
160
161    /// The number of allowed injected files for each tenant.
162    ///
163    /// **Available until version 2.56**
164    #[arg(help_heading = "Body parameters", long)]
165    server_groups: Option<i32>,
166}
167
168impl QuotaSetCommand {
169    /// Perform command action
170    pub async fn take_action<C: CliArgs>(
171        &self,
172        parsed_args: &C,
173        client: &mut AsyncOpenStack,
174    ) -> Result<(), OpenStackCliError> {
175        info!("Set QuotaSet");
176
177        let op = OutputProcessor::from_args(parsed_args, Some("compute.quota_set"), Some("set"));
178        op.validate_args(parsed_args)?;
179
180        let mut ep_builder = set_236::Request::builder();
181        ep_builder.header(
182            http::header::HeaderName::from_static("openstack-api-version"),
183            http::header::HeaderValue::from_static("compute 2.36"),
184        );
185
186        ep_builder.id(&self.path.id);
187        // Set query parameters
188        if let Some(id) = &self.query.user.user_id {
189            // user_id is passed. No need to lookup
190            ep_builder.user_id(id);
191        } else if let Some(name) = &self.query.user.user_name {
192            // user_name is passed. Need to lookup resource
193            let mut sub_find_builder = find_user::Request::builder();
194            warn!(
195                "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."
196            );
197
198            sub_find_builder.id(name);
199            let find_ep = sub_find_builder
200                .build()
201                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
202            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
203            // Try to extract resource id
204            match find_data.get("id") {
205                Some(val) => match val.as_str() {
206                    Some(id_str) => {
207                        ep_builder.user_id(id_str.to_owned());
208                    }
209                    None => {
210                        return Err(OpenStackCliError::ResourceAttributeNotString(
211                            serde_json::to_string(&val)?,
212                        ));
213                    }
214                },
215                None => {
216                    return Err(OpenStackCliError::ResourceAttributeMissing(
217                        "id".to_string(),
218                    ));
219                }
220            };
221        } else if self.query.user.current_user {
222            ep_builder.user_id(
223                client
224                    .get_auth_info()
225                    .ok_or_eyre("Cannot determine current authentication information")?
226                    .token
227                    .user
228                    .id,
229            );
230        }
231
232        // Set body parameters
233        // Set Request.quota_set data
234        let args = &self.quota_set;
235        let mut quota_set_builder = set_236::QuotaSetBuilder::default();
236        if let Some(val) = &args.cores {
237            quota_set_builder.cores(*val);
238        }
239
240        if let Some(val) = &args.force {
241            quota_set_builder.force(*val);
242        }
243
244        if let Some(val) = &args.injected_file_content_bytes {
245            quota_set_builder.injected_file_content_bytes(*val);
246        }
247
248        if let Some(val) = &args.injected_file_path_bytes {
249            quota_set_builder.injected_file_path_bytes(*val);
250        }
251
252        if let Some(val) = &args.injected_files {
253            quota_set_builder.injected_files(*val);
254        }
255
256        if let Some(val) = &args.instances {
257            quota_set_builder.instances(*val);
258        }
259
260        if let Some(val) = &args.key_pairs {
261            quota_set_builder.key_pairs(*val);
262        }
263
264        if let Some(val) = &args.metadata_items {
265            quota_set_builder.metadata_items(*val);
266        }
267
268        if let Some(val) = &args.ram {
269            quota_set_builder.ram(*val);
270        }
271
272        if let Some(val) = &args.server_group_members {
273            quota_set_builder.server_group_members(*val);
274        }
275
276        if let Some(val) = &args.server_groups {
277            quota_set_builder.server_groups(*val);
278        }
279
280        ep_builder.quota_set(
281            quota_set_builder
282                .build()
283                .wrap_err("error preparing the request data")?,
284        );
285
286        let ep = ep_builder
287            .build()
288            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
289
290        let data: serde_json::Value = ep.query_async(client).await?;
291
292        op.output_single::<response::set_236::QuotaSetResponse>(data.clone())?;
293        // Show command specific hints
294        op.show_command_hint()?;
295        Ok(())
296    }
297}