-
Notifications
You must be signed in to change notification settings - Fork 5
/
router_factory.go
324 lines (298 loc) · 9.5 KB
/
router_factory.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
package gobis
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/mitchellh/mapstructure"
log "github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"github.com/vulcand/oxy/buffer"
"github.com/vulcand/oxy/forward"
"net/http"
"net/url"
"reflect"
"runtime"
"strings"
)
const (
GobisHeaderName = "X-Gobis-Forward"
XGobisUsername = "X-Gobis-Username"
XGobisGroups = "X-Gobis-Groups"
)
type JsonError struct {
Status int `json:"status"`
Title string `json:"title"`
Details string `json:"details"`
RouteName string `json:"route_name"`
}
type RouterFactory interface {
CreateMuxRouter([]ProxyRoute, string) (*mux.Router, error)
CreateForwardHandler(ProxyRoute) (http.HandlerFunc, error)
CreateReverseHandler(ProxyRoute) (http.Handler, error)
}
type CreateTransportFunc func(ProxyRoute) http.RoundTripper
type RouterFactoryService struct {
CreateTransportFunc CreateTransportFunc
MiddlewareHandlers []MiddlewareHandler
muxRouterFunc func() *mux.Router
middlewareChain *MiddlewareChainRoutes
}
type ErrMiddleware string
func (e ErrMiddleware) Error() string {
return string(e)
}
func NewRouterFactory(middlewareHandlers ...MiddlewareHandler) RouterFactory {
return NewRouterFactoryWithMuxRouter(func() *mux.Router {
return mux.NewRouter()
}, middlewareHandlers...)
}
func NewRouterFactoryWithMuxRouter(muxRouterOption func() *mux.Router, middlewares ...MiddlewareHandler) RouterFactory {
factory := &RouterFactoryService{
CreateTransportFunc: func(proxyRoute ProxyRoute) http.RoundTripper {
return NewRouteTransport(proxyRoute)
},
MiddlewareHandlers: middlewares,
muxRouterFunc: muxRouterOption,
}
factory.middlewareChain = NewMiddlewareChainRoutes(factory)
return factory
}
func (r RouterFactoryService) CreateMuxRouter(proxyRoutes []ProxyRoute, startPath string) (*mux.Router, error) {
log.Debug("github.com/orange-cloudfoundry/proxy: Creating handlers ...")
startPath = strings.TrimSuffix(startPath, "/")
parentRtr := r.muxRouterFunc()
var rtr *mux.Router
if startPath != "" {
rtr = parentRtr.PathPrefix(startPath).Subrouter()
} else {
rtr = parentRtr
}
for _, proxyRoute := range proxyRoutes {
entry := log.WithField("route_name", proxyRoute.Name)
entry.Debug("orange-cloudfoundry/gobis/proxy: Creating handler ...")
proxyHandler, err := r.CreateForwardHandler(proxyRoute)
if err != nil {
return nil, err
}
rtr.NewRoute().
Name(proxyRoute.Name).
MatcherFunc(r.routeMatch(proxyRoute, startPath)).
Handler(proxyHandler)
entry.Debug("orange-cloudfoundry/gobis/proxy: Finished handler .")
}
log.Debug("orange-cloudfoundry/gobis/proxy: Finished creating handlers ...")
return parentRtr, nil
}
func (r RouterFactoryService) CreateReverseHandler(proxyRoute ProxyRoute) (http.Handler, error) {
entry := log.WithField("route_name", proxyRoute.Name)
if proxyRoute.ForwardHandler != nil {
entry.Debug("orange-cloudfoundry/gobis/proxy: Handler for routes will use forward handler provided.")
return proxyRoute.ForwardHandler, nil
}
var err error
var fwd *forward.Forwarder
if !proxyRoute.NoBuffer {
entry.Debug("orange-cloudfoundry/gobis/proxy: Handler for routes will use buffer.")
fwd, err = forward.New(forward.RoundTripper(r.CreateTransportFunc(proxyRoute)))
} else {
entry.Debug("orange-cloudfoundry/gobis/proxy: Handler for routes will use direct stream.")
fwd, err = forward.New(forward.RoundTripper(r.CreateTransportFunc(proxyRoute)), forward.Stream(true))
}
if err != nil {
return nil, err
}
if proxyRoute.NoBuffer {
return fwd, nil
}
return buffer.New(fwd, buffer.Retry(`IsNetworkError() && Attempts() < 2`))
}
func (r RouterFactoryService) routeMatch(proxyRoute ProxyRoute, startPath string) mux.MatcherFunc {
return func(req *http.Request, rm *mux.RouteMatch) bool {
if len(proxyRoute.Methods) > 0 && !funk.ContainsString(proxyRoute.Methods, req.Method) {
return false
}
path := proxyRoute.RequestPath(req)
if startPath != "" {
path = strings.TrimPrefix(path, startPath)
}
matcher := proxyRoute.RouteMatcher()
if !matcher.MatchString(path) {
return false
}
sub := matcher.FindStringSubmatch(path)
finalPath := ""
if len(sub) >= 2 {
finalPath = sub[1]
}
SetPath(req, finalPath)
upstreamUrl := proxyRoute.UpstreamUrl(req)
if proxyRoute.ForwardedHeader != "" {
req.URL.RawQuery = upstreamUrl.RawQuery
}
if proxyRoute.Url == "" || proxyRoute.ForwardedHeader == "" {
return true
}
origUpstreamUrl, _ := url.Parse(proxyRoute.Url)
if origUpstreamUrl.Host != upstreamUrl.Host {
return false
}
if origUpstreamUrl.Path == "" || origUpstreamUrl.Path == "/" {
return true
}
origPathMatcher := NewPathMatcher(origUpstreamUrl.Path).pathMatcher
return origPathMatcher.MatchString(path)
}
}
func (r RouterFactoryService) CreateForwardHandler(proxyRoute ProxyRoute) (http.HandlerFunc, error) {
httpHandler, err := r.CreateReverseHandler(proxyRoute)
if err != nil {
return nil, err
}
forwardHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Del(GobisHeaderName)
restPath := Path(req)
ForwardRequest(proxyRoute, req, restPath)
httpHandler.ServeHTTP(w, req)
})
var handler http.Handler
handler = forwardHandler
for i := len(r.MiddlewareHandlers) - 1; i >= 0; i-- {
middleware := r.MiddlewareHandlers[i]
params := paramsToSchema(proxyRoute.MiddlewareParams, middleware.Schema())
handler, err = middlewareHandlerToHandler(middleware, proxyRoute, params, handler)
if err != nil {
return nil, err
}
}
if len(proxyRoute.Routes) > 0 {
handler, err = middlewareHandlerToHandler(r.middlewareChain, proxyRoute, proxyRoute.Routes, handler)
if err != nil {
return nil, err
}
}
return func(w http.ResponseWriter, req *http.Request) {
req.Header.Set(GobisHeaderName, "true")
w.Header().Set(GobisHeaderName, "true")
if proxyRoute.OptionsPassthrough &&
req.Method == "OPTIONS" &&
(req.Header.Get("Access-Control-Request-Method") != "" || req.Header.Get("Access-Control-Request-Headers") != "") {
forwardHandler.ServeHTTP(w, req)
return
}
if proxyRoute.HostsPassthrough.Match(req.URL.Host) {
forwardHandler.ServeHTTP(w, req)
return
}
setRouteName(req, proxyRoute.Name)
defer panicRecover(proxyRoute, w)
handler.ServeHTTP(w, req)
}, nil
}
func middlewareHandlerToHandler(middleware MiddlewareHandler, proxyRoute ProxyRoute, params interface{}, next http.Handler) (http.Handler, error) {
entry := log.WithField("route_name", proxyRoute.Name)
funcName := GetMiddlewareName(middleware)
entry.Debugf("orange-cloudfoundry/gobis/proxy: Adding %s middleware ...", funcName)
handler, err := middleware.Handler(proxyRoute, params, next)
if err != nil {
return nil, ErrMiddleware(fmt.Sprintf("Failed to add middleware %s: %s", funcName, err.Error()))
}
entry.Debugf("orange-cloudfoundry/gobis/proxy: Finished adding %s middleware.", funcName)
return handler, nil
}
func paramsToSchema(params interface{}, schema interface{}) interface{} {
if params != nil && reflect.TypeOf(params).Kind() != reflect.Map {
params = InterfaceToMap(params)
}
val := reflect.New(reflect.TypeOf(schema))
err := mapstructure.Decode(params, val.Interface())
if err != nil {
panic(err)
}
return val.Elem().Interface()
}
func ForwardRequest(proxyRoute ProxyRoute, req *http.Request, restPath string) {
removeDirtyHeaders(req)
req.Header.Add(XGobisUsername, Username(req))
req.Header.Add(XGobisGroups, strings.Join(Groups(req), ","))
fwdUrl := proxyRoute.UpstreamUrl(req)
req.URL.Host = fwdUrl.Host
req.URL.Scheme = fwdUrl.Scheme
finalPath := fwdUrl.Path + restPath
finalPath = strings.TrimSuffix(finalPath, "/")
req.URL.Path = finalPath
reqValues := req.URL.Query()
for key, values := range fwdUrl.Query() {
for _, value := range values {
reqValues.Add(key, value)
}
}
req.URL.RawQuery = reqValues.Encode()
if fwdUrl.User != nil && fwdUrl.User.Username() != "" {
password, _ := fwdUrl.User.Password()
req.SetBasicAuth(fwdUrl.User.Username(), password)
}
req.RequestURI = req.URL.RequestURI()
}
func removeDirtyHeaders(req *http.Request) {
dirtyHeadersPtr := DirtyHeaders(req)
if dirtyHeadersPtr == nil {
return
}
dirtyHeaders := *dirtyHeadersPtr
for header, oldValue := range dirtyHeaders {
if oldValue == "" {
req.Header.Del(header)
continue
}
req.Header.Set(header, oldValue)
}
}
func panicRecover(proxyRoute ProxyRoute, w http.ResponseWriter) {
err := recover()
if err == nil {
return
}
w.WriteHeader(http.StatusInternalServerError)
if proxyRoute.ShowError {
w.Header().Set("Content-Type", "application/json")
errMsg := JsonError{
Status: http.StatusInternalServerError,
Title: http.StatusText(http.StatusInternalServerError),
Details: fmt.Sprint(err),
RouteName: proxyRoute.Name,
}
b, _ := json.MarshalIndent(errMsg, "", "\t")
if _, err := w.Write(b); err != nil {
log.Errorf("write failed: %s", err.Error())
}
}
entry := log.WithField("route_name", proxyRoute.Name)
identName, identFile := identifyPanic()
if identName != "" {
entry.WithField("func", identName)
}
entry.WithField("file", identFile)
entry.Error(err)
}
func identifyPanic() (string, string) {
var name, file string
var line int
var pc [16]uintptr
n := runtime.Callers(3, pc[:])
for _, pc := range pc[:n] {
fn := runtime.FuncForPC(pc)
if fn == nil {
continue
}
file, line = fn.FileLine(pc)
name = fn.Name()
if !strings.HasPrefix(name, "runtime.") {
break
}
}
filefinal := fmt.Sprintf("%s:%d", file, line)
if file == "" && name == "" {
return "", fmt.Sprintf("pc:%x", pc)
}
return name, filefinal
}