decouple rpc server and shutdown logic from cmd.
This commit is contained in:
+143
@@ -0,0 +1,143 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"github.com/ipfs/go-cid"
|
||||
logging "github.com/ipfs/go-log/v2"
|
||||
"github.com/multiformats/go-multiaddr"
|
||||
manet "github.com/multiformats/go-multiaddr/net"
|
||||
"go.opencensus.io/tag"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/filecoin-project/go-jsonrpc"
|
||||
"github.com/filecoin-project/go-jsonrpc/auth"
|
||||
|
||||
"github.com/filecoin-project/lotus/api"
|
||||
"github.com/filecoin-project/lotus/api/v0api"
|
||||
"github.com/filecoin-project/lotus/api/v1api"
|
||||
"github.com/filecoin-project/lotus/metrics"
|
||||
"github.com/filecoin-project/lotus/node/impl"
|
||||
)
|
||||
|
||||
var rpclog = logging.Logger("rpc")
|
||||
|
||||
func ServeRPC(a v1api.FullNode, addr multiaddr.Multiaddr, maxRequestSize int64) (StopFunc, error) {
|
||||
serverOptions := make([]jsonrpc.ServerOption, 0)
|
||||
if maxRequestSize != 0 { // config set
|
||||
serverOptions = append(serverOptions, jsonrpc.WithMaxRequestSize(maxRequestSize))
|
||||
}
|
||||
serveRpc := func(path string, hnd interface{}) {
|
||||
rpcServer := jsonrpc.NewServer(serverOptions...)
|
||||
rpcServer.Register("Filecoin", hnd)
|
||||
|
||||
ah := &auth.Handler{
|
||||
Verify: a.AuthVerify,
|
||||
Next: rpcServer.ServeHTTP,
|
||||
}
|
||||
|
||||
http.Handle(path, ah)
|
||||
}
|
||||
|
||||
pma := api.PermissionedFullAPI(metrics.MetricedFullAPI(a))
|
||||
|
||||
serveRpc("/rpc/v1", pma)
|
||||
serveRpc("/rpc/v0", &v0api.WrapperV1Full{FullNode: pma})
|
||||
|
||||
importAH := &auth.Handler{
|
||||
Verify: a.AuthVerify,
|
||||
Next: handleImport(a.(*impl.FullNodeAPI)),
|
||||
}
|
||||
|
||||
http.Handle("/rest/v0/import", importAH)
|
||||
|
||||
http.Handle("/debug/metrics", metrics.Exporter())
|
||||
http.Handle("/debug/pprof-set/block", handleFractionOpt("BlockProfileRate", runtime.SetBlockProfileRate))
|
||||
http.Handle("/debug/pprof-set/mutex", handleFractionOpt("MutexProfileFraction", func(x int) {
|
||||
runtime.SetMutexProfileFraction(x)
|
||||
}))
|
||||
|
||||
// Start listening to the addr; if invalid or occupied, we will fail early.
|
||||
lst, err := manet.Listen(addr)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("could not listen: %w", err)
|
||||
}
|
||||
|
||||
// Instantiate the server and start listening.
|
||||
srv := &http.Server{
|
||||
Handler: http.DefaultServeMux,
|
||||
BaseContext: func(listener net.Listener) context.Context {
|
||||
ctx, _ := tag.New(context.Background(), tag.Upsert(metrics.APIInterface, "lotus-daemon"))
|
||||
return ctx
|
||||
},
|
||||
}
|
||||
|
||||
go func() {
|
||||
err = srv.Serve(manet.NetListener(lst))
|
||||
if err != http.ErrServerClosed {
|
||||
log.Warnf("rpc server failed: %s", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return srv.Shutdown, err
|
||||
}
|
||||
|
||||
func handleImport(a *impl.FullNodeAPI) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != "PUT" {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
if !auth.HasPerm(r.Context(), nil, api.PermWrite) {
|
||||
w.WriteHeader(401)
|
||||
_ = json.NewEncoder(w).Encode(struct{ Error string }{"unauthorized: missing write permission"})
|
||||
return
|
||||
}
|
||||
|
||||
c, err := a.ClientImportLocal(r.Context(), r.Body)
|
||||
if err != nil {
|
||||
w.WriteHeader(500)
|
||||
_ = json.NewEncoder(w).Encode(struct{ Error string }{err.Error()})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(200)
|
||||
err = json.NewEncoder(w).Encode(struct{ Cid cid.Cid }{c})
|
||||
if err != nil {
|
||||
log.Errorf("/rest/v0/import: Writing response failed: %+v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleFractionOpt(name string, setter func(int)) http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(rw, "only POST allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
asfr := r.Form.Get("x")
|
||||
if len(asfr) == 0 {
|
||||
http.Error(rw, "parameter 'x' must be set", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fr, err := strconv.Atoi(asfr)
|
||||
if err != nil {
|
||||
http.Error(rw, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
log.Infof("setting %s to %d", name, fr)
|
||||
setter(fr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
type ShutdownHandler struct {
|
||||
Component string
|
||||
StopFunc StopFunc
|
||||
}
|
||||
|
||||
// MonitorShutdown manages shutdown requests, by watching signals and invoking
|
||||
// the supplied handlers in order.
|
||||
//
|
||||
// It watches SIGTERM and SIGINT OS signals, as well as the trigger channel.
|
||||
// When any of them fire, it calls the supplied handlers in order. If any of
|
||||
// them errors, it merely logs the error.
|
||||
//
|
||||
// Once the shutdown has completed, it closes the returned channel. The caller
|
||||
// can watch this channel
|
||||
func MonitorShutdown(triggerCh <-chan struct{}, handlers ...ShutdownHandler) <-chan struct{} {
|
||||
sigCh := make(chan os.Signal, 2)
|
||||
out := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case sig := <-sigCh:
|
||||
log.Warnw("received shutdown", "signal", sig)
|
||||
case <-triggerCh:
|
||||
log.Warn("received shutdown")
|
||||
}
|
||||
|
||||
log.Warn("Shutting down...")
|
||||
|
||||
// Call all the handlers, logging on failure and success.
|
||||
for _, h := range handlers {
|
||||
if err := h.StopFunc(context.TODO()); err != nil {
|
||||
log.Errorf("shutting down %s failed: %s", h.Component, err)
|
||||
continue
|
||||
}
|
||||
log.Infof("%s shut down successfully ", h.Component)
|
||||
}
|
||||
|
||||
log.Warn("Graceful shutdown successful")
|
||||
|
||||
// Sync all loggers.
|
||||
_ = log.Sync() //nolint:errcheck
|
||||
close(out)
|
||||
}()
|
||||
|
||||
signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMonitorShutdown(t *testing.T) {
|
||||
signalCh := make(chan struct{})
|
||||
|
||||
// Three shutdown handlers.
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(3)
|
||||
h := ShutdownHandler{
|
||||
Component: "handler",
|
||||
StopFunc: func(_ context.Context) error {
|
||||
wg.Done()
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
finishCh := MonitorShutdown(signalCh, h, h, h)
|
||||
|
||||
// Nothing here after 10ms.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
require.Len(t, finishCh, 0)
|
||||
|
||||
// Now trigger the shutdown.
|
||||
close(signalCh)
|
||||
wg.Wait()
|
||||
<-finishCh
|
||||
}
|
||||
Reference in New Issue
Block a user