feat: optimize code (#96)

optimize code and fix testcase
This commit is contained in:
naison
2023-11-23 12:35:34 +08:00
committed by GitHub
parent 0e0885afd5
commit 1a9593f140
23 changed files with 101 additions and 105 deletions

View File

@@ -166,4 +166,14 @@ jobs:
choco install make
- name: Build
run: make kubevpn-windows-amd64
run: make kubevpn-windows-amd64
upload-coverage-reports-to-codecov:
runs-on: ubuntu-latest
if: ${{ always() }}
needs: [ "linux", "macos", "windows" ]
steps:
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

View File

@@ -7,6 +7,9 @@
[![GitHub License][5]](https://github.com/KubeNetworks/kubevpn/blob/main/LICENSE)
[![Docker Pulls][6]](https://hub.docker.com/r/naison/kubevpn)
[![Releases][7]](https://github.com/KubeNetworks/kubevpn/releases)
[![GoDoc](https://godoc.org/github.com/KubeNetworks/kubevpn?status.png)](https://godoc.org/github.com/KubeNetworks/kubevpn)
[![Test coverage](http://gocover.io/_badge/github.com/KubeNetworks/kubevpn)](https://gocover.io/github.com/KubeNetworks/kubevpn)
[1]: https://img.shields.io/github/actions/workflow/status/KubeNetworks/kubevpn/release.yml?logo=github

View File

@@ -7,6 +7,8 @@
[![GitHub License][5]](https://github.com/KubeNetworks/kubevpn/blob/main/LICENSE)
[![Docker Pulls][6]](https://hub.docker.com/r/naison/kubevpn)
[![Releases][7]](https://github.com/KubeNetworks/kubevpn/releases)
[![GoDoc](https://godoc.org/github.com/KubeNetworks/kubevpn?status.png)](https://godoc.org/github.com/KubeNetworks/kubevpn)
[![Test coverage](http://gocover.io/_badge/github.com/KubeNetworks/kubevpn)](https://gocover.io/github.com/KubeNetworks/kubevpn)
[1]: https://img.shields.io/github/actions/workflow/status/KubeNetworks/kubevpn/release.yml?logo=github

View File

@@ -1,16 +0,0 @@
package handler
import (
"fmt"
"github.com/wencaiwulue/kubevpn/pkg/util"
"testing"
)
func TestName(t *testing.T) {
cmd := fmt.Sprintf(`hash kubevpn1 || type kubevpn1 || which kubevpn1 || command -v kubevpn1`)
serverIP, stderr, err := util.RemoteRun(&util.SshConfig{
ConfigAlias: "ry-dev-agd",
}, cmd, nil)
fmt.Println(string(serverIP), string(stderr), err)
}

View File

@@ -0,0 +1,59 @@
package daemon
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
)
func TestHttpOverUnix(t *testing.T) {
file := filepath.Join(os.TempDir(), "kubevpn.socks")
client := http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 10 * time.Second,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
d.Timeout = 30 * time.Second
d.KeepAlive = 30 * time.Second
return d.DialContext(ctx, "unix", file)
},
},
}
go func() {
listener, err := net.Listen("unix", file)
if err != nil {
t.Fatal(err)
}
defer listener.Close()
downgradingServer := &http.Server{}
defer downgradingServer.Close()
var h2Server http2.Server
err = http2.ConfigureServer(downgradingServer, &h2Server)
if err != nil {
t.Fatal(err)
}
downgradingServer.Handler = h2c.NewHandler(http.HandlerFunc(http.DefaultServeMux.ServeHTTP), &h2Server)
downgradingServer.Serve(listener)
}()
time.Sleep(time.Second * 2)
//var resp *http.Response
resp, err := client.Get("http://test" + "/ws")
if err != nil {
t.Fatal(err)
}
all, _ := io.ReadAll(resp.Body)
fmt.Println(string(all))
}

View File

@@ -1,61 +0,0 @@
package daemon
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"testing"
"time"
)
func TestName(t *testing.T) {
httpc := http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
d.Timeout = 30 * time.Second
d.KeepAlive = 30 * time.Second
return d.DialContext(ctx, "unix", GetSockPath(false))
},
},
}
resp, err := httpc.Get("http://test" + "/ws")
if err != nil {
t.Fatal(err)
}
//c.Transport = transport // use the unix dialer
//uri := fmt.Sprintf("http://%s/%s", daemon.GetSockPath(false), "ws")
//resp, err := c.Get(uri)
//if err != nil {
// fmt.Println(err.Error())
// return
//}
all, _ := io.ReadAll(resp.Body)
fmt.Println(string(all))
}
type unixDialer struct {
net.Dialer
}
// overriding net.Dialer.Dial to force unix socket connection
func (d *unixDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
parts := strings.Split(address, ":")
return d.Dialer.Dial("unix", parts[0])
}
// copied from http.DefaultTransport with minimal changes
var transport http.RoundTripper = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&unixDialer{net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
},
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
}

View File

@@ -398,7 +398,7 @@ func DoDev(ctx context.Context, devOption *Options, conf *util.SshConfig, flags
return err
}
if inspect.State == nil {
return fmt.Errorf("can not get container status, please make contianer name is valid")
return fmt.Errorf("can not get container status, please make container name is valid")
}
if !inspect.State.Running {
return fmt.Errorf("container %s status is %s, expect is running, please make sure your outer docker name is correct", mode.ConnectedContainer(), inspect.State.Status)

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package openvpn

View File

@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package openvpn
@@ -13,7 +12,7 @@ import (
//go:embed exe/tap-windows-9.21.2.exe
var fs embed.FS
// driver download from https://build.openvpn.net/downloads/releases/
// driver download from https://build.openvpn.net/downloads/releases/
func Install() error {
bytes, err := fs.ReadFile("exe/tap-windows-9.21.2.exe")
if err != nil {

View File

@@ -1,5 +1,4 @@
//go:build windows && amd64
// +build windows,amd64
package wintun

View File

@@ -1,5 +1,4 @@
//go:build windows && arm
// +build windows,arm
package wintun

View File

@@ -1,5 +1,4 @@
//go:build windows && arm64
// +build windows,arm64
package wintun

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package wintun

View File

@@ -1,6 +1,4 @@
//go:build windows && (x86 || 386)
// +build windows
// +build x86 386
package wintun

View File

@@ -8,6 +8,7 @@ import (
"os/exec"
"reflect"
"runtime"
"strings"
"sync"
"testing"
"time"
@@ -38,6 +39,7 @@ var (
)
func TestFunctions(t *testing.T) {
Init()
kubevpnConnect(t)
t.Run(runtime.FuncForPC(reflect.ValueOf(pingPodIP).Pointer()).Name(), pingPodIP)
t.Run(runtime.FuncForPC(reflect.ValueOf(dialUDP).Pointer()).Name(), dialUDP)
@@ -306,20 +308,24 @@ func server(port int) {
}
func kubevpnConnect(t *testing.T) {
ctx2, timeoutFunc := context.WithTimeout(context.Background(), 2*time.Hour)
defer timeoutFunc()
cmd := exec.CommandContext(ctx2, "kubevpn", "proxy", "--debug", "deployments/reviews")
output, err := cmd.CombinedOutput()
cmd := exec.Command("kubevpn", "proxy", "--debug", "deployments/reviews")
check := func(log string) {
line := "+" + strings.Repeat("-", len(log)-2) + "+"
t.Log(line)
t.Log(log)
t.Log(line)
t.Log("\n")
}
stdout, stderr, err := util.RunWithRollingOutWithChecker(cmd, check)
if err != nil {
t.Log(string(output))
t.Log(stdout, stderr)
t.Error(err)
t.Fail()
return
}
}
func init1() {
func Init() {
var err error
configFlags := genericclioptions.NewConfigFlags(true)

View File

@@ -32,7 +32,11 @@ func main() {
if err != nil {
panic(err)
}
tunConn, err := listener.Accept()
var tunConn net.Conn
tunConn, err = listener.Accept()
if err != nil {
log.Fatal(err)
}
defer tunConn.Close()
tcpConn, err := net.Dial("tcp", ":1080")
if err != nil {

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package util

View File

@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package util

View File

@@ -1,5 +1,4 @@
//go:build !windows
// +build !windows
package util

View File

@@ -1,5 +1,4 @@
//go:build windows
// +build windows
package util

View File

@@ -56,12 +56,13 @@ func getCIDRFromCNI(clientset *kubernetes.Clientset, restclient *rest.RESTClient
var cmd = `grep -a -R "service-cluster-ip-range\|cluster-cidr" /etc/cni/proc/*/cmdline | grep -a -v grep | tr "\0" "\n"`
var result []*net.IPNet
content, err := Shell(clientset, restclient, restconfig, pod.Name, "", pod.Namespace, []string{"sh", "-c", cmd})
var content string
content, err = Shell(clientset, restclient, restconfig, pod.Name, "", pod.Namespace, []string{"sh", "-c", cmd})
if err != nil {
return nil, err
}
var result []*net.IPNet
for _, s := range strings.Split(content, "\n") {
result = Deduplicate(append(result, parseCIDRFromString(s)...))
}

View File

@@ -129,7 +129,7 @@ func TransferImage(ctx context.Context, conf *SshConfig, imageSource, imageTarge
}
defer os.Remove(file.Name())
logrus.Infof("Transfering image %s", imageTarget)
logrus.Infof("Transferring image %s", imageTarget)
filename := filepath.Base(file.Name())
cmd := fmt.Sprintf(
"(docker load image -i ~/.kubevpn/%s && docker push %s) || (nerdctl image load -i ~/.kubevpn/%s && nerdctl image push %s)",

View File

@@ -40,13 +40,13 @@ func GetManifest(httpCli *http.Client, os string, arch string) (version string,
var all []byte
all, err = io.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("failed to read all reponse from github api, err: %v", err)
err = fmt.Errorf("failed to read all response from github api, err: %v", err)
return
}
var m RootEntity
err = json.Unmarshal(all, &m)
if err != nil {
err = fmt.Errorf("failed to unmarshal reponse, err: %v", err)
err = fmt.Errorf("failed to unmarshal response, err: %v", err)
return
}
version = m.TagName