mirror of
https://github.com/kubenetworks/kubevpn.git
synced 2025-12-24 11:51:13 +08:00
feat: use kubectl style new cmd
This commit is contained in:
@@ -10,6 +10,9 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/client-go/util/retry"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
"k8s.io/kubectl/pkg/util/i18n"
|
||||
"k8s.io/kubectl/pkg/util/templates"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/config"
|
||||
"github.com/wencaiwulue/kubevpn/pkg/driver"
|
||||
@@ -17,64 +20,73 @@ import (
|
||||
"github.com/wencaiwulue/kubevpn/pkg/util"
|
||||
)
|
||||
|
||||
var connect = handler.ConnectOptions{}
|
||||
func CmdConnect(factory cmdutil.Factory) *cobra.Command {
|
||||
var connect = handler.ConnectOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "connect",
|
||||
Short: i18n.T("Connect to kubernetes cluster network, or proxy kubernetes workloads inbound traffic into local PC"),
|
||||
Long: templates.LongDesc(i18n.T(`Connect to kubernetes cluster network, or proxy kubernetes workloads inbound traffic into local PC`)),
|
||||
Example: templates.Examples(i18n.T(`
|
||||
# Connect to k8s cluster network
|
||||
kubevpn connect
|
||||
|
||||
func init() {
|
||||
connectCmd.Flags().StringVar(&connect.KubeconfigPath, "kubeconfig", "", "kubeconfig")
|
||||
connectCmd.Flags().StringVarP(&connect.Namespace, "namespace", "n", "", "namespace")
|
||||
connectCmd.PersistentFlags().StringArrayVar(&connect.Workloads, "workloads", []string{}, "workloads, like: pods/tomcat, deployment/nginx, replicaset/tomcat...")
|
||||
connectCmd.Flags().StringToStringVarP(&connect.Headers, "headers", "H", map[string]string{}, "headers, format is k=v, like: k1=v1,k2=v2")
|
||||
connectCmd.Flags().BoolVar(&config.Debug, "debug", false, "true/false")
|
||||
connectCmd.Flags().StringVar(&config.Image, "image", config.Image, "use this image to startup container")
|
||||
RootCmd.AddCommand(connectCmd)
|
||||
}
|
||||
# Reverse proxy
|
||||
- reverse deployment
|
||||
kubevpn connect --workloads=deployment/productpage
|
||||
- reverse service
|
||||
kubevpn connect --workloads=service/productpage
|
||||
|
||||
var connectCmd = &cobra.Command{
|
||||
Use: "connect",
|
||||
Short: "Connect to kubernetes cluster network, or proxy kubernetes workloads inbound traffic into local PC",
|
||||
Long: `Connect to kubernetes cluster network, or proxy kubernetes workloads inbound traffic into local PC`,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
if !util.IsAdmin() {
|
||||
util.RunWithElevated()
|
||||
os.Exit(0)
|
||||
} else {
|
||||
go func() { log.Info(http.ListenAndServe("localhost:6060", nil)) }()
|
||||
}
|
||||
},
|
||||
PreRun: func(*cobra.Command, []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
if util.IsWindows() {
|
||||
driver.InstallWireGuardTunDriver()
|
||||
}
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if err := connect.InitClient(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
connect.PreCheckResource()
|
||||
if err := connect.DoConnect(); err != nil {
|
||||
log.Errorln(err)
|
||||
handler.Cleanup(syscall.SIGQUIT)
|
||||
# Reverse proxy with mesh, traffic with header a=1, will hit local PC, otherwise no effect
|
||||
kubevpn connect --workloads=service/productpage --headers a=1
|
||||
`)),
|
||||
PersistentPreRun: func(*cobra.Command, []string) {
|
||||
if !util.IsAdmin() {
|
||||
util.RunWithElevated()
|
||||
os.Exit(0)
|
||||
} else {
|
||||
go func() { log.Info(http.ListenAndServe("localhost:6060", nil)) }()
|
||||
}
|
||||
},
|
||||
PreRun: func(*cobra.Command, []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
if util.IsWindows() {
|
||||
driver.InstallWireGuardTunDriver()
|
||||
}
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if err := connect.InitClient(factory); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
connect.PreCheckResource()
|
||||
if err := connect.DoConnect(); err != nil {
|
||||
log.Errorln(err)
|
||||
handler.Cleanup(syscall.SIGQUIT)
|
||||
select {}
|
||||
}
|
||||
fmt.Println(`---------------------------------------------------------------------------`)
|
||||
fmt.Println(` Now you can access resources in the kubernetes cluster, enjoy it :) `)
|
||||
fmt.Println(`---------------------------------------------------------------------------`)
|
||||
select {}
|
||||
}
|
||||
fmt.Println(`---------------------------------------------------------------------------`)
|
||||
fmt.Println(` Now you can access resources in the kubernetes cluster, enjoy it :) `)
|
||||
fmt.Println(`---------------------------------------------------------------------------`)
|
||||
select {}
|
||||
},
|
||||
PostRun: func(_ *cobra.Command, _ []string) {
|
||||
if util.IsWindows() {
|
||||
if err := retry.OnError(retry.DefaultRetry, func(err error) bool {
|
||||
return err != nil
|
||||
}, func() error {
|
||||
return driver.UninstallWireGuardTunDriver()
|
||||
}); err != nil {
|
||||
wd, _ := os.Getwd()
|
||||
filename := filepath.Join(wd, "wintun.dll")
|
||||
if err = os.Rename(filename, filepath.Join(os.TempDir(), "wintun.dll")); err != nil {
|
||||
log.Debugln(err)
|
||||
},
|
||||
PostRun: func(_ *cobra.Command, _ []string) {
|
||||
if util.IsWindows() {
|
||||
if err := retry.OnError(retry.DefaultRetry, func(err error) bool {
|
||||
return err != nil
|
||||
}, func() error {
|
||||
return driver.UninstallWireGuardTunDriver()
|
||||
}); err != nil {
|
||||
wd, _ := os.Getwd()
|
||||
filename := filepath.Join(wd, "wintun.dll")
|
||||
if err = os.Rename(filename, filepath.Join(os.TempDir(), "wintun.dll")); err != nil {
|
||||
log.Debugln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringArrayVar(&connect.Workloads, "workloads", []string{}, "Kubernetes workloads, special which workloads you want to proxy it to local PC, If not special, just connect to cluster network, like: pods/tomcat, deployment/nginx, replicaset/tomcat etc")
|
||||
cmd.Flags().StringToStringVarP(&connect.Headers, "headers", "H", map[string]string{}, "Traffic with special headers with reverse it to local PC, you should startup your service after reverse workloads successfully, If not special, redirect all traffic to local PC, format is k=v, like: k1=v1,k2=v2")
|
||||
cmd.Flags().BoolVar(&config.Debug, "debug", false, "enable debug mode or not, true or false")
|
||||
cmd.Flags().StringVar(&config.Image, "image", config.Image, "use this image to startup container")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -3,29 +3,28 @@ package cmds
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/config"
|
||||
"github.com/wencaiwulue/kubevpn/pkg/controlplane"
|
||||
"github.com/wencaiwulue/kubevpn/pkg/util"
|
||||
)
|
||||
|
||||
var (
|
||||
watchDirectoryFilename string
|
||||
port uint = 9002
|
||||
)
|
||||
|
||||
func init() {
|
||||
controlPlaneCmd.Flags().StringVarP(&watchDirectoryFilename, "watchDirectoryFilename", "w", "/etc/envoy/envoy-config.yaml", "full path to directory to watch for files")
|
||||
controlPlaneCmd.Flags().BoolVar(&config.Debug, "debug", false, "true/false")
|
||||
RootCmd.AddCommand(controlPlaneCmd)
|
||||
}
|
||||
|
||||
var controlPlaneCmd = &cobra.Command{
|
||||
Use: "control-plane",
|
||||
Short: "Control-plane is a envoy xds server",
|
||||
Long: `Control-plane is a envoy xds server, distribute envoy route configuration`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
controlplane.Main(watchDirectoryFilename, port, log.StandardLogger())
|
||||
},
|
||||
func CmdControlPlane(_ cmdutil.Factory) *cobra.Command {
|
||||
var (
|
||||
watchDirectoryFilename string
|
||||
port uint = 9002
|
||||
)
|
||||
cmd := &cobra.Command{
|
||||
Use: "control-plane",
|
||||
Short: "Control-plane is a envoy xds server",
|
||||
Long: `Control-plane is a envoy xds server, distribute envoy route configuration`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
controlplane.Main(watchDirectoryFilename, port, log.StandardLogger())
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVarP(&watchDirectoryFilename, "watchDirectoryFilename", "w", "/etc/envoy/envoy-config.yaml", "full path to directory to watch for files")
|
||||
cmd.Flags().BoolVar(&config.Debug, "debug", false, "true/false")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -3,26 +3,27 @@ package cmds
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/handler"
|
||||
)
|
||||
|
||||
func init() {
|
||||
resetCmd.Flags().StringVar(&connect.KubeconfigPath, "kubeconfig", "", "kubeconfig")
|
||||
resetCmd.Flags().StringVarP(&connect.Namespace, "namespace", "n", "", "namespace")
|
||||
RootCmd.AddCommand(resetCmd)
|
||||
}
|
||||
|
||||
var resetCmd = &cobra.Command{
|
||||
Use: "reset",
|
||||
Short: "Reset KubeVPN",
|
||||
Long: `Reset KubeVPN if any error occurs`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if err := connect.InitClient(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err := connect.Reset(cmd.Context())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Infoln("done")
|
||||
},
|
||||
func CmdReset(factory cmdutil.Factory) *cobra.Command {
|
||||
var connect = handler.ConnectOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "reset",
|
||||
Short: "Reset KubeVPN",
|
||||
Long: `Reset KubeVPN if any error occurs`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if err := connect.InitClient(factory); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
err := connect.Reset(cmd.Context())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Infoln("done")
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -1,9 +1,31 @@
|
||||
package cmds
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
)
|
||||
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "kubevpn",
|
||||
Short: "kubevpn",
|
||||
Long: `kubevpn`,
|
||||
func NewKubeVPNCommand() *cobra.Command {
|
||||
var cmd = &cobra.Command{
|
||||
Use: "kubevpn",
|
||||
Short: "kubevpn",
|
||||
Long: `kubevpn`,
|
||||
}
|
||||
|
||||
flags := cmd.PersistentFlags()
|
||||
configFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
|
||||
configFlags.AddFlags(flags)
|
||||
matchVersionFlags := cmdutil.NewMatchVersionFlags(configFlags)
|
||||
matchVersionFlags.AddFlags(flags)
|
||||
factory := cmdutil.NewFactory(matchVersionFlags)
|
||||
|
||||
cmd.AddCommand(CmdConnect(factory))
|
||||
cmd.AddCommand(CmdReset(factory))
|
||||
cmd.AddCommand(CmdControlPlane(factory))
|
||||
cmd.AddCommand(CmdServe(factory))
|
||||
cmd.AddCommand(CmdUpgrade(factory))
|
||||
cmd.AddCommand(CmdWebhook(factory))
|
||||
cmd.AddCommand(CmdVersion(factory))
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -6,34 +6,33 @@ import (
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/config"
|
||||
"github.com/wencaiwulue/kubevpn/pkg/handler"
|
||||
"github.com/wencaiwulue/kubevpn/pkg/util"
|
||||
)
|
||||
|
||||
var route handler.Route
|
||||
|
||||
func init() {
|
||||
ServerCmd.Flags().StringArrayVarP(&route.ServeNodes, "nodeCommand", "L", []string{}, "command needs to be executed")
|
||||
ServerCmd.Flags().StringVarP(&route.ChainNode, "chainCommand", "F", "", "command needs to be executed")
|
||||
ServerCmd.Flags().BoolVar(&config.Debug, "debug", false, "true/false")
|
||||
RootCmd.AddCommand(ServerCmd)
|
||||
}
|
||||
|
||||
var ServerCmd = &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "Server side, startup traffic manager, forward inbound and outbound traffic",
|
||||
Long: `Server side, startup traffic manager, forward inbound and outbound traffic.`,
|
||||
PreRun: func(*cobra.Command, []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
go func() { log.Info(http.ListenAndServe("localhost:6060", nil)) }()
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := handler.Start(context.Background(), route)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
select {}
|
||||
},
|
||||
func CmdServe(factory cmdutil.Factory) *cobra.Command {
|
||||
var route handler.Route
|
||||
cmd := &cobra.Command{
|
||||
Use: "serve",
|
||||
Short: "Server side, startup traffic manager, forward inbound and outbound traffic",
|
||||
Long: `Server side, startup traffic manager, forward inbound and outbound traffic.`,
|
||||
PreRun: func(*cobra.Command, []string) {
|
||||
util.InitLogger(config.Debug)
|
||||
go func() { log.Info(http.ListenAndServe("localhost:6060", nil)) }()
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := handler.Start(context.Background(), route)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
select {}
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringArrayVarP(&route.ServeNodes, "nodeCommand", "L", []string{}, "command needs to be executed")
|
||||
cmd.Flags().StringVarP(&route.ChainNode, "chainCommand", "F", "", "command needs to be executed")
|
||||
cmd.Flags().BoolVar(&config.Debug, "debug", false, "true/false")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/oauth2"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/upgrade"
|
||||
)
|
||||
@@ -16,22 +17,21 @@ var (
|
||||
GitHubOAuthToken = ""
|
||||
)
|
||||
|
||||
var upgradeCmd = &cobra.Command{
|
||||
Use: "upgrade",
|
||||
Short: "Upgrade KubeVPN version",
|
||||
Long: `Upgrade KubeVPN version, automatically download latest KubeVPN from GitHub`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
var client = http.DefaultClient
|
||||
if GitHubOAuthToken != "" {
|
||||
client = oauth2.NewClient(cmd.Context(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: GitHubOAuthToken, TokenType: "Bearer"}))
|
||||
}
|
||||
err := upgrade.Main(Version, client)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(upgradeCmd)
|
||||
func CmdUpgrade(_ cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "upgrade",
|
||||
Short: "Upgrade KubeVPN version",
|
||||
Long: `Upgrade KubeVPN version, automatically download latest KubeVPN from GitHub`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
var client = http.DefaultClient
|
||||
if GitHubOAuthToken != "" {
|
||||
client = oauth2.NewClient(cmd.Context(), oauth2.StaticTokenSource(&oauth2.Token{AccessToken: GitHubOAuthToken, TokenType: "Bearer"}))
|
||||
}
|
||||
err := upgrade.Main(Version, client)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/config"
|
||||
)
|
||||
@@ -28,24 +29,26 @@ func reformatDate(buildTime string) string {
|
||||
return buildTime
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of KubeVPN",
|
||||
Long: `This is the version of KubeVPN`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("KubeVPN: CLI\n")
|
||||
fmt.Printf(" Version: %s\n", Version)
|
||||
fmt.Printf(" Image: %s\n", config.Image)
|
||||
fmt.Printf(" Branch: %s\n", Branch)
|
||||
fmt.Printf(" Git commit: %s\n", GitCommit)
|
||||
fmt.Printf(" Built time: %s\n", reformatDate(BuildTime))
|
||||
fmt.Printf(" Built OS/Arch: %s\n", OsArch)
|
||||
fmt.Printf(" Built Go version: %s\n", runtime.Version())
|
||||
},
|
||||
func CmdVersion(cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of KubeVPN",
|
||||
Long: `This is the version of KubeVPN`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("KubeVPN: CLI\n")
|
||||
fmt.Printf(" Version: %s\n", Version)
|
||||
fmt.Printf(" Image: %s\n", config.Image)
|
||||
fmt.Printf(" Branch: %s\n", Branch)
|
||||
fmt.Printf(" Git commit: %s\n", GitCommit)
|
||||
fmt.Printf(" Built time: %s\n", reformatDate(BuildTime))
|
||||
fmt.Printf(" Built OS/Arch: %s\n", OsArch)
|
||||
fmt.Printf(" Built Go version: %s\n", runtime.Version())
|
||||
},
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(versionCmd)
|
||||
// Prefer version number inserted at build using --ldflags
|
||||
if Version == "" {
|
||||
if i, ok := debug.ReadBuildInfo(); ok {
|
||||
|
||||
@@ -2,20 +2,20 @@ package cmds
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
cmdutil "k8s.io/kubectl/pkg/cmd/util"
|
||||
|
||||
"github.com/wencaiwulue/kubevpn/pkg/webhook"
|
||||
)
|
||||
|
||||
var CmdWebhook = &cobra.Command{
|
||||
Use: "webhook",
|
||||
Short: "Starts a HTTP server, useful for creating MutatingAdmissionWebhook",
|
||||
Long: `Starts a HTTP server, useful for creating MutatingAdmissionWebhook.
|
||||
func CmdWebhook(cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "webhook",
|
||||
Short: "Starts a HTTP server, useful for creating MutatingAdmissionWebhook",
|
||||
Long: `Starts a HTTP server, useful for creating MutatingAdmissionWebhook.
|
||||
After deploying it to Kubernetes cluster, the Administrator needs to create a MutatingWebhookConfiguration
|
||||
in the Kubernetes cluster to register remote webhook admission controllers.`,
|
||||
Args: cobra.MaximumNArgs(0),
|
||||
Run: webhook.Main,
|
||||
}
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(CmdWebhook)
|
||||
Args: cobra.MaximumNArgs(0),
|
||||
Run: webhook.Main,
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -7,5 +7,5 @@ import (
|
||||
)
|
||||
|
||||
func main() {
|
||||
_ = cmds.RootCmd.Execute()
|
||||
_ = cmds.NewKubeVPNCommand().Execute()
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"k8s.io/apimachinery/pkg/util/runtime"
|
||||
"k8s.io/apimachinery/pkg/util/sets"
|
||||
"k8s.io/apimachinery/pkg/watch"
|
||||
"k8s.io/cli-runtime/pkg/genericclioptions"
|
||||
"k8s.io/cli-runtime/pkg/resource"
|
||||
"k8s.io/client-go/kubernetes"
|
||||
v12 "k8s.io/client-go/kubernetes/typed/core/v1"
|
||||
@@ -36,16 +35,15 @@ import (
|
||||
)
|
||||
|
||||
type ConnectOptions struct {
|
||||
KubeconfigPath string
|
||||
Namespace string
|
||||
Headers map[string]string
|
||||
Workloads []string
|
||||
clientset *kubernetes.Clientset
|
||||
restclient *rest.RESTClient
|
||||
config *rest.Config
|
||||
factory cmdutil.Factory
|
||||
cidrs []*net.IPNet
|
||||
dhcp *DHCPManager
|
||||
Namespace string
|
||||
Headers map[string]string
|
||||
Workloads []string
|
||||
clientset *kubernetes.Clientset
|
||||
restclient *rest.RESTClient
|
||||
config *rest.Config
|
||||
factory cmdutil.Factory
|
||||
cidrs []*net.IPNet
|
||||
dhcp *DHCPManager
|
||||
// needs to give it back to dhcp
|
||||
usedIPs []*net.IPNet
|
||||
routerIP net.IP
|
||||
@@ -111,14 +109,14 @@ func (c *ConnectOptions) DoConnect() (err error) {
|
||||
c.addCleanUpResourceHandler(c.clientset, c.Namespace)
|
||||
trafficMangerNet := net.IPNet{IP: config.RouterIP, Mask: config.CIDR.Mask}
|
||||
c.dhcp = NewDHCPManager(c.clientset.CoreV1().ConfigMaps(c.Namespace), c.Namespace, &trafficMangerNet)
|
||||
if err = c.dhcp.InitDHCP(); err != nil {
|
||||
if err = c.dhcp.InitDHCP(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
err = c.GetCIDR()
|
||||
err = c.GetCIDR(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.routerIP, err = CreateOutboundPod(c.factory, c.clientset, c.Namespace, trafficMangerNet.String(), c.cidrs)
|
||||
c.routerIP, err = CreateOutboundPod(ctx, c.factory, c.clientset, c.Namespace, trafficMangerNet.String(), c.cidrs)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -332,13 +330,8 @@ func Start(ctx context.Context, r Route) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConnectOptions) InitClient() (err error) {
|
||||
configFlags := genericclioptions.NewConfigFlags(true).WithDeprecatedPasswordFlag()
|
||||
if _, err = os.Stat(c.KubeconfigPath); err == nil {
|
||||
configFlags.KubeConfig = &c.KubeconfigPath
|
||||
}
|
||||
|
||||
c.factory = cmdutil.NewFactory(cmdutil.NewMatchVersionFlags(configFlags))
|
||||
func (c *ConnectOptions) InitClient(f cmdutil.Factory) (err error) {
|
||||
c.factory = f
|
||||
|
||||
if c.config, err = c.factory.ToRESTConfig(); err != nil {
|
||||
return
|
||||
@@ -349,12 +342,9 @@ func (c *ConnectOptions) InitClient() (err error) {
|
||||
if c.clientset, err = c.factory.KubernetesClientSet(); err != nil {
|
||||
return
|
||||
}
|
||||
if len(c.Namespace) == 0 {
|
||||
if c.Namespace, _, err = c.factory.ToRawKubeConfigLoader().Namespace(); err != nil {
|
||||
return
|
||||
}
|
||||
if c.Namespace, _, err = c.factory.ToRawKubeConfigLoader().Namespace(); err != nil {
|
||||
return
|
||||
}
|
||||
log.Infof("kubeconfig path: %s, namespace: %s, workloads: %v", c.KubeconfigPath, c.Namespace, c.Workloads)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -445,7 +435,7 @@ func (c *ConnectOptions) GetRunningPodList() ([]v1.Pod, error) {
|
||||
// https://stackoverflow.com/questions/45903123/kubernetes-set-service-cidr-and-pod-cidr-the-same
|
||||
// https://stackoverflow.com/questions/44190607/how-do-you-find-the-cluster-service-cidr-of-a-kubernetes-cluster/54183373#54183373
|
||||
// https://stackoverflow.com/questions/44190607/how-do-you-find-the-cluster-service-cidr-of-a-kubernetes-cluster
|
||||
func (c *ConnectOptions) GetCIDR() (err error) {
|
||||
func (c *ConnectOptions) GetCIDR(ctx context.Context) (err error) {
|
||||
// (1) get cidr from cache
|
||||
var value string
|
||||
value, err = c.dhcp.Get(config.KeyClusterIPv4POOLS)
|
||||
|
||||
@@ -32,13 +32,13 @@ func NewDHCPManager(client corev1.ConfigMapInterface, namespace string, cidr *ne
|
||||
}
|
||||
|
||||
// todo optimize dhcp, using mac address, ip and deadline as unit
|
||||
func (d *DHCPManager) InitDHCP() error {
|
||||
cm, err := d.client.Get(context.Background(), config.ConfigMapPodTrafficManager, metav1.GetOptions{})
|
||||
func (d *DHCPManager) InitDHCP(ctx context.Context) error {
|
||||
cm, err := d.client.Get(ctx, config.ConfigMapPodTrafficManager, metav1.GetOptions{})
|
||||
if err == nil {
|
||||
// add key envoy in case of mount not exist content
|
||||
if _, found := cm.Data[config.KeyEnvoy]; !found {
|
||||
_, err = d.client.Patch(
|
||||
context.Background(),
|
||||
ctx,
|
||||
cm.Name,
|
||||
types.MergePatchType,
|
||||
[]byte(fmt.Sprintf(`{"data":{"%s":"%s"}}`, config.KeyEnvoy, "")),
|
||||
@@ -59,7 +59,7 @@ func (d *DHCPManager) InitDHCP() error {
|
||||
config.KeyRefCount: "0",
|
||||
},
|
||||
}
|
||||
_, err = d.client.Create(context.Background(), cm, metav1.CreateOptions{})
|
||||
_, err = d.client.Create(ctx, cm, metav1.CreateOptions{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("create dhcp error, err: %v", err)
|
||||
}
|
||||
|
||||
@@ -39,8 +39,8 @@ import (
|
||||
"github.com/wencaiwulue/kubevpn/pkg/util"
|
||||
)
|
||||
|
||||
func CreateOutboundPod(factory cmdutil.Factory, clientset *kubernetes.Clientset, namespace string, trafficManagerIP string, nodeCIDR []*net.IPNet) (ip net.IP, err error) {
|
||||
service, err := clientset.CoreV1().Services(namespace).Get(context.Background(), config.ConfigMapPodTrafficManager, metav1.GetOptions{})
|
||||
func CreateOutboundPod(ctx context.Context, factory cmdutil.Factory, clientset *kubernetes.Clientset, namespace string, trafficManagerIP string, nodeCIDR []*net.IPNet) (ip net.IP, err error) {
|
||||
service, err := clientset.CoreV1().Services(namespace).Get(ctx, config.ConfigMapPodTrafficManager, metav1.GetOptions{})
|
||||
if err == nil {
|
||||
_, err = polymorphichelpers.AttachablePodForObjectFn(factory, service, 2*time.Second)
|
||||
if err == nil {
|
||||
@@ -52,24 +52,25 @@ func CreateOutboundPod(factory cmdutil.Factory, clientset *kubernetes.Clientset,
|
||||
return net.ParseIP(service.Spec.ClusterIP), nil
|
||||
}
|
||||
}
|
||||
var deleteResource = func() {
|
||||
_ = clientset.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(context.Background(), config.ConfigMapPodTrafficManager+"."+namespace, metav1.DeleteOptions{})
|
||||
_ = clientset.RbacV1().RoleBindings(namespace).Delete(context.Background(), config.ConfigMapPodTrafficManager, metav1.DeleteOptions{})
|
||||
_ = clientset.RbacV1().Roles(namespace).Delete(context.Background(), config.ConfigMapPodTrafficManager, metav1.DeleteOptions{})
|
||||
_ = clientset.CoreV1().ServiceAccounts(namespace).Delete(context.Background(), config.ConfigMapPodTrafficManager, metav1.DeleteOptions{})
|
||||
_ = clientset.CoreV1().Services(namespace).Delete(context.Background(), config.ConfigMapPodTrafficManager, metav1.DeleteOptions{})
|
||||
_ = clientset.AppsV1().Deployments(namespace).Delete(context.Background(), config.ConfigMapPodTrafficManager, metav1.DeleteOptions{})
|
||||
var deleteResource = func(ctx context.Context) {
|
||||
options := metav1.DeleteOptions{}
|
||||
_ = clientset.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(ctx, config.ConfigMapPodTrafficManager+"."+namespace, options)
|
||||
_ = clientset.RbacV1().RoleBindings(namespace).Delete(ctx, config.ConfigMapPodTrafficManager, options)
|
||||
_ = clientset.RbacV1().Roles(namespace).Delete(ctx, config.ConfigMapPodTrafficManager, options)
|
||||
_ = clientset.CoreV1().ServiceAccounts(namespace).Delete(ctx, config.ConfigMapPodTrafficManager, options)
|
||||
_ = clientset.CoreV1().Services(namespace).Delete(ctx, config.ConfigMapPodTrafficManager, options)
|
||||
_ = clientset.AppsV1().Deployments(namespace).Delete(ctx, config.ConfigMapPodTrafficManager, options)
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
deleteResource()
|
||||
deleteResource(context.Background())
|
||||
}
|
||||
}()
|
||||
deleteResource()
|
||||
deleteResource(context.Background())
|
||||
log.Infoln("traffic manager not exist, try to create it...")
|
||||
|
||||
// 1) label namespace
|
||||
ns, err := clientset.CoreV1().Namespaces().Get(context.Background(), namespace, metav1.GetOptions{})
|
||||
ns, err := clientset.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -77,7 +78,7 @@ func CreateOutboundPod(factory cmdutil.Factory, clientset *kubernetes.Clientset,
|
||||
ns.Labels = map[string]string{}
|
||||
}
|
||||
ns.Labels["ns"] = namespace
|
||||
_, err = clientset.CoreV1().Namespaces().Update(context.Background(), ns, metav1.UpdateOptions{})
|
||||
_, err = clientset.CoreV1().Namespaces().Update(ctx, ns, metav1.UpdateOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -137,7 +138,7 @@ func CreateOutboundPod(factory cmdutil.Factory, clientset *kubernetes.Clientset,
|
||||
tcp10800 := "10800-for-tcp"
|
||||
tcp9002 := "9002-for-envoy"
|
||||
tcp80 := "80-for-webhook"
|
||||
svc, err := clientset.CoreV1().Services(namespace).Create(context.Background(), &v1.Service{
|
||||
svc, err := clientset.CoreV1().Services(namespace).Create(ctx, &v1.Service{
|
||||
ObjectMeta: metav1.ObjectMeta{
|
||||
Name: config.ConfigMapPodTrafficManager,
|
||||
Namespace: namespace,
|
||||
@@ -319,14 +320,14 @@ kubevpn serve -L "tcp://:10800" -L "tun://:8422?net=${TrafficManagerIP}" --debug
|
||||
},
|
||||
},
|
||||
}
|
||||
watchStream, err := clientset.CoreV1().Pods(namespace).Watch(context.Background(), metav1.ListOptions{
|
||||
watchStream, err := clientset.CoreV1().Pods(namespace).Watch(ctx, metav1.ListOptions{
|
||||
LabelSelector: fields.OneTermEqualSelector("app", config.ConfigMapPodTrafficManager).String(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer watchStream.Stop()
|
||||
if _, err = clientset.AppsV1().Deployments(namespace).Create(context.Background(), deployment, metav1.CreateOptions{}); err != nil {
|
||||
if _, err = clientset.AppsV1().Deployments(namespace).Create(ctx, deployment, metav1.CreateOptions{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var last string
|
||||
|
||||
@@ -82,7 +82,7 @@ func TestGetIPFromDHCP(t *testing.T) {
|
||||
}
|
||||
_, ipNet, err := net.ParseCIDR("192.168.1.100/24")
|
||||
manager := NewDHCPManager(clientset.CoreV1().ConfigMaps("test"), "test", ipNet)
|
||||
manager.InitDHCP()
|
||||
manager.InitDHCP(context.Background())
|
||||
for i := 0; i < 10; i++ {
|
||||
ipNet, err := manager.RentIPRandom()
|
||||
ipNet2, err := manager.RentIPRandom()
|
||||
@@ -125,11 +125,11 @@ func TestGetTopControllerByLabel(t *testing.T) {
|
||||
|
||||
func TestPreCheck(t *testing.T) {
|
||||
options := ConnectOptions{
|
||||
KubeconfigPath: filepath.Join(homedir.HomeDir(), ".kube", "mesh"),
|
||||
Namespace: "naison-test",
|
||||
Workloads: []string{"services/authors"},
|
||||
//KubeconfigPath: filepath.Join(homedir.HomeDir(), ".kube", "mesh"),
|
||||
Namespace: "naison-test",
|
||||
Workloads: []string{"services/authors"},
|
||||
}
|
||||
options.InitClient()
|
||||
options.InitClient(nil)
|
||||
options.PreCheckResource()
|
||||
fmt.Println(options.Workloads)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user