-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathlookup.go
221 lines (184 loc) · 6.12 KB
/
lookup.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
package handlers
import (
"fmt"
"log/slog"
"net/http"
"regexp"
"strings"
"github.com/urfave/negroni/v3"
router_http "code.cloudfoundry.org/gorouter/common/http"
"code.cloudfoundry.org/gorouter/errorwriter"
log "code.cloudfoundry.org/gorouter/logger"
"code.cloudfoundry.org/gorouter/metrics"
"code.cloudfoundry.org/gorouter/registry"
"code.cloudfoundry.org/gorouter/route"
)
const CfAppInstance = "X-CF-APP-INSTANCE"
type InvalidInstanceHeaderError struct {
headerValue string
}
func (err InvalidInstanceHeaderError) Error() string {
return fmt.Sprintf("invalid-app-instance-header: %s", err.headerValue)
}
type lookupHandler struct {
registry registry.Registry
reporter metrics.ProxyReporter
logger *slog.Logger
errorWriter errorwriter.ErrorWriter
EmptyPoolResponseCode503 bool
}
// NewLookup creates a handler responsible for looking up a route.
func NewLookup(
registry registry.Registry,
rep metrics.ProxyReporter,
logger *slog.Logger,
ew errorwriter.ErrorWriter,
emptyPoolResponseCode503 bool,
) negroni.Handler {
return &lookupHandler{
registry: registry,
reporter: rep,
logger: logger,
errorWriter: ew,
EmptyPoolResponseCode503: emptyPoolResponseCode503,
}
}
func (l *lookupHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
logger := LoggerWithTraceInfo(l.logger, r)
// gorouter requires the Host header to know to which backend to proxy to.
//
// The Host header is optional in HTTP/1.0,
// so we must explicitly check that the Host is set.
//
// Also, when some load balancers which are used to load balance gorouters
// (e.g. AWS Classic ELB)
// receive HTTP/1.0 requests without a host headers,
// they optimistically add their IP address to the host header.
//
// Therefore to not expose the internal IP address of the load balancer,
// we must check that the Host is not also the source of the request.
//
// It is not vali for the Host header to be an IP address,
// because Gorouter should not have an IP address as a route.
if r.Host == "" || hostWithoutPort(r.Host) == hostWithoutPort(r.RemoteAddr) {
l.handleMissingHost(rw, r, logger)
return
}
pool, err := l.lookup(r, logger)
if _, ok := err.(InvalidInstanceHeaderError); ok {
l.handleInvalidInstanceHeader(rw, r, logger)
return
}
if pool == nil {
l.handleMissingRoute(rw, r, logger)
return
}
if pool.IsEmpty() {
if l.EmptyPoolResponseCode503 {
l.handleUnavailableRoute(rw, r, logger)
return
} else {
l.handleMissingRoute(rw, r, logger)
return
}
}
if pool.IsOverloaded() {
l.handleOverloadedRoute(rw, r, logger)
return
}
requestInfo, err := ContextRequestInfo(r)
if err != nil {
log.Panic(logger, "request-info-err", log.ErrAttr(err))
return
}
requestInfo.RoutePool = pool
next(rw, r)
}
func (l *lookupHandler) handleInvalidInstanceHeader(rw http.ResponseWriter, r *http.Request, logger *slog.Logger) {
l.reporter.CaptureBadRequest()
AddRouterErrorHeader(rw, "invalid_cf_app_instance_header")
addNoCacheControlHeader(rw)
l.errorWriter.WriteError(
rw,
http.StatusBadRequest,
"Invalid X-CF-App-Instance Header",
logger,
)
}
func (l *lookupHandler) handleMissingHost(rw http.ResponseWriter, r *http.Request, logger *slog.Logger) {
l.reporter.CaptureBadRequest()
AddRouterErrorHeader(rw, "empty_host")
addInvalidResponseCacheControlHeader(rw)
l.errorWriter.WriteError(
rw,
http.StatusBadRequest,
"Request had empty Host header",
logger,
)
}
func (l *lookupHandler) handleMissingRoute(rw http.ResponseWriter, r *http.Request, logger *slog.Logger) {
l.reporter.CaptureBadRequest()
AddRouterErrorHeader(rw, "unknown_route")
addNoCacheControlHeader(rw)
errorMsg := fmt.Sprintf("Requested route ('%s') does not exist.", r.Host)
returnStatus := http.StatusNotFound
if appInstanceHeader := r.Header.Get(router_http.CfAppInstance); appInstanceHeader != "" {
guid, idx := splitInstanceHeader(appInstanceHeader)
errorMsg = fmt.Sprintf("Requested instance ('%s') with guid ('%s') does not exist for route ('%s')", idx, guid, r.Host)
returnStatus = http.StatusBadRequest
}
l.errorWriter.WriteError(
rw,
returnStatus,
errorMsg,
logger,
)
}
func (l *lookupHandler) handleUnavailableRoute(rw http.ResponseWriter, r *http.Request, logger *slog.Logger) {
AddRouterErrorHeader(rw, "no_endpoints")
addInvalidResponseCacheControlHeader(rw)
l.errorWriter.WriteError(
rw,
http.StatusServiceUnavailable,
fmt.Sprintf("Requested route ('%s') has no available endpoints.", r.Host),
logger,
)
}
func (l *lookupHandler) handleOverloadedRoute(rw http.ResponseWriter, r *http.Request, logger *slog.Logger) {
l.reporter.CaptureBackendExhaustedConns()
l.logger.Info("connection-limit-reached")
AddRouterErrorHeader(rw, "Connection Limit Reached")
l.errorWriter.WriteError(
rw,
http.StatusServiceUnavailable,
fmt.Sprintf("Requested route ('%s') has reached the connection limit.", r.Host),
logger,
)
}
func (l *lookupHandler) lookup(r *http.Request, logger *slog.Logger) (*route.EndpointPool, error) {
requestPath := r.URL.EscapedPath()
uri := route.Uri(hostWithoutPort(r.Host) + requestPath)
appInstanceHeader := r.Header.Get(router_http.CfAppInstance)
if appInstanceHeader != "" {
err := validateInstanceHeader(appInstanceHeader)
if err != nil {
logger.Error("invalid-app-instance-header", log.ErrAttr(err))
return nil, InvalidInstanceHeaderError{headerValue: appInstanceHeader}
}
appID, appIndex := splitInstanceHeader(appInstanceHeader)
return l.registry.LookupWithInstance(uri, appID, appIndex), nil
}
return l.registry.Lookup(uri), nil
}
func validateInstanceHeader(appInstanceHeader string) error {
// Regex to match format of `APP_GUID:INSTANCE_ID`
r := regexp.MustCompile(`^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}:\d+$`)
if !r.MatchString(appInstanceHeader) {
return fmt.Errorf("Incorrect %s header : %s", CfAppInstance, appInstanceHeader)
}
return nil
}
func splitInstanceHeader(appInstanceHeader string) (string, string) {
appDetails := strings.Split(appInstanceHeader, ":")
return appDetails[0], appDetails[1]
}