github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/cmd/pebble_monitor/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"time"
     8  
     9  	"github.com/machinefi/w3bstream/pkg/depends/base/consts"
    10  	base "github.com/machinefi/w3bstream/pkg/depends/base/types"
    11  	"github.com/machinefi/w3bstream/pkg/depends/conf/postgres"
    12  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder"
    13  	"github.com/machinefi/w3bstream/pkg/depends/x/misc/timer"
    14  	"github.com/machinefi/w3bstream/pkg/models"
    15  	"github.com/machinefi/w3bstream/pkg/modules/robot_notifier"
    16  	"github.com/machinefi/w3bstream/pkg/modules/robot_notifier/lark"
    17  	"github.com/machinefi/w3bstream/pkg/types"
    18  )
    19  
    20  func main() {
    21  	ep := base.Endpoint{}
    22  	err := ep.UnmarshalText([]byte("postgres://w3bstream:8ShjeQUc@d';d4n@34.172.94.245:5432/w3bstream?sslmode=disable"))
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  
    27  	nc := &types.RobotNotifierConfig{
    28  		Vendor: "lark",
    29  		Env:    "prod",
    30  		URL:    "https://open.larksuite.com/open-apis/bot/v2/hook/f8d7cd45-4b45-40fe-9635-5e2f85e19155",
    31  		Secret: "vztL7BIOyDw10XEd9H5B6",
    32  		SignFn: nil,
    33  	}
    34  	nc.Init()
    35  
    36  	_ = os.Setenv(consts.EnvProjectName, "srv-pebble-pending-monitor")
    37  	_ = os.Setenv(consts.EnvProjectVersion, "0.0.1")
    38  
    39  	ctx := types.WithRobotNotifierConfig(context.Background(), nc)
    40  
    41  	db := postgres.Endpoint{
    42  		Master:   ep,
    43  		PoolSize: 1,
    44  		Database: models.DB,
    45  	}
    46  	db.SetDefault()
    47  	if err := db.Init(); err != nil {
    48  		panic(err)
    49  	}
    50  
    51  	count := int64(0)
    52  	msg := ""
    53  	interval := time.Minute
    54  	threshold := int64(100)
    55  
    56  	for {
    57  		cost := timer.Start()
    58  		err = db.QueryAndScan(builder.Expr("SELECT count(1) FROM applet_management.t_event WHERE f_project_id = 1456942923637714945 AND f_stage = 1"), &count)
    59  		du := cost()
    60  		now := time.Now().Format("2006-01-02T15:04:05")
    61  
    62  		if err != nil {
    63  			msg = fmt.Sprintf("[%s] query failed: %v database cost: %ds", now, err, int(du.Seconds()))
    64  			// fmt.Println(msg)
    65  			time.Sleep(interval)
    66  			continue
    67  		}
    68  		msg = fmt.Sprintf("[%s] pebble task pending: %d query cost: %ds", now, count, int(du.Seconds()))
    69  		fmt.Println(msg)
    70  		if count > threshold {
    71  			goto PUSH
    72  		}
    73  		time.Sleep(interval)
    74  		continue
    75  	PUSH:
    76  		content, _ := lark.Build(ctx, "Pebble Task Pending", "WARNING", msg)
    77  		if len(content) > 0 {
    78  			_ = robot_notifier.Push(ctx, content)
    79  		}
    80  		time.Sleep(interval)
    81  		continue
    82  	}
    83  }