/
inbound.go
264 lines (233 loc) · 7.99 KB
/
inbound.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
// Copyright (c) 2021 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package http
import (
"context"
"net"
"net/http"
"strings"
"time"
"github.com/opentracing/opentracing-go"
"go.uber.org/yarpc/api/transport"
"go.uber.org/yarpc/api/x/introspection"
intnet "go.uber.org/yarpc/internal/net"
"go.uber.org/yarpc/pkg/lifecycle"
"go.uber.org/yarpc/yarpcerrors"
"go.uber.org/zap"
)
// We want a value that's around 5 seconds, but slightly higher than how
// long a successful HTTP shutdown can take.
// There's a specific path in the HTTP shutdown path that can take 5 seconds:
// https://golang.org/src/net/http/server.go?s=83923:83977#L2710
// This avoids timeouts in shutdown caused by new idle connections, without
// making the timeout too large.
const defaultShutdownTimeout = 6 * time.Second
// InboundOption customizes the behavior of an HTTP Inbound constructed with
// NewInbound.
type InboundOption func(*Inbound)
func (InboundOption) httpOption() {}
// Mux specifies that the HTTP server should make the YARPC endpoint available
// under the given pattern on the given ServeMux. By default, the YARPC
// service is made available on all paths of the HTTP server. By specifying a
// ServeMux, users can narrow the endpoints under which the YARPC service is
// available and offer their own non-YARPC endpoints.
func Mux(pattern string, mux *http.ServeMux) InboundOption {
return func(i *Inbound) {
i.mux = mux
i.muxPattern = pattern
}
}
// Interceptor specifies a function which can wrap the YARPC handler. If
// provided, this function will be called with an http.Handler which will
// route requests through YARPC. The http.Handler returned by this function
// may delegate requests to the provided YARPC handler to route them through
// YARPC.
func Interceptor(interceptor func(yarpcHandler http.Handler) http.Handler) InboundOption {
return func(i *Inbound) {
i.interceptor = interceptor
}
}
// GrabHeaders specifies additional headers that are not prefixed with
// ApplicationHeaderPrefix that should be propagated to the caller.
//
// All headers given must begin with x- or X- or the Inbound that the
// returned option is passed to will return an error when Start is called.
//
// Headers specified with GrabHeaders are case-insensitive.
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
func GrabHeaders(headers ...string) InboundOption {
return func(i *Inbound) {
for _, header := range headers {
i.grabHeaders[strings.ToLower(header)] = struct{}{}
}
}
}
// ShutdownTimeout specifies the maximum duration the inbound should wait for
// closing idle connections, and pending calls to complete.
//
// Set to 0 to wait for a complete drain.
//
// Defaults to 5 seconds.
func ShutdownTimeout(timeout time.Duration) InboundOption {
return func(i *Inbound) {
i.shutdownTimeout = timeout
}
}
// NewInbound builds a new HTTP inbound that listens on the given address and
// sharing this transport.
func (t *Transport) NewInbound(addr string, opts ...InboundOption) *Inbound {
i := &Inbound{
once: lifecycle.NewOnce(),
addr: addr,
shutdownTimeout: defaultShutdownTimeout,
tracer: t.tracer,
logger: t.logger,
transport: t,
grabHeaders: make(map[string]struct{}),
bothResponseError: true,
}
for _, opt := range opts {
opt(i)
}
return i
}
// Inbound receives YARPC requests using an HTTP server. It may be constructed
// using the NewInbound method on the Transport.
type Inbound struct {
addr string
mux *http.ServeMux
muxPattern string
server *intnet.HTTPServer
shutdownTimeout time.Duration
router transport.Router
tracer opentracing.Tracer
logger *zap.Logger
transport *Transport
grabHeaders map[string]struct{}
interceptor func(http.Handler) http.Handler
once *lifecycle.Once
// should only be false in testing
bothResponseError bool
}
// Tracer configures a tracer on this inbound.
func (i *Inbound) Tracer(tracer opentracing.Tracer) *Inbound {
i.tracer = tracer
return i
}
// SetRouter configures a router to handle incoming requests.
// This satisfies the transport.Inbound interface, and would be called
// by a dispatcher when it starts.
func (i *Inbound) SetRouter(router transport.Router) {
i.router = router
}
// Transports returns the inbound's HTTP transport.
func (i *Inbound) Transports() []transport.Transport {
return []transport.Transport{i.transport}
}
// Start starts the inbound with a given service detail, opening a listening
// socket.
func (i *Inbound) Start() error {
return i.once.Start(i.start)
}
func (i *Inbound) start() error {
if i.router == nil {
return yarpcerrors.Newf(yarpcerrors.CodeInternal, "no router configured for transport inbound")
}
for header := range i.grabHeaders {
if !strings.HasPrefix(header, "x-") {
return yarpcerrors.Newf(yarpcerrors.CodeInvalidArgument, "header %s does not begin with 'x-'", header)
}
}
var httpHandler http.Handler = handler{
router: i.router,
tracer: i.tracer,
grabHeaders: i.grabHeaders,
bothResponseError: i.bothResponseError,
logger: i.logger,
}
if i.interceptor != nil {
httpHandler = i.interceptor(httpHandler)
}
if i.mux != nil {
i.mux.Handle(i.muxPattern, httpHandler)
httpHandler = i.mux
}
i.server = intnet.NewHTTPServer(&http.Server{
Addr: i.addr,
Handler: httpHandler,
})
if err := i.server.ListenAndServe(); err != nil {
return err
}
i.addr = i.server.Listener().Addr().String() // in case it changed
i.logger.Info("started HTTP inbound", zap.String("address", i.addr))
if len(i.router.Procedures()) == 0 {
i.logger.Warn("no procedures specified for HTTP inbound")
}
return nil
}
// Stop the inbound using Shutdown.
func (i *Inbound) Stop() error {
ctx, cancel := context.WithTimeout(context.Background(), i.shutdownTimeout)
defer cancel()
return i.shutdown(ctx)
}
// shutdown the inbound, closing the listening socket, closing idle
// connections, and waiting for all pending calls to complete.
func (i *Inbound) shutdown(ctx context.Context) error {
return i.once.Stop(func() error {
if i.server == nil {
return nil
}
return i.server.Shutdown(ctx)
})
}
// IsRunning returns whether the inbound is currently running
func (i *Inbound) IsRunning() bool {
return i.once.IsRunning()
}
// Addr returns the address on which the server is listening. Returns nil if
// Start has not been called yet.
func (i *Inbound) Addr() net.Addr {
if i.server == nil {
return nil
}
listener := i.server.Listener()
if listener == nil {
return nil
}
return listener.Addr()
}
// Introspect returns the state of the inbound for introspection purposes.
func (i *Inbound) Introspect() introspection.InboundStatus {
state := "Stopped"
if i.IsRunning() {
state = "Started"
}
var addrString string
if addr := i.Addr(); addr != nil {
addrString = addr.String()
}
return introspection.InboundStatus{
Transport: "http",
Endpoint: addrString,
State: state,
}
}