lotus/cmd/lotus-provider/run.go

424 lines
11 KiB
Go
Raw Normal View History

2023-08-23 23:57:34 +00:00
package main
import (
"context"
"encoding/base64"
"encoding/json"
2023-08-23 23:57:34 +00:00
"fmt"
"net"
"net/http"
2023-08-23 23:57:34 +00:00
"os"
"strings"
2023-08-26 03:07:17 +00:00
"time"
2023-08-23 23:57:34 +00:00
"github.com/gbrlsnchs/jwt/v3"
2023-12-02 02:48:16 +00:00
"github.com/gorilla/mux"
2023-11-04 10:04:46 +00:00
ds "github.com/ipfs/go-datastore"
dssync "github.com/ipfs/go-datastore/sync"
2023-10-16 15:28:58 +00:00
"github.com/pkg/errors"
"github.com/samber/lo"
2023-08-23 23:57:34 +00:00
"github.com/urfave/cli/v2"
"go.opencensus.io/stats"
"go.opencensus.io/tag"
2023-11-04 10:04:46 +00:00
"golang.org/x/xerrors"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/go-address"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/go-jsonrpc/auth"
2023-11-04 10:04:46 +00:00
"github.com/filecoin-project/go-statestore"
2023-11-14 00:06:11 +00:00
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/build"
lcli "github.com/filecoin-project/lotus/cli"
cliutil "github.com/filecoin-project/lotus/cli/util"
"github.com/filecoin-project/lotus/journal"
2023-10-25 22:10:52 +00:00
"github.com/filecoin-project/lotus/journal/alerting"
"github.com/filecoin-project/lotus/journal/fsjournal"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/lib/harmony/harmonydb"
2023-08-26 03:07:17 +00:00
"github.com/filecoin-project/lotus/lib/harmony/harmonytask"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/lib/ulimit"
"github.com/filecoin-project/lotus/metrics"
"github.com/filecoin-project/lotus/node"
"github.com/filecoin-project/lotus/node/config"
"github.com/filecoin-project/lotus/node/modules/dtypes"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/node/repo"
2023-10-25 19:13:56 +00:00
"github.com/filecoin-project/lotus/provider"
2023-11-29 15:44:22 +00:00
"github.com/filecoin-project/lotus/provider/lpmessage"
2023-11-10 19:36:41 +00:00
"github.com/filecoin-project/lotus/provider/lpwinning"
2023-11-22 16:36:10 +00:00
"github.com/filecoin-project/lotus/storage/ctladdr"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/storage/paths"
"github.com/filecoin-project/lotus/storage/sealer"
"github.com/filecoin-project/lotus/storage/sealer/ffiwrapper"
2023-08-23 23:57:34 +00:00
"github.com/filecoin-project/lotus/storage/sealer/storiface"
)
2023-10-16 15:28:58 +00:00
type stackTracer interface {
StackTrace() errors.StackTrace
}
2023-08-23 23:57:34 +00:00
var runCmd = &cli.Command{
Name: "run",
Usage: "Start a lotus provider process",
Flags: []cli.Flag{
&cli.StringFlag{
2023-08-30 04:16:05 +00:00
Name: "listen",
Usage: "host address and port the worker api will listen on",
Value: "0.0.0.0:12300",
EnvVars: []string{"LOTUS_WORKER_LISTEN"},
2023-08-23 23:57:34 +00:00
},
&cli.BoolFlag{
Name: "nosync",
Usage: "don't check full-node sync status",
},
2023-08-25 23:17:31 +00:00
&cli.BoolFlag{
Name: "halt-after-init",
Usage: "only run init, then return",
Hidden: true,
},
2023-08-23 23:57:34 +00:00
&cli.BoolFlag{
Name: "manage-fdlimit",
Usage: "manage open file limit",
Value: true,
},
2023-10-18 21:47:00 +00:00
&cli.StringSliceFlag{
Name: "layers",
Usage: "list of layers to be interpreted (atop defaults). Default: base",
Value: cli.NewStringSlice("base"),
},
&cli.StringFlag{
Name: "storage-json",
Usage: "path to json file containing storage config",
2023-10-30 23:45:09 +00:00
Value: "~/.lotus-provider/storage.json",
},
2023-10-26 22:19:39 +00:00
&cli.StringFlag{
Name: "journal",
Usage: "path to journal files",
2023-10-30 23:45:09 +00:00
Value: "~/.lotus-provider/",
2023-10-26 22:19:39 +00:00
},
2023-08-23 23:57:34 +00:00
},
2023-10-16 15:28:58 +00:00
Action: func(cctx *cli.Context) (err error) {
defer func() {
if err != nil {
if err, ok := err.(stackTracer); ok {
for _, f := range err.StackTrace() {
fmt.Printf("%+s:%d\n", f, f)
}
}
}
}()
2023-08-23 23:57:34 +00:00
if !cctx.Bool("enable-gpu-proving") {
err := os.Setenv("BELLMAN_NO_GPU", "true")
if err != nil {
return err
}
}
ctx, _ := tag.New(lcli.DaemonContext(cctx),
tag.Insert(metrics.Version, build.BuildVersion),
tag.Insert(metrics.Commit, build.CurrentCommit),
tag.Insert(metrics.NodeType, "provider"),
)
2023-11-15 16:04:04 +00:00
shutdownChan := make(chan struct{})
ctx, ctxclose := context.WithCancel(ctx)
go func() {
<-shutdownChan
ctxclose()
}()
2023-08-23 23:57:34 +00:00
// Register all metric views
/*
if err := view.Register(
metrics.MinerNodeViews...,
); err != nil {
log.Fatalf("Cannot register the view: %v", err)
}
*/
// Set the metric to one so it is published to the exporter
stats.Record(ctx, metrics.LotusInfo.M(1))
if cctx.Bool("manage-fdlimit") {
if _, _, err := ulimit.ManageFdLimit(); err != nil {
log.Errorf("setting file descriptor limit: %s", err)
}
}
2023-11-15 04:58:43 +00:00
deps, err := getDeps(ctx, cctx)
2023-08-23 23:57:34 +00:00
2023-10-16 15:28:58 +00:00
if err != nil {
return err
}
cfg, db, full, verif, lw, as, maddrs, stor, si, localStore := deps.cfg, deps.db, deps.full, deps.verif, deps.lw, deps.as, deps.maddrs, deps.stor, deps.si, deps.localStore
2023-10-30 18:40:23 +00:00
var activeTasks []harmonytask.TaskInterface
sender, sendTask := lpmessage.NewSender(full, full, db)
activeTasks = append(activeTasks, sendTask)
2023-10-26 22:19:39 +00:00
///////////////////////////////////////////////////////////////////////
///// Task Selection
///////////////////////////////////////////////////////////////////////
{
if cfg.Subsystems.EnableWindowPost {
wdPostTask, wdPoStSubmitTask, derlareRecoverTask, err := provider.WindowPostScheduler(ctx, cfg.Fees, cfg.Proving, full, verif, lw, sender,
2023-10-27 23:08:18 +00:00
as, maddrs, db, stor, si, cfg.Subsystems.WindowPostMaxTasks)
2023-10-26 22:19:39 +00:00
if err != nil {
return err
}
2023-11-09 16:32:32 +00:00
activeTasks = append(activeTasks, wdPostTask, wdPoStSubmitTask, derlareRecoverTask)
}
2023-11-10 19:17:05 +00:00
if cfg.Subsystems.EnableWinningPost {
winPoStTask := lpwinning.NewWinPostTask(cfg.Subsystems.WinningPostMaxTasks, db, lw, verif, full, maddrs)
activeTasks = append(activeTasks, winPoStTask)
}
}
log.Infow("This lotus_provider instance handles",
"miner_addresses", maddrs,
"tasks", lo.Map(activeTasks, func(t harmonytask.TaskInterface, _ int) string { return t.TypeDetails().Name }))
taskEngine, err := harmonytask.New(db, activeTasks, deps.listenAddr)
if err != nil {
return err
}
2023-08-26 03:07:17 +00:00
defer taskEngine.GracefullyTerminate(time.Hour)
2023-08-23 23:57:34 +00:00
fh := &paths.FetchHandler{Local: localStore, PfHandler: &paths.DefaultPartialFileHandler{}}
remoteHandler := func(w http.ResponseWriter, r *http.Request) {
if !auth.HasPerm(r.Context(), nil, api.PermAdmin) {
w.WriteHeader(401)
_ = json.NewEncoder(w).Encode(struct{ Error string }{"unauthorized: missing admin permission"})
2023-08-23 23:57:34 +00:00
return
}
fh.ServeHTTP(w, r)
}
2023-08-23 23:57:34 +00:00
// local APIs
{
// debugging
mux := mux.NewRouter()
mux.PathPrefix("/").Handler(http.DefaultServeMux) // pprof
mux.PathPrefix("/remote").HandlerFunc(remoteHandler)
/*ah := &auth.Handler{
Verify: authv,
Next: mux.ServeHTTP,
}*/ // todo
2023-08-23 23:57:34 +00:00
}
// Serve the RPC.
2023-08-30 20:57:20 +00:00
/*
srv := &http.Server{
Handler: sealworker.WorkerHandler(nodeApi.AuthVerify, remoteHandler, workerApi, true),
ReadHeaderTimeout: timeout,
BaseContext: func(listener net.Listener) context.Context {
ctx, _ := tag.New(context.Background(), tag.Upsert(metrics.APIInterface, "lotus-worker"))
return ctx
},
2023-08-30 20:57:20 +00:00
}
go func() {
<-ctx.Done()
log.Warn("Shutting down...")
if err := srv.Shutdown(context.TODO()); err != nil {
log.Errorf("shutting down RPC server failed: %s", err)
}
log.Warn("Graceful shutdown successful")
}()
2023-08-30 20:57:20 +00:00
*/
2023-08-23 23:57:34 +00:00
// Monitor for shutdown.
2023-10-26 22:19:39 +00:00
// TODO provide a graceful shutdown API on shutdownChan
2023-08-30 20:57:20 +00:00
finishCh := node.MonitorShutdown(shutdownChan) //node.ShutdownHandler{Component: "rpc server", StopFunc: rpcStopper},
//node.ShutdownHandler{Component: "provider", StopFunc: stop},
2023-08-23 23:57:34 +00:00
<-finishCh
return nil
},
}
2023-09-20 03:48:39 +00:00
func makeDB(cctx *cli.Context) (*harmonydb.DB, error) {
dbConfig := config.HarmonyDB{
Username: cctx.String("db-user"),
Password: cctx.String("db-password"),
Hosts: strings.Split(cctx.String("db-host"), ","),
Database: cctx.String("db-name"),
Port: cctx.String("db-port"),
}
return harmonydb.NewFromConfig(dbConfig)
}
type jwtPayload struct {
Allow []auth.Permission
}
func StorageAuth(apiKey string) (sealer.StorageAuth, error) {
if apiKey == "" {
return nil, xerrors.Errorf("no api key provided")
}
rawKey, err := base64.StdEncoding.DecodeString(apiKey)
if err != nil {
return nil, xerrors.Errorf("decoding api key: %w", err)
}
key := jwt.NewHS256(rawKey)
p := jwtPayload{
Allow: []auth.Permission{"admin"},
}
token, err := jwt.Sign(&p, key)
if err != nil {
return nil, err
}
2023-09-20 03:48:39 +00:00
headers := http.Header{}
headers.Add("Authorization", "Bearer "+string(token))
return sealer.StorageAuth(headers), nil
2023-09-20 03:48:39 +00:00
}
type Deps struct {
cfg *config.LotusProviderConfig
db *harmonydb.DB
full api.FullNode
verif storiface.Verifier
lw *sealer.LocalWorker
as *ctladdr.AddressSelector
maddrs []dtypes.MinerAddress
stor *paths.Remote
2023-11-15 14:50:32 +00:00
si *paths.DBIndex
localStore *paths.Local
listenAddr string
}
2023-11-15 04:58:43 +00:00
func getDeps(ctx context.Context, cctx *cli.Context) (*Deps, error) {
// Open repo
repoPath := cctx.String(FlagRepoPath)
fmt.Println("repopath", repoPath)
r, err := repo.NewFS(repoPath)
if err != nil {
return nil, err
}
ok, err := r.Exists()
if err != nil {
return nil, err
}
if !ok {
if err := r.Init(repo.Provider); err != nil {
return nil, err
}
}
db, err := makeDB(cctx)
if err != nil {
return nil, err
}
///////////////////////////////////////////////////////////////////////
///// Dependency Setup
///////////////////////////////////////////////////////////////////////
// The config feeds into task runners & their helpers
cfg, err := getConfig(cctx, db)
if err != nil {
return nil, err
}
log.Debugw("config", "config", cfg)
var verif storiface.Verifier = ffiwrapper.ProofVerifier
as, err := provider.AddressSelector(&cfg.Addresses)()
if err != nil {
return nil, err
}
de, err := journal.ParseDisabledEvents(cfg.Journal.DisabledEvents)
if err != nil {
return nil, err
}
j, err := fsjournal.OpenFSJournalPath(cctx.String("journal"), de)
if err != nil {
return nil, err
}
full, fullCloser, err := cliutil.GetFullNodeAPIV1LotusProvider(cctx, cfg.Apis.ChainApiInfo)
if err != nil {
return nil, err
}
2023-11-15 16:04:04 +00:00
go func() {
select {
case <-ctx.Done():
fullCloser()
_ = j.Close()
}
}()
sa, err := StorageAuth(cfg.Apis.StorageRPCSecret)
if err != nil {
2023-11-15 01:53:00 +00:00
return nil, xerrors.Errorf(`'%w' while parsing the config toml's
[Apis]
StorageRPCSecret=%v
Get it with: jq .PrivateKey ~/.lotus-miner/keystore/MF2XI2BNNJ3XILLQOJUXMYLUMU`, err, cfg.Apis.StorageRPCSecret)
}
al := alerting.NewAlertingSystem(j)
2023-11-15 14:50:32 +00:00
si := paths.NewDBIndex(al, db)
bls := &paths.BasicLocalStorage{
PathToJSON: cctx.String("storage-json"),
}
listenAddr := cctx.String("listen")
const unspecifiedAddress = "0.0.0.0"
addressSlice := strings.Split(listenAddr, ":")
if ip := net.ParseIP(addressSlice[0]); ip != nil {
if ip.String() == unspecifiedAddress {
rip, err := db.GetRoutableIP()
if err != nil {
return nil, err
}
listenAddr = rip + ":" + addressSlice[1]
}
}
localStore, err := paths.NewLocal(ctx, bls, si, []string{"http://" + listenAddr + "/remote"})
if err != nil {
return nil, err
}
stor := paths.NewRemote(localStore, si, http.Header(sa), 10, &paths.DefaultPartialFileHandler{})
wstates := statestore.New(dssync.MutexWrap(ds.NewMapDatastore()))
// todo localWorker isn't the abstraction layer we want to use here, we probably want to go straight to ffiwrapper
// maybe with a lotus-provider specific abstraction. LocalWorker does persistent call tracking which we probably
// don't need (ehh.. maybe we do, the async callback system may actually work decently well with harmonytask)
lw := sealer.NewLocalWorker(sealer.WorkerConfig{}, stor, localStore, si, nil, wstates)
var maddrs []dtypes.MinerAddress
for _, s := range cfg.Addresses.MinerAddresses {
addr, err := address.NewFromString(s)
if err != nil {
return nil, err
}
maddrs = append(maddrs, dtypes.MinerAddress(addr))
}
return &Deps{ // lint: intentionally not-named so it will fail if one is forgotten
cfg,
db,
full,
verif,
lw,
as,
maddrs,
stor,
si,
localStore,
listenAddr,
}, nil
}