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 Rule command
//!
//! Wraps invoking of the `v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id}` with `PUT` method

use clap::Args;
use eyre::WrapErr;
use tracing::info;

use openstack_sdk::AsyncOpenStack;

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

use clap::ValueEnum;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::load_balancer::v2::l7policy::rule::set;
use openstack_types::load_balancer::v2::l7policy::rule::response::set::RuleResponse;

/// Updates a L7 rule.
///
/// If the request is valid, the service returns the `Accepted (202)` response
/// code. To confirm the update, check that the L7 rule provisioning status is
/// `ACTIVE`. If the status is `PENDING_UPDATE`, use a GET operation to poll
/// the L7 rule object for changes.
///
/// This operation returns the updated L7 rule object with the `ACTIVE`,
/// `PENDING_UPDATE`, or `ERROR` provisioning status.
#[derive(Args)]
#[command(about = "Update a L7 Rule")]
pub struct RuleCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// Defines attributes that are acceptable of a PUT request.
    #[command(flatten)]
    rule: Rule,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// l7policy_id parameter for
    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_l7policy_id",
        value_name = "L7POLICY_ID"
    )]
    l7policy_id: String,

    /// rule_id parameter for
    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_id",
        value_name = "ID"
    )]
    id: String,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum CompareType {
    Contains,
    EndsWith,
    EqualTo,
    Regex,
    StartsWith,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Type {
    Cookie,
    FileType,
    Header,
    HostName,
    Path,
    SslConnHasCert,
    SslDnField,
    SslVerifyResult,
}

/// Rule Body data
#[derive(Args, Clone)]
struct Rule {
    /// The administrative state of the resource, which is up (`true`) or down
    /// (`false`). Default is `true`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    admin_state_up: Option<bool>,

    /// The comparison type for the L7 rule. One of `CONTAINS`, `ENDS_WITH`,
    /// `EQUAL_TO`, `REGEX`, or `STARTS_WITH`.
    #[arg(help_heading = "Body parameters", long)]
    compare_type: Option<CompareType>,

    /// When `true` the logic of the rule is inverted. For example, with invert
    /// `true`, equal to would become not equal to. Default is `false`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    invert: Option<bool>,

    /// The key to use for the comparison. For example, the name of the cookie
    /// to evaluate.
    #[arg(help_heading = "Body parameters", long)]
    key: Option<String>,

    /// A list of simple strings assigned to the resource.
    ///
    /// **New in version 2.5**
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    tags: Option<Vec<String>>,

    /// The L7 rule type. One of `COOKIE`, `FILE_TYPE`, `HEADER`, `HOST_NAME`,
    /// `PATH`, `SSL_CONN_HAS_CERT`, `SSL_VERIFY_RESULT`, or `SSL_DN_FIELD`.
    #[arg(help_heading = "Body parameters", long)]
    _type: Option<Type>,

    /// The value to use for the comparison. For example, the file type to
    /// compare.
    #[arg(help_heading = "Body parameters", long)]
    value: Option<String>,
}

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

        let op = OutputProcessor::from_args(
            parsed_args,
            Some("load-balancer.l7policy/rule"),
            Some("set"),
        );
        op.validate_args(parsed_args)?;

        let mut ep_builder = set::Request::builder();

        ep_builder.l7policy_id(&self.path.l7policy_id);
        ep_builder.id(&self.path.id);

        // Set body parameters
        // Set Request.rule data
        let args = &self.rule;
        let mut rule_builder = set::RuleBuilder::default();
        if let Some(val) = &args.admin_state_up {
            rule_builder.admin_state_up(*val);
        }

        if let Some(val) = &args.compare_type {
            let tmp = match val {
                CompareType::Contains => set::CompareType::Contains,
                CompareType::EndsWith => set::CompareType::EndsWith,
                CompareType::EqualTo => set::CompareType::EqualTo,
                CompareType::Regex => set::CompareType::Regex,
                CompareType::StartsWith => set::CompareType::StartsWith,
            };
            rule_builder.compare_type(tmp);
        }

        if let Some(val) = &args.invert {
            rule_builder.invert(*val);
        }

        if let Some(val) = &args.key {
            rule_builder.key(val);
        }

        if let Some(val) = &args.tags {
            rule_builder.tags(val.iter().map(Into::into).collect::<Vec<_>>());
        }

        if let Some(val) = &args._type {
            let tmp = match val {
                Type::Cookie => set::Type::Cookie,
                Type::FileType => set::Type::FileType,
                Type::Header => set::Type::Header,
                Type::HostName => set::Type::HostName,
                Type::Path => set::Type::Path,
                Type::SslConnHasCert => set::Type::SslConnHasCert,
                Type::SslDnField => set::Type::SslDnField,
                Type::SslVerifyResult => set::Type::SslVerifyResult,
            };
            rule_builder._type(tmp);
        }

        if let Some(val) = &args.value {
            rule_builder.value(val);
        }

        ep_builder.rule(
            rule_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::<RuleResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}