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 Subnet command
//!
//! Wraps invoking of the `v2.0/subnets/{subnet_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::subnet::find;
use openstack_sdk::api::network::v2::subnet::set;
use openstack_types::network::v2::subnet::response::set::SubnetResponse;
use serde_json::Value;

/// Updates a subnet.
///
/// Some attributes, such as IP version (ip_version), CIDR (cidr), and segment
/// (segment_id) cannot be updated. Attempting to update these attributes
/// results in a `400 Bad Request` error.
///
/// Normal response codes: 200
///
/// Error response codes: 400, 401, 403, 404, 412
#[derive(Args)]
#[command(about = "Update subnet")]
pub struct SubnetCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    #[command(flatten)]
    subnet: Subnet,
}

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

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// subnet_id parameter for /v2.0/subnets/{subnet_id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_id",
        value_name = "ID"
    )]
    id: String,
}
/// Subnet Body data
#[derive(Args, Clone)]
struct Subnet {
    /// Allocation pools with `start` and `end` IP addresses for this subnet.
    /// If allocation_pools are not specified, OpenStack Networking
    /// automatically allocates pools for covering all IP addresses in the
    /// CIDR, excluding the address reserved for the subnet gateway by default.
    ///
    /// 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)]
    allocation_pools: Option<Vec<Value>>,

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

    /// List of dns name servers associated with the subnet. Default is an
    /// empty list.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    dns_nameservers: Option<Vec<String>>,

    /// Whether to publish DNS records for IPs from this subnet. Default is
    /// `false`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    dns_publish_fixed_ip: Option<bool>,

    /// Indicates whether dhcp is enabled or disabled for the subnet. Default
    /// is `true`.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    enable_dhcp: Option<bool>,

    /// Gateway IP of this subnet. If the value is `null` that implies no
    /// gateway is associated with the subnet.
    #[arg(help_heading = "Body parameters", long)]
    gateway_ip: Option<String>,

    /// Set explicit NULL for the gateway_ip
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "gateway_ip")]
    no_gateway_ip: bool,

    /// Additional routes for the subnet. A list of dictionaries with
    /// `destination` and `nexthop` parameters. Default value 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)]
    host_routes: Option<Vec<Value>>,

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

    /// The ID of a network segment the subnet is associated with. It is
    /// available when `segment` extension is enabled.
    #[arg(help_heading = "Body parameters", long)]
    segment_id: Option<String>,

    /// Set explicit NULL for the segment_id
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "segment_id")]
    no_segment_id: bool,

    /// The service types associated with the subnet.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
    service_types: Option<Vec<String>>,
}

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

        let op = OutputProcessor::from_args(parsed_args, Some("network.subnet"), 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.subnet data
        let args = &self.subnet;
        let mut subnet_builder = set::SubnetBuilder::default();
        if let Some(val) = &args.allocation_pools {
            let allocation_pools_builder: Vec<set::AllocationPools> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<set::AllocationPools>(v.to_owned()))
                .collect::<Vec<set::AllocationPools>>();
            subnet_builder.allocation_pools(allocation_pools_builder);
        }

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

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

        if let Some(val) = &args.dns_publish_fixed_ip {
            subnet_builder.dns_publish_fixed_ip(*val);
        }

        if let Some(val) = &args.enable_dhcp {
            subnet_builder.enable_dhcp(*val);
        }

        if let Some(val) = &args.gateway_ip {
            subnet_builder.gateway_ip(Some(val.into()));
        } else if args.no_gateway_ip {
            subnet_builder.gateway_ip(None);
        }

        if let Some(val) = &args.host_routes {
            let host_routes_builder: Vec<set::HostRoutes> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<set::HostRoutes>(v.to_owned()))
                .collect::<Vec<set::HostRoutes>>();
            subnet_builder.host_routes(host_routes_builder);
        }

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

        if let Some(val) = &args.segment_id {
            subnet_builder.segment_id(Some(val.into()));
        } else if args.no_segment_id {
            subnet_builder.segment_id(None);
        }

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

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