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

//! List Rules command
//!
//! Wraps invoking of the `v2/lbaas/l7policies/{l7policy_id}/rules` with `GET` method

use clap::Args;
use eyre::OptionExt;
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_by_name;
use openstack_sdk::api::identity::v3::project::find as find_project;
use openstack_sdk::api::load_balancer::v2::l7policy::rule::list;
use openstack_sdk::api::{Pagination, paged};
use openstack_types::load_balancer::v2::l7policy::rule::response::list::RuleResponse;
use tracing::warn;

/// Lists all L7 rules for the project.
///
/// Use the `fields` query parameter to control which fields are returned in
/// the response body. Additionally, you can filter results by using query
/// string parameters. For information, see
/// [Filtering and column selection](#filtering).
///
/// Administrative users can specify a project ID that is different than their
/// own to list L7 policies for other projects.
///
/// The list might be empty.
#[derive(Args)]
#[command(about = "List L7 Rules")]
pub struct RulesCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// Total limit of entities count to return. Use this when there are too many entries.
    #[arg(long, default_value_t = 10000)]
    max_items: usize,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {
    #[arg(help_heading = "Query parameters", long)]
    _type: Option<String>,

    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
    admin_state_up: Option<bool>,

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

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

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

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

    /// Page size
    #[arg(
        help_heading = "Query parameters",
        long("page-size"),
        visible_alias("limit")
    )]
    limit: Option<i32>,

    /// ID of the last item in the previous list
    #[arg(help_heading = "Query parameters", long)]
    marker: Option<String>,

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

    /// The page direction.
    #[arg(action=clap::ArgAction::Set, help_heading = "Query parameters", long)]
    page_reverse: Option<bool>,

    /// Project resource for which the operation should be performed.
    #[command(flatten)]
    project: ProjectInput,

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

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

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

/// Project input select group
#[derive(Args)]
#[group(required = false, multiple = false)]
struct ProjectInput {
    /// Project Name.
    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_NAME")]
    project_name: Option<String>,
    /// Project ID.
    #[arg(long, help_heading = "Path parameters", value_name = "PROJECT_ID")]
    project_id: Option<String>,
    /// Current project.
    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
    current_project: bool,
}

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// l7policy_id parameter for
    /// /v2/lbaas/l7policies/{l7policy_id}/rules/{rule_id} API
    #[arg(
        help_heading = "Path parameters",
        id = "path_param_l7policy_id",
        value_name = "L7POLICY_ID"
    )]
    l7policy_id: String,
}

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

        let op = OutputProcessor::from_args(
            parsed_args,
            Some("load-balancer.l7policy/rule"),
            Some("list"),
        );
        op.validate_args(parsed_args)?;

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

        ep_builder.l7policy_id(&self.path.l7policy_id);
        // Set query parameters
        if let Some(val) = &self.query.admin_state_up {
            ep_builder.admin_state_up(*val);
        }
        if let Some(val) = &self.query.compare_type {
            ep_builder.compare_type(val);
        }
        if let Some(val) = &self.query.created_at {
            ep_builder.created_at(val);
        }
        if let Some(val) = &self.query.invert {
            ep_builder.invert(val);
        }
        if let Some(val) = &self.query.key {
            ep_builder.key(val);
        }
        if let Some(val) = &self.query.limit {
            ep_builder.limit(*val);
        }
        if let Some(val) = &self.query.marker {
            ep_builder.marker(val);
        }
        if let Some(val) = &self.query.operating_status {
            ep_builder.operating_status(val);
        }
        if let Some(val) = &self.query.page_reverse {
            ep_builder.page_reverse(*val);
        }
        if let Some(id) = &self.query.project.project_id {
            // project_id is passed. No need to lookup
            ep_builder.project_id(id);
        } else if let Some(name) = &self.query.project.project_name {
            // project_name is passed. Need to lookup resource
            let mut sub_find_builder = find_project::Request::builder();
            warn!(
                "Querying project by name (because of `--project-name` parameter passed) may not be definite. This may fail in which case parameter `--project-id` should be used instead."
            );

            sub_find_builder.id(name);
            let find_ep = sub_find_builder
                .build()
                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
            // Try to extract resource id
            match find_data.get("id") {
                Some(val) => match val.as_str() {
                    Some(id_str) => {
                        ep_builder.project_id(id_str.to_owned());
                    }
                    None => {
                        return Err(OpenStackCliError::ResourceAttributeNotString(
                            serde_json::to_string(&val)?,
                        ));
                    }
                },
                None => {
                    return Err(OpenStackCliError::ResourceAttributeMissing(
                        "id".to_string(),
                    ));
                }
            };
        } else if self.query.project.current_project {
            ep_builder.project_id(
                client
                    .get_auth_info()
                    .ok_or_eyre("Cannot determine current authentication information")?
                    .token
                    .user
                    .id,
            );
        }
        if let Some(val) = &self.query.provisioning_status {
            ep_builder.provisioning_status(val);
        }
        if let Some(val) = &self.query.rule_value {
            ep_builder.rule_value(val);
        }
        if let Some(val) = &self.query._type {
            ep_builder._type(val);
        }
        if let Some(val) = &self.query.updated_at {
            ep_builder.updated_at(val);
        }

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data: Vec<serde_json::Value> = paged(ep, Pagination::Limit(self.max_items))
            .query_async(client)
            .await?;
        op.output_list::<RuleResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}