Skip to content

Commit

Permalink
save running mode to file when updating, recover from it when restarts
Browse files Browse the repository at this point in the history
  • Loading branch information
rickyyangz committed Apr 11, 2019
1 parent b150ab6 commit 022def7
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 21 deletions.
16 changes: 11 additions & 5 deletions admin/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func GetHandler(config *config.Config) types.AbciQueryHandler {
}
res := abci.ResponseQuery{
Code: uint32(sdk.ABCICodeOK),
Value: []byte{uint8(runtime.RunningMode)},
Value: []byte{uint8(runtime.GetRunningMode())},
}
return &res
}
Expand All @@ -47,20 +47,26 @@ func GetHandler(config *config.Config) types.AbciQueryHandler {
return &res
}

var runningMode runtime.Mode
if mode == "0" {
runtime.RunningMode = runtime.NormalMode
runningMode = runtime.NormalMode
} else if mode == "1" {
runtime.RunningMode = runtime.TransferOnlyMode
runningMode = runtime.TransferOnlyMode
} else if mode == "2" {
runtime.RunningMode = runtime.RecoverOnlyMode
runningMode = runtime.RecoverOnlyMode
} else {
res := sdk.ErrUnknownRequest("invalid mode").QueryResult()
return &res
}
err = runtime.UpdateRunningMode(config, runningMode)
if err != nil {
res := sdk.ErrUnknownRequest(err.Error()).QueryResult()
return &res
}

res := abci.ResponseQuery{
Code: uint32(sdk.ABCICodeOK),
Value: []byte{uint8(runtime.RunningMode)},
Value: []byte{uint8(runtime.GetRunningMode())},
}
return &res
}
Expand Down
11 changes: 6 additions & 5 deletions admin/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,25 @@ var TxBlackList = map[runtime.Mode][]string{
}

func TxNotAllowedError() sdk.Error {
return sdk.ErrInternal(fmt.Sprintf("The tx is not allowed, RunningMode: %v", runtime.RunningMode))
return sdk.ErrInternal(fmt.Sprintf("The tx is not allowed, RunningMode: %v", runtime.GetRunningMode()))
}

func IsTxAllowed(tx sdk.Tx) bool {
if runtime.RunningMode == runtime.NormalMode {
mode := runtime.GetRunningMode()
if mode == runtime.NormalMode {
return true
}

for _, msg := range tx.GetMsgs() {
if !isMsgAllowed(msg) {
if !isMsgAllowed(msg, mode) {
return false
}
}
return true
}

func isMsgAllowed(msg sdk.Msg) bool {
for _, msgType := range TxBlackList[runtime.RunningMode] {
func isMsgAllowed(msg sdk.Msg, mode runtime.Mode) bool {
for _, msgType := range TxBlackList[mode] {
if msgType == msg.Type() {
return false
}
Expand Down
15 changes: 9 additions & 6 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,6 @@ type BinanceChain struct {

// NewBinanceChain creates a new instance of the BinanceChain.
func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseAppOptions ...func(*baseapp.BaseApp)) *BinanceChain {
// set running mode from cmd parameter or config
err := runtime.SetRunningMode(runtime.Mode(ServerContext.StartMode))
if err != nil {
cmn.Exit(err.Error())
}
// create app-level codec for txs and accounts
var cdc = Codec
// create composed tx decoder
Expand All @@ -125,6 +120,7 @@ func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseApp
// set upgrade config
app.setUpgradeConfig()
app.SetPruning(viper.GetString("pruning"))
app.initRunningMode()
app.SetCommitMultiStoreTracer(traceStore)

// mappers
Expand Down Expand Up @@ -216,7 +212,7 @@ func NewBinanceChain(logger log.Logger, db dbm.DB, traceStore io.Writer, baseApp
app.MountStoresTransient(common.TParamsStoreKey, common.TStakeStoreKey)

// block store required to hydrate dex OB
err = app.LoadCMSLatestVersion()
err := app.LoadCMSLatestVersion()
if err != nil {
cmn.Exit(err.Error())
}
Expand Down Expand Up @@ -245,6 +241,13 @@ func (app *BinanceChain) setUpgradeConfig() {
// upgrade.Mgr.AddUpgradeHeight(,)
}

func (app *BinanceChain) initRunningMode() {
err := runtime.RecoverFromFile(ServerContext.Config.RootDir, runtime.Mode(ServerContext.StartMode))
if err != nil {
cmn.Exit(err.Error())
}
}

func (app *BinanceChain) initDex(pairMapper dex.TradingPairMapper) {
app.DexKeeper = dex.NewOrderKeeper(common.DexStoreKey, app.AccountKeeper, pairMapper,
app.RegisterCodespace(dex.DefaultCodespace), app.baseConfig.OrderKeeperConcurrency, app.Codec,
Expand Down
2 changes: 0 additions & 2 deletions cmd/bnbchaind/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ func main() {
server.AddCommands(ctx.ToCosmosServerCtx(), cdc, rootCmd, exportAppStateAndTMValidators)
startCmd := server.StartCmd(ctx.ToCosmosServerCtx(), newApp)
startCmd.Flags().Int64VarP(&ctx.PublicationConfig.FromHeightInclusive, "fromHeight", "f", 1, "from which height (inclusive) we want publish market data")
startCmd.Flags().Uint8Var(&ctx.BaseConfig.StartMode, "mode", uint8(0), "running mode when start up")
ctx.Viper.BindPFlag("base.startMode", startCmd.Flags().Lookup("mode"))
rootCmd.AddCommand(startCmd)

// prepare and add flags
Expand Down
42 changes: 39 additions & 3 deletions common/runtime/mode.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ package runtime

import (
"fmt"
"os"
"path/filepath"
"sync"

"github.com/binance-chain/node/common/log"
"github.com/tendermint/tendermint/config"
)

type Mode uint8
Expand All @@ -12,12 +18,42 @@ const (
RecoverOnlyMode
)

var RunningMode = NormalMode
var (
runningMode = NormalMode
mtx = new(sync.RWMutex)
)

func SetRunningMode(mode Mode) error {
func GetRunningMode() Mode {
mtx.RLock()
defer mtx.RUnlock()
return runningMode
}

func setRunningMode(mode Mode) error {
if mode != NormalMode && mode != TransferOnlyMode && mode != RecoverOnlyMode {
return fmt.Errorf("invalid mode %v", mode)
}
RunningMode = mode

mtx.Lock()
runningMode = mode
mtx.Unlock()
return nil
}

func UpdateRunningMode(cfg *config.Config, mode Mode) error {
err := setRunningMode(mode)
if err != nil {
return err
}
var params *runtimeParams
path := filepath.Join(cfg.RootDir, "config", fileName)
if _, err := os.Stat(path); os.IsNotExist(err) {
log.Debug("path does not exist", "path", path)
params = &runtimeParams{Mode:mode}
} else {
params = mustReadFromFile(path)
params.Mode = mode
}
mustSaveToFile(path, params)
return nil
}
56 changes: 56 additions & 0 deletions common/runtime/recover.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package runtime

import (
"encoding/json"
"os"
"path/filepath"

"github.com/tendermint/tendermint/libs/common"

"github.com/binance-chain/node/common/log"
)

const fileName = "recover_params.json"

type runtimeParams struct {
Mode Mode `json:"mode"`
}

func RecoverFromFile(homeDir string, defaultStartMode Mode) error {
path := filepath.Join(homeDir, "config", fileName)
var mode Mode
if _, err := os.Stat(path); os.IsNotExist(err) {
log.Debug("path does not exist", "path", path)
mode = defaultStartMode
} else {
params := mustReadFromFile(path)
mode = params.Mode
}

return setRunningMode(mode)
}

func mustSaveToFile(path string, params *runtimeParams) {
contents, err := json.MarshalIndent(params, "", " ")
if err != nil {
panic(err)
}
err = common.WriteFileAtomic(path, contents, 0600)
if err != nil {
panic(err)
}
}

func mustReadFromFile(path string) *runtimeParams {
contents, err := common.ReadFile(path)
if err != nil {
panic(err)
}

var res runtimeParams
err = json.Unmarshal(contents, &res)
if err != nil {
panic(err)
}
return &res
}

0 comments on commit 022def7

Please sign in to comment.