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

@@ -2,18 +2,14 @@ package action
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"time"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"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/handler"
plog "github.com/wencaiwulue/kubevpn/v2/pkg/log"
@@ -117,11 +113,7 @@ func (svr *Server) redirectConnectToSudoDaemon(req *rpc.ConnectRequest, resp rpc
})
if !sshConf.IsEmpty() {
var path string
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)
file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), true)
if err != nil {
return err
}

View File

@@ -116,7 +116,7 @@ func disconnectByKubeconfig(ctx context.Context, svr *Server, kubeconfigBytes st
var err error
var sshConf = ssh.ParseSshFromRPC(jump)
if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(kubeconfigBytes), "", false)
file, err = ssh.SshJump(ctx, sshConf, []byte(kubeconfigBytes), false)
} else {
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
defer os.Remove(file)
if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false)
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else {
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 ctx = plog.WithLogger(resp.Context(), logger)
if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false)
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
}

View File

@@ -5,12 +5,9 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"time"
"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/handler"
plog "github.com/wencaiwulue/kubevpn/v2/pkg/log"
@@ -105,11 +102,7 @@ func (svr *Server) Sync(resp rpc.Daemon_SyncServer) (err error) {
return nil
})
if !sshConf.IsEmpty() {
var path string
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)
file, err = ssh.SshJump(sshCtx, sshConf, []byte(req.KubeconfigBytes), false)
} else {
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 ctx = plog.WithLogger(resp.Context(), logger)
if !sshConf.IsEmpty() {
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), "", false)
file, err = ssh.SshJump(ctx, sshConf, []byte(req.KubeconfigBytes), false)
} else {
file, err = util.ConvertToTempKubeconfigFile([]byte(req.KubeconfigBytes), "")
}

View File

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

View File

@@ -10,6 +10,7 @@ import (
"net/netip"
"net/url"
"os"
"path/filepath"
"strconv"
"sync"
"time"
@@ -135,7 +136,7 @@ func PortMapUntil(ctx context.Context, conf *SshConfig, remote, local netip.Addr
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 {
var stdout []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)
return
}
path, err = pkgutil.ConvertToTempKubeconfigFile(marshal, tempPath)
path, err = pkgutil.ConvertToTempKubeconfigFile(marshal, GenKubeconfigTempPath(conf, kubeconfigBytes))
if err != nil {
plog.G(ctx).Errorf("failed to write kubeconfig: %v", err)
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 {
path, err := SshJump(ctx, sshConf, kubeconfigBytes, "", print)
path, err := SshJump(ctx, sshConf, kubeconfigBytes, print)
if err != nil {
return err
}
@@ -438,3 +439,11 @@ func copyStream(ctx context.Context, local net.Conn, remote net.Conn) {
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 (
"fmt"
"os"
"path/filepath"
"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 {
@@ -16,3 +24,51 @@ func ContainerNet(name string) string {
func GenEnvoyUID(ns, uid string) string {
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 (
"context"
"encoding/json"
"fmt"
"net"
"net/url"
"os"
"reflect"
"strings"
"unsafe"
errors2 "github.com/pkg/errors"
@@ -129,17 +127,11 @@ func GetAPIServerFromKubeConfigBytes(kubeconfigBytes []byte) *net.IPNet {
func ConvertToTempKubeconfigFile(kubeconfigBytes []byte, path string) (string, error) {
var f *os.File
var err error
if path != "" {
f, err = os.Create(path)
} else {
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)
if path == "" {
path = GenKubeconfigTempPath(kubeconfigBytes)
}
f, err = os.Create(path)
if err != nil {
return "", err
}
@@ -158,41 +150,6 @@ func ConvertToTempKubeconfigFile(kubeconfigBytes []byte, path string) (string, e
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 {
configFlags := genericclioptions.NewConfigFlags(true)
configFlags.WrapConfigFn = func(c *rest.Config) *rest.Config {