cauto 2 years ago
parent
commit
b04927f357

+ 10 - 0
api/v1/node.go

@@ -90,3 +90,13 @@ type NodeStatusReq struct {
 type NodeStatusRes struct {
 	NodeItme []*model.UserItem
 }
+
+type NodeConfigReq struct {
+	g.Meta   `path:"/nodeconfig" tags:"nodeconfig" method:"get" summary:"节点配置请求"`
+	ServerId int    `p:"serverid"`
+	SshCom   string `p:"sshcom"`
+	SshPass  string `p:"sshpass"`
+	SshUser  string `p:"sshuser"`
+}
+type NodeConfigRes struct {
+}

+ 1 - 1
hack/config.yaml

@@ -14,7 +14,7 @@ gfcli:
     extra: ""
   gen:
     dao:
-      - link: "mysql:root:123456@tcp(127.0.0.1:3306)/nodeMonitor"
+      - link: "mysql:nodemonitor:m4A6zLaDnRCNd4xw@tcp(156.234.193.212:33060)/nodemonitor?loc=Local&parseTime=true"
         # tables: "sys_user"
         # removePrefix: "gf_"
         descriptionTag: true

+ 35 - 2
internal/cmd/cmd.go

@@ -2,12 +2,17 @@ package cmd
 
 import (
 	"context"
+	"fmt"
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/net/ghttp"
 	"github.com/gogf/gf/v2/net/goai"
 	"github.com/gogf/gf/v2/os/gcmd"
+	"github.com/gogf/gf/v2/os/gcron"
+	"github.com/gogf/gf/v2/os/glog"
 	"nodeMonitor/internal/consts"
 	"nodeMonitor/internal/router"
+	"nodeMonitor/internal/service"
+	"nodeMonitor/internal/task"
 )
 
 var (
@@ -24,6 +29,16 @@ var (
 			// Custom enhance API document.
 			enhanceOpenAPIDoc(s)
 
+			err = StartPingStart(ctx)
+			if err != nil {
+				return err
+			}
+
+			defer func() {
+				gcron.Stop("ping_status")
+				gcron.Remove("ping_status")
+			}()
+
 			s.Run()
 			return nil
 		},
@@ -46,7 +61,25 @@ func enhanceOpenAPIDoc(s *ghttp.Server) {
 	}
 }
 
-func StartPingStart(ctx context.Context) string {
+func StartPingStart(ctx context.Context) error {
+	nodePing, err := g.Cfg().Get(ctx, "node.nodePing")
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return err
+	}
+
+	pingconfig, err := service.PingConfig().Get(ctx)
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return err
+	}
+
+	if nodePing.Int() == 1 {
+		s := fmt.Sprintf("*/%d * * * * *", pingconfig.PingTime)
+		_, err = gcron.AddSingleton(ctx, s, func(ctx context.Context) {
+			go task.Ping(ctx)
+		}, "ping_status")
+	}
 
-	return ""
+	return nil
 }

+ 1 - 1
internal/controller/Node.go

@@ -94,7 +94,7 @@ func (c *sNode) Start(ctx context.Context, req *v1.NodeCronStartReq) (res *v1.No
 	} else {
 		s := fmt.Sprintf("*/%d * * * * *", StartTime)
 		_, err = gcron.AddSingleton(ctx, s, func(ctx context.Context) {
-			go task.Ping(ctx)
+			go task.PingStatus(ctx)
 		}, taskName.String())
 		res.RetEntry = gcron.Entries()
 		res.RetCronCount = gcron.Size()

+ 54 - 0
internal/logic/nodeconfig/nodeConfig.go

@@ -0,0 +1,54 @@
+package nodeconfig
+
+import (
+	"github.com/gogf/gf/v2/database/gdb"
+	"github.com/gogf/gf/v2/frame/g"
+	"golang.org/x/net/context"
+	"nodeMonitor/internal/dao"
+	"nodeMonitor/internal/model"
+	"nodeMonitor/internal/model/do"
+	"nodeMonitor/internal/model/entity"
+	"nodeMonitor/internal/service"
+)
+
+type (
+	sNodeConfig struct{}
+)
+
+func init() {
+	service.RegisterNodeConfig(New())
+}
+func New() *sNodeConfig {
+	return &sNodeConfig{}
+}
+
+// Get 获取节点配置
+func (c *sNodeConfig) Get(ctx context.Context, id int) (nodeConfig *entity.Nodeconfig, err error) {
+	var node = new(entity.Nodeconfig)
+	err = dao.Nodeconfig.Ctx(ctx).Where("serverid", id).Scan(&node)
+	nodeConfig = node
+	return
+}
+
+// Create 创建节点配置
+func (c *sNodeConfig) Create(ctx context.Context, input model.NodeConfigAndEditCreateInput) error {
+	return dao.Nodeconfig.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
+		_, err := dao.Nodeconfig.Ctx(ctx).Data(do.Nodeconfig{
+			Serverid:    input.ServerId,
+			Sshcommand:  input.SshCom,
+			Sshpassword: input.SshPass,
+			Sshusername: input.SshUser,
+		}).Insert()
+		return err
+	})
+}
+
+// Edit 编辑节点配置
+func (c *sNodeConfig) Edit(ctx context.Context, input model.NodeConfigAndEditCreateInput) error {
+	_, err := dao.Nodeconfig.Ctx(ctx).Where("serverid", input.ServerId).Update(g.Map{
+		"sshcommand":  input.SshCom,
+		"sshpassword": input.SshPass,
+		"sshusername": input.SshUser,
+	})
+	return err
+}

+ 39 - 0
internal/logic/pingconfig/pingConfig.go

@@ -0,0 +1,39 @@
+package pingconfig
+
+import (
+	"golang.org/x/net/context"
+	"nodeMonitor/internal/dao"
+	"nodeMonitor/internal/model"
+	"nodeMonitor/internal/model/do"
+	"nodeMonitor/internal/model/entity"
+	"nodeMonitor/internal/service"
+)
+
+type (
+	sPingConfig struct{}
+)
+
+func init() {
+	service.RegisterPingConfig(New())
+}
+
+func New() *sPingConfig {
+	return &sPingConfig{}
+}
+
+// Edit 编辑节点配置
+func (c *sPingConfig) Edit(ctx context.Context, input model.PingConfigEditInput) error {
+	_, err := dao.Nodeconfig.Ctx(ctx).Update(do.Pingconfig{
+		NodeDie:   input.NodeDie,
+		NodeCount: input.NodeCount,
+		NodeLoos:  input.NodeLoos,
+	})
+	return err
+}
+
+// Get   编辑节点配置
+func (c *sPingConfig) Get(ctx context.Context) (*entity.Pingconfig, error) {
+	var pingconfig = new(entity.Pingconfig)
+	err := dao.Nodeconfig.Ctx(ctx).Scan(&pingconfig)
+	return pingconfig, err
+}

+ 14 - 0
internal/model/node.go

@@ -14,6 +14,20 @@ type NodeCreateInput struct {
 	UrlStatus int
 }
 
+type NodeConfigAndEditCreateInput struct {
+	ServerId int
+	SshCom   string
+	SshPass  string
+	SshUser  string
+}
+
+// node_count //node_loos
+type PingConfigEditInput struct {
+	NodeDie   int
+	NodeCount int
+	NodeLoos  int
+}
+
 type NodeEditInput struct {
 	Id        int
 	Name      string

+ 7 - 1
internal/router/router.go

@@ -5,9 +5,15 @@ import (
 	"nodeMonitor/internal/controller"
 )
 
+func MiddlewareCORS(r *ghttp.Request) {
+	corsOptions := r.Response.DefaultCORSOptions()
+	//corsOptions.AllowDomain = []string{"goframe.org", "baidu.com"}
+	r.Response.CORS(corsOptions)
+	r.Middleware.Next()
+}
 func BindController(group *ghttp.RouterGroup) {
 	group.Group("/api/v1", func(group *ghttp.RouterGroup) {
-		group.Middleware(ghttp.MiddlewareHandlerResponse)
+		group.Middleware(ghttp.MiddlewareHandlerResponse, MiddlewareCORS)
 		//group.Middleware(middleware.Middleware().CORS)
 		//group.Middleware(ghttp.MiddlewareCORS())
 		NodeRouter(group)

+ 18 - 11
internal/task/ping.go

@@ -31,38 +31,43 @@ func Ping(ctx context.Context) {
 	}
 
 	wg.Wait()
-	go PingStatus(ctx)
+	//go PingStatus(ctx)
 }
 
 func PingStatus(ctx context.Context) {
-
+	var wg sync.WaitGroup
 	nodeList, err := service.Node().GetNode(ctx)
 	if err != nil {
 		glog.Debug(ctx, err.Error())
 		return
 	}
 	for _, target := range nodeList {
-		CheckNodeStatus(ctx, target)
+		wg.Add(1)
+		go CheckNodeStatus(ctx, target, &wg)
 	}
-
+	wg.Wait()
 }
 
 func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, hostPort int, serverid int) {
 	//var ipSlice []string
 	//ipSlice = append(ipSlice, "kdvkr-02.xyz")
 	//ipSlice = append(ipSlice, "kdvkr-04.xyz")
-	pingCount, err := g.Cfg().Get(ctx, "node.pingCount")
+	//pingCount, err := g.Cfg().Get(ctx, "node.pingCount")
+	//if err != nil {
+	//	glog.Debug(ctx, err.Error())
+	//	return
+	//}
+	pingconfig, err := service.PingConfig().Get(ctx)
 	if err != nil {
 		glog.Debug(ctx, err.Error())
 		return
 	}
-
 	stat := model.PingSt{}
 	stat.MinDelay = -1
 	lossPK := 0
 	addr, err := net.ResolveIPAddr("ip", t)
 	if err == nil {
-		for i := 0; i < pingCount.Int(); i++ {
+		for i := 0; i < pingconfig.NodeCount; i++ {
 			starttime := time.Now().UnixNano()
 
 			var rest nettools.IPingResult
@@ -86,7 +91,7 @@ func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, h
 				}
 				stat.RevcPk = stat.RevcPk + 1
 			} else {
-				//glog.Debug(ctx, "[func:StartPing IcmpPing] ID:", i, " IP:", addr, "| err:", rest.Error())
+				glog.Debug(ctx, "[func:StartPing IcmpPing] ID:", i, " IP:", addr, "| err:", rest.Error())
 				lossPK = lossPK + 1
 			}
 			stat.SendPk = stat.SendPk + 1
@@ -99,7 +104,7 @@ func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, h
 		} else {
 			stat.AvgDelay = 0.0
 		}
-		//glog.Debug(ctx, "[func:IcmpPing] Finish Addr:", addr, " MaxDelay:", stat.MaxDelay, " MinDelay:", stat.MinDelay, " AvgDelay:", stat.AvgDelay, " Revc:", stat.RevcPk, " LossPK:", stat.LossPk)
+		glog.Debug(ctx, "[func:IcmpPing] Finish Addr:", addr, " MaxDelay:", stat.MaxDelay, " MinDelay:", stat.MinDelay, " AvgDelay:", stat.AvgDelay, " Revc:", stat.RevcPk, " LossPK:", stat.LossPk)
 	} else {
 		stat.AvgDelay = 0.00
 		stat.MinDelay = 0.00
@@ -107,7 +112,7 @@ func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, h
 		stat.SendPk = 0
 		stat.RevcPk = 0
 		stat.LossPk = 100
-		//glog.Debug(ctx, "[func:IcmpPing] Finish Addr:", addr, " Unable to resolve destination host")
+		glog.Debug(ctx, "[func:IcmpPing] Finish Addr:", addr, " Unable to resolve destination host")
 	}
 
 	//添加到数据库
@@ -132,7 +137,7 @@ func AddPingLog(ctx context.Context, pingres model.PingSt, addr string, serverid
 	return
 }
 
-func CheckNodeStatus(ctx context.Context, target *entity.Node) {
+func CheckNodeStatus(ctx context.Context, target *entity.Node, wg *sync.WaitGroup) {
 
 	glog.Debug(ctx, "start url req .....")
 	//获取不通的IP进程url请求
@@ -167,6 +172,8 @@ func CheckNodeStatus(ctx context.Context, target *entity.Node) {
 		}
 	}
 
+	wg.Done()
+
 }
 
 func SSHTaskCommand(ctx context.Context, host string, port int) {

+ 5 - 1
manifest/config/config.yaml

@@ -31,7 +31,8 @@ database:
     Path: "resource/log/sql"
 
   default:
-    link: "mysql:nodeMonitor:NNmeANyDyftp2Nan@tcp(127.0.0.1:8366)/nodemonitor?loc=Local&parseTime=true"
+    link: "mysql:nodeMonitor:m4A6zLaDnRCNd4xw@tcp(127.0.0.1:3306)/nodemonitor?loc=Local&parseTime=true"
+    #link: "mysql:nodeMonitor:m4A6zLaDnRCNd4xw@tcp(127.0.0.1:3306)/nodemonitor?loc=Local&parseTime=true"
     debug: true
     charset: "utf8mb4" #数据库编码
     dryRun: false #空跑
@@ -49,6 +50,9 @@ node:
   sshCommand: "" #用于执行ssh 命令
   sshPassword: "" #ssh密码
   sshUsername: "root"
+  nodePing: 1 #用于表示是不是检测PING的节点
+
+
 #gfToken:
 #  cacheKey: "gfToken_"
 #  timeOut: 10800

+ 17 - 0
manifest/node.service

@@ -0,0 +1,17 @@
+[Unit]
+# 单元描述
+Description=node
+
+[Service]
+Type=simple
+# 程序执行的目录
+WorkingDirectory=/www/wwwroot/nodeMonitor
+# 启动的脚本命令
+ExecStart=/www/wwwroot/nodeMonitor/nodeMonitor
+# 重启条件
+Restart=always
+# 几秒后重启
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target

+ 17 - 0
manifest/nodeping/node.service

@@ -0,0 +1,17 @@
+[Unit]
+# 单元描述
+Description=node
+
+[Service]
+Type=simple
+# 程序执行的目录
+WorkingDirectory=/root/nodeMonitor
+# 启动的脚本命令
+ExecStart=/root/nodeMonitor/nodeMonitor
+# 重启条件
+Restart=always
+# 几秒后重启
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target

+ 11 - 0
manifest/nodeping/node.sh

@@ -0,0 +1,11 @@
+echo net.ipv4.ping_group_range = 0 2147483647  /etc/sysctl.conf
+sudo sysctl --system
+wget
+rm -rf nodeMonitor
+mkdir nodeMonitor
+unzip -d /nodeMonitor nodemonitor.zip
+mv node.service /etc/systemd/system/node.service
+systemctl daemon-reload
+systemctl start node
+systemctl status node
+systemctl enable node