-
Notifications
You must be signed in to change notification settings - Fork 81
/
proxy.go
214 lines (190 loc) · 4.73 KB
/
proxy.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
package agents
import (
"bytes"
"compress/flate"
"compress/gzip"
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"kubegems.io/kubegems/pkg/log"
"kubegems.io/kubegems/pkg/utils/proxy"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)
func (c TypedClient) Proxy(ctx context.Context, obj client.Object, port int, req *http.Request, writer http.ResponseWriter, rewritefunc func(r *http.Response) error) error {
gvk, err := apiutil.GVKForObject(obj, c.scheme)
if err != nil {
return err
}
if gvk.Kind != "Service" && gvk.Kind != "Pod" {
return fmt.Errorf("unsupported proxy for %s", gvk.GroupKind().String())
}
addr := fmt.Sprintf("%s/internal/core/v1/namespaces/%s/%s/%s:%d/proxy",
c.BaseAddr.String(),
obj.GetNamespace(),
gvk.Kind,
obj.GetName(),
port,
)
target, err := url.Parse(addr)
if err != nil {
return err
}
(&httputil.ReverseProxy{
Director: func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = target.Path + req.URL.Path
req.Host = target.Host
},
Transport: c.http.Transport,
ModifyResponse: rewritefunc,
}).ServeHTTP(writer, req)
return nil
}
// ResponseBodyRewriter 会正确处理 gzip 以及 deflate 的content-encodeing 以及response 的content-length
// 用于需要修改代理的响应体是非常有用
func ResponseBodyRewriter(rewritefunc func(io.Reader, io.Writer) error) func(resp *http.Response) error {
return func(r *http.Response) error {
reader := r.Body
writer := &bytes.Buffer{}
defer func() {
r.Body.Close()
r.Body = io.NopCloser(writer)
r.ContentLength = int64(writer.Len())
r.Header.Set("Content-Length", strconv.Itoa(writer.Len()))
}()
switch r.Header.Get("Content-Encoding") {
case "gzip":
gzr, err := gzip.NewReader(reader)
if err != nil {
return err
}
gzw := gzip.NewWriter(writer)
defer func() {
gzw.Close()
gzw.Flush()
}()
return rewritefunc(gzr, gzw)
case "deflate":
flw, err := flate.NewWriter(writer, 0)
if err != nil {
return err
}
defer func() {
flw.Close()
flw.Flush()
}()
return rewritefunc(flate.NewReader(reader), flw)
default:
return rewritefunc(reader, writer)
}
}
}
type PortForwarder struct {
ctx context.Context
cancel context.CancelFunc
httpRequestUrl *url.URL
httpreq *http.Request
ln net.Listener
}
func newPortForwarder(ctx context.Context, target string) (*PortForwarder, error) {
u, err := url.Parse(target)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(ctx)
p := &PortForwarder{
ctx: ctx,
cancel: cancel,
httpRequestUrl: u,
httpreq: req,
}
if err := p.start(); err != nil {
return nil, err
}
return p, nil
}
func (p *PortForwarder) start() error {
// listen
ln, err := net.Listen("tcp", "localhost:0")
if err != nil {
return err
}
p.ln = ln
log.Infof("port forwarder listening on %s", ln.Addr().String())
go func() {
defer ln.Close()
for {
conn, err := ln.Accept()
select {
case <-p.ctx.Done():
return
default:
}
if err != nil {
log.Errorf("error accepting connection: %v", err)
continue
}
go p.servconn(conn)
}
}()
return nil
}
func (p *PortForwarder) servconn(conn net.Conn) {
dst, err := net.Dial("tcp", p.httpRequestUrl.Host)
if err != nil {
log.Errorf("error dial: %v", err)
return
}
// open as http
if err := p.httpreq.Write(dst); err != nil {
log.Errorf("error wrilte request: %v", err)
return
}
// using as tcp
if err := proxy.CopyDuplex(conn, dst, -1); err != nil {
log.Errorf("error copy duplex: %v", err)
}
}
func (p *PortForwarder) ListenAddr() net.Addr {
return p.ln.Addr()
}
func (p *PortForwarder) Stop() {
p.cancel()
p.ln.Close()
}
// PortForward
// Deprecated: 无法使用,因 service 与 agent 中间还有一层 http proxy(apiserver). 无法直接使用 tcp 。
func (c TypedClient) PortForward(ctx context.Context, obj client.Object, port int) (*PortForwarder, error) {
gvk, err := apiutil.GVKForObject(obj, c.scheme)
if err != nil {
return nil, err
}
if gvk.Kind != "Service" && gvk.Kind != "Pod" {
return nil, fmt.Errorf("unsupported port forwarding of %s", gvk.GroupKind().String())
}
queries := url.Values{}
queries.Set("port", strconv.Itoa(port))
addr := fmt.Sprintf("%s/internal/core/v1/namespaces/%s/%s/%s/portforward?%s",
c.BaseAddr.String(),
obj.GetNamespace(),
gvk.Kind,
obj.GetName(),
queries.Encode(),
)
forwarder, err := newPortForwarder(ctx, addr)
if err != nil {
return nil, err
}
return forwarder, nil
}