refactor: change temp kubeconfig to ~/.kubevpn/tmp

This commit is contained in:
fengcaiwen
2025-04-29 21:39:45 +08:00
parent 9ba873494f
commit ebaa4098f1
3 changed files with 49 additions and 3 deletions

View File

@@ -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)
}

View File

@@ -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
}

View File

@@ -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 {