|
| 1 | +package portforward |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "os/signal" |
| 11 | + "strconv" |
| 12 | + "sync" |
| 13 | + |
| 14 | + "github.com/revolyssup/k8sdebug/pkg" |
| 15 | + "github.com/spf13/cobra" |
| 16 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 17 | + "k8s.io/client-go/kubernetes" |
| 18 | + "k8s.io/client-go/tools/clientcmd" |
| 19 | + "k8s.io/client-go/tools/portforward" |
| 20 | + "k8s.io/client-go/transport/spdy" |
| 21 | +) |
| 22 | + |
| 23 | +var ( |
| 24 | + namespace string |
| 25 | + typ string |
| 26 | + hostport string |
| 27 | +) |
| 28 | +var labels string |
| 29 | + |
| 30 | +func forwardToPod(hostConn net.Conn, podCon net.Conn) { |
| 31 | + //Copy data bidirectionally |
| 32 | + go io.Copy(hostConn, podCon) |
| 33 | + io.Copy(podCon, hostConn) |
| 34 | +} |
| 35 | + |
| 36 | +var connPool []string |
| 37 | + |
| 38 | +var policy string |
| 39 | + |
| 40 | +func getPodConnection(fw forwarder) (net.Conn, error) { |
| 41 | + podConn, err := net.Dial("tcp", fmt.Sprintf(":%d", fw.Port())) |
| 42 | + if err != nil { |
| 43 | + return nil, err |
| 44 | + } |
| 45 | + return podConn, nil |
| 46 | +} |
| 47 | + |
| 48 | +type forwarder interface { |
| 49 | + Port() int |
| 50 | +} |
| 51 | + |
| 52 | +type roundRobin struct { |
| 53 | + connNumber int |
| 54 | +} |
| 55 | + |
| 56 | +func (rr *roundRobin) Port() int { |
| 57 | + portNum := 8080 + (rr.connNumber % len(connPool)) |
| 58 | + rr.connNumber++ |
| 59 | + return portNum |
| 60 | +} |
| 61 | +func getForwarder(policy string) forwarder { |
| 62 | + switch policy { |
| 63 | + case "round-robin": |
| 64 | + return &roundRobin{} |
| 65 | + } |
| 66 | + return nil |
| 67 | +} |
| 68 | +func NewCommand() *cobra.Command { |
| 69 | + cmd := &cobra.Command{ |
| 70 | + Use: "port-forward", |
| 71 | + Run: func(cmd *cobra.Command, args []string) { |
| 72 | + fw := getForwarder(policy) |
| 73 | + if fw == nil { |
| 74 | + fmt.Errorf("invalid policy for forwarding traffic\n") |
| 75 | + return |
| 76 | + } |
| 77 | + listener, err := net.Listen("tcp", fmt.Sprintf(":%s", hostport)) |
| 78 | + if err != nil { |
| 79 | + panic(err) |
| 80 | + } |
| 81 | + defer listener.Close() |
| 82 | + ctx, cancel := context.WithCancel(context.Background()) |
| 83 | + defer cancel() |
| 84 | + go func() { |
| 85 | + for { |
| 86 | + select { |
| 87 | + case <-ctx.Done(): |
| 88 | + return |
| 89 | + default: |
| 90 | + hostConn, err := listener.Accept() |
| 91 | + if err != nil { |
| 92 | + fmt.Printf("Accept error: %v", err) |
| 93 | + continue |
| 94 | + } |
| 95 | + podConn, err := getPodConnection(fw) |
| 96 | + if err != nil { |
| 97 | + fmt.Printf("Pod connection error: %v", err) |
| 98 | + continue |
| 99 | + } |
| 100 | + forwardToPod(hostConn, podConn) |
| 101 | + } |
| 102 | + |
| 103 | + } |
| 104 | + }() |
| 105 | + kubeconfig := clientcmd.NewDefaultClientConfigLoadingRules().GetDefaultFilename() |
| 106 | + config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) |
| 107 | + if err != nil { |
| 108 | + panic(err.Error()) |
| 109 | + } |
| 110 | + cs := kubernetes.NewForConfigOrDie(config) |
| 111 | + opts := metav1.ListOptions{} |
| 112 | + if labels != "" { |
| 113 | + opts.LabelSelector = labels |
| 114 | + } |
| 115 | + initialList, err := cs.CoreV1().Pods(namespace).List(context.TODO(), opts) |
| 116 | + if err != nil { |
| 117 | + panic("Exiting runner..." + err.Error()) |
| 118 | + } |
| 119 | + connPool = make([]string, 0) |
| 120 | + pods := initialList.Items |
| 121 | + fmt.Printf(pkg.ColorLine(fmt.Sprintf("listening on %s using %s policy across %d pods\n", hostport, policy, len(pods)), pkg.ColorGreen)) |
| 122 | + for i, pod := range pods { |
| 123 | + req := cs.CoreV1().RESTClient().Post(). |
| 124 | + Resource("pods"). |
| 125 | + Namespace(namespace). |
| 126 | + Name(pod.Name). |
| 127 | + SubResource("portforward") |
| 128 | + transporter, upgrader, err := spdy.RoundTripperFor(config) |
| 129 | + if err != nil { |
| 130 | + fmt.Println("coudnot open connection for pod", pod.Name) |
| 131 | + continue |
| 132 | + } |
| 133 | + dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transporter}, "POST", req.URL()) |
| 134 | + stopChan := make(chan struct{}) |
| 135 | + readyChan := make(chan struct{}) |
| 136 | + hostPort := 8080 + i |
| 137 | + hostPortStr := fmt.Sprintf("%s:80", strconv.Itoa(hostPort)) |
| 138 | + connPool = append(connPool, hostPortStr) |
| 139 | + forwarder, err := portforward.New(dialer, []string{hostPortStr}, stopChan, readyChan, os.Stdout, os.Stderr) |
| 140 | + if err != nil { |
| 141 | + fmt.Println("coudnot forward connection for pod", pod.Name) |
| 142 | + continue |
| 143 | + } |
| 144 | + go func() { |
| 145 | + if err := forwarder.ForwardPorts(); err != nil { |
| 146 | + // errChan <- fmt.Errorf("port forwarding failed: %v", err) |
| 147 | + fmt.Println("coudnot forward connection for pod", pod.Name) |
| 148 | + } |
| 149 | + }() |
| 150 | + } |
| 151 | + var wg sync.WaitGroup |
| 152 | + sigchan := make(chan os.Signal) |
| 153 | + signal.Notify(sigchan, os.Interrupt) |
| 154 | + wg.Add(1) |
| 155 | + go func() { |
| 156 | + <-sigchan |
| 157 | + wg.Done() |
| 158 | + listener.Close() |
| 159 | + }() |
| 160 | + wg.Wait() |
| 161 | + fmt.Println("Stopping watcher...") |
| 162 | + }, |
| 163 | + } |
| 164 | + |
| 165 | + cmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "default", "Name of the pod") |
| 166 | + cmd.PersistentFlags().StringVarP(&typ, "type", "t", "pod", "Name of the pod") |
| 167 | + cmd.PersistentFlags().StringVar(&policy, "policy", "round-robin", "policy to use while sending requests") |
| 168 | + cmd.Flags().StringVarP(&labels, "labels", "l", "", "list of key value pairs to use as labels while filtering pods.") |
| 169 | + cmd.Flags().StringVar(&hostport, "hostport", "3000", "host port on which requests will be sent") |
| 170 | + return cmd |
| 171 | +} |
0 commit comments