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

/// Creates a subnet on a network.
///
/// OpenStack Networking does not try to derive the correct IP version from the
/// CIDR. If you do not specify the `gateway_ip` attribute, OpenStack
/// Networking allocates an address from the CIDR for the gateway for the
/// subnet.
///
/// To specify a subnet without a gateway, set the `gateway_ip` attribute to
/// `null` in the request body. If you do not specify the `allocation_pools`
/// attribute, OpenStack Networking automatically allocates pools for covering
/// all IP addresses in the CIDR, excluding the address reserved for the subnet
/// gateway. Otherwise, you can explicitly specify allocation pools as shown in
/// the following example.
///
/// When you specify both the `allocation_pools` and `gateway_ip` attributes,
/// you must ensure that the gateway IP does not overlap with the allocation
/// pools; otherwise, the call returns the `Conflict (409)` response code.
///
/// A subnet can have one or more name servers and host routes. Hosts in this
/// subnet use the name servers. Devices with IP addresses from this subnet,
/// not including the local subnet route, use the host routes.
///
/// Specify the `ipv6_ra_mode` and `ipv6_address_mode` attributes to create
/// subnets that support IPv6 configurations, such as stateless address
/// autoconfiguration (SLAAC), DHCPv6 stateful, and DHCPv6 stateless
/// configurations.
///
/// A subnet can optionally be associated with a network segment when it is
/// created by specifying the `segment_id` of a valid segment on the specified
/// network. A network with subnets associated in this way is called a routed
/// network. On any given network, all of the subnets must be associated with
/// segments or none of them can be. Neutron enforces this invariant.
/// Currently, routed networks are only supported for provider networks.
///
/// Normal response codes: 201
///
/// Error response codes: 400, 401, 403, 404, 409
#[derive(Args)]
#[command(about = "Create subnet")]
pub struct SubnetCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// A `subnet` object.
    #[command(flatten)]
    subnet: Subnet,
}

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

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

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Ipv6AddressMode {
    Dhcpv6Stateful,
    Dhcpv6Stateless,
    Slaac,
}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Ipv6RaMode {
    Dhcpv6Stateful,
    Dhcpv6Stateless,
    Slaac,
}

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

    /// The CIDR of the subnet.
    #[arg(help_heading = "Body parameters", long)]
    cidr: Option<String>,

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

    /// 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. If the gateway_ip is not
    /// specified, OpenStack Networking allocates an address from the CIDR for
    /// the gateway for the subnet by default.
    #[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>>,

    /// The IP protocol version. Value is `4` or `6`.
    #[arg(help_heading = "Body parameters", long)]
    ip_version: i32,

    /// The IPv6 address modes specifies mechanisms for assigning IP addresses.
    /// Value is `slaac`, `dhcpv6-stateful`, `dhcpv6-stateless`.
    #[arg(help_heading = "Body parameters", long)]
    ipv6_address_mode: Option<Ipv6AddressMode>,

    /// The IPv6 router advertisement specifies whether the networking service
    /// should transmit ICMPv6 packets, for a subnet. Value is `slaac`,
    /// `dhcpv6-stateful`, `dhcpv6-stateless`.
    #[arg(help_heading = "Body parameters", long)]
    ipv6_ra_mode: Option<Ipv6RaMode>,

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

    /// The ID of the network to which the subnet belongs.
    #[arg(help_heading = "Body parameters", long)]
    network_id: String,

    /// The prefix length to use for subnet allocation from a subnet pool. If
    /// not specified, the `default_prefixlen` value of the subnet pool will be
    /// used.
    #[arg(help_heading = "Body parameters", long)]
    prefixlen: Option<u32>,

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

    /// The ID of the subnet pool associated with the subnet.
    #[arg(help_heading = "Body parameters", long)]
    subnetpool_id: Option<String>,

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

    /// The ID of the project that owns the resource. Only administrative and
    /// users with advsvc role can specify a project ID other than their own.
    /// You cannot change this value through authorization policies.
    #[arg(help_heading = "Body parameters", long)]
    tenant_id: Option<String>,

    /// Whether to allocate this subnet from the default subnet pool.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    use_default_subnetpool: Option<bool>,
}

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

        let op = OutputProcessor::from_args(parsed_args, Some("network.subnet"), Some("create"));
        op.validate_args(parsed_args)?;

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

        // Set body parameters
        // Set Request.subnet data
        let args = &self.subnet;
        let mut subnet_builder = create::SubnetBuilder::default();
        if let Some(val) = &args.allocation_pools {
            let allocation_pools_builder: Vec<create::AllocationPools> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::AllocationPools>(v.to_owned()))
                .collect::<Vec<create::AllocationPools>>();
            subnet_builder.allocation_pools(allocation_pools_builder);
        }

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

        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<create::HostRoutes> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::HostRoutes>(v.to_owned()))
                .collect::<Vec<create::HostRoutes>>();
            subnet_builder.host_routes(host_routes_builder);
        }

        subnet_builder.ip_version(args.ip_version);

        if let Some(val) = &args.ipv6_address_mode {
            let tmp = match val {
                Ipv6AddressMode::Dhcpv6Stateful => create::Ipv6AddressMode::Dhcpv6Stateful,
                Ipv6AddressMode::Dhcpv6Stateless => create::Ipv6AddressMode::Dhcpv6Stateless,
                Ipv6AddressMode::Slaac => create::Ipv6AddressMode::Slaac,
            };
            subnet_builder.ipv6_address_mode(tmp);
        }

        if let Some(val) = &args.ipv6_ra_mode {
            let tmp = match val {
                Ipv6RaMode::Dhcpv6Stateful => create::Ipv6RaMode::Dhcpv6Stateful,
                Ipv6RaMode::Dhcpv6Stateless => create::Ipv6RaMode::Dhcpv6Stateless,
                Ipv6RaMode::Slaac => create::Ipv6RaMode::Slaac,
            };
            subnet_builder.ipv6_ra_mode(tmp);
        }

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

        subnet_builder.network_id(&args.network_id);

        if let Some(val) = &args.prefixlen {
            subnet_builder.prefixlen(*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<_>>());
        }

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

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

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

        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(())
    }
}