From 1da48075fe9e51741a4fe75c4abc8da055a2f35d Mon Sep 17 00:00:00 2001 From: Abhilash Shetty Date: Thu, 23 Jan 2025 13:59:35 +0000 Subject: [PATCH] feat(plugin): add support to fetch ns from kubeconfig context If '---ns_from_context' flag is set then we fetch ns from the kubeconfig context, otherwise, --namespace arg is used. '---ns_from_context' takes precedence over -n if both are used. Signed-off-by: Abhilash Shetty --- Cargo.lock | 1 + k8s/plugin/Cargo.toml | 1 + k8s/plugin/src/main.rs | 20 +++++++++++++++----- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3ef7d11cc..c2845a43e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2234,6 +2234,7 @@ dependencies = [ "console-logger", "constants", "humantime", + "kube 0.94.2", "kube-forward", "kube-proxy", "openapi", diff --git a/k8s/plugin/Cargo.toml b/k8s/plugin/Cargo.toml index e53a41748..4b4e67651 100644 --- a/k8s/plugin/Cargo.toml +++ b/k8s/plugin/Cargo.toml @@ -24,6 +24,7 @@ rest-plugin = { path = "../../dependencies/control-plane/control-plane/plugin", console-logger = { path = "../../console-logger" } supportability = { path = "../supportability" } upgrade = { path = "../upgrade" } +kube = { version = "0.94.2", features = ["derive", "runtime"] } kube-proxy = { path = "../../dependencies/control-plane/k8s/proxy" } kube-forward = { path = "../../dependencies/control-plane/k8s/forward" } tokio = { version = "1.41.0" } diff --git a/k8s/plugin/src/main.rs b/k8s/plugin/src/main.rs index c4af5c6a3..0f9003b9e 100644 --- a/k8s/plugin/src/main.rs +++ b/k8s/plugin/src/main.rs @@ -1,11 +1,11 @@ use clap::Parser; use plugin::ExecuteOperation; use resources::{init_rest, Error, Operations}; +pub mod resources; +use kube::Client; use std::{env, ops::Deref}; -pub mod resources; - #[derive(Parser, Debug)] #[clap(name = utils::package_description!(), version = utils::version_info_str!())] #[group(skip)] @@ -20,12 +20,22 @@ struct CliArgs { #[clap(flatten)] args: resources::CliArgs, + + /// Use namespace from the current `kubeconfig` context, + /// Takes precedence over --namespace or -n flag. + #[clap(global = true, long, short = 'c', default_value = "false")] + ns_from_context: bool, } impl CliArgs { - fn args() -> Self { + async fn args() -> Self { let mut args = CliArgs::parse(); - args.args.namespace = args.namespace.clone(); + args.args.namespace = if args.ns_from_context { + let client = Client::try_default().await.expect("Client init failed"); + client.default_namespace().to_string() + } else { + args.namespace.clone() + }; args } } @@ -40,7 +50,7 @@ impl Deref for CliArgs { #[tokio::main] async fn main() { - let cli_args = CliArgs::args(); + let cli_args = CliArgs::args().await; let _tracer_flusher = cli_args.init_tracing(); if let Err(error) = cli_args.execute().await {