refactor: optimize code (#702)

This commit is contained in:
naison
2025-08-14 19:12:59 +08:00
committed by GitHub
parent aef13e4c74
commit 4ddba64737
11 changed files with 79 additions and 76 deletions

View File

@@ -259,7 +259,7 @@ func GetConnectionIDByConfig(cmd *cobra.Command, config Config) (string, error)
var file string var file string
defer os.Remove(file) defer os.Remove(file)
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
file, err = pkgssh.SshJump(cmd.Context(), sshConf, kubeConfigBytes, "", false) file, err = pkgssh.SshJump(cmd.Context(), sshConf, kubeConfigBytes, false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile(kubeConfigBytes, "") file, err = util.ConvertToTempKubeconfigFile(kubeConfigBytes, "")
} }

View File

@@ -2,18 +2,14 @@ package action
import ( import (
"context" "context"
"fmt"
"io" "io"
"os" "os"
"path/filepath"
"time"
"github.com/golang/protobuf/proto" "github.com/golang/protobuf/proto"
"github.com/pkg/errors" "github.com/pkg/errors"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/wencaiwulue/kubevpn/v2/pkg/config"
"github.com/wencaiwulue/kubevpn/v2/pkg/daemon/rpc" "github.com/wencaiwulue/kubevpn/v2/pkg/daemon/rpc"
"github.com/wencaiwulue/kubevpn/v2/pkg/handler" "github.com/wencaiwulue/kubevpn/v2/pkg/handler"
plog "github.com/wencaiwulue/kubevpn/v2/pkg/log" plog "github.com/wencaiwulue/kubevpn/v2/pkg/log"
@@ -117,11 +113,7 @@ func (svr *Server) redirectConnectToSudoDaemon(req *rpc.ConnectRequest, resp rpc
}) })
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
var path string file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), true)
if sshConf.RemoteKubeconfig != "" {
path = filepath.Join(config.GetTempPath(), fmt.Sprintf("%s_%d", sshConf.GenKubeconfigIdentify(), time.Now().Unix()))
}
file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), path, true)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -116,7 +116,7 @@ func disconnectByKubeconfig(ctx context.Context, svr *Server, kubeconfigBytes st
var err error var err error
var sshConf = ssh.ParseSshFromRPC(jump) var sshConf = ssh.ParseSshFromRPC(jump)
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(kubeconfigBytes), "", false) file, err = ssh.SshJump(ctx, sshConf, []byte(kubeconfigBytes), false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile([]byte(kubeconfigBytes), "") file, err = util.ConvertToTempKubeconfigFile([]byte(kubeconfigBytes), "")
} }

View File

@@ -38,7 +38,7 @@ func (svr *Server) Proxy(resp rpc.Daemon_ProxyServer) (err error) {
var file string var file string
defer os.Remove(file) defer os.Remove(file)
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false) file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "") file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
} }

View File

@@ -25,7 +25,7 @@ func (svr *Server) Reset(resp rpc.Daemon_ResetServer) error {
var sshConf = ssh.ParseSshFromRPC(req.SshJump) var sshConf = ssh.ParseSshFromRPC(req.SshJump)
var ctx = plog.WithLogger(resp.Context(), logger) var ctx = plog.WithLogger(resp.Context(), logger)
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false) file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "") file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
} }

View File

@@ -5,12 +5,9 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"time"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/wencaiwulue/kubevpn/v2/pkg/config"
"github.com/wencaiwulue/kubevpn/v2/pkg/daemon/rpc" "github.com/wencaiwulue/kubevpn/v2/pkg/daemon/rpc"
"github.com/wencaiwulue/kubevpn/v2/pkg/handler" "github.com/wencaiwulue/kubevpn/v2/pkg/handler"
plog "github.com/wencaiwulue/kubevpn/v2/pkg/log" plog "github.com/wencaiwulue/kubevpn/v2/pkg/log"
@@ -105,11 +102,7 @@ func (svr *Server) Sync(resp rpc.Daemon_SyncServer) (err error) {
return nil return nil
}) })
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
var path string file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), false)
if sshConf.RemoteKubeconfig != "" {
path = filepath.Join(config.GetTempPath(), fmt.Sprintf("%s_%d", sshConf.GenKubeconfigIdentify(), time.Now().Unix()))
}
file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), path, false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "") file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
} }

View File

@@ -29,7 +29,7 @@ func (svr *Server) Uninstall(resp rpc.Daemon_UninstallServer) (err error) {
var sshConf = ssh.ParseSshFromRPC(req.SshJump) var sshConf = ssh.ParseSshFromRPC(req.SshJump)
var ctx = plog.WithLogger(resp.Context(), logger) var ctx = plog.WithLogger(resp.Context(), logger)
if !sshConf.IsEmpty() { if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false) file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else { } else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "") file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
} }

View File

@@ -90,14 +90,10 @@ func sanitizeFilename(name string) string {
} }
} }
} }
fname := result.String() fname := result.String()
fname = strings.Trim(fname, "-_.") fname = strings.Trim(fname, "-_.")
if fname == "" { if fname == "" {
return "ip-address" return "ip-address"
} }
return fname return fname
} }

View File

@@ -10,6 +10,7 @@ import (
"net/netip" "net/netip"
"net/url" "net/url"
"os" "os"
"path/filepath"
"strconv" "strconv"
"sync" "sync"
"time" "time"
@@ -135,7 +136,7 @@ func PortMapUntil(ctx context.Context, conf *SshConfig, remote, local netip.Addr
return nil return nil
} }
func SshJump(ctx context.Context, conf *SshConfig, kubeconfigBytes []byte, tempPath string, print bool) (path string, err error) { func SshJump(ctx context.Context, conf *SshConfig, kubeconfigBytes []byte, print bool) (path string, err error) {
if len(conf.RemoteKubeconfig) != 0 { if len(conf.RemoteKubeconfig) != 0 {
var stdout []byte var stdout []byte
var stderr []byte var stderr []byte
@@ -278,7 +279,7 @@ func SshJump(ctx context.Context, conf *SshConfig, kubeconfigBytes []byte, tempP
plog.G(ctx).Errorf("failed to marshal config: %v", err) plog.G(ctx).Errorf("failed to marshal config: %v", err)
return return
} }
path, err = pkgutil.ConvertToTempKubeconfigFile(marshal, tempPath) path, err = pkgutil.ConvertToTempKubeconfigFile(marshal, GenKubeconfigTempPath(conf, kubeconfigBytes))
if err != nil { if err != nil {
plog.G(ctx).Errorf("failed to write kubeconfig: %v", err) plog.G(ctx).Errorf("failed to write kubeconfig: %v", err)
return return
@@ -296,7 +297,7 @@ func SshJump(ctx context.Context, conf *SshConfig, kubeconfigBytes []byte, tempP
} }
func SshJumpAndSetEnv(ctx context.Context, sshConf *SshConfig, kubeconfigBytes []byte, print bool) error { func SshJumpAndSetEnv(ctx context.Context, sshConf *SshConfig, kubeconfigBytes []byte, print bool) error {
path, err := SshJump(ctx, sshConf, kubeconfigBytes, "", print) path, err := SshJump(ctx, sshConf, kubeconfigBytes, print)
if err != nil { if err != nil {
return err return err
} }
@@ -438,3 +439,11 @@ func copyStream(ctx context.Context, local net.Conn, remote net.Conn) {
return return
} }
} }
func GenKubeconfigTempPath(conf *SshConfig, kubeconfigBytes []byte) string {
if conf != nil && conf.RemoteKubeconfig != "" {
return filepath.Join(config.GetTempPath(), fmt.Sprintf("%s_%d", conf.GenKubeconfigIdentify(), time.Now().Unix()))
}
return pkgutil.GenKubeconfigTempPath(kubeconfigBytes)
}

View File

@@ -2,7 +2,15 @@ package util
import ( import (
"fmt" "fmt"
"os"
"path/filepath"
"strings" "strings"
"time"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"github.com/wencaiwulue/kubevpn/v2/pkg/config"
) )
func Join(names ...string) string { func Join(names ...string) string {
@@ -16,3 +24,51 @@ func ContainerNet(name string) string {
func GenEnvoyUID(ns, uid string) string { func GenEnvoyUID(ns, uid string) string {
return fmt.Sprintf("%s.%s", ns, uid) return fmt.Sprintf("%s.%s", ns, uid)
} }
func GenKubeconfigTempPath(kubeconfigBytes []byte) string {
var path string
cluster, ns, _ := GetCluster(kubeconfigBytes)
if !ContainsPathSeparator(cluster) && !ContainsPathSeparator(ns) {
pattern := fmt.Sprintf("%s_%s_%d", cluster, ns, time.Now().Unix())
pattern = strings.ReplaceAll(pattern, string(os.PathSeparator), "-")
path = filepath.Join(config.GetTempPath(), pattern)
} else {
path = filepath.Join(config.GetTempPath(), fmt.Sprintf("%d", time.Now().Unix()))
}
return path
}
func ContainsPathSeparator(pattern string) bool {
for i := 0; i < len(pattern); i++ {
if os.IsPathSeparator(pattern[i]) {
return true
}
}
return false
}
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
}

View File

@@ -3,12 +3,10 @@ package util
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"net" "net"
"net/url" "net/url"
"os" "os"
"reflect" "reflect"
"strings"
"unsafe" "unsafe"
errors2 "github.com/pkg/errors" errors2 "github.com/pkg/errors"
@@ -129,17 +127,11 @@ func GetAPIServerFromKubeConfigBytes(kubeconfigBytes []byte) *net.IPNet {
func ConvertToTempKubeconfigFile(kubeconfigBytes []byte, path string) (string, error) { func ConvertToTempKubeconfigFile(kubeconfigBytes []byte, path string) (string, error) {
var f *os.File var f *os.File
var err error var err error
if path != "" {
f, err = os.Create(path) if path == "" {
} else { path = GenKubeconfigTempPath(kubeconfigBytes)
pattern := "*.kubeconfig"
cluster, ns, _ := GetCluster(kubeconfigBytes)
if cluster != "" && !containerPathSeparator(cluster) && !containerPathSeparator(ns) {
pattern = fmt.Sprintf("%s_%s_%s", cluster, ns, pattern)
pattern = strings.ReplaceAll(pattern, string(os.PathSeparator), "-")
}
f, err = os.CreateTemp(config.GetTempPath(), pattern)
} }
f, err = os.Create(path)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -158,41 +150,6 @@ func ConvertToTempKubeconfigFile(kubeconfigBytes []byte, path string) (string, e
return f.Name(), nil return f.Name(), nil
} }
func containerPathSeparator(pattern string) bool {
for i := 0; i < len(pattern); i++ {
if os.IsPathSeparator(pattern[i]) {
return true
}
}
return false
}
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 { func InitFactory(kubeconfigBytes string, ns string) cmdutil.Factory {
configFlags := genericclioptions.NewConfigFlags(true) configFlags := genericclioptions.NewConfigFlags(true)
configFlags.WrapConfigFn = func(c *rest.Config) *rest.Config { configFlags.WrapConfigFn = func(c *rest.Config) *rest.Config {