Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,23 @@ func NewCommand() *cobra.Command {
Use: "kubetrigger",
Long: cmdLongHelp,
RunE: runCli,
PreRunE: func(_ *cobra.Command, _ []string) error {
PreRunE: func(c *cobra.Command, _ []string) error {
logger.Infof("kube-trigger version=%s", version.Version)
fromEnv, err := applyEnv(c.Flags())
if err != nil {
return err
}
if err := opt.validate(); err != nil {
if len(fromEnv) > 0 {
return fmt.Errorf("%w (options set from the environment: %s)", err, strings.Join(fromEnv, ", "))
}
return err
}
return nil
},
}
c.AddCommand(newVersionCommand())
addFlags(opt, c.Flags())
if err := opt.validate(); err != nil {
panic(err)
}
return c
}

Expand All @@ -133,6 +140,7 @@ func addFlags(opt *option, f *pflag.FlagSet) {
f.IntVar(&opt.RetryDelay, FlagRetryDelay, defaultRetryDelay, "First delay to retry actions in seconds, subsequent delay will grow exponentially")
f.IntVar(&opt.Timeout, FlagTimeout, defaultTimeout, "Timeout for running each action")
f.IntVar(&opt.RegistrySize, FlagRegistrySize, defaultRegistrySize, "Cache size for filters and actions")
f.BoolVar(&opt.ActionRetry, FlagActionRetry, defaultActionRetry, "Re-run an action if it fails, up to --max-retry times")
f.StringVar(&k8sresourcewatcher.MultiClusterConfigType, "multi-cluster-config-type", k8sresourcewatcher.TypeClusterGateway, "Multi-cluster config type, supported types: cluster-gateway, cluster-gateway-kubeconfig")
f.BoolVar(&enableLeaderElection, FlagLeaderElect, false, "Enable leader election for kube-trigger. Enabling this will ensure there is only one active kube-trigger.")
f.DurationVar(&leaseDuration, FlagLeaderElectionLeaseDuration, defaultLeaseDuration, "The duration that non-leader candidates will wait to force acquire leadership.")
Expand Down
55 changes: 55 additions & 0 deletions pkg/cmd/env.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright 2026 The KubeVela Authors.

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 cmd

import (
"errors"
"fmt"
"os"
"strings"

"github.com/spf13/pflag"
)

// applyEnv sets each flag not given on the command line from its environment
// variable, so the order is command line, then environment, then default. It
// returns the variables it applied.
func applyEnv(fs *pflag.FlagSet) ([]string, error) {
var applied []string
var errs []error
fs.VisitAll(func(f *pflag.Flag) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
if f.Changed || f.Name == "help" {
return
}
name := envName(f.Name)
v, ok := os.LookupEnv(name)
if !ok {
return
}
if err := fs.Set(f.Name, v); err != nil {
errs = append(errs, fmt.Errorf("$%s: %w", name, err))
return
}
applied = append(applied, "$"+name)
})
return applied, errors.Join(errs...)
}

// envName is a flag's environment variable: its name in capitals, with - as _.
func envName(flag string) string {
return strings.ToUpper(strings.ReplaceAll(flag, "-", "_"))
}
116 changes: 116 additions & 0 deletions pkg/cmd/env_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Copyright 2026 The KubeVela Authors.

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 cmd

import (
"os"
"testing"
"time"

"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// clearEnv unsets every flag's variable for the test, so nothing the test
// process inherits leaks in.
func clearEnv(t *testing.T, fs *pflag.FlagSet) {
fs.VisitAll(func(f *pflag.Flag) {
t.Setenv(envName(f.Name), "")
require.NoError(t, os.Unsetenv(envName(f.Name)))
})
}

// parse reads args into a fresh option, then applies the environment.
func parse(t *testing.T, args ...string) (*option, error) {
o := newOption()
fs := pflag.NewFlagSet("kubetrigger", pflag.ContinueOnError)
addFlags(o, fs)
require.NoError(t, fs.Parse(args))
_, err := applyEnv(fs)
return o, err
}

func TestEnvSetsAFlagNotGiven(t *testing.T) {
t.Setenv("MAX_RETRY", "9")
o, err := parse(t)
Comment thread
briankane marked this conversation as resolved.
Resolved
require.NoError(t, err)
assert.Equal(t, 9, o.MaxRetry)
}

func TestFlagBeatsEnv(t *testing.T) {
t.Setenv("MAX_RETRY", "9")
o, err := parse(t, "--max-retry=3")
require.NoError(t, err)
assert.Equal(t, 3, o.MaxRetry)
}

func TestDefaultWithoutEither(t *testing.T) {
fs := pflag.NewFlagSet("kubetrigger", pflag.ContinueOnError)
addFlags(newOption(), fs)
clearEnv(t, fs)
o, err := parse(t)
require.NoError(t, err)
assert.Equal(t, defaultMaxRetry, o.MaxRetry)
}

func TestEnvNames(t *testing.T) {
t.Setenv("PER_WORKER_QPS", "7")
t.Setenv("LEADER_ELECT", "true")
t.Setenv("LEADER_ELECTION_LEASE_DURATION", "42s")
o, err := parse(t)
require.NoError(t, err)
assert.Equal(t, 7, o.PerWorkerQPS)
assert.True(t, enableLeaderElection)
assert.Equal(t, 42*time.Second, leaseDuration)
}

func TestBadEnvValueNamesItsVariable(t *testing.T) {
t.Setenv("MAX_RETRY", "lots")
_, err := parse(t)
assert.ErrorContains(t, err, "MAX_RETRY")
}

func TestValidationNamesTheVariable(t *testing.T) {
for name, env := range map[string]map[string]string{
"a number out of range": {"WORKERS": "0"},
"a bad log level": {"LOG_LEVEL": "bogus"},
} {
t.Run(name, func(t *testing.T) {
c := NewCommand()
clearEnv(t, c.Flags())
var variable string
for k, v := range env {
t.Setenv(k, v)
variable = k
}
require.NoError(t, c.ParseFlags(nil))
assert.ErrorContains(t, c.PreRunE(c, nil), variable)
})
}
}

func TestActionRetry(t *testing.T) {
Comment thread
briankane marked this conversation as resolved.
Resolved
o, err := parse(t, "--action-retry")
require.NoError(t, err)
assert.True(t, o.ActionRetry)

t.Setenv("ACTION_RETRY", "true")
o, err = parse(t)
require.NoError(t, err)
assert.True(t, o.ActionRetry)
}
2 changes: 1 addition & 1 deletion pkg/cmd/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func newOption() *option {
func (o *option) validate() error {
_, err := logrus.ParseLevel(o.LogLevel)
if err != nil {
return err
return fmt.Errorf("%s: %w", FlagLogLevel, err)
}
if o.Config == "" {
return fmt.Errorf("%s not specified", FlagConfig)
Expand Down
Loading