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 Pool command
//!
//! Wraps invoking of the `v2/lbaas/pools/{pool_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::find;
use openstack_sdk::api::load_balancer::v2::pool::find;
use openstack_sdk::api::load_balancer::v2::pool::set;
use openstack_types::load_balancer::v2::pool::response::set::PoolResponse;

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

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

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

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

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// pool_id parameter for /v2/lbaas/pools/{pool_id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_id",
        value_name = "ID"
    )]
    id: String,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum LbAlgorithm {
    LeastConnections,
    RoundRobin,
    SourceIp,
    SourceIpPort,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Type {
    AppCookie,
    HttpCookie,
    SourceIp,
}

/// SessionPersistence Body data
#[derive(Args, Clone)]
#[group(required = false, multiple = true)]
struct SessionPersistence {
    #[arg(help_heading = "Body parameters", long)]
    cookie_name: Option<String>,

    #[arg(help_heading = "Body parameters", long)]
    persistence_granularity: Option<String>,

    #[arg(help_heading = "Body parameters", long)]
    persistence_timeout: Option<i32>,

    #[arg(help_heading = "Body parameters", long)]
    _type: Option<Type>,
}

/// Pool Body data
#[derive(Args, Clone)]
struct Pool {
    /// 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>,

    /// A list of ALPN protocols. Available protocols: http/1.0, http/1.1, h2
    ///
    /// **New in version 2.24**
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    alpn_protocols: Option<Vec<String>>,

    /// The reference of the
    /// [key manager service](https://docs.openstack.org/castellan/latest/)
    /// secret containing a PEM format CA certificate bundle for `tls_enabled`
    /// pools.
    ///
    /// **New in version 2.8**
    #[arg(help_heading = "Body parameters", long)]
    ca_tls_container_ref: Option<String>,

    /// The reference of the
    /// [key manager service](https://docs.openstack.org/castellan/latest/)
    /// secret containing a PEM format CA revocation list file for
    /// `tls_enabled` pools.
    #[arg(help_heading = "Body parameters", long)]
    crl_container_ref: Option<String>,

    /// A human-readable description for the resource.
    #[arg(help_heading = "Body parameters", long)]
    description: Option<String>,

    /// The load balancing algorithm for the pool. One of `LEAST_CONNECTIONS`,
    /// `ROUND_ROBIN`, or `SOURCE_IP`.
    #[arg(help_heading = "Body parameters", long)]
    lb_algorithm: Option<LbAlgorithm>,

    /// Human-readable name of the resource.
    #[arg(help_heading = "Body parameters", long)]
    name: Option<String>,

    /// A JSON object specifying the session persistence for the pool or `null`
    /// for no session persistence. See
    /// [Pool Session Persistence](#session-persistence). Default is `null`.
    #[command(flatten)]
    session_persistence: Option<SessionPersistence>,

    /// 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>>,

    /// List of ciphers in OpenSSL format (colon-separated). See
    /// <https://www.openssl.org/docs/man1.1.1/man1/ciphers.html>
    ///
    /// **New in version 2.15**
    #[arg(help_heading = "Body parameters", long)]
    tls_ciphers: Option<String>,

    /// The reference to the
    /// [key manager service](https://docs.openstack.org/castellan/latest/)
    /// secret containing a PKCS12 format certificate/key bundle for
    /// `tls_enabled` pools for TLS client authentication to the member
    /// servers.
    ///
    /// **New in version 2.8**
    #[arg(help_heading = "Body parameters", long)]
    tls_container_ref: Option<String>,

    /// When `true` connections to backend member servers will use TLS
    /// encryption. Default is `false`.
    ///
    /// **New in version 2.8**
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    tls_enabled: Option<bool>,

    /// A list of TLS protocol versions. Available versions: SSLv3, TLSv1,
    /// TLSv1.1, TLSv1.2, TLSv1.3
    ///
    /// **New in version 2.17**
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    tls_versions: Option<Vec<String>>,
}

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

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

        let mut find_builder = find::Request::builder();

        find_builder.id(&self.path.id);

        let find_ep = find_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
        let find_data: serde_json::Value = find(find_ep).query_async(client).await?;

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

        let resource_id = find_data["id"]
            .as_str()
            .ok_or_else(|| eyre::eyre!("resource ID must be a string"))?
            .to_string();
        ep_builder.id(resource_id.clone());

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

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

        if let Some(val) = &args.ca_tls_container_ref {
            pool_builder.ca_tls_container_ref(val);
        }

        if let Some(val) = &args.crl_container_ref {
            pool_builder.crl_container_ref(val);
        }

        if let Some(val) = &args.description {
            pool_builder.description(val);
        }

        if let Some(val) = &args.lb_algorithm {
            let tmp = match val {
                LbAlgorithm::LeastConnections => set::LbAlgorithm::LeastConnections,
                LbAlgorithm::RoundRobin => set::LbAlgorithm::RoundRobin,
                LbAlgorithm::SourceIp => set::LbAlgorithm::SourceIp,
                LbAlgorithm::SourceIpPort => set::LbAlgorithm::SourceIpPort,
            };
            pool_builder.lb_algorithm(tmp);
        }

        if let Some(val) = &args.name {
            pool_builder.name(val);
        }

        if let Some(val) = &args.session_persistence {
            let mut session_persistence_builder = set::SessionPersistenceBuilder::default();
            if let Some(val) = &val.cookie_name {
                session_persistence_builder.cookie_name(val);
            }
            if let Some(val) = &val.persistence_granularity {
                session_persistence_builder.persistence_granularity(val);
            }
            if let Some(val) = &val.persistence_timeout {
                session_persistence_builder.persistence_timeout(*val);
            }
            if let Some(val) = &val._type {
                let tmp = match val {
                    Type::AppCookie => set::Type::AppCookie,
                    Type::HttpCookie => set::Type::HttpCookie,
                    Type::SourceIp => set::Type::SourceIp,
                };
                session_persistence_builder._type(tmp);
            }
            pool_builder.session_persistence(
                session_persistence_builder
                    .build()
                    .wrap_err("error preparing the request data")?,
            );
        }

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

        if let Some(val) = &args.tls_ciphers {
            pool_builder.tls_ciphers(val);
        }

        if let Some(val) = &args.tls_container_ref {
            pool_builder.tls_container_ref(val);
        }

        if let Some(val) = &args.tls_enabled {
            pool_builder.tls_enabled(*val);
        }

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

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