Files
velero/pkg/client/config.go
T
5b0aa81663 feat(cli): add velero client config set namespace-mode=auto (#10127)
* Issue #3194: Add velero client set-context-as-velero-namespace command

Saves the namespace of the current (or a specified) kubeconfig context
into the Velero client config file, so operational commands default to
it without requiring --namespace on every invocation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>

* Fix CI: rename changelog to PR number, add unit tests for coverage

- changelogs/unreleased must be named <pr-number>-<username>; rename
  from the 0000 placeholder to 10127 to satisfy hack/changelog-check.sh.
- Extract the command's logic into setContextAsVeleroNamespace so it's
  testable without triggering os.Exit via cmd.CheckError, and add unit
  tests covering: namespace read from context, context with no explicit
  namespace, overwriting an existing config value, and invalid
  kubeconfig path. Addresses 0% codecov patch coverage on the PR.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>

* Move set-namespace-from-context under client config

Shubham suggested nesting the new command under `config` for
hierarchy consistency, and renaming it since the original
set-context-as-velero-namespace name was long and ambiguous. Moves
it to `velero client config set-namespace-from-context`, matching
the existing config get/set subcommands and my follow-up naming
suggestion on the review thread.

AI-Tool-Used: Claude Code
AI-Tool-Use-Level: Category 3 (Low)
AI-Code-Category: Category 1 (Production)
Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>

* Replace set-namespace-from-context with namespace-mode=auto

kaovilai noted on #10127 that a one-shot command to snapshot the
kubecontext namespace becomes redundant once a config toggle can
resolve it dynamically, and isn't much simpler than the existing
`config set namespace=...` alternative.

Drop the dedicated set-namespace-from-context subcommand and instead
teach the client Factory to resolve the operational namespace from the
current kubeconfig context on every invocation when
`namespace-mode=auto` is set via the existing generic
`config set` command. Explicit --namespace flags and VELERO_NAMESPACE
still take precedence, so the new mode only changes behavior when
neither is set.

AI-Tool-Used: Claude Code
AI-Tool-Use-Level: Category 2 (Medium)
AI-Code-Category: Category 1 (Production)
Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>

* Address PR review: doc, fallback test, t.Setenv

Resolve feedback from PR #10127 review 4966054980:
- Document how to disable namespace-mode=auto (namespace-mode=)
  and note the fallback to the static namespace, in namespace.md.
- Add a factory test covering the fallback to the stored/default
  namespace when kubeconfig namespace resolution fails.
- Switch the VELERO_NAMESPACE override test to t.Setenv, wrapped
  in a subtest so its cleanup runs before later tests execute.

AI-Tool-Used: Claude Code
AI-Tool-Use-Level: Category 2 (Medium)
AI-Code-Category: Category 2 (Non-Production)
Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>

---------

Signed-off-by: lubronzhan <lubron.zhan@broadcom.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 15:23:55 -04:00

171 lines
3.7 KiB
Go

/*
Copyright 2021 the Velero contributors.
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.
*/
package client
import (
"encoding/json"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/cockroachdb/errors"
)
const (
ConfigKeyNamespace = "namespace"
ConfigKeyNamespaceMode = "namespace-mode"
ConfigKeyFeatures = "features"
ConfigKeyCACert = "cacert"
ConfigKeyColorized = "colorized"
// NamespaceModeAuto is the ConfigKeyNamespaceMode value that makes Velero resolve the
// namespace for operational commands from the current kubeconfig context on every
// invocation, instead of the static ConfigKeyNamespace value.
NamespaceModeAuto = "auto"
)
// VeleroConfig is a map of strings to any for deserializing Velero client config options.
// The alias is a way to attach type-asserting convenience methods.
type VeleroConfig map[string]any
// LoadConfig loads the Velero client configuration file and returns it as a VeleroConfig. If the
// file does not exist, an empty map is returned.
func LoadConfig() (VeleroConfig, error) {
fileName := configFileName()
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
// If the file isn't there, just return an empty map
return VeleroConfig{}, nil
}
if err != nil {
// For any other Stat() error, return it
return nil, errors.WithStack(err)
}
configFile, err := os.Open(fileName)
if err != nil {
return nil, errors.WithStack(err)
}
defer configFile.Close()
var config VeleroConfig
if err := json.NewDecoder(configFile).Decode(&config); err != nil {
return nil, errors.WithStack(err)
}
return config, nil
}
// SaveConfig saves the passed in config map to the Velero client configuration file.
func SaveConfig(config VeleroConfig) error {
fileName := configFileName()
// Try to make the directory in case it doesn't exist
dir := filepath.Dir(fileName)
if err := os.MkdirAll(dir, 0700); err != nil {
return errors.WithStack(err)
}
configFile, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
return errors.WithStack(err)
}
defer configFile.Close()
return json.NewEncoder(configFile).Encode(&config)
}
func (c VeleroConfig) Namespace() string {
val, ok := c[ConfigKeyNamespace]
if !ok {
return ""
}
ns, ok := val.(string)
if !ok {
return ""
}
return ns
}
func (c VeleroConfig) NamespaceMode() string {
val, ok := c[ConfigKeyNamespaceMode]
if !ok {
return ""
}
mode, ok := val.(string)
if !ok {
return ""
}
return mode
}
func (c VeleroConfig) Features() []string {
val, ok := c[ConfigKeyFeatures]
if !ok {
return []string{}
}
features, ok := val.(string)
if !ok {
return []string{}
}
return strings.Split(features, ",")
}
func (c VeleroConfig) Colorized() bool {
val, ok := c[ConfigKeyColorized]
if !ok {
return true
}
valString, ok := val.(string)
if !ok {
return true
}
colorized, err := strconv.ParseBool(valString)
if err != nil {
return true
}
return colorized
}
func (c VeleroConfig) CACertFile() string {
val, ok := c[ConfigKeyCACert]
if !ok {
return ""
}
caCertFile, ok := val.(string)
if !ok {
return ""
}
return caCertFile
}
func configFileName() string {
return filepath.Join(os.Getenv("HOME"), ".config", "velero", "config.json")
}