Commit 22cfb9c7 authored by 李伟@五瓣科技's avatar 李伟@五瓣科技

Initial commit

parents
Pipeline #518 failed with stages
package main
import (
"context"
"math/big"
"os"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/tendermint/tendermint/libs/log"
)
type Client struct {
cliCtx *ethclient.Client
timerTicker *TimerTicker
Logger log.Logger
Moniker string
}
func NewClient(nodeRpc string) (*Client, error) {
//cliCtx := context.NewCLIContext().WithNodeURI("tcp://192.168.3.200:26657")
client, err := ethclient.Dial(nodeRpc)
if err != nil {
return nil, err
}
cli := Client{
cliCtx: client,
Logger: log.NewTMLogger(os.Stdout),
}
//cli.Moniker = status.NodeInfo.Moniker
cli.timerTicker = NewTimerticker(&cli)
cli.timerTicker.OnStart()
return &cli, nil
}
// LatestBlockHeight returns the latest block height on the active chain
func (c *Client) LatestBlockHeight() (*big.Int, error) {
header, err := c.cliCtx.HeaderByNumber(context.Background(), nil)
if err != nil {
return nil, err
}
return header.Number, nil
}
module github.com/halleproject/node-monitor
go 1.14
require (
github.com/CaduceusMetaverseProtocol/CMPChain v0.0.0-20220408090237-8aa6d10b33c0 // indirect
github.com/aliyun/alibaba-cloud-sdk-go v1.61.535
github.com/cosmos/cosmos-sdk v0.34.4-0.20200406170659-df5badaf4c2b
github.com/cosmos/ethermint v0.0.0-00010101000000-000000000000
github.com/ethereum/go-ethereum v1.9.13
github.com/spf13/cobra v1.0.0
github.com/tendermint/tendermint v0.33.3
)
replace github.com/cosmos/cosmos-sdk => github.com/halleproject/cosmos-sdk v0.34.4-0.1.0
replace github.com/cosmos/ethermint => github.com/halleproject/hallechain v0.1.4
This diff is collapsed.
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
var nodeRpc string
func init() {
rootCmd.Flags().StringVarP(&nodeRpc, "nodeRpc", "n", "http://127.0.0.1:8545", "monitor the node by the address")
}
var rootCmd = &cobra.Command{
Use: "node-monitor",
Short: "monitor halle chain",
Run: func(cmd *cobra.Command, args []string) {
cli, err := NewClient(nodeRpc)
if err != nil {
panic(err)
}
cli.Monitor()
},
}
package main
// import (
// "encoding/json"
// "fmt"
// "testing"
// "time"
// )
//
// func TestValidatorsByHeight(t *testing.T) {
//
// height := 79895
//
// cfg := NodeConfig{
// RPCNode: "tcp://192.168.3.200:26657",
// APIServerEndpoint: "http://192.168.3.100:8545",
// }
//
// cli := NewClient(&cfg)
//
// valSet, err := cli.ValidatorSet(int64(height))
// if err != nil {
// t.Errorf("validatorset error: %v \n", err.Error())
// }
//
// jsonValSetAsJson, err := json.MarshalIndent(valSet, "", "\t")
// if err != nil {
// t.Errorf("validator json marshal err: %v \n", err.Error())
// }
//
// t.Logf("height: %v \n %s \n", height, jsonValSetAsJson)
//
// }
//
// //Validators()
//
// func TestValidatorsOld(t *testing.T) {
//
// cfg := NodeConfig{
// RPCNode: "tcp://192.168.3.200:26657",
// APIServerEndpoint: "http://192.168.3.100:8545",
// }
//
// cli := NewClient(&cfg)
//
// valSet, err := cli.Validators()
// if err != nil {
// t.Errorf("validatorset error: %v \n", err.Error())
// }
//
// jsonValSetAsJson, err := json.MarshalIndent(valSet, "", "\t")
// if err != nil {
// t.Errorf("validator json marshal err: %v \n", err.Error())
// }
//
// t.Logf("height: %s \n", jsonValSetAsJson)
//
// }
//
// func TestAlarm(t *testing.T) {
//
// ticker1 := time.NewTicker(1 * time.Second)
// i := 1
// for c := range ticker1.C {
// i++
// fmt.Println(c.Format("2006/01/02 15:04:05.999999999"))
// if i > 5 {
// ticker1.Stop()
// break
// }
// }
// fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"), " 1 Finished.")
//
// i = 1
// ticker2 := time.AfterFunc(1*time.Second, func() {
// i++
// fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"))
// })
//
// for {
// select {
// case <-ticker2.C:
// fmt.Println("nsmei")
// case <-time.After(3 * time.Second):
// if i <= 5 {
// ticker2.Reset(1 * time.Second)
// continue
// }
// goto BRK
// }
// BRK:
// ticker2.Stop()
// break
// }
// fmt.Println(time.Now().Format("2006/01/02 15:04:05.999999999"), " 2 Finished.")
// }
package main
import (
"fmt"
"math/big"
"time"
)
func (cli *Client) Monitor() {
lastHeight := big.NewInt(0)
lastTime := time.Now()
apiErrTry := 0
for {
if apiErrTry > 5 {
cli.Logger.Debug("query api failed, send alarm !!!", "try times", apiErrTry)
alarm := AlarmInfo{
AlarmType: Query,
Detail: fmt.Sprintf("query failed, try times: %v", apiErrTry),
Time: time.Now(),
}
cli.timerTicker.Data <- alarm
apiErrTry = 0
}
height, err := cli.LatestBlockHeight()
if err != nil {
cli.Logger.Debug("faild to query block height")
apiErrTry++
time.Sleep(1 * time.Second)
continue
}
if lastHeight.Cmp(height) == 0 {
alarmTime := time.Now()
elapse := alarmTime.Sub(lastTime).Seconds()
if elapse < 120 {
time.Sleep(5 * time.Second)
continue
}
cli.Logger.Debug(fmt.Sprintf("Block height %v is not increased, take time: %v seconds.", height, elapse))
alarm := AlarmInfo{
AlarmType: BlockHeight,
Detail: fmt.Sprintf("Block %v doesnot increased, take time: %v seconds.", height, elapse),
Time: time.Now(),
}
cli.timerTicker.Data <- alarm
time.Sleep(5 * time.Second)
continue
}
lastHeight = height
lastTime = time.Now()
apiErrTry = 0
}
}
package main
import (
"encoding/json"
"fmt"
"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
)
func (c *Client) SendAlarm(datas []AlarmInfo) (string, error) {
c.Logger.Debug("param", "datas len", len(datas))
if len(datas) == 1 {
c.Logger.Debug(datas[0].String())
return SendSMS(c.Moniker, datas[0].AlarmType.String(), "15611084264,18001052350")
}
var qC, bC, vC uint
for _, v := range datas {
switch v.AlarmType {
case Query:
qC++
case BlockHeight:
bC++
case Validator:
vC++
}
}
c.Logger.Debug(fmt.Sprintf("%v%v", c.Moniker, fmt.Sprintf("query: %d block: %d val: %d", qC, bC, vC)))
//return timeStr, nil
return SendSMS(c.Moniker, fmt.Sprintf("q:%db:%d", qC, bC), "15611084264,18001052350")
}
type content struct {
//Name string `json:"name"`
Detail string `json:"code"`
}
func SendSMS(node, detail string, phone string) (string, error) {
client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", "LTAIgKB4YutaanZN", "FulRUnVp1xPRUKWgOjh3P7niYGgHet")
if err != nil {
return "", err
}
request := dysmsapi.CreateSendSmsRequest()
request.Scheme = "https"
request.SignName = "福利墙"
request.TemplateCode = "SMS_95550089"
cnt := content{detail}
cByte, _ := json.Marshal(cnt)
fmt.Printf("%s\n",cByte)
request.TemplateParam = string(cByte)
//continue
request.PhoneNumbers = phone
resp, err := client.SendSms(request)
if err != nil {
fmt.Println(phone, "sms failed : ", err.Error())
return "", err
}
return resp.BaseResponse.String(), nil
}
package main
import (
"fmt"
"testing"
)
func TestSendSMS(t *testing.T) {
fmt.Println("测试短信发送")
res, err := SendSMS("name", "1234234" ,"15611084264")
if err != nil {
t.Error(err)
}
t.Log(res)
}
package main
import (
"fmt"
"os"
"time"
"github.com/tendermint/tendermint/libs/log"
)
var (
tickTockBufferSize = 100000
)
type AlarmType uint8
func (a AlarmType) String() string {
switch a {
case 0:
return "query"
case 1:
return "Block"
case 2:
return "Val"
default:
return "just support 0,1,2"
}
}
const (
Query AlarmType = iota
BlockHeight
Validator
)
type AlarmInfo struct {
AlarmType AlarmType
Detail string
Time time.Time
}
func (ai *AlarmInfo) String() string {
return fmt.Sprintf("alarm type: %s detail: %s time: %s ", ai.AlarmType, ai.Detail, ai.Time.Format("2006-01-02 15:04:05"))
}
type TimerTicker struct {
ticker *time.Ticker
Data chan AlarmInfo
Logger log.Logger
Cli *Client
}
func NewTimerticker(cli *Client) *TimerTicker {
tt := &TimerTicker{
Cli: cli,
ticker: time.NewTicker(10 * time.Second),
Data: make(chan AlarmInfo, tickTockBufferSize),
Logger: log.NewTMLogger(os.Stdout),
}
//tt.stopTimer() // don't want to fire until the first scheduled timeout
return tt
}
func (t *TimerTicker) OnStart() error {
go t.timeoutRoutine()
return nil
}
// stop the timer and drain if necessary
func (t *TimerTicker) stopTicker() {
if t.ticker != nil {
t.ticker.Stop()
}
}
func (t *TimerTicker) timeoutRoutine() {
t.Logger.Debug("Starting timeout routine")
var ti time.Time
var count uint64
for {
select {
case newti := <-t.ticker.C:
t.Logger.Debug("Received tick", "old_ti", ti, "new_ti", newti)
ti = newti
l := len(t.Data)
if l == 0 {
//count = 0
if count != 0 {
t.ticker = time.NewTicker(10 * time.Second)
count = 0
}
continue
}
datas := make([]AlarmInfo, 0)
t.Logger.Debug("datas len", "len", l)
for i := 0; i < l; i++ {
data, ok := <-t.Data
if !ok {
return
}
datas = append(datas, data)
}
count++
switch count {
case 1:
t.ticker = time.NewTicker(time.Minute)
case 3:
t.ticker = time.NewTicker(10 * time.Minute)
case 6:
t.ticker = time.NewTicker(time.Hour)
}
t.Logger.Debug("send msg.", "times", count)
res, err := t.Cli.SendAlarm(datas)
if err != nil {
t.Logger.Error(err.Error())
}
t.Logger.Debug(res, "times", count)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment