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`.

//! Create Healthmonitor command
//!
//! Wraps invoking of the `v2/lbaas/healthmonitors` with `POST` 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::healthmonitor::create;
use openstack_types::load_balancer::v2::healthmonitor::response::create::HealthmonitorResponse;

/// Creates a health monitor on a pool.
///
/// Health monitors define how the load balancer monitors backend servers to
/// determine if they are available to service requests.
///
/// This operation provisions a new health monitor by using the configuration
/// that you define in the request object. After the API validates the request
/// and starts the provisioning process, the API returns a response object that
/// contains a unique ID and the status of provisioning the health monitor.
///
/// In the response, the health monitor [provisioning status](#prov-status) is
/// `ACTIVE`, `PENDING_CREATE`, or `ERROR`.
///
/// If the status is `PENDING_CREATE`, issue GET
/// `/v2/lbaas/healthmonitors/{healthmonitor_id}` to view the progress of the
/// provisioning operation. When the health monitor status changes to `ACTIVE`,
/// the health monitor is successfully provisioned and is ready for further
/// configuration.
///
/// If the API cannot fulfill the request due to insufficient data or data that
/// is not valid, the service returns the HTTP `Bad Request (400)` response
/// code with information about the failure in the response body. Validation
/// errors require that you correct the error and submit the request again.
///
/// Specifying a project_id is deprecated. The health monitor will inherit the
/// project_id of the parent load balancer.
///
/// At a minimum, you must specify these health monitor attributes:
///
/// Some attributes receive default values if you omit them from the request:
///
/// To create a health monitor, the parent load balancer must have an `ACTIVE`
/// provisioning status.
#[derive(Args)]
#[command(about = "Create Health Monitor")]
pub struct HealthmonitorCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// Defines mandatory and optional attributes of a POST request.
    #[command(flatten)]
    healthmonitor: Healthmonitor,
}

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

/// Path parameters
#[derive(Args)]
struct PathParameters {}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum HttpMethod {
    Connect,
    Delete,
    Get,
    Head,
    Options,
    Patch,
    Post,
    Put,
    Trace,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Type {
    Http,
    Https,
    Ping,
    Sctp,
    Tcp,
    TlsHello,
    UdpConnect,
}

/// Healthmonitor Body data
#[derive(Args, Clone)]
struct Healthmonitor {
    /// 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 time, in seconds, between sending probes to members.
    #[arg(help_heading = "Body parameters", long)]
    delay: i32,

    /// The domain name, which be injected into the HTTP Host Header to the
    /// backend server for HTTP health check.
    ///
    /// **New in version 2.10**
    #[arg(help_heading = "Body parameters", long)]
    domain_name: Option<String>,

    /// The list of HTTP status codes expected in response from the member to
    /// declare it healthy. Specify one of the following values:
    ///
    /// - A single value, such as `200`
    /// - A list, such as `200, 202`
    /// - A range, such as `200-204`
    ///
    /// The default is 200.
    #[arg(help_heading = "Body parameters", long)]
    expected_codes: Option<String>,

    /// The HTTP method that the health monitor uses for requests. One of
    /// `CONNECT`, `DELETE`, `GET`, `HEAD`, `OPTIONS`, `PATCH`, `POST`, `PUT`,
    /// or `TRACE`. The default is `GET`.
    #[arg(help_heading = "Body parameters", long)]
    http_method: Option<HttpMethod>,

    /// The HTTP version. One of `1.0` or `1.1`. The default is `1.0`.
    ///
    /// **New in version 2.10**
    #[arg(help_heading = "Body parameters", long)]
    http_version: Option<f32>,

    /// The number of successful checks before changing the `operating status`
    /// of the member to `ONLINE`. A valid value is from `1` to `10`.
    #[arg(help_heading = "Body parameters", long)]
    max_retries: i32,

    /// The number of allowed check failures before changing the
    /// `operating status` of the member to `ERROR`. A valid value is from `1`
    /// to `10`. The default is `3`.
    #[arg(help_heading = "Body parameters", long)]
    max_retries_down: Option<i32>,

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

    /// The ID of the pool.
    #[arg(help_heading = "Body parameters", long)]
    pool_id: String,

    /// The ID of the project owning this resource. (deprecated)
    #[arg(help_heading = "Body parameters", long)]
    project_id: 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>>,

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

    /// The maximum time, in seconds, that a monitor waits to connect before it
    /// times out. This value must be less than the delay value.
    #[arg(help_heading = "Body parameters", long)]
    timeout: i32,

    /// The type of health monitor. One of `HTTP`, `HTTPS`, `PING`, `SCTP`,
    /// `TCP`, `TLS-HELLO`, or `UDP-CONNECT`.
    #[arg(help_heading = "Body parameters", long)]
    _type: Type,

    /// The HTTP URL path of the request sent by the monitor to test the health
    /// of a backend member. Must be a string that begins with a forward slash
    /// (`/`). The default URL path is `/`.
    #[arg(help_heading = "Body parameters", long)]
    url_path: Option<String>,
}

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

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

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

        // Set body parameters
        // Set Request.healthmonitor data
        let args = &self.healthmonitor;
        let mut healthmonitor_builder = create::HealthmonitorBuilder::default();
        if let Some(val) = &args.admin_state_up {
            healthmonitor_builder.admin_state_up(*val);
        }

        healthmonitor_builder.delay(args.delay);

        if let Some(val) = &args.domain_name {
            healthmonitor_builder.domain_name(val);
        }

        if let Some(val) = &args.expected_codes {
            healthmonitor_builder.expected_codes(val);
        }

        if let Some(val) = &args.http_method {
            let tmp = match val {
                HttpMethod::Connect => create::HttpMethod::Connect,
                HttpMethod::Delete => create::HttpMethod::Delete,
                HttpMethod::Get => create::HttpMethod::Get,
                HttpMethod::Head => create::HttpMethod::Head,
                HttpMethod::Options => create::HttpMethod::Options,
                HttpMethod::Patch => create::HttpMethod::Patch,
                HttpMethod::Post => create::HttpMethod::Post,
                HttpMethod::Put => create::HttpMethod::Put,
                HttpMethod::Trace => create::HttpMethod::Trace,
            };
            healthmonitor_builder.http_method(tmp);
        }

        if let Some(val) = &args.http_version {
            healthmonitor_builder.http_version(*val);
        }

        healthmonitor_builder.max_retries(args.max_retries);

        if let Some(val) = &args.max_retries_down {
            healthmonitor_builder.max_retries_down(*val);
        }

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

        healthmonitor_builder.pool_id(&args.pool_id);

        if let Some(val) = &args.project_id {
            healthmonitor_builder.project_id(val);
        }

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

        if let Some(val) = &args.tenant_id {
            healthmonitor_builder.tenant_id(val);
        }

        healthmonitor_builder.timeout(args.timeout);

        let tmp = match &args._type {
            Type::Http => create::Type::Http,
            Type::Https => create::Type::Https,
            Type::Ping => create::Type::Ping,
            Type::Sctp => create::Type::Sctp,
            Type::Tcp => create::Type::Tcp,
            Type::TlsHello => create::Type::TlsHello,
            Type::UdpConnect => create::Type::UdpConnect,
        };
        healthmonitor_builder._type(tmp);

        if let Some(val) = &args.url_path {
            healthmonitor_builder.url_path(val);
        }

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