handler stack creation moved from rpc to node pkg

This commit is contained in:
renaynay 2020-03-24 21:28:18 +01:00
parent 6becdde07b
commit 46eb11c667
No known key found for this signature in database
GPG key ID: 731E44FAAFCD0274
4 changed files with 137 additions and 91 deletions

View file

@ -21,8 +21,6 @@ import (
"context"
"fmt"
"math/big"
"os"
"os/signal"
"strings"
"time"
@ -40,7 +38,6 @@ import (
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
@ -848,69 +845,69 @@ func splitAndTrim(input string) []string {
return result
}
func retesteth(ctx *cli.Context) error {
log.Info("Welcome to retesteth!")
// register signer API with server
var (
extapiURL string
)
apiImpl := &RetestethAPI{}
var testApi RetestethTestAPI = apiImpl
var ethApi RetestethEthAPI = apiImpl
var debugApi RetestethDebugAPI = apiImpl
var web3Api RetestWeb3API = apiImpl
rpcAPI := []rpc.API{
{
Namespace: "test",
Public: true,
Service: testApi,
Version: "1.0",
},
{
Namespace: "eth",
Public: true,
Service: ethApi,
Version: "1.0",
},
{
Namespace: "debug",
Public: true,
Service: debugApi,
Version: "1.0",
},
{
Namespace: "web3",
Public: true,
Service: web3Api,
Version: "1.0",
},
}
vhosts := splitAndTrim(ctx.GlobalString(utils.RPCVirtualHostsFlag.Name))
cors := splitAndTrim(ctx.GlobalString(utils.RPCCORSDomainFlag.Name))
// start http server
var RetestethHTTPTimeouts = rpc.HTTPTimeouts{
ReadTimeout: 120 * time.Second,
WriteTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}
httpEndpoint := fmt.Sprintf("%s:%d", ctx.GlobalString(utils.RPCListenAddrFlag.Name), ctx.Int(rpcPortFlag.Name))
listener, _, err := rpc.StartHTTPEndpoint(httpEndpoint, rpcAPI, []string{"test", "eth", "debug", "web3"}, cors, vhosts, RetestethHTTPTimeouts, []string{})
if err != nil {
utils.Fatalf("Could not start RPC api: %v", err)
}
extapiURL = fmt.Sprintf("http://%s", httpEndpoint)
log.Info("HTTP endpoint opened", "url", extapiURL)
defer func() {
listener.Close()
log.Info("HTTP endpoint closed", "url", httpEndpoint)
}()
abortChan := make(chan os.Signal, 11)
signal.Notify(abortChan, os.Interrupt)
sig := <-abortChan
log.Info("Exiting...", "signal", sig)
func retesteth(ctx *cli.Context) error { // TODO uncomment and fix test
//log.Info("Welcome to retesteth!")
//// register signer API with server
//var (
// extapiURL string
//)
//apiImpl := &RetestethAPI{}
//var testApi RetestethTestAPI = apiImpl
//var ethApi RetestethEthAPI = apiImpl
//var debugApi RetestethDebugAPI = apiImpl
//var web3Api RetestWeb3API = apiImpl
//rpcAPI := []rpc.API{
// {
// Namespace: "test",
// Public: true,
// Service: testApi,
// Version: "1.0",
// },
// {
// Namespace: "eth",
// Public: true,
// Service: ethApi,
// Version: "1.0",
// },
// {
// Namespace: "debug",
// Public: true,
// Service: debugApi,
// Version: "1.0",
// },
// {
// Namespace: "web3",
// Public: true,
// Service: web3Api,
// Version: "1.0",
// },
//}
//vhosts := splitAndTrim(ctx.GlobalString(utils.RPCVirtualHostsFlag.Name))
//cors := splitAndTrim(ctx.GlobalString(utils.RPCCORSDomainFlag.Name))
//
//// start http server
//var RetestethHTTPTimeouts = rpc.HTTPTimeouts{
// ReadTimeout: 120 * time.Second,
// WriteTimeout: 120 * time.Second,
// IdleTimeout: 120 * time.Second,
//}
//httpEndpoint := fmt.Sprintf("%s:%d", ctx.GlobalString(utils.RPCListenAddrFlag.Name), ctx.Int(rpcPortFlag.Name))
//listener, err := rpc.StartHTTPEndpoint(httpEndpoint, rpcAPI, []string{"test", "eth", "debug", "web3"}, RetestethHTTPTimeouts, )
//if err != nil {
// utils.Fatalf("Could not start RPC api: %v", err)
//}
//extapiURL = fmt.Sprintf("http://%s", httpEndpoint)
//log.Info("HTTP endpoint opened", "url", extapiURL)
//
//defer func() {
// listener.Close()
// log.Info("HTTP endpoint closed", "url", httpEndpoint)
//}()
//
//abortChan := make(chan os.Signal, 11)
//signal.Notify(abortChan, os.Interrupt)
//
//sig := <-abortChan
//log.Info("Exiting...", "signal", sig)
return nil
}

View file

@ -20,6 +20,7 @@ import (
"errors"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"reflect"
@ -368,7 +369,29 @@ func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors
if endpoint == "" {
return nil
}
listener, handler, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, cors, vhosts, timeouts, wsOrigins)
srv := rpc.NewServer()
// TODO put this stuff in a separate function
// Generate the whitelist based on the allowed modules
whitelist := make(map[string]bool)
for _, module := range modules {
whitelist[module] = true
}
// Register all the APIs exposed by the services
for _, api := range apis {
if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
if err := srv.RegisterName(api.Namespace, api.Service); err != nil {
return err
}
log.Debug("HTTP registered", "namespace", api.Namespace)
}
}
// create handler stack
handler := n.CreateHandler(srv, cors, vhosts, wsOrigins)
listener, err := rpc.StartHTTPEndpoint(endpoint, apis, modules, timeouts, handler)
if err != nil {
return err
}
@ -383,11 +406,17 @@ func (n *Node) startHTTP(endpoint string, apis []rpc.API, modules []string, cors
// All listeners booted successfully
n.httpEndpoint = endpoint
n.httpListener = listener
n.httpHandler = handler
n.httpHandler = srv
return nil
}
// CreateHandler creates the handler stack necessary to handle both http rpc requests and websocket requests
func (n *Node) CreateHandler(srv *rpc.Server, cors []string, vhosts []string, wsOrigins []string) http.Handler {
handler := rpc.NewHTTPHandlerStack(srv, cors, vhosts)
return rpc.NewWebsocketUpgradeHandler(handler, srv.WebsocketHandler(wsOrigins))
}
// stopHTTP terminates the HTTP RPC endpoint.
func (n *Node) stopHTTP() {
if n.httpListener != nil {

View file

@ -18,6 +18,8 @@ package rpc
import (
"net"
"net/http"
"time"
"github.com/ethereum/go-ethereum/log"
)
@ -42,37 +44,46 @@ func checkModuleAvailability(modules []string, apis []API) (bad, available []str
}
// StartHTTPEndpoint starts the HTTP RPC endpoint, configured with cors/vhosts/modules.
func StartHTTPEndpoint(endpoint string, apis []API, modules []string, cors []string, vhosts []string, timeouts HTTPTimeouts, wsOrigins []string) (net.Listener, *Server, error) {
func StartHTTPEndpoint(endpoint string, apis []API, modules []string, timeouts HTTPTimeouts, handler http.Handler) (net.Listener, error) {
if bad, available := checkModuleAvailability(modules, apis); len(bad) > 0 {
log.Error("Unavailable modules in HTTP API list", "unavailable", bad, "available", available)
}
// Generate the whitelist based on the allowed modules
whitelist := make(map[string]bool)
for _, module := range modules {
whitelist[module] = true
}
// Register all the APIs exposed by the services
handler := NewServer()
for _, api := range apis {
if whitelist[api.Namespace] || (len(whitelist) == 0 && api.Public) {
if err := handler.RegisterName(api.Namespace, api.Service); err != nil {
return nil, nil, err
}
log.Debug("HTTP registered", "namespace", api.Namespace)
}
}
// All APIs registered, start the HTTP listener
// Start the HTTP listener
var (
listener net.Listener
err error
)
if listener, err = net.Listen("tcp", endpoint); err != nil {
return nil, nil, err
return nil, err
}
// TODO put timeout registration in separate function
// Make sure timeout values are meaningful
if timeouts.ReadTimeout < time.Second {
log.Warn("Sanitizing invalid HTTP read timeout", "provided", timeouts.ReadTimeout, "updated", DefaultHTTPTimeouts.ReadTimeout)
timeouts.ReadTimeout = DefaultHTTPTimeouts.ReadTimeout
}
if timeouts.WriteTimeout < time.Second {
log.Warn("Sanitizing invalid HTTP write timeout", "provided", timeouts.WriteTimeout, "updated", DefaultHTTPTimeouts.WriteTimeout)
timeouts.WriteTimeout = DefaultHTTPTimeouts.WriteTimeout
}
if timeouts.IdleTimeout < time.Second {
log.Warn("Sanitizing invalid HTTP idle timeout", "provided", timeouts.IdleTimeout, "updated", DefaultHTTPTimeouts.IdleTimeout)
timeouts.IdleTimeout = DefaultHTTPTimeouts.IdleTimeout
}
go NewHTTPServer(cors, vhosts, timeouts, handler, handler.WebsocketHandler(wsOrigins)).Serve(listener)
return listener, handler, err
// Bundle and start the HTTP server
httpSrv := &http.Server{
Handler: handler,
ReadTimeout: timeouts.ReadTimeout,
WriteTimeout: timeouts.WriteTimeout,
IdleTimeout: timeouts.IdleTimeout,
}
go httpSrv.Serve(listener)
// go NewHTTPServer(cors, vhosts, timeouts, handler, handler.WebsocketHandler(wsOrigins)).Serve(listener) // TODO REMOVE
return listener, err
}
// StartWSEndpoint starts a websocket endpoint.

View file

@ -217,7 +217,7 @@ func NewHTTPServer(cors []string, vhosts []string, timeouts HTTPTimeouts, srv ht
handler := newCorsHandler(srv, cors)
handler = newVHostHandler(vhosts, handler)
handler = newGzipHandler(handler)
handler = newWebsocketUpgradeHandler(handler, ws)
handler = NewWebsocketUpgradeHandler(handler, ws)
// Make sure timeout values are meaningful
if timeouts.ReadTimeout < time.Second {
@ -298,6 +298,14 @@ func validateRequest(r *http.Request) (int, error) {
return http.StatusUnsupportedMediaType, err
}
// NewHTTPHandlerStack TODO document
func NewHTTPHandlerStack(srv *Server, cors []string, vhosts []string) http.Handler {
// Wrap the CORS-handler within a host-handler
handler := newCorsHandler(srv, cors)
handler = newVHostHandler(vhosts, handler)
return newGzipHandler(handler)
}
func newCorsHandler(srv http.Handler, allowedOrigins []string) http.Handler {
// disable CORS support if user has not specified a custom CORS configuration
if len(allowedOrigins) == 0 {
@ -359,10 +367,11 @@ func newVHostHandler(vhosts []string, next http.Handler) http.Handler {
return &virtualHostHandler{vhostMap, next}
}
func newWebsocketUpgradeHandler(h http.Handler, ws http.Handler) http.Handler {
func NewWebsocketUpgradeHandler(h http.Handler, ws http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if isWebsocket(r) {
ws.ServeHTTP(w, r)
log.Debug("serving websocket request")
return
}