lotus/cmd/lotus/rpc.go

85 lines
2.0 KiB
Go
Raw Normal View History

2019-07-18 23:18:26 +00:00
package main
import (
2019-09-17 14:23:08 +00:00
"context"
2019-10-23 09:18:22 +00:00
"encoding/json"
2019-07-18 23:18:26 +00:00
"net/http"
2019-09-30 23:25:45 +00:00
_ "net/http/pprof"
2019-09-17 14:23:08 +00:00
"os"
"os/signal"
"syscall"
2019-07-18 23:18:26 +00:00
2019-10-23 09:18:22 +00:00
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/lib/auth"
"github.com/filecoin-project/lotus/lib/jsonrpc"
"github.com/filecoin-project/lotus/node"
2019-10-23 09:18:22 +00:00
"github.com/filecoin-project/lotus/node/impl"
2019-07-18 23:18:26 +00:00
)
2019-09-17 14:23:08 +00:00
var log = logging.Logger("main")
func serveRPC(a api.FullNode, stop node.StopFunc, addr string) error {
2019-07-18 23:18:26 +00:00
rpcServer := jsonrpc.NewServer()
2019-07-24 01:10:26 +00:00
rpcServer.Register("Filecoin", api.PermissionedFullAPI(a))
2019-07-24 13:40:42 +00:00
ah := &auth.Handler{
Verify: a.AuthVerify,
2019-07-25 12:54:19 +00:00
Next: rpcServer.ServeHTTP,
2019-07-24 13:40:42 +00:00
}
http.Handle("/rpc/v0", ah)
2019-09-17 14:23:08 +00:00
2019-10-23 09:18:22 +00:00
importAH := &auth.Handler{
Verify: a.AuthVerify,
Next: handleImport(a.(*impl.FullNodeAPI)),
}
http.Handle("/rest/v0/import", importAH)
2019-09-17 14:23:08 +00:00
srv := &http.Server{Addr: addr, Handler: http.DefaultServeMux}
sigChan := make(chan os.Signal, 2)
go func() {
<-sigChan
if err := srv.Shutdown(context.TODO()); err != nil {
log.Errorf("shutting down RPC server failed: %s", err)
}
2019-10-20 06:17:03 +00:00
if err := stop(context.TODO()); err != nil {
log.Errorf("graceful shutting down failed: %s", err)
}
2019-09-17 14:23:08 +00:00
}()
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
return srv.ListenAndServe()
2019-07-18 23:18:26 +00:00
}
2019-10-23 09:18:22 +00:00
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 !api.HasPerm(r.Context(), 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
}
}
}