-
Notifications
You must be signed in to change notification settings - Fork 672
/
server.go
395 lines (344 loc) · 10.9 KB
/
server.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package server
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"path"
"sync"
"time"
"github.com/NYTimes/gziphandler"
"github.com/rs/cors"
"go.uber.org/zap"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/ips"
"github.com/ava-labs/avalanchego/utils/logging"
)
const (
baseURL = "/ext"
readHeaderTimeout = 10 * time.Second
)
var (
errUnknownLockOption = errors.New("invalid lock options")
_ PathAdder = readPathAdder{}
_ Server = &server{}
)
type PathAdder interface {
// AddRoute registers a route to a handler.
AddRoute(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error
// AddAliases registers aliases to the server
AddAliases(endpoint string, aliases ...string) error
}
type PathAdderWithReadLock interface {
// AddRouteWithReadLock registers a route to a handler assuming the http
// read lock is currently held.
AddRouteWithReadLock(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error
// AddAliasesWithReadLock registers aliases to the server assuming the http read
// lock is currently held.
AddAliasesWithReadLock(endpoint string, aliases ...string) error
}
// Server maintains the HTTP router
type Server interface {
PathAdder
PathAdderWithReadLock
// Initialize creates the API server at the provided host and port
Initialize(log logging.Logger,
factory logging.Factory,
host string,
port uint16,
allowedOrigins []string,
shutdownTimeout time.Duration,
nodeID ids.NodeID,
wrappers ...Wrapper)
// Dispatch starts the API server
Dispatch() error
// DispatchTLS starts the API server with the provided TLS certificate
DispatchTLS(certBytes, keyBytes []byte) error
// RegisterChain registers the API endpoints associated with this chain. That is,
// add <route, handler> pairs to server so that API calls can be made to the VM.
// This method runs in a goroutine to avoid a deadlock in the event that the caller
// holds the engine's context lock. Namely, this could happen when the P-Chain is
// creating a new chain and holds the P-Chain's lock when this function is held,
// and at the same time the server's lock is held due to an API call and is trying
// to grab the P-Chain's lock.
RegisterChain(chainName string, engine common.Engine)
// AddChainRoute registers a route to a chain's handler
AddChainRoute(
handler *common.HTTPHandler,
ctx *snow.ConsensusContext,
base, endpoint string,
) error
// Shutdown this server
Shutdown() error
}
type server struct {
// log this server writes to
log logging.Logger
// generates new logs for chains to write to
factory logging.Factory
// points the the router handlers
handler http.Handler
// Listens for HTTP traffic on this address
listenHost string
listenPort uint16
shutdownTimeout time.Duration
// Maps endpoints to handlers
router *router
srv *http.Server
}
// New returns an instance of a Server.
func New() Server {
return &server{}
}
func (s *server) Initialize(
log logging.Logger,
factory logging.Factory,
host string,
port uint16,
allowedOrigins []string,
shutdownTimeout time.Duration,
nodeID ids.NodeID,
wrappers ...Wrapper,
) {
s.log = log
s.factory = factory
s.listenHost = host
s.listenPort = port
s.shutdownTimeout = shutdownTimeout
s.router = newRouter()
s.log.Info("API created",
zap.Strings("allowedOrigins", allowedOrigins),
)
corsHandler := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowCredentials: true,
}).Handler(s.router)
gzipHandler := gziphandler.GzipHandler(corsHandler)
s.handler = http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// Attach this node's ID as a header
w.Header().Set("node-id", nodeID.String())
gzipHandler.ServeHTTP(w, r)
},
)
for _, wrapper := range wrappers {
s.handler = wrapper.WrapHandler(s.handler)
}
}
func (s *server) Dispatch() error {
listenAddress := fmt.Sprintf("%s:%d", s.listenHost, s.listenPort)
listener, err := net.Listen("tcp", listenAddress)
if err != nil {
return err
}
ipPort, err := ips.ToIPPort(listener.Addr().String())
if err != nil {
s.log.Info("HTTP API server listening",
zap.String("address", listenAddress),
)
} else {
s.log.Info("HTTP API server listening",
zap.String("host", s.listenHost),
zap.Uint16("port", ipPort.Port),
)
}
s.srv = &http.Server{
Handler: s.handler,
ReadHeaderTimeout: readHeaderTimeout,
}
return s.srv.Serve(listener)
}
func (s *server) DispatchTLS(certBytes, keyBytes []byte) error {
listenAddress := fmt.Sprintf("%s:%d", s.listenHost, s.listenPort)
cert, err := tls.X509KeyPair(certBytes, keyBytes)
if err != nil {
return err
}
config := &tls.Config{
MinVersion: tls.VersionTLS12,
Certificates: []tls.Certificate{cert},
}
listener, err := tls.Listen("tcp", listenAddress, config)
if err != nil {
return err
}
ipPort, err := ips.ToIPPort(listener.Addr().String())
if err != nil {
s.log.Info("HTTPS API server listening",
zap.String("address", listenAddress),
)
} else {
s.log.Info("HTTPS API server listening",
zap.String("host", s.listenHost),
zap.Uint16("port", ipPort.Port),
)
}
s.srv = &http.Server{
Addr: listenAddress,
Handler: s.handler,
ReadHeaderTimeout: readHeaderTimeout,
}
return s.srv.Serve(listener)
}
func (s *server) RegisterChain(chainName string, engine common.Engine) {
go s.registerChain(chainName, engine)
}
func (s *server) registerChain(chainName string, engine common.Engine) {
var (
handlers map[string]*common.HTTPHandler
err error
)
ctx := engine.Context()
ctx.Lock.Lock()
handlers, err = engine.GetVM().CreateHandlers()
ctx.Lock.Unlock()
if err != nil {
s.log.Error("failed to create handlers",
zap.String("chainName", chainName),
zap.Error(err),
)
return
}
s.log.Verbo("about to add API endpoints",
zap.Stringer("chainID", ctx.ChainID),
)
// all subroutes to a chain begin with "bc/<the chain's ID>"
defaultEndpoint := path.Join(constants.ChainAliasPrefix, ctx.ChainID.String())
// Register each endpoint
for extension, handler := range handlers {
// Validate that the route being added is valid
// e.g. "/foo" and "" are ok but "\n" is not
_, err := url.ParseRequestURI(extension)
if extension != "" && err != nil {
s.log.Error("could not add route to chain's API handler",
zap.String("reason", "route is malformed"),
zap.Error(err),
)
continue
}
if err := s.AddChainRoute(handler, ctx, defaultEndpoint, extension); err != nil {
s.log.Error("error adding route",
zap.Error(err),
)
}
}
}
func (s *server) AddChainRoute(handler *common.HTTPHandler, ctx *snow.ConsensusContext, base, endpoint string) error {
url := fmt.Sprintf("%s/%s", baseURL, base)
s.log.Info("adding route",
zap.String("url", url),
zap.String("endpoint", endpoint),
)
// Apply middleware to grab/release chain's lock before/after calling API method
h, err := lockMiddleware(handler.Handler, handler.LockOptions, &ctx.Lock)
if err != nil {
return err
}
// Apply middleware to reject calls to the handler before the chain finishes bootstrapping
h = rejectMiddleware(h, ctx)
return s.router.AddRouter(url, endpoint, h)
}
func (s *server) AddRoute(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error {
return s.addRoute(handler, lock, base, endpoint)
}
func (s *server) AddRouteWithReadLock(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error {
s.router.lock.RUnlock()
defer s.router.lock.RLock()
return s.addRoute(handler, lock, base, endpoint)
}
func (s *server) addRoute(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error {
url := fmt.Sprintf("%s/%s", baseURL, base)
s.log.Info("adding route",
zap.String("url", url),
zap.String("endpoint", endpoint),
)
// Apply middleware to grab/release chain's lock before/after calling API method
h, err := lockMiddleware(handler.Handler, handler.LockOptions, lock)
if err != nil {
return err
}
return s.router.AddRouter(url, endpoint, h)
}
// Wraps a handler by grabbing and releasing a lock before calling the handler.
func lockMiddleware(handler http.Handler, lockOption common.LockOption, lock *sync.RWMutex) (http.Handler, error) {
switch lockOption {
case common.WriteLock:
return middlewareHandler{
before: lock.Lock,
after: lock.Unlock,
handler: handler,
}, nil
case common.ReadLock:
return middlewareHandler{
before: lock.RLock,
after: lock.RUnlock,
handler: handler,
}, nil
case common.NoLock:
return handler, nil
default:
return nil, errUnknownLockOption
}
}
// Reject middleware wraps a handler. If the chain that the context describes is
// not done state-syncing/bootstrapping, writes back an error.
func rejectMiddleware(handler http.Handler, ctx *snow.ConsensusContext) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // If chain isn't done bootstrapping, ignore API calls
if ctx.GetState() != snow.NormalOp {
w.WriteHeader(http.StatusServiceUnavailable)
// Doesn't matter if there's an error while writing. They'll get the StatusServiceUnavailable code.
_, _ = w.Write([]byte("API call rejected because chain is not done bootstrapping"))
} else {
handler.ServeHTTP(w, r)
}
})
}
func (s *server) AddAliases(endpoint string, aliases ...string) error {
url := fmt.Sprintf("%s/%s", baseURL, endpoint)
endpoints := make([]string, len(aliases))
for i, alias := range aliases {
endpoints[i] = fmt.Sprintf("%s/%s", baseURL, alias)
}
return s.router.AddAlias(url, endpoints...)
}
func (s *server) AddAliasesWithReadLock(endpoint string, aliases ...string) error {
// This is safe, as the read lock doesn't actually need to be held once the
// http handler is called. However, it is unlocked later, so this function
// must end with the lock held.
s.router.lock.RUnlock()
defer s.router.lock.RLock()
return s.AddAliases(endpoint, aliases...)
}
func (s *server) Shutdown() error {
if s.srv == nil {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), s.shutdownTimeout)
err := s.srv.Shutdown(ctx)
cancel()
// If shutdown times out, make sure the server is still shutdown.
_ = s.srv.Close()
return err
}
type readPathAdder struct {
pather PathAdderWithReadLock
}
func PathWriterFromWithReadLock(pather PathAdderWithReadLock) PathAdder {
return readPathAdder{
pather: pather,
}
}
func (a readPathAdder) AddRoute(handler *common.HTTPHandler, lock *sync.RWMutex, base, endpoint string) error {
return a.pather.AddRouteWithReadLock(handler, lock, base, endpoint)
}
func (a readPathAdder) AddAliases(endpoint string, aliases ...string) error {
return a.pather.AddAliasesWithReadLock(endpoint, aliases...)
}