-
Notifications
You must be signed in to change notification settings - Fork 398
/
remote.go
148 lines (125 loc) · 4.49 KB
/
remote.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
/*
Copyright 2020 The OpenYurt Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package remote
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"github.com/openyurtio/openyurt/pkg/yurthub/cachemanager"
"github.com/openyurtio/openyurt/pkg/yurthub/healthchecker"
"github.com/openyurtio/openyurt/pkg/yurthub/transport"
"github.com/openyurtio/openyurt/pkg/yurthub/util"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/klog"
)
// RemoteProxy is an reverse proxy for remote server
type RemoteProxy struct {
checker healthchecker.HealthChecker
reverseProxy *httputil.ReverseProxy
cacheMgr cachemanager.CacheManager
remoteServer *url.URL
stopCh <-chan struct{}
}
// NewRemoteProxy creates an *RemoteProxy object, and will be used by LoadBalancer
func NewRemoteProxy(remoteServer *url.URL,
cacheMgr cachemanager.CacheManager,
transportMgr transport.Interface,
healthChecker healthchecker.HealthChecker,
stopCh <-chan struct{}) (*RemoteProxy, error) {
currentTransport := transportMgr.CurrentTransport()
if currentTransport == nil {
return nil, fmt.Errorf("could not get current transport when init proxy backend(%s)", remoteServer.String())
}
proxyBackend := &RemoteProxy{
checker: healthChecker,
reverseProxy: httputil.NewSingleHostReverseProxy(remoteServer),
cacheMgr: cacheMgr,
remoteServer: remoteServer,
stopCh: stopCh,
}
proxyBackend.reverseProxy.Transport = currentTransport
proxyBackend.reverseProxy.ModifyResponse = proxyBackend.modifyResponse
proxyBackend.reverseProxy.FlushInterval = -1
proxyBackend.reverseProxy.ErrorHandler = proxyBackend.errorHandler
return proxyBackend, nil
}
// Name represents the address of remote server
func (rp *RemoteProxy) Name() string {
return rp.remoteServer.String()
}
func (rp *RemoteProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rp.reverseProxy.ServeHTTP(rw, req)
}
// IsHealthy returns healthy status of remote server
func (rp *RemoteProxy) IsHealthy() bool {
return rp.checker.IsHealthy(rp.remoteServer)
}
func (rp *RemoteProxy) modifyResponse(resp *http.Response) error {
if resp == nil || resp.Request == nil {
klog.Infof("no request info in response, skip cache response")
return nil
}
req := resp.Request
ctx := req.Context()
// re-added transfer-encoding=chunked response header for watch request
if info, exists := apirequest.RequestInfoFrom(ctx); exists {
if info.Verb == "watch" {
klog.V(5).Infof("add transfer-encoding=chunked header into response for req %s", util.ReqString(req))
h := resp.Header
if hv := h.Get("Transfer-Encoding"); hv == "" {
h.Add("Transfer-Encoding", "chunked")
}
}
}
// cache resp with storage interface
if resp.StatusCode >= http.StatusOK && resp.StatusCode <= http.StatusPartialContent {
if rp.cacheMgr.CanCacheFor(req) {
reqContentType, _ := util.ReqContentTypeFrom(ctx)
respContentType := resp.Header.Get("Content-Type")
if len(respContentType) == 0 {
respContentType = reqContentType
}
ctx = util.WithRespContentType(ctx, respContentType)
req = req.WithContext(ctx)
rc, prc := util.NewDualReadCloser(resp.Body, true)
go func(req *http.Request, prc io.ReadCloser, stopCh <-chan struct{}) {
err := rp.cacheMgr.CacheResponse(req, prc, stopCh)
if err != nil && err != io.EOF && err != context.Canceled {
klog.Errorf("%s response cache ended with error, %v", util.ReqString(req), err)
}
}(req, prc, rp.stopCh)
resp.Body = rc
}
}
return nil
}
func (rp *RemoteProxy) errorHandler(rw http.ResponseWriter, req *http.Request, err error) {
klog.V(2).Infof("remote proxy error handler: %s, %v", util.ReqString(req), err)
if !rp.cacheMgr.CanCacheFor(req) {
rw.WriteHeader(http.StatusBadGateway)
return
}
ctx := req.Context()
if info, ok := apirequest.RequestInfoFrom(ctx); ok {
if info.Verb == "get" || info.Verb == "list" {
if obj, err := rp.cacheMgr.QueryCache(req); err == nil {
util.WriteObject(http.StatusOK, obj, rw, req)
return
}
}
}
rw.WriteHeader(http.StatusBadGateway)
}