Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix redefine flag #2992

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion bindings/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func NewKubernetes(logger logger.Logger) bindings.InputBinding {
}

func (k *kubernetesInput) Init(ctx context.Context, metadata bindings.Metadata) error {
client, err := kubeclient.GetKubeClient()
client, err := kubeclient.GetKubeClient(k.logger)
if err != nil {
return err
}
Expand Down
9 changes: 6 additions & 3 deletions crypto/kubernetes/secrets/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,17 @@ const (
type kubeSecretsCrypto struct {
contribCrypto.LocalCryptoBaseComponent

logger logger.Logger
md secretsMetadata
kubeClient kubernetes.Interface
}

// NewKubeSecretsCrypto returns a new Kubernetes secrets crypto provider.
// The key arguments in methods can be in the format "namespace/secretName/key" or "secretName/key" if using the default namespace passed as component metadata.
func NewKubeSecretsCrypto(_ logger.Logger) contribCrypto.SubtleCrypto {
k := &kubeSecretsCrypto{}
func NewKubeSecretsCrypto(log logger.Logger) contribCrypto.SubtleCrypto {
k := &kubeSecretsCrypto{
logger: log,
}
k.RetrieveKeyFn = k.retrieveKeyFromSecret
return k
}
Expand All @@ -62,7 +65,7 @@ func (k *kubeSecretsCrypto) Init(_ context.Context, metadata contribCrypto.Metad
}

// Init Kubernetes client
k.kubeClient, err = kubeclient.GetKubeClient()
k.kubeClient, err = kubeclient.GetKubeClient(k.logger)
if err != nil {
return fmt.Errorf("failed to init Kubernetes client: %w", err)
}
Expand Down
58 changes: 47 additions & 11 deletions internal/authentication/kubernetes/client.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2021 The Dapr Authors
Copyright 2023 The Dapr 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
Expand All @@ -14,33 +14,69 @@ limitations under the License.
package kubernetes

import (
"flag"
"os"
"path/filepath"
"strings"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"

"github.com/dapr/kit/logger"
)

const (
cliFlagName = "kubeconfig"
envVarName = "KUBECONFIG"
)

//nolint:gochecknoglobals
var kubeconfig *string
var defaultKubeConfig string

//nolint:gochecknoinits
func init() {
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
defaultKubeConfig = filepath.Join(home, ".kube", "config")
}
}

func getKubeconfigPath(log logger.Logger, args []string) string {
// Check if the path is set via the CLI flag `--kubeconfig`
// This is deprecated but kept for backwards compatibility
var cliVal string
for i, a := range args {
parts := strings.SplitN(a, "=", 2)
if parts[0] == "-"+cliFlagName || parts[0] == "--"+cliFlagName {
// Case: "--kubeconfig=val" or "-kubeconfig=val"
if len(parts) == 2 {
cliVal = parts[1]
break
} else if len(args) > (i+1) && !strings.HasPrefix(args[i+1], "-") {
// Case: "--kubeconfig val" or "-kubeconfig val"
cliVal = args[i+1]
break
}
}
}
if cliVal != "" {
log.Warnf("Setting kubeconfig using the CLI flag '--%s' is deprecated and will be removed in a future version", cliFlagName)
return cliVal
}

// Check if we have the KUBECONFIG env var
envVal := os.Getenv(envVarName)
if envVal != "" {
return envVal
}

// Return the default value
return defaultKubeConfig
}

// GetKubeClient returns a kubernetes client.
func GetKubeClient() (*kubernetes.Clientset, error) {
flag.Parse()
func GetKubeClient(log logger.Logger) (*kubernetes.Clientset, error) {
conf, err := rest.InClusterConfig()
if err != nil {
conf, err = clientcmd.BuildConfigFromFlags("", *kubeconfig)
conf, err = clientcmd.BuildConfigFromFlags("", getKubeconfigPath(log, os.Args))
if err != nil {
return nil, err
}
Expand Down
61 changes: 61 additions & 0 deletions internal/authentication/kubernetes/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Copyright 2023 The Dapr 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 kubernetes

import (
"io"
"strings"
"testing"

"github.com/dapr/kit/logger"
)

func TestGetKubeconfigPath(t *testing.T) {
log := logger.NewLogger("test")
log.SetOutput(io.Discard)
tests := []struct {
name string
args []string
env string
want string
}{
{name: "return default value", want: defaultKubeConfig},
{name: "CLI flag -kubeconfig cli.yaml", args: []string{"binary", "-kubeconfig", "cli.yaml"}, want: "cli.yaml"},
{name: "CLI flag -kubeconfig=cli.yaml", args: []string{"binary", "-kubeconfig=cli.yaml"}, want: "cli.yaml"},
{name: "CLI flag --kubeconfig cli.yaml", args: []string{"binary", "--kubeconfig", "cli.yaml"}, want: "cli.yaml"},
{name: "CLI flag --kubeconfig=cli.yaml", args: []string{"binary", "--kubeconfig=cli.yaml"}, want: "cli.yaml"},
{name: "CLI flag --kubeconfig cli.yaml not as last", args: []string{"binary", "--kubeconfig", "cli.yaml", "--foo", "example"}, want: "cli.yaml"},
{name: "CLI flag --kubeconfig=cli.yaml not as last", args: []string{"binary", "--kubeconfig=cli.yaml", "--foo", "example"}, want: "cli.yaml"},
{name: "CLI flag --kubeconfig with no value as last", args: []string{"binary", "--kubeconfig"}, want: defaultKubeConfig},
{name: "CLI flag --kubeconfig with no value and more flags", args: []string{"binary", "--kubeconfig", "--foo"}, want: defaultKubeConfig},
{name: "env var", env: "KUBECONFIG=env.yaml", want: "env.yaml"},
{name: "CLI flag has priority over env var", args: []string{"binary", "-kubeconfig", "cli.yaml"}, env: "KUBECONFIG=env.yaml", want: "cli.yaml"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.env != "" {
parts := strings.SplitN(tt.env, "=", 2)
t.Setenv(parts[0], parts[1])
}

args := tt.args
if args == nil {
args = []string{}
}
if got := getKubeconfigPath(log, args); got != tt.want {
t.Errorf("getKubeconfigPath() = %v, want %v", got, tt.want)
}
})
}
}
2 changes: 1 addition & 1 deletion secretstores/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewKubernetesSecretStore(logger logger.Logger) secretstores.SecretStore {

// Init creates a Kubernetes client.
func (k *kubernetesSecretStore) Init(_ context.Context, metadata secretstores.Metadata) error {
client, err := kubeclient.GetKubeClient()
client, err := kubeclient.GetKubeClient(k.logger)
if err != nil {
return err
}
Expand Down
Loading