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 Router command
//!
//! Wraps invoking of the `v2.0/routers/{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 openstack_sdk::api::QueryAsync;
use openstack_sdk::api::find;
use openstack_sdk::api::network::v2::router::find;
use openstack_sdk::api::network::v2::router::set;
use openstack_types::network::v2::router::response::set::RouterResponse;
use serde_json::Value;

/// Updates a logical router.
///
/// This operation does not enable the update of router interfaces. To update a
/// router interface, use the add router interface and remove router interface
/// operations.
///
/// Normal response codes: 200
///
/// Error response codes: 400, 401, 404, 412
#[derive(Args)]
#[command(about = "Update router")]
pub struct RouterCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// A `router` object.
    #[command(flatten)]
    router: Router,
}

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

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// id parameter for /v2.0/routers/{id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_id",
        value_name = "ID"
    )]
    id: String,
}
/// ExternalGatewayInfo Body data
#[derive(Args, Clone)]
#[group(required = false, multiple = true)]
struct ExternalGatewayInfo {
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    enable_snat: Option<bool>,

    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    external_fixed_ips: Option<Vec<Value>>,

    #[arg(help_heading = "Body parameters", long, required = false)]
    network_id: String,

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

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

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

    /// `true` indicates a distributed router. It is available when `dvr`
    /// extension is enabled.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    distributed: Option<Option<bool>>,

    /// Enable NDP proxy attribute. Default is `false`, To persist this
    /// attribute value, set the `enable_ndp_proxy_by_default` option in the
    /// `neutron.conf` file. It is available when `router-extend-ndp-proxy`
    /// extension is enabled.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    enable_ndp_proxy: Option<Option<bool>>,

    /// The external gateway information of the router. If the router has an
    /// external gateway, this would be a dict with `network_id`,
    /// `enable_snat`, `external_fixed_ips` and `qos_policy_id`. Otherwise,
    /// this would be `null`.
    #[command(flatten)]
    external_gateway_info: Option<ExternalGatewayInfo>,

    /// `true` indicates a highly-available router. It is available when
    /// `l3-ha` extension is enabled.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    ha: Option<Option<bool>>,

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

    /// The extra routes configuration for L3 router. A list of dictionaries
    /// with `destination` and `nexthop` parameters. It is available when
    /// `extraroute` extension is enabled. Default is an empty list (`[]`).
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    routes: Option<Vec<Value>>,
}

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

        let op = OutputProcessor::from_args(parsed_args, Some("network.router"), 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.router data
        let args = &self.router;
        let mut router_builder = set::RouterBuilder::default();
        if let Some(val) = &args.admin_state_up {
            router_builder.admin_state_up(*val);
        }

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

        if let Some(val) = &args.distributed {
            router_builder.distributed(*val);
        }

        if let Some(val) = &args.enable_ndp_proxy {
            router_builder.enable_ndp_proxy(*val);
        }

        if let Some(val) = &args.external_gateway_info {
            let mut external_gateway_info_builder = set::ExternalGatewayInfoBuilder::default();
            if let Some(val) = &val.enable_snat {
                external_gateway_info_builder.enable_snat(*val);
            }
            if let Some(val) = &val.external_fixed_ips {
                let external_fixed_ips_builder: Vec<set::ExternalFixedIps> = val
                    .iter()
                    .flat_map(|v| serde_json::from_value::<set::ExternalFixedIps>(v.to_owned()))
                    .collect::<Vec<set::ExternalFixedIps>>();
                external_gateway_info_builder.external_fixed_ips(external_fixed_ips_builder);
            }

            external_gateway_info_builder.network_id(&val.network_id);
            if let Some(val) = &val.qos_policy_id {
                external_gateway_info_builder.qos_policy_id(Some(val.into()));
            }
            router_builder.external_gateway_info(
                external_gateway_info_builder
                    .build()
                    .wrap_err("error preparing the request data")?,
            );
        }

        if let Some(val) = &args.ha {
            router_builder.ha(*val);
        }

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

        if let Some(val) = &args.routes {
            let routes_builder: Vec<set::Routes> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<set::Routes>(v.to_owned()))
                .collect::<Vec<set::Routes>>();
            router_builder.routes(routes_builder);
        }

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