-
Notifications
You must be signed in to change notification settings - Fork 9
/
portforward.go
47 lines (39 loc) · 1.26 KB
/
portforward.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package utils
import (
"fmt"
"net/http"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
func RunPortForward(kubeconfig, namespace, podName string, port int) (stopChannel chan struct{}, localPort int, err error) {
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
return nil, 0, err
}
kubeCli, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, 0, fmt.Errorf("failed to get kubernetes Clientset: %v", err)
}
req := kubeCli.CoreV1().RESTClient().Post().Namespace(namespace).
Resource("pods").Name(podName).SubResource("portforward")
readyChannel := make(chan struct{})
stopChannel = make(chan struct{}, 1)
transport, upgrader, err := spdy.RoundTripperFor(cfg)
if err != nil {
return nil, 0, err
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, "POST", req.URL())
fw, err := portforward.NewOnAddresses(dialer, []string{"127.0.0.1"}, []string{fmt.Sprintf(":%d", port)}, stopChannel, readyChannel, nil, nil)
if err != nil {
return nil, 0, err
}
go fw.ForwardPorts()
<-readyChannel
ports, err := fw.GetPorts()
if err != nil {
return nil, 0, err
}
return stopChannel, int(ports[0].Local), nil
}