Skip to content

Commit

Permalink
chore: refactor kubernetes client constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Nov 28, 2024
1 parent 750b4a2 commit 1dafecf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
17 changes: 5 additions & 12 deletions context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,25 +346,18 @@ func (k *Context) WithKubeconfig(input types.EnvVar) (*Context, error) {
if k.GetNamespace() == "" {
return nil, k.Oops().Errorf("namespace is required")
}

val, err := k.GetEnvValueFromCache(input, k.GetNamespace())
if err != nil {
return k, k.Oops().Wrap(err)
}

var client kubernetes.Interface
var rest *rest.Config

if strings.HasPrefix(val, "/") {
if client, rest, err = dutyKubernetes.NewClient(k.Logger, val); err != nil {
return k, k.Oops().Wrap(err)
}
} else {
if client, rest, err = dutyKubernetes.NewClientWithConfig(k.Logger, []byte(val)); err != nil {
return k, k.Oops().Wrap(err)
}
clientset, restConfig, err := dutyKubernetes.NewClientFromPathOrConfig(k.Logger, val)
if err != nil {
return k, k.Oops().Wrap(err)
}

c := k.WithKubernetes(client, rest)
c := k.WithKubernetes(clientset, restConfig)

return &c, nil

Expand Down
19 changes: 19 additions & 0 deletions kubernetes/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"
"os"
"regexp"
"strings"
"time"

"github.com/flanksource/commons/console"
Expand Down Expand Up @@ -100,6 +101,24 @@ func NewClientWithConfig(logger logger.Logger, kubeConfig []byte) (kubernetes.In
}
}

func NewClientFromPathOrConfig(logger logger.Logger, kubeconfigOrPath string) (kubernetes.Interface, *rest.Config, error) {
var client kubernetes.Interface
var rest *rest.Config
var err error

if strings.HasPrefix(kubeconfigOrPath, "/") {
if client, rest, err = NewClient(logger, kubeconfigOrPath); err != nil {
return nil, nil, err
}
} else {
if client, rest, err = NewClientWithConfig(logger, []byte(kubeconfigOrPath)); err != nil {
return nil, nil, err
}
}

return client, rest, err
}

func trace(clogger logger.Logger, config *rest.Config) *rest.Config {
if clogger.IsLevelEnabled(7) {
clogger.Infof("tracing kubernetes API calls")
Expand Down

0 comments on commit 1dafecf

Please sign in to comment.