feat: add APIServer ip to route table if ssh info is not empty (#361)

This commit is contained in:
naison
2024-10-25 21:25:42 +08:00
committed by GitHub
parent aa881a589e
commit 65ae890842
6 changed files with 56 additions and 0 deletions

View File

@@ -130,6 +130,11 @@ func (option *Options) Connect(ctx context.Context, sshConfig *pkgssh.SshConfig,
if err != nil {
return err
}
if !sshConfig.IsEmpty() {
if ip := util.GetAPIServerFromKubeConfigBytes(kubeConfigBytes); ip != nil {
option.ExtraRouteInfo.ExtraCIDR = append(option.ExtraRouteInfo.ExtraCIDR, ip.String())
}
}
logLevel := log.InfoLevel
if config.Debug {
logLevel = log.DebugLevel

View File

@@ -99,6 +99,10 @@ func (config *SshConfig) ToRPC() *rpc.SshJump {
}
}
func (config *SshConfig) IsEmpty() bool {
return config.ConfigAlias == "" && config.Addr == "" && config.Jump == ""
}
func AddSshFlags(flags *pflag.FlagSet, sshConf *SshConfig) {
// for ssh jumper host
flags.StringVar(&sshConf.Addr, "ssh-addr", "", "Optional ssh jump server address to dial as <hostname>:<port>, eg: 127.0.0.1:22")

View File

@@ -3,6 +3,8 @@ package util
import (
"context"
"encoding/json"
"net"
"net/url"
"os"
"reflect"
"unsafe"
@@ -96,6 +98,36 @@ func ConvertToKubeConfigBytes(factory cmdutil.Factory) ([]byte, string, error) {
return marshal, namespace, nil
}
func GetAPIServerFromKubeConfigBytes(kubeconfigBytes []byte) *net.IPNet {
kubeConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfigBytes)
if err != nil {
return nil
}
var host string
host, _, err = net.SplitHostPort(kubeConfig.Host)
if err != nil {
u, err2 := url.Parse(kubeConfig.Host)
if err2 != nil {
return nil
}
host, _, err = net.SplitHostPort(u.Host)
if err != nil {
return nil
}
}
ip := net.ParseIP(host)
if ip == nil {
return nil
}
var mask net.IPMask
if ip.To4() != nil {
mask = net.CIDRMask(32, 32)
} else {
mask = net.CIDRMask(128, 128)
}
return &net.IPNet{IP: ip, Mask: mask}
}
func ConvertToTempKubeconfigFile(kubeconfigBytes []byte) (string, error) {
temp, err := os.CreateTemp("", "*.kubeconfig")
if err != nil {