-
Notifications
You must be signed in to change notification settings - Fork 9
/
portforward.go
393 lines (311 loc) · 11.9 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package kubernetes
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/httpstream"
"k8s.io/client-go/rest"
"k8s.io/client-go/transport/spdy"
"namespacelabs.dev/foundation/framework/rpcerrors/multierr"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/executor"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnnet"
"namespacelabs.dev/foundation/internal/runtime"
"namespacelabs.dev/foundation/internal/runtime/kubernetes/client"
"namespacelabs.dev/foundation/internal/runtime/kubernetes/kubeobserver"
"namespacelabs.dev/foundation/schema"
)
type PodResolver interface {
Resolve(context.Context) (v1.Pod, error)
}
type StartAndBlockPortFwdArgs struct {
Namespace string
Identifier string
LocalAddrs []string
LocalPort int // 0 to be dynamically allocated.
ContainerPort int
PodResolver PodResolver
ReportPorts func(runtime.ForwardedPort)
}
const PortForwardProtocolV1Name = "portforward.k8s.io"
func (u *Cluster) RawForwardPort(ctx context.Context, desc, ns string, podLabels map[string]string, containerPort int, localAddrs []string, callback runtime.SinglePortForwardedFunc) (io.Closer, error) {
ctxWithCancel, cancel := context.WithCancel(ctx)
p := kubeobserver.NewPodObserver(ctxWithCancel, u.cli, ns, podLabels)
go func() {
if err := u.StartAndBlockPortFwd(ctxWithCancel, StartAndBlockPortFwdArgs{
Namespace: ns,
Identifier: desc,
LocalAddrs: localAddrs,
LocalPort: 0,
ContainerPort: containerPort,
PodResolver: p,
ReportPorts: callback,
}); err != nil {
fmt.Fprintf(console.Errors(ctx), "port forwarding for %s (%d) failed: %v\n", desc, containerPort, err)
}
}()
return closerCallback(cancel), nil
}
func (u *Cluster) RawDialServer(ctx context.Context, ns string, podLabels map[string]string, port *schema.Endpoint_Port) (net.Conn, error) {
pod, err := kubeobserver.ResolvePod(ctx, u.cli, ns, podLabels)
if err != nil {
return nil, err
}
fmt.Fprintf(console.Debug(ctx), "resolving port %v\n", port)
containerPort, err := resolveContainerPort(pod, port)
if err != nil {
return nil, err
}
fmt.Fprintf(console.Debug(ctx), "resolved port %v -> %d\n", port, containerPort)
config, restClient, err := client.MakeGroupVersionBasedClientAndConfig(ctx, u.RESTConfig(), v1.SchemeGroupVersion)
if err != nil {
return nil, err
}
debug := console.Debug(ctx)
streamConn, err := dialPod(ctx, restClient, config, pod.Namespace, pod.Name)
if err != nil {
fmt.Fprintf(debug, "kube/dial: %s/%s: %d: stream connect failed: %v\n", pod.Namespace, pod.Name, containerPort, err)
return nil, err
}
return createConnection(ctx, streamConn, pod, 0, containerPort)
}
func resolveContainerPort(pod v1.Pod, port *schema.Endpoint_Port) (int, error) {
if port.Name != "" && port.ContainerPort != 0 {
return 0, fnerrors.BadInputError("port name and container port may not both be set: name=%q, port=%d", port.Name, port.ContainerPort)
}
if port.ContainerPort < 0 {
return 0, fnerrors.BadInputError("invalid port number: %d", port.ContainerPort)
}
if port.ContainerPort != 0 {
return int(port.ContainerPort), nil
}
var resolved int
for _, c := range pod.Spec.Containers {
for _, p := range c.Ports {
if p.Name != port.Name {
continue
}
if resolved == 0 {
resolved = int(p.ContainerPort)
continue
}
if resolved != int(p.ContainerPort) {
return 0, fnerrors.InternalError("found conflicting specs for port %q in pod %q: %d != %d", port.Name, pod.Name, resolved, p.ContainerPort)
}
}
}
return resolved, nil
}
func (r *Cluster) StartAndBlockPortFwd(ctx context.Context, args StartAndBlockPortFwdArgs) error {
config, restClient, err := client.MakeGroupVersionBasedClientAndConfig(ctx, r.RESTConfig(), v1.SchemeGroupVersion)
if err != nil {
return err
}
debug := console.Debug(ctx)
eg := executor.New(ctx, "kubernetes.portforward")
for _, localAddr := range args.LocalAddrs {
lst, err := fnnet.ListenPort(ctx, localAddr, args.LocalPort, args.ContainerPort)
if err != nil {
return err
}
eg.Go(func(context.Context) error {
defer lst.Close()
localPort := lst.Addr().(*net.TCPAddr).Port
fmt.Fprintf(debug, "kube/portfwd: %s: %d: listening on port %d\n", args.Identifier, args.ContainerPort, localPort)
args.ReportPorts(runtime.ForwardedPort{
LocalPort: uint(localPort),
ContainerPort: uint(args.ContainerPort),
})
for {
conn, err := lst.Accept()
if err != nil {
return err
}
fmt.Fprintf(debug, "kube/portfwd: %s: %d: accepted new connection: %v\n", args.Identifier, args.ContainerPort, conn.RemoteAddr())
eg.Go(func(ctx context.Context) error {
defer conn.Close()
t := time.Now()
pod, err := args.PodResolver.Resolve(ctx)
if err != nil {
fmt.Fprintf(debug, "kube/portfwd: %s: %d: %s: resolve failed: %v\n", args.Identifier, args.ContainerPort, conn.RemoteAddr(), err)
return nil // Do not propagate error.
}
fmt.Fprintf(debug, "kube/portfwd: %s: %d: %s: resolved to %s/%s (took %v)\n", args.Identifier, args.ContainerPort, conn.RemoteAddr(), pod.Namespace, pod.Name, time.Since(t))
t = time.Now()
streamConn, err := dialPod(ctx, restClient, config, pod.Namespace, pod.Name)
if err != nil {
fmt.Fprintf(debug, "kube/portfwd: %s: %d: %s: stream connect failed: %v\n", args.Identifier, args.ContainerPort, conn.RemoteAddr(), err)
return nil // Do not propagate error.
}
fmt.Fprintf(debug, "kube/portfwd: %s: %d: %s: connected (took %v)\n", args.Identifier, args.ContainerPort, conn.RemoteAddr(), time.Since(t))
return handleConnection(ctx, streamConn, conn, 0, args.Identifier, args.ContainerPort)
})
}
})
}
return eg.Wait()
}
func dialPod(ctx context.Context, restClient rest.Interface, config *rest.Config, ns, podName string) (httpstream.Connection, error) {
reqtmpl := restClient.Post().Resource("pods").Namespace(ns).Name(podName).SubResource("portforward")
transport, upgrader, err := spdy.RoundTripperFor(config)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", reqtmpl.URL().String(), nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %v", err)
}
streamConn, _, err := spdy.Negotiate(upgrader, &http.Client{Transport: transport}, req, PortForwardProtocolV1Name)
if err != nil {
return nil, err
}
return streamConn, err
}
func createConnection(ctx context.Context, streamConn httpstream.Connection, pod v1.Pod, requestID int, containerPort int) (net.Conn, error) {
headers := http.Header{}
headers.Set(v1.StreamType, v1.StreamTypeError)
headers.Set(v1.PortHeader, fmt.Sprintf("%d", containerPort))
headers.Set(v1.PortForwardRequestIDHeader, fmt.Sprintf("%d", requestID))
makeErr := func(msg string, err error) error {
return fmt.Errorf("kube/dial: %s/%s: %d: %s: %w", pod.Namespace, pod.Name, containerPort, msg, err)
}
errorStream, err := streamConn.CreateStream(headers)
if err != nil {
return nil, makeErr("failed to create error stream", err)
}
// create data stream
headers.Set(v1.StreamType, v1.StreamTypeData)
dataStream, err := streamConn.CreateStream(headers)
if err != nil {
return nil, makeErr("failed to create data stream", err)
}
// The assumption is that if an error is received, the dataStream will also fail.
go func() {
defer errorStream.Close()
defer streamConn.Close()
message, err := io.ReadAll(errorStream)
switch {
case err != nil:
fmt.Fprintf(console.Errors(ctx), "%v\n", makeErr("error reading from error stream", err))
case len(message) > 0:
fmt.Fprintf(console.Errors(ctx), "%v\n", makeErr("error ocurred during forwarding", fnerrors.New(string(message))))
}
}()
return &podConn{Stream: dataStream, parent: streamConn, ns: pod.Namespace, name: pod.Namespace, containerPort: containerPort}, nil
}
type podConn struct {
httpstream.Stream
parent httpstream.Connection
ns, name string
containerPort int
}
var _ net.Conn = &podConn{}
func (pc *podConn) Close() error {
var errs []error
if err := pc.Stream.Close(); err != nil {
errs = append(errs, err)
}
if err := pc.parent.Close(); err != nil {
errs = append(errs, err)
}
return multierr.New(errs...)
}
func (pc *podConn) LocalAddr() net.Addr {
return podAddr{"local"}
}
func (pc *podConn) RemoteAddr() net.Addr {
return podAddr{fmt.Sprintf("%s/%s:%d", pc.ns, pc.name, pc.containerPort)}
}
func (pc *podConn) SetDeadline(t time.Time) error {
if t.IsZero() {
return nil
}
return fnerrors.InternalError("SetDeadline: not implemented")
}
func (pc *podConn) SetReadDeadline(t time.Time) error {
if t.IsZero() {
return nil
}
return fnerrors.InternalError("SetReadDeadline: not implemented")
}
func (pc *podConn) SetWriteDeadline(t time.Time) error {
if t.IsZero() {
return nil
}
return fnerrors.InternalError("SetWriteDeadline: not implemented")
}
type podAddr struct{ desc string }
func (p podAddr) Network() string { return "kubernetes-pod" }
func (p podAddr) String() string { return p.desc }
func handleConnection(ctx context.Context, streamConn httpstream.Connection, conn net.Conn, requestID int, debugid string, containerPort int) error {
defer conn.Close()
localAddr := conn.(*net.TCPConn).LocalAddr().(*net.TCPAddr)
remoteAddr := conn.(*net.TCPConn).RemoteAddr().(*net.TCPAddr)
headers := http.Header{}
headers.Set(v1.StreamType, v1.StreamTypeError)
headers.Set(v1.PortHeader, fmt.Sprintf("%d", containerPort))
headers.Set(v1.PortForwardRequestIDHeader, fmt.Sprintf("%d", requestID))
makeErr := func(msg string, err error) error {
return fmt.Errorf("kube/portfwd: %s: %d -> %d: %s: %w", debugid, localAddr.Port, containerPort, msg, err)
}
errorStream, err := streamConn.CreateStream(headers)
if err != nil {
return makeErr("failed to create error stream", err)
}
// we're not writing to this stream
errorStream.Close()
errorChan := make(chan error)
go func() {
defer close(errorChan)
message, err := io.ReadAll(errorStream)
switch {
case err != nil:
errorChan <- makeErr("error reading from error stream", err)
case len(message) > 0:
errorChan <- makeErr("error ocurred during forwarding", fnerrors.New(string(message)))
}
}()
// create data stream
headers.Set(v1.StreamType, v1.StreamTypeData)
dataStream, err := streamConn.CreateStream(headers)
if err != nil {
return makeErr("failed to create data stream", err)
}
localError := make(chan struct{})
remoteDone := make(chan struct{})
go func() {
// inform the select below that the remote copy is done
defer close(remoteDone)
// Copy from the remote side to the local port.
if _, err := io.Copy(conn, dataStream); err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
fmt.Fprintf(console.Warnings(ctx), "%v\n", makeErr("error copying from remote stream to local connection", err))
}
}()
go func() {
// inform server we're not sending any more data after copy unblocks
defer dataStream.Close()
// Copy from the local port to the remote side.
if _, err := io.Copy(dataStream, conn); err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
fmt.Fprintf(console.Warnings(ctx), "%v\n", makeErr("error copying from remote stream to local connection", err))
// break out of the select below without waiting for the other copy to finish
close(localError)
}
}()
// wait for either a local->remote error or for copying from remote->local to finish
select {
case <-remoteDone:
case <-localError:
}
fmt.Fprintf(console.Debug(ctx), "kube/portfwd: %s: %d -> %d: remote addr: %v: closed connection: %v\n", debugid, localAddr.Port, containerPort, remoteAddr, err)
// always expect something on errorChan (it may be nil)
return <-errorChan
}