Browse Source

App -> App()

pull/32/head
Matthew Wampler-Doty 10 years ago
committed by Jae Kwon
parent
commit
f03547007a
13 changed files with 97 additions and 85 deletions
  1. +7
    -7
      alert/alert.go
  2. +5
    -5
      alert/email.go
  3. +1
    -1
      block/block.go
  4. +1
    -1
      cmd/gen_validator.go
  5. +60
    -48
      config/config.go
  6. +1
    -1
      consensus/state.go
  7. +10
    -10
      daemon/daemon.go
  8. +3
    -3
      db/db.go
  9. +3
    -3
      logger/log.go
  10. +2
    -2
      rpc/http_server.go
  11. +2
    -2
      rpc/net.go
  12. +1
    -1
      state/priv_validator.go
  13. +1
    -1
      state/state_test.go

+ 7
- 7
alert/alert.go View File

@ -15,16 +15,16 @@ var alertCountSince int = 0
func Alert(message string) { func Alert(message string) {
log.Error("<!> ALERT <!>\n" + message) log.Error("<!> ALERT <!>\n" + message)
now := time.Now().Unix() now := time.Now().Unix()
if now-lastAlertUnix > int64(config.App.GetInt("Alert.MinInterval")) {
message = fmt.Sprintf("%v:%v", config.App.GetString("Network"), message)
if now-lastAlertUnix > int64(config.App().GetInt("Alert.MinInterval")) {
message = fmt.Sprintf("%v:%v", config.App().GetString("Network"), message)
if alertCountSince > 0 { if alertCountSince > 0 {
message = fmt.Sprintf("%v (+%v more since)", message, alertCountSince) message = fmt.Sprintf("%v (+%v more since)", message, alertCountSince)
alertCountSince = 0 alertCountSince = 0
} }
if len(config.App.GetString("Alert.TwilioSid")) > 0 {
if len(config.App().GetString("Alert.TwilioSid")) > 0 {
go sendTwilio(message) go sendTwilio(message)
} }
if len(config.App.GetString("Alert.EmailRecipients")) > 0 {
if len(config.App().GetString("Alert.EmailRecipients")) > 0 {
go sendEmail(message) go sendEmail(message)
} }
} else { } else {
@ -41,8 +41,8 @@ func sendTwilio(message string) {
if len(message) > 50 { if len(message) > 50 {
message = message[:50] message = message[:50]
} }
twilio := gotwilio.NewTwilioClient(config.App.GetString("Alert.TwilioSid"), config.App.GetString("Alert.TwilioToken"))
res, exp, err := twilio.SendSMS(config.App.GetString("Alert.TwilioFrom"), config.App.GetString("Alert.TwilioTo"), message, "", "")
twilio := gotwilio.NewTwilioClient(config.App().GetString("Alert.TwilioSid"), config.App().GetString("Alert.TwilioToken"))
res, exp, err := twilio.SendSMS(config.App().GetString("Alert.TwilioFrom"), config.App().GetString("Alert.TwilioTo"), message, "", "")
if exp != nil || err != nil { if exp != nil || err != nil {
log.Error("sendTwilio error", "res", res, "exp", exp, "error", err) log.Error("sendTwilio error", "res", res, "exp", exp, "error", err)
} }
@ -58,7 +58,7 @@ func sendEmail(message string) {
if len(subject) > 80 { if len(subject) > 80 {
subject = subject[:80] subject = subject[:80]
} }
err := SendEmail(subject, message, config.App.GetStringSlice("Alert.EmailRecipients"))
err := SendEmail(subject, message, config.App().GetStringSlice("Alert.EmailRecipients"))
if err != nil { if err != nil {
log.Error("sendEmail error", "error", err, "message", message) log.Error("sendEmail error", "error", err, "message", message)
} }


+ 5
- 5
alert/email.go View File

@ -19,7 +19,7 @@ import (
// Convenience function // Convenience function
func SendEmail(subject, body string, tos []string) error { func SendEmail(subject, body string, tos []string) error {
email := Compose(subject, body) email := Compose(subject, body)
email.From = config.App.GetString("SMTP.User")
email.From = config.App().GetString("SMTP.User")
email.ContentType = "text/html; charset=utf-8" email.ContentType = "text/html; charset=utf-8"
email.AddRecipients(tos...) email.AddRecipients(tos...)
err := email.Send() err := email.Send()
@ -86,12 +86,12 @@ func (e *Email) Send() error {
auth := smtp.PlainAuth( auth := smtp.PlainAuth(
"", "",
config.App.GetString("SMTP.User"),
config.App.GetString("SMTP.Password"),
config.App.GetString("SMTP.Host"),
config.App().GetString("SMTP.User"),
config.App().GetString("SMTP.Password"),
config.App().GetString("SMTP.Host"),
) )
conn, err := smtp.Dial(fmt.Sprintf("%v:%v", config.App.GetString("SMTP.Host"), config.App.GetString("SMTP.Port")))
conn, err := smtp.Dial(fmt.Sprintf("%v:%v", config.App().GetString("SMTP.Host"), config.App().GetString("SMTP.Port")))
if err != nil { if err != nil {
return err return err
} }


+ 1
- 1
block/block.go View File

@ -24,7 +24,7 @@ type Block struct {
// Basic validation that doesn't involve state data. // Basic validation that doesn't involve state data.
func (b *Block) ValidateBasic(lastBlockHeight uint, lastBlockHash []byte, func (b *Block) ValidateBasic(lastBlockHeight uint, lastBlockHash []byte,
lastBlockParts PartSetHeader, lastBlockTime time.Time) error { lastBlockParts PartSetHeader, lastBlockTime time.Time) error {
if b.Network != config.App.GetString("Network") {
if b.Network != config.App().GetString("Network") {
return errors.New("Wrong Block.Header.Network") return errors.New("Wrong Block.Header.Network")
} }
if b.Height != lastBlockHeight+1 { if b.Height != lastBlockHeight+1 {


+ 1
- 1
cmd/gen_validator.go View File

@ -18,7 +18,7 @@ Paste the following JSON into your %v file
%v %v
`, `,
config.App.GetString("PrivValidatorFile"),
config.App().GetString("PrivValidatorFile"),
string(privValidatorJSONBytes), string(privValidatorJSONBytes),
) )
} }

+ 60
- 48
config/config.go View File

@ -7,13 +7,23 @@ import (
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
flag "github.com/spf13/pflag" flag "github.com/spf13/pflag"
"github.com/tendermint/confer" "github.com/tendermint/confer"
) )
var rootDir string
var App *confer.Config
var app *confer.Config
var appMtx sync.Mutex
func App() *confer.Config {
appMtx.Lock()
defer appMtx.Unlock()
if app == nil {
Init("")
}
return app
}
// NOTE: If you change this, maybe also change initDefaults() // NOTE: If you change this, maybe also change initDefaults()
var defaultConfig = `# This is a TOML config file. var defaultConfig = `# This is a TOML config file.
@ -75,44 +85,27 @@ var defaultGenesis = `
` `
// NOTE: If you change this, maybe also change defaultConfig // NOTE: If you change this, maybe also change defaultConfig
func initDefaults() {
App.SetDefault("Network", "tendermint_testnet0")
App.SetDefault("ListenAddr", "0.0.0.0:8080")
App.SetDefault("DB.Backend", "leveldb")
App.SetDefault("DB.Dir", rootDir+"/data")
App.SetDefault("Log.Stdout.Level", "info")
App.SetDefault("Log.File.Dir", rootDir+"/log")
App.SetDefault("Log.File.Level", "debug")
App.SetDefault("RPC.HTTP.ListenAddr", "127.0.0.1:8081")
App.SetDefault("GenesisFile", rootDir+"/genesis.json")
App.SetDefault("AddrBookFile", rootDir+"/addrbook.json")
App.SetDefault("PrivValidatorfile", rootDir+"/priv_validator.json")
}
// Check if a file exists; if not, ensure the directory is made and write the file
func checkWriteFile(configFile, contents string) {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
if strings.Index(configFile, "/") != -1 {
err := os.MkdirAll(filepath.Dir(configFile), 0700)
if err != nil {
fmt.Printf("Could not create directory: %v", err)
os.Exit(1)
}
}
err := ioutil.WriteFile(configFile, []byte(contents), 0600)
if err != nil {
fmt.Printf("Could not write config file: %v", err)
os.Exit(1)
}
fmt.Printf("Config file written to %v.\n", configFile)
}
func initDefaults(rootDir string) {
app.SetDefault("Network", "tendermint_testnet0")
app.SetDefault("ListenAddr", "0.0.0.0:8080")
app.SetDefault("DB.Backend", "leveldb")
app.SetDefault("DB.Dir", rootDir+"/data")
app.SetDefault("Log.Stdout.Level", "info")
app.SetDefault("Log.File.Dir", rootDir+"/log")
app.SetDefault("Log.File.Level", "debug")
app.SetDefault("RPC.HTTP.ListenAddr", "0.0.0.0:8081")
app.SetDefault("GenesisFile", rootDir+"/genesis.json")
app.SetDefault("AddrBookFile", rootDir+"/addrbook.json")
app.SetDefault("PrivValidatorfile", rootDir+"/priv_validator.json")
} }
func init() {
func Init(rootDir string) {
// Get RootDir // Get RootDir
rootDir = os.Getenv("TMROOT")
if rootDir == "" {
rootDir = os.Getenv("TMROOT")
}
if rootDir == "" { if rootDir == "" {
rootDir = os.Getenv("HOME") + "/.tendermint" rootDir = os.Getenv("HOME") + "/.tendermint"
} }
@ -124,15 +117,34 @@ func init() {
checkWriteFile(genesisFile, defaultGenesis) checkWriteFile(genesisFile, defaultGenesis)
// Initialize Config // Initialize Config
App = confer.NewConfig()
initDefaults()
app = confer.NewConfig()
initDefaults(rootDir)
paths := []string{configFile} paths := []string{configFile}
if err := App.ReadPaths(paths...); err != nil {
if err := app.ReadPaths(paths...); err != nil {
log.Warn("Error reading configuration", "paths", paths, "error", err) log.Warn("Error reading configuration", "paths", paths, "error", err)
} }
// Confused? // Confused?
// App.Debug()
// app.Debug()
}
// Check if a file exists; if not, ensure the directory is made and write the file
func checkWriteFile(configFile, contents string) {
if _, err := os.Stat(configFile); os.IsNotExist(err) {
if strings.Index(configFile, "/") != -1 {
err := os.MkdirAll(filepath.Dir(configFile), 0700)
if err != nil {
fmt.Printf("Could not create directory: %v", err)
os.Exit(1)
}
}
err := ioutil.WriteFile(configFile, []byte(contents), 0600)
if err != nil {
fmt.Printf("Could not write config file: %v", err)
os.Exit(1)
}
fmt.Printf("Config file written to %v.\n", configFile)
}
} }
func ParseFlags(args []string) { func ParseFlags(args []string) {
@ -141,20 +153,20 @@ func ParseFlags(args []string) {
// Declare flags // Declare flags
flags.BoolVar(&printHelp, "help", false, "Print this help message.") flags.BoolVar(&printHelp, "help", false, "Print this help message.")
flags.String("listen_addr", App.GetString("ListenAddr"), "Listen address. (0.0.0.0:0 means any interface, any port)")
flags.String("seed_node", App.GetString("SeedNode"), "Address of seed node")
flags.String("rpc_http_listen_addr", App.GetString("RPC.HTTP.ListenAddr"), "RPC listen address. Port required")
flags.String("listen_addr", app.GetString("ListenAddr"), "Listen address. (0.0.0.0:0 means any interface, any port)")
flags.String("seed_node", app.GetString("SeedNode"), "Address of seed node")
flags.String("rpc_http_listen_addr", app.GetString("RPC.HTTP.ListenAddr"), "RPC listen address. Port required")
flags.Parse(args) flags.Parse(args)
if printHelp { if printHelp {
flags.PrintDefaults() flags.PrintDefaults()
os.Exit(0) os.Exit(0)
} }
// Merge parsed flag values onto App.
App.BindPFlag("ListenAddr", flags.Lookup("listen_addr"))
App.BindPFlag("SeedNode", flags.Lookup("seed_node"))
App.BindPFlag("RPC.HTTP.ListenAddr", flags.Lookup("rpc_http_listen_addr"))
// Merge parsed flag values onto app.
app.BindPFlag("ListenAddr", flags.Lookup("listen_addr"))
app.BindPFlag("SeedNode", flags.Lookup("seed_node"))
app.BindPFlag("RPC.HTTP.ListenAddr", flags.Lookup("rpc_http_listen_addr"))
// Confused? // Confused?
//App.Debug()
//app.Debug()
} }

+ 1
- 1
consensus/state.go View File

@ -619,7 +619,7 @@ func (cs *ConsensusState) RunActionPropose(height uint, round uint) {
txs := cs.mempoolReactor.Mempool.GetProposalTxs() txs := cs.mempoolReactor.Mempool.GetProposalTxs()
block = &blk.Block{ block = &blk.Block{
Header: &blk.Header{ Header: &blk.Header{
Network: config.App.GetString("Network"),
Network: config.App().GetString("Network"),
Height: cs.Height, Height: cs.Height,
Time: time.Now(), Time: time.Now(),
Fees: 0, // TODO fees Fees: 0, // TODO fees


+ 10
- 10
daemon/daemon.go View File

@ -36,21 +36,21 @@ func NewNode() *Node {
stateDB := dbm.GetDB("state") stateDB := dbm.GetDB("state")
state := sm.LoadState(stateDB) state := sm.LoadState(stateDB)
if state == nil { if state == nil {
state = sm.MakeGenesisStateFromFile(stateDB, config.App.GetString("GenesisFile"))
state = sm.MakeGenesisStateFromFile(stateDB, config.App().GetString("GenesisFile"))
state.Save() state.Save()
} }
// Get PrivValidator // Get PrivValidator
var privValidator *sm.PrivValidator var privValidator *sm.PrivValidator
if _, err := os.Stat(config.App.GetString("PrivValidatorFile")); err == nil {
privValidator = sm.LoadPrivValidator(config.App.GetString("PrivValidatorFile"))
log.Info("Loaded PrivValidator", "file", config.App.GetString("PrivValidatorFile"), "privValidator", privValidator)
if _, err := os.Stat(config.App().GetString("PrivValidatorFile")); err == nil {
privValidator = sm.LoadPrivValidator(config.App().GetString("PrivValidatorFile"))
log.Info("Loaded PrivValidator", "file", config.App().GetString("PrivValidatorFile"), "privValidator", privValidator)
} else { } else {
log.Info("No PrivValidator found", "file", config.App.GetString("PrivValidatorFile"))
log.Info("No PrivValidator found", "file", config.App().GetString("PrivValidatorFile"))
} }
// Get PEXReactor // Get PEXReactor
book := p2p.NewAddrBook(config.App.GetString("AddrBookFile"))
book := p2p.NewAddrBook(config.App().GetString("AddrBookFile"))
pexReactor := p2p.NewPEXReactor(book) pexReactor := p2p.NewPEXReactor(book)
// Get MempoolReactor // Get MempoolReactor
@ -126,13 +126,13 @@ func Daemon() {
// Create & start node // Create & start node
n := NewNode() n := NewNode()
l := p2p.NewDefaultListener("tcp", config.App.GetString("ListenAddr"), false)
l := p2p.NewDefaultListener("tcp", config.App().GetString("ListenAddr"), false)
n.AddListener(l) n.AddListener(l)
n.Start() n.Start()
// If seedNode is provided by config, dial out. // If seedNode is provided by config, dial out.
if config.App.GetString("SeedNode") != "" {
addr := p2p.NewNetAddressString(config.App.GetString("SeedNode"))
if config.App().GetString("SeedNode") != "" {
addr := p2p.NewNetAddressString(config.App().GetString("SeedNode"))
peer, err := n.sw.DialPeerWithAddress(addr) peer, err := n.sw.DialPeerWithAddress(addr)
if err != nil { if err != nil {
log.Error("Error dialing seed", "error", err) log.Error("Error dialing seed", "error", err)
@ -145,7 +145,7 @@ func Daemon() {
} }
// Run the RPC server. // Run the RPC server.
if config.App.GetString("RPC.HTTP.ListenAddr") != "" {
if config.App().GetString("RPC.HTTP.ListenAddr") != "" {
rpc.SetRPCBlockStore(n.blockStore) rpc.SetRPCBlockStore(n.blockStore)
rpc.SetRPCConsensusState(n.consensusState) rpc.SetRPCConsensusState(n.consensusState)
rpc.SetRPCMempoolReactor(n.mempoolReactor) rpc.SetRPCMempoolReactor(n.mempoolReactor)


+ 3
- 3
db/db.go View File

@ -31,19 +31,19 @@ func GetDB(name string) DB {
if db != nil { if db != nil {
return db.(DB) return db.(DB)
} }
switch config.App.GetString("DB.Backend") {
switch config.App().GetString("DB.Backend") {
case DBBackendMemDB: case DBBackendMemDB:
db := NewMemDB() db := NewMemDB()
dbs.Set(name, db) dbs.Set(name, db)
return db return db
case DBBackendLevelDB: case DBBackendLevelDB:
db, err := NewLevelDB(path.Join(config.App.GetString("DB.Dir"), name+".db"))
db, err := NewLevelDB(path.Join(config.App().GetString("DB.Dir"), name+".db"))
if err != nil { if err != nil {
panic(err) panic(err)
} }
dbs.Set(name, db) dbs.Set(name, db)
return db return db
default: default:
panic(Fmt("Unknown DB backend: %v", config.App.GetString("DB.Backend")))
panic(Fmt("Unknown DB backend: %v", config.App().GetString("DB.Backend")))
} }
} }

+ 3
- 3
logger/log.go View File

@ -24,12 +24,12 @@ func init() {
// By default, there's a stdout terminal format handler. // By default, there's a stdout terminal format handler.
handlers = append(handlers, log15.LvlFilterHandler( handlers = append(handlers, log15.LvlFilterHandler(
getLevel(config.App.GetString("Log.Stdout.Level")),
getLevel(config.App().GetString("Log.Stdout.Level")),
log15.StreamHandler(os.Stdout, log15.TerminalFormat()), log15.StreamHandler(os.Stdout, log15.TerminalFormat()),
)) ))
// Maybe also write to a file. // Maybe also write to a file.
if _logFileDir := config.App.GetString("Log.File.Dir"); _logFileDir != "" {
if _logFileDir := config.App().GetString("Log.File.Dir"); _logFileDir != "" {
// Create log dir if it doesn't exist // Create log dir if it doesn't exist
err := os.MkdirAll(_logFileDir, 0700) err := os.MkdirAll(_logFileDir, 0700)
if err != nil { if err != nil {
@ -38,7 +38,7 @@ func init() {
} }
// File handler // File handler
handlers = append(handlers, log15.LvlFilterHandler( handlers = append(handlers, log15.LvlFilterHandler(
getLevel(config.App.GetString("Log.File.Level")),
getLevel(config.App().GetString("Log.File.Level")),
log15.Must.FileHandler(_logFileDir+"/tendermint.log", log15.LogfmtFormat()), log15.Must.FileHandler(_logFileDir+"/tendermint.log", log15.LogfmtFormat()),
)) ))
} }


+ 2
- 2
rpc/http_server.go View File

@ -17,9 +17,9 @@ import (
func StartHTTPServer() { func StartHTTPServer() {
initHandlers() initHandlers()
log.Info(Fmt("Starting RPC HTTP server on %s", config.App.GetString("RPC.HTTP.ListenAddr")))
log.Info(Fmt("Starting RPC HTTP server on %s", config.App().GetString("RPC.HTTP.ListenAddr")))
go func() { go func() {
log.Crit("RPC HTTPServer stopped", "result", http.ListenAndServe(config.App.GetString("RPC.HTTP.ListenAddr"), RecoverAndLogHandler(http.DefaultServeMux)))
log.Crit("RPC HTTPServer stopped", "result", http.ListenAndServe(config.App().GetString("RPC.HTTP.ListenAddr"), RecoverAndLogHandler(http.DefaultServeMux)))
}() }()
} }


+ 2
- 2
rpc/net.go View File

@ -17,14 +17,14 @@ func StatusHandler(w http.ResponseWriter, r *http.Request) {
LatestBlockHeight uint LatestBlockHeight uint
LatestBlockTime int64 // nano LatestBlockTime int64 // nano
Network string Network string
}{genesisHash, latestBlockHash, latestHeight, latestBlockTime, config.App.GetString("Network")})
}{genesisHash, latestBlockHash, latestHeight, latestBlockTime, config.App().GetString("Network")})
} }
func NetInfoHandler(w http.ResponseWriter, r *http.Request) { func NetInfoHandler(w http.ResponseWriter, r *http.Request) {
o, i, _ := p2pSwitch.NumPeers() o, i, _ := p2pSwitch.NumPeers()
numPeers := o + i numPeers := o + i
listening := p2pSwitch.IsListening() listening := p2pSwitch.IsListening()
network := config.App.GetString("Network")
network := config.App().GetString("Network")
WriteAPIResponse(w, API_OK, struct { WriteAPIResponse(w, API_OK, struct {
NumPeers int NumPeers int
Listening bool Listening bool


+ 1
- 1
state/priv_validator.go View File

@ -68,7 +68,7 @@ func GenPrivValidator() *PrivValidator {
LastHeight: 0, LastHeight: 0,
LastRound: 0, LastRound: 0,
LastStep: stepNone, LastStep: stepNone,
filename: config.App.GetString("PrivValidatorFile"),
filename: config.App().GetString("PrivValidatorFile"),
} }
} }


+ 1
- 1
state/state_test.go View File

@ -55,7 +55,7 @@ func TestCopyState(t *testing.T) {
func makeBlock(t *testing.T, state *State, commits []blk.Commit, txs []blk.Tx) *blk.Block { func makeBlock(t *testing.T, state *State, commits []blk.Commit, txs []blk.Tx) *blk.Block {
block := &blk.Block{ block := &blk.Block{
Header: &blk.Header{ Header: &blk.Header{
Network: config.App.GetString("Network"),
Network: config.App().GetString("Network"),
Height: state.LastBlockHeight + 1, Height: state.LastBlockHeight + 1,
Time: state.LastBlockTime.Add(time.Minute), Time: state.LastBlockTime.Add(time.Minute),
Fees: 0, Fees: 0,


Loading…
Cancel
Save