-
Notifications
You must be signed in to change notification settings - Fork 90
/
portforward.go
360 lines (300 loc) · 9.63 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package k8sutil
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"time"
"github.com/phayes/freeport"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/auth"
"github.com/replicatedhq/kots/pkg/logger"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
)
func init() {
// Note this changes loggers globbaly for apimachinery packages,
// but this is the only way to silence port forwarder.
f, _ := os.Create(filepath.Join(os.TempDir(), "portforward.log"))
logger := func(err error) {
if f == nil {
return
}
fmt.Fprintf(f, "%v\n", err)
}
runtime.ErrorHandlers = []func(error){logger}
}
func IsPortAvailable(port int) bool {
host := ":" + strconv.Itoa(port)
server, err := net.Listen("tcp", host)
if err != nil {
return false
}
server.Close()
return true
}
// PortForward starts a local port forward to a pod in the cluster
// if localport is set, it will attempt to use that port locally.
// always check the port number returned though, because a port conflict
// could cause a different port to be used
func PortForward(kubernetesConfigFlags *genericclioptions.ConfigFlags, localPort int, remotePort int, namespace string, podName string, pollForAdditionalPorts bool, stopCh <-chan struct{}, log *logger.Logger) (int, <-chan error, error) {
if localPort == 0 {
freePort, err := freeport.GetFreePort()
if err != nil {
return 0, nil, errors.Wrap(err, "failed to get free port")
}
localPort = freePort
}
if !IsPortAvailable(localPort) {
freePort, err := freeport.GetFreePort()
if err != nil {
return 0, nil, errors.Wrap(err, "failed to get free port")
}
localPort = freePort
}
// port forward
cfg, err := kubernetesConfigFlags.ToRESTConfig()
if err != nil {
return 0, nil, errors.Wrap(err, "failed to convert kube flags to rest config")
}
roundTripper, upgrader, err := spdy.RoundTripperFor(cfg)
if err != nil {
return 0, nil, err
}
path := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", namespace, podName)
scheme := ""
hostIP := cfg.Host
u, err := url.Parse(cfg.Host)
if err != nil {
return 0, nil, err
}
if u.Scheme == "http" || u.Scheme == "https" {
scheme = u.Scheme
hostIP = u.Host
}
serverURL := url.URL{Scheme: scheme, Path: path, Host: hostIP}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: roundTripper}, http.MethodPost, &serverURL)
stopChan, readyChan := make(chan struct{}, 1), make(chan struct{}, 1)
out, errOut := new(bytes.Buffer), new(bytes.Buffer)
forwarder, err := portforward.New(dialer, []string{fmt.Sprintf("%d:%d", localPort, remotePort)}, stopChan, readyChan, out, errOut)
if err != nil {
return 0, nil, err
}
errChan := make(chan error, 2) // 2 go routines are writing to this channel
go func() {
for range readyChan {
}
if len(errOut.String()) != 0 {
errChan <- errors.Errorf("remote error: %s", errOut)
} else if len(out.String()) != 0 {
// fmt.Println(out.String())
}
}()
var forwardErr error
go func() {
// Locks until stopChan is closed.
// The main function may timeout before this returns an error
forwardErr = forwarder.ForwardPorts()
if forwardErr != nil {
errChan <- errors.Wrap(forwardErr, "forward ports")
}
}()
// Block until the new service is responding, limited to (math) seconds
quickClient := &http.Client{
Timeout: time.Millisecond * 200,
}
start := time.Now()
for {
if forwardErr != nil {
return 0, nil, forwardErr
}
response, err := quickClient.Get(fmt.Sprintf("http://localhost:%d/healthz", localPort))
if err == nil && response.StatusCode == http.StatusOK {
break
}
if time.Now().Sub(start) > time.Duration(time.Second*10) {
if err == nil {
err = errors.Errorf("service responded with status %s", response.Status)
}
return 0, nil, err
}
time.Sleep(time.Millisecond * 100)
if quickClient.Timeout < time.Second {
quickClient.Timeout = quickClient.Timeout + time.Millisecond*100
}
}
if pollForAdditionalPorts {
type AdditionalPort struct {
ServiceName string `json:"serviceName"`
ServicePort int `json:"servicePort"`
LocalPort int `json:"localPort"`
}
forwardedAdditionalPorts := map[AdditionalPort]chan struct{}{}
keepPolling := true
go func() {
<-stopChan
keepPolling = false
}()
uri := fmt.Sprintf("http://localhost:%d/api/v1/kots/ports", localPort)
sleepTime := time.Second * 1
go func() {
for keepPolling {
time.Sleep(sleepTime)
sleepTime = time.Second * 5
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
runtime.HandleError(errors.Wrap(err, "failed to create request"))
continue
}
req.Header.Set("Accept", "application/json")
authSlug, err := auth.GetOrCreateAuthSlug(kubernetesConfigFlags, namespace)
if err != nil {
runtime.HandleError(errors.Wrap(err, "failed to get kotsadm auth slug"))
continue
}
req.Header.Add("Authorization", authSlug)
resp, err := http.DefaultClient.Do(req)
if err != nil {
runtime.HandleError(errors.Wrap(err, "failed to get ports"))
continue
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
runtime.HandleError(errors.Wrap(err, "failed to parse response"))
continue
}
desiredAdditionalPorts := []AdditionalPort{}
if err := json.Unmarshal(b, &desiredAdditionalPorts); err != nil {
runtime.HandleError(errors.Wrap(err, "failed to decode response"))
continue
}
for _, desiredAdditionalPort := range desiredAdditionalPorts {
alreadyForwarded := false
for forwardedAdditionalPort := range forwardedAdditionalPorts {
// Avoid port conflicts by only taking the first to claim a local port
if forwardedAdditionalPort.LocalPort == desiredAdditionalPort.LocalPort {
alreadyForwarded = true
break
}
}
if alreadyForwarded {
continue
}
serviceStopCh, err := ServiceForward(kubernetesConfigFlags, desiredAdditionalPort.LocalPort, desiredAdditionalPort.ServicePort, namespace, desiredAdditionalPort.ServiceName)
if err != nil {
runtime.HandleError(errors.Wrap(err, "failed to forward port"))
continue // try again
}
if serviceStopCh == nil {
// we didn't do the port forwarding, probably because the pod isn't ready.
// try again next loop
runtime.HandleError(errors.New("failed to forward port; pod not ready?"))
continue // try again
}
forwardedAdditionalPorts[desiredAdditionalPort] = serviceStopCh
log.ActionWithoutSpinner("Go to http://localhost:%d to access the application", desiredAdditionalPort.LocalPort)
}
}
}()
}
return localPort, errChan, nil
}
func ServiceForward(kubernetesConfigFlags *genericclioptions.ConfigFlags, localPort int, remotePort int, namespace string, serviceName string) (chan struct{}, error) {
if !IsPortAvailable(localPort) {
return nil, errors.Errorf("Unable to connect to cluster. There's another process using port %d.", localPort)
}
clientset, err := GetClientset(kubernetesConfigFlags)
if err != nil {
return nil, errors.Wrap(err, "failed to create clientset")
}
svc, err := clientset.CoreV1().Services(namespace).Get(serviceName, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrap(err, "failed to get service")
}
selector := labels.SelectorFromSet(svc.Spec.Selector)
podName, err := getFirstPod(clientset, namespace, selector.String())
if err != nil {
return nil, errors.Wrap(err, "failed to get first pod")
}
if podName == "" {
// not ready yet
return nil, nil
}
cfg, err := kubernetesConfigFlags.ToRESTConfig()
if err != nil {
return nil, errors.Wrap(err, "failed to convert kube flags to rest config")
}
roundTripper, upgrader, err := spdy.RoundTripperFor(cfg)
if err != nil {
return nil, err
}
path := fmt.Sprintf("/api/v1/namespaces/%s/pods/%s/portforward", namespace, podName)
scheme := ""
hostIP := cfg.Host
u, err := url.Parse(cfg.Host)
if err != nil {
return nil, err
}
if u.Scheme == "http" || u.Scheme == "https" {
scheme = u.Scheme
hostIP = u.Host
}
serverURL := url.URL{Scheme: scheme, Path: path, Host: hostIP}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: roundTripper}, http.MethodPost, &serverURL)
stopChan, readyChan := make(chan struct{}, 1), make(chan struct{}, 1)
out, errOut := new(bytes.Buffer), new(bytes.Buffer)
forwarder, err := portforward.New(dialer, []string{fmt.Sprintf("%d:%d", localPort, remotePort)}, stopChan, readyChan, out, errOut)
if err != nil {
return nil, err
}
go func() {
for range readyChan {
}
if len(errOut.String()) != 0 {
panic(errOut.String())
} else if len(out.String()) != 0 {
// fmt.Println(out.String())
}
}()
go func() error {
if err = forwarder.ForwardPorts(); err != nil { // Locks until stopChan is closed.
panic(err)
}
return nil
}()
return stopChan, nil
}
func getFirstPod(clientset *kubernetes.Clientset, namespace string, selector string) (string, error) {
options := metav1.ListOptions{LabelSelector: selector}
podList, err := clientset.CoreV1().Pods(namespace).List(options)
if err != nil {
return "", errors.Wrap(err, "failed to list pods")
}
for _, pod := range podList.Items {
if pod.Status.Phase == corev1.PodRunning {
isNotReady := false
for _, status := range pod.Status.ContainerStatuses {
if !status.Ready {
isNotReady = true
}
}
if !isNotReady {
return pod.Name, nil
}
}
}
return "", nil
}