k8s源码设计模式之Proxy

Proxy也就是代理模式

代理模式是一种结构型设计模式, 让你能够提供对象的替代品或其占位符。 代理控制着对于原对象的访问, 并允许在将请求提交给对象前后进行一些处理。

upgradeawarehandler.go文件中还定义了一个UpgradeAwareHandler结构体,它可以将HTTP请求转换为WebSocket请求,并将转换后的WebSocket请求传递给目标组件,以支持使用WebSocket协议与目标组件进行通信。

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
// vendor/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go
// UpgradeAwareHandler实现了ServeHTTP方法
type UpgradeAwareHandler struct {
// UpgradeRequired will reject non-upgrade connections if true.
UpgradeRequired bool
// Location is the location of the upstream proxy. It is used as the location to Dial on the upstream server
// for upgrade requests unless UseRequestLocationOnUpgrade is true.
Location *url.URL
// AppendLocationPath determines if the original path of the Location should be appended to the upstream proxy request path
AppendLocationPath bool
// Transport provides an optional round tripper to use to proxy. If nil, the default proxy transport is used
Transport http.RoundTripper
// UpgradeTransport, if specified, will be used as the backend transport when upgrade requests are provided.
// This allows clients to disable HTTP/2.
UpgradeTransport UpgradeRequestRoundTripper
// WrapTransport indicates whether the provided Transport should be wrapped with default proxy transport behavior (URL rewriting, X-Forwarded-* header setting)
WrapTransport bool
// UseRequestLocation will use the incoming request URL when talking to the backend server.
UseRequestLocation bool
// UseLocationHost overrides the HTTP host header in requests to the backend server to use the Host from Location.
// This will override the req.Host field of a request, while UseRequestLocation will override the req.URL field
// of a request. The req.URL.Host specifies the server to connect to, while the req.Host field
// specifies the Host header value to send in the HTTP request. If this is false, the incoming req.Host header will
// just be forwarded to the backend server.
UseLocationHost bool
// FlushInterval controls how often the standard HTTP proxy will flush content from the upstream.
FlushInterval time.Duration
// MaxBytesPerSec controls the maximum rate for an upstream connection. No rate is imposed if the value is zero.
MaxBytesPerSec int64
// Responder is passed errors that occur while setting up proxying.
Responder ErrorResponder
// Reject to forward redirect response
RejectForwardingRedirects bool
}

// proxyStream proxies stream to url.
// pkg/kubelet/server/server.go
func proxyStream(w http.ResponseWriter, r *http.Request, url *url.URL) {
// TODO(random-liu): Set MaxBytesPerSec to throttle the stream.
handler := proxy.NewUpgradeAwareHandler(url, nil /*transport*/, false /*wrapTransport*/, true /*upgradeRequired*/, &responder{})
handler.ServeHTTP(w, r)
}

REF:
1.staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go
2.pkg/kubelet/server/server.go