openstack_cli 0.13.5

OpenStack client rewritten in Rust
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Set QuotaSet command [microversion = 2.36]
//!
//! Wraps invoking of the `v2.1/os-quota-sets/{id}` with `PUT` method

use clap::Args;
use eyre::{OptionExt, WrapErr};
use tracing::info;

use openstack_sdk::AsyncOpenStack;

use crate::Cli;
use crate::OpenStackCliError;
use crate::output::OutputProcessor;

use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::compute::v2::quota_set::set_236;
use openstack_sdk::api::find_by_name;
use openstack_sdk::api::identity::v3::user::find as find_user;
use openstack_types::compute::v2::quota_set::response::set::QuotaSetResponse;
use tracing::warn;

/// Update the quotas for a project or a project and a user.
///
/// Users can force the update even if the quota has already been used and the
/// reserved quota exceeds the new quota. To force the update, specify the
/// `"force": True` attribute in the request body, the default value is
/// `false`.
///
/// Normal response codes: 200
///
/// Error response codes: badRequest(400), unauthorized(401), forbidden(403)
#[derive(Args)]
#[command(about = "Update Quotas (microversion = 2.36)")]
pub struct QuotaSetCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// A `quota_set` object.
    #[command(flatten)]
    quota_set: QuotaSet,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {
    /// User resource for which the operation should be performed.
    #[command(flatten)]
    user: UserInput,
}

/// User input select group
#[derive(Args)]
#[group(required = false, multiple = false)]
struct UserInput {
    /// User Name.
    #[arg(long, help_heading = "Path parameters", value_name = "USER_NAME")]
    user_name: Option<String>,
    /// User ID.
    #[arg(long, help_heading = "Path parameters", value_name = "USER_ID")]
    user_id: Option<String>,
    /// Current authenticated user.
    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
    current_user: bool,
}

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// id parameter for /v2.1/os-quota-sets/{id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_id",
        value_name = "ID"
    )]
    id: String,
}
/// QuotaSet Body data
#[derive(Args, Clone)]
struct QuotaSet {
    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    cores: Option<i32>,

    /// You can force the update even if the quota has already been used and
    /// the reserved quota exceeds the new quota. To force the update, specify
    /// the `"force": "True"`. Default is `False`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    force: Option<bool>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    injected_file_content_bytes: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    injected_file_path_bytes: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    injected_files: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    instances: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    key_pairs: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    metadata_items: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    ram: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    server_group_members: Option<i32>,

    /// The number of allowed injected files for each tenant.
    ///
    /// **Available until version 2.56**
    #[arg(help_heading = "Body parameters", long)]
    server_groups: Option<i32>,
}

impl QuotaSetCommand {
    /// Perform command action
    pub async fn take_action(
        &self,
        parsed_args: &Cli,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Set QuotaSet");

        let op = OutputProcessor::from_args(parsed_args, Some("compute.quota_set"), Some("set"));
        op.validate_args(parsed_args)?;

        let mut ep_builder = set_236::Request::builder();
        ep_builder.header(
            http::header::HeaderName::from_static("openstack-api-version"),
            http::header::HeaderValue::from_static("compute 2.36"),
        );

        ep_builder.id(&self.path.id);
        // Set query parameters
        if let Some(id) = &self.query.user.user_id {
            // user_id is passed. No need to lookup
            ep_builder.user_id(id);
        } else if let Some(name) = &self.query.user.user_name {
            // user_name is passed. Need to lookup resource
            let mut sub_find_builder = find_user::Request::builder();
            warn!(
                "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."
            );

            sub_find_builder.id(name);
            let find_ep = sub_find_builder
                .build()
                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
            // Try to extract resource id
            match find_data.get("id") {
                Some(val) => match val.as_str() {
                    Some(id_str) => {
                        ep_builder.user_id(id_str.to_owned());
                    }
                    None => {
                        return Err(OpenStackCliError::ResourceAttributeNotString(
                            serde_json::to_string(&val)?,
                        ));
                    }
                },
                None => {
                    return Err(OpenStackCliError::ResourceAttributeMissing(
                        "id".to_string(),
                    ));
                }
            };
        } else if self.query.user.current_user {
            ep_builder.user_id(
                client
                    .get_auth_info()
                    .ok_or_eyre("Cannot determine current authentication information")?
                    .token
                    .user
                    .id,
            );
        }

        // Set body parameters
        // Set Request.quota_set data
        let args = &self.quota_set;
        let mut quota_set_builder = set_236::QuotaSetBuilder::default();
        if let Some(val) = &args.cores {
            quota_set_builder.cores(*val);
        }

        if let Some(val) = &args.force {
            quota_set_builder.force(*val);
        }

        if let Some(val) = &args.injected_file_content_bytes {
            quota_set_builder.injected_file_content_bytes(*val);
        }

        if let Some(val) = &args.injected_file_path_bytes {
            quota_set_builder.injected_file_path_bytes(*val);
        }

        if let Some(val) = &args.injected_files {
            quota_set_builder.injected_files(*val);
        }

        if let Some(val) = &args.instances {
            quota_set_builder.instances(*val);
        }

        if let Some(val) = &args.key_pairs {
            quota_set_builder.key_pairs(*val);
        }

        if let Some(val) = &args.metadata_items {
            quota_set_builder.metadata_items(*val);
        }

        if let Some(val) = &args.ram {
            quota_set_builder.ram(*val);
        }

        if let Some(val) = &args.server_group_members {
            quota_set_builder.server_group_members(*val);
        }

        if let Some(val) = &args.server_groups {
            quota_set_builder.server_groups(*val);
        }

        ep_builder.quota_set(
            quota_set_builder
                .build()
                .wrap_err("error preparing the request data")?,
        );

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data = ep.query_async(client).await?;
        op.output_single::<QuotaSetResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}