feat: optimize code

This commit is contained in:
fengcaiwen
2023-03-16 19:11:22 +08:00
committed by wencaiwulue
parent a545f3a958
commit 1970f30f9d
13 changed files with 173 additions and 144 deletions

View File

@@ -5,24 +5,13 @@ import (
"context"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"text/tabwriter"
"github.com/docker/docker/api/types/mount"
"github.com/moby/term"
"github.com/spf13/cobra"
"golang.org/x/exp/constraints"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/kubectl/pkg/cmd/util"
"github.com/wencaiwulue/kubevpn/pkg/config"
"github.com/wencaiwulue/kubevpn/pkg/cp"
)
func PrintStatus(pod *corev1.Pod, writer io.Writer) {
@@ -103,60 +92,3 @@ func GetEnv(ctx context.Context, f util.Factory, ns, pod string) (map[string][]s
}
return result, nil
}
// GetVolume key format: [container name]-[volume mount name]
func GetVolume(ctx context.Context, f util.Factory, ns, pod string) (map[string][]mount.Mount, error) {
clientSet, err := f.KubernetesClientSet()
if err != nil {
return nil, err
}
var get *corev1.Pod
get, err = clientSet.CoreV1().Pods(ns).Get(ctx, pod, v1.GetOptions{})
if err != nil {
return nil, err
}
result := map[string][]mount.Mount{}
for _, c := range get.Spec.Containers {
// if container name is vpn or envoy-proxy, not need to download volume
if c.Name == config.ContainerSidecarVPN || c.Name == config.ContainerSidecarEnvoyProxy {
continue
}
var m []mount.Mount
for _, volumeMount := range c.VolumeMounts {
if volumeMount.MountPath == "/tmp" {
continue
}
join := filepath.Join(os.TempDir(), strconv.Itoa(rand.Int()))
err = os.MkdirAll(join, 0755)
if err != nil {
return nil, err
}
if volumeMount.SubPath != "" {
join = filepath.Join(join, volumeMount.SubPath)
}
// pod-namespace/pod-name:path
remotePath := fmt.Sprintf("%s/%s:%s", ns, pod, volumeMount.MountPath)
stdIn, stdOut, stdErr := term.StdStreams()
copyOptions := cp.NewCopyOptions(genericclioptions.IOStreams{In: stdIn, Out: stdOut, ErrOut: stdErr})
copyOptions.Container = c.Name
copyOptions.MaxTries = 10
err = copyOptions.Complete(f, &cobra.Command{}, []string{remotePath, join})
if err != nil {
return nil, err
}
err = copyOptions.Run()
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to download volume %s path %s to %s, err: %v, ignore...\n", volumeMount.Name, remotePath, join, err)
continue
}
m = append(m, mount.Mount{
Type: mount.TypeBind,
Source: join,
Target: volumeMount.MountPath,
})
fmt.Printf("%s:%s\n", join, volumeMount.MountPath)
}
result[c.Name] = m
}
return result, nil
}

View File

@@ -31,6 +31,7 @@ import (
k8sruntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/cli-runtime/pkg/genericclioptions"
runtimeresource "k8s.io/cli-runtime/pkg/resource"
@@ -631,30 +632,48 @@ func AllContainerIsRunning(pod *v1.Pod) bool {
}
func CleanExtensionLib() {
if IsWindows() {
err := retry.OnError(retry.DefaultRetry, func(err error) bool {
return err != nil
}, func() error {
return driver.UninstallWireGuardTunDriver()
})
if err != nil {
var wd string
wd, err = os.Getwd()
if err != nil {
return
}
filename := filepath.Join(wd, "wintun.dll")
var temp *os.File
if temp, err = os.CreateTemp("", ""); err != nil {
return
}
if err = temp.Close(); err != nil {
return
}
if err = os.Rename(filename, temp.Name()); err != nil {
log.Debugln(err)
}
}
if !IsWindows() {
return
}
path, err := os.Executable()
if err != nil {
return
}
filename := filepath.Join(filepath.Dir(path), "wintun.dll")
_ = retry.OnError(
// step : 0 13 34 55 100 194 433 661 1384 2689 (ms)
// total: 5.57s
wait.Backoff{
Steps: 10,
Duration: 10 * time.Millisecond,
Factor: 2.0,
Jitter: 0.5,
},
func(error) bool {
_, err = os.Lstat(filename)
return !errors.Is(err, os.ErrNotExist)
},
func() error {
err = driver.UninstallWireGuardTunDriver()
return fmt.Errorf("%v", err)
},
)
_, err = os.Lstat(filename)
if errors.Is(err, os.ErrNotExist) {
return
}
var temp *os.File
if temp, err = os.CreateTemp("", ""); err != nil {
return
}
if err = temp.Close(); err != nil {
return
}
if err = os.Remove(temp.Name()); err != nil {
return
}
if err = os.Rename(filename, temp.Name()); err != nil {
log.Debugln(err)
}
}

View File

@@ -3,6 +3,7 @@ package util
import (
"encoding/json"
"net"
"strings"
"testing"
"github.com/containernetworking/cni/libcni"
@@ -94,6 +95,9 @@ func TestPing(t *testing.T) {
}
ipConn, err := net.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
if strings.Contains(err.Error(), "operation not permitted") {
return
}
t.Error(err)
}
bytes := buf.Bytes()