diff --git a/pkg/config/const.go b/pkg/config/const.go index e0e0e68d..430dd89c 100644 --- a/pkg/config/const.go +++ b/pkg/config/const.go @@ -21,6 +21,8 @@ const ( LogFile = "daemon.log" ConfigFile = "config.yaml" + + TmpDir = "tmp" ) //go:embed config.yaml @@ -51,6 +53,14 @@ func init() { if err != nil { panic(err) } + err = os.MkdirAll(GetTempPath(), 0755) + if err != nil { + panic(err) + } + err = os.Chmod(GetTempPath(), 0755) + if err != nil { + panic(err) + } path := filepath.Join(HomePath, ConfigFile) _, err = os.Stat(path) @@ -85,3 +95,7 @@ func GetSyncthingPath() string { func GetConfigFilePath() string { return filepath.Join(HomePath, ConfigFile) } + +func GetTempPath() string { + return filepath.Join(HomePath, TmpDir) +} diff --git a/pkg/ssh/ssh.go b/pkg/ssh/ssh.go index 96d39f04..0a26b719 100644 --- a/pkg/ssh/ssh.go +++ b/pkg/ssh/ssh.go @@ -333,9 +333,9 @@ func SshJump(ctx context.Context, conf *SshConfig, flags *pflag.FlagSet, print b return } if print { - plog.G(ctx).Infof("Use temporary kubeconfig: %s", path) + plog.G(ctx).Infof("Use temp kubeconfig: %s", path) } else { - plog.G(ctx).Debugf("Use temporary kubeconfig: %s", path) + plog.G(ctx).Debugf("Use temp kubeconfig: %s", path) } return } diff --git a/pkg/util/ns.go b/pkg/util/ns.go index 7e70b1e9..93416a4f 100644 --- a/pkg/util/ns.go +++ b/pkg/util/ns.go @@ -3,6 +3,7 @@ package util import ( "context" "encoding/json" + "fmt" "net" "net/url" "os" @@ -128,7 +129,12 @@ func GetAPIServerFromKubeConfigBytes(kubeconfigBytes []byte) *net.IPNet { } func ConvertToTempKubeconfigFile(kubeconfigBytes []byte) (string, error) { - temp, err := os.CreateTemp("", "*.kubeconfig") + pattern := "*.kubeconfig" + cluster, ns, _ := GetCluster(kubeconfigBytes) + if cluster != "" { + pattern = fmt.Sprintf("%s_%s_%s", cluster, ns, pattern) + } + temp, err := os.CreateTemp(config.GetTempPath(), pattern) if err != nil { return "", err } @@ -147,6 +153,32 @@ func ConvertToTempKubeconfigFile(kubeconfigBytes []byte) (string, error) { return temp.Name(), nil } +func GetCluster(kubeConfigBytes []byte) (cluster string, ns string, err error) { + var clientConfig clientcmd.ClientConfig + clientConfig, err = clientcmd.NewClientConfigFromBytes(kubeConfigBytes) + if err != nil { + return + } + var rawConfig api.Config + rawConfig, err = clientConfig.RawConfig() + if err != nil { + return + } + if err = api.FlattenConfig(&rawConfig); err != nil { + return + } + if rawConfig.Contexts == nil { + return + } + kubeContext := rawConfig.Contexts[rawConfig.CurrentContext] + if kubeContext == nil { + return + } + cluster = kubeContext.Cluster + ns = kubeContext.Namespace + return +} + func InitFactory(kubeconfigBytes string, ns string) cmdutil.Factory { configFlags := genericclioptions.NewConfigFlags(true) configFlags.WrapConfigFn = func(c *rest.Config) *rest.Config {