Browse Source

Merge remote-tracking branch 'origin/master'

cauto 2 years ago
parent
commit
742fec9478

+ 3 - 1
api/v1/hello.go

@@ -2,11 +2,13 @@ package v1
 
 import (
 	"github.com/gogf/gf/v2/frame/g"
+	"nodeMonitor/internal/model"
 )
 
 type HelloReq struct {
 	g.Meta `path:"/hello" tags:"Hello" method:"get" summary:"You first hello api"`
 }
 type HelloRes struct {
-	g.Meta `mime:"application/json" example:"json"`
+	g.Meta   `mime:"application/json" example:"json"`
+	NodeItme []*model.NodeItme
 }

+ 1 - 1
api/v1/node.go

@@ -22,7 +22,7 @@ type NodeRes struct {
 
 type NodeDelReq struct {
 	g.Meta `path:"/del" tags:"del" method:"post" summary:"删除节点"`
-	Host   string `p:"host" v:"required#节点不能为空"`
+	Id     int `p:"id" v:"required#节点Id不能为空"`
 }
 
 type NodeDelRes struct {

+ 28 - 51
db/nodeMonitor.sql

@@ -1,53 +1,30 @@
-/*
- Navicat Premium Data Transfer
+create table node
+(
+    id         int auto_increment comment 'ID主键自动添加'
+        primary key,
+    name       varchar(128)  not null comment '服务器名称',
+    host       varchar(20)   not null comment '服务器IP',
+    port       int           not null comment '服务器端口',
+    url        text          not null comment '服务器切换地址',
+    update_at  datetime      null comment '更新时间',
+    create_at  datetime      null comment '创建时间',
+    ping_type  int default 0 not null comment '服务器延迟类型 0 icmp 1 tcp',
+    url_status int           null comment '用于表示url是否执行完成',
+    node_ms    int default 0 null comment '节点延迟'
+)
+    charset = utf8mb4;
 
- Source Server         : localhost
- Source Server Type    : MySQL
- Source Server Version : 50734
- Source Host           : localhost:3306
- Source Schema         : nodeMonitor
+create table pinglog
+(
+    id        int auto_increment
+        primary key,
+    maxdelay  varchar(64) null comment '最大延迟',
+    mindelay  varchar(64) null comment '最小延迟',
+    avgdelay  varchar(64) null comment '平均延迟',
+    losspk    varchar(64) null comment '丢包率',
+    update_at datetime    null comment '更新时间',
+    create_at datetime    null comment '创建时间',
+    serverid  int         null comment '服务器ID'
+)
+    charset = utf8mb4;
 
- Target Server Type    : MySQL
- Target Server Version : 50734
- File Encoding         : 65001
-
- Date: 03/11/2022 16:23:13
-*/
-
-SET NAMES utf8mb4;
-SET FOREIGN_KEY_CHECKS = 0;
-
--- ----------------------------
--- Table structure for node
--- ----------------------------
-DROP TABLE IF EXISTS `node`;
-CREATE TABLE `node` (
-  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID主键自动添加',
-  `name` varchar(128) NOT NULL COMMENT '服务器名称',
-  `host` varchar(20) NOT NULL COMMENT '服务器IP',
-  `port` int(11) NOT NULL COMMENT '服务器端口',
-  `url` text NOT NULL COMMENT '服务器切换地址',
-  `update_at` datetime DEFAULT NULL COMMENT '更新时间',
-  `create_at` datetime DEFAULT NULL COMMENT '创建时间',
-  `ping_type` int(11) NOT NULL DEFAULT '0' COMMENT '服务器延迟类型 0 icmp 1 tcp',
-  `url_status` int(11) DEFAULT NULL COMMENT '用于表示url是否执行完成',
-  PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
-
--- ----------------------------
--- Table structure for pinglog
--- ----------------------------
-DROP TABLE IF EXISTS `pinglog`;
-CREATE TABLE `pinglog` (
-  `id` int(11) NOT NULL AUTO_INCREMENT,
-  `maxdelay` varchar(64) DEFAULT NULL COMMENT '最大延迟',
-  `mindelay` varchar(64) DEFAULT NULL COMMENT '最小延迟',
-  `avgdelay` varchar(64) DEFAULT NULL COMMENT '平均延迟',
-  `losspk` varchar(64) DEFAULT NULL COMMENT '丢包率',
-  `update_at` datetime DEFAULT NULL COMMENT '更新时间',
-  `create_at` datetime DEFAULT NULL COMMENT '创建时间',
-  `host` varchar(128) DEFAULT NULL COMMENT '服务器IP',
-  PRIMARY KEY (`id`)
-) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=utf8mb4;
-
-SET FOREIGN_KEY_CHECKS = 1;

+ 1 - 1
hack/config.yaml

@@ -8,5 +8,5 @@ gfcli:
         # tables: "sys_user"
         # removePrefix: "gf_"
         descriptionTag: true
-        noModelComment: true
+        noModelComment: false
         # path: "./tmp"

+ 2 - 4
internal/controller/Node.go

@@ -20,9 +20,7 @@ type sNode struct {
 }
 
 func (c *sNode) Add(ctx context.Context, req *v1.NodeReq) (res *v1.NodeRes, err error) {
-	exist, err := service.Node().IsExist(ctx, model.NodeDelInput{
-		Host: req.Host,
-	})
+	exist, err := service.Node().IsExist(ctx, req.Host)
 	if err != nil {
 		return
 	}
@@ -45,7 +43,7 @@ func (c *sNode) Add(ctx context.Context, req *v1.NodeReq) (res *v1.NodeRes, err
 func (c *sNode) Del(ctx context.Context, req *v1.NodeDelReq) (res *v1.NodeDelRes, err error) {
 
 	err = service.Node().Del(ctx, model.NodeDelInput{
-		Host: req.Host,
+		Id: req.Id,
 	})
 
 	return

+ 8 - 6
internal/controller/hello.go

@@ -2,7 +2,6 @@ package controller
 
 import (
 	"context"
-	"github.com/gogf/gf/v2/frame/g"
 	"nodeMonitor/api/v1"
 	"nodeMonitor/internal/service"
 	"time"
@@ -16,15 +15,18 @@ type cHello struct{}
 
 func (c *cHello) Hello(ctx context.Context, req *v1.HelloReq) (res *v1.HelloRes, err error) {
 
+	res = new(v1.HelloRes)
 	//t1 := time.Now()
 
+	res.NodeItme, err = service.Node().GetNodePingStatus(ctx)
+
 	//Format("2006-01-02 15:04")
 	g.RequestFromCtx(ctx).Response.Writeln(time.Now())
 
-	status, err := service.Ping().GetStatus(ctx, "kdvkr-04.xyz")
-	if err != nil {
-		return res, err
-	}
-	g.RequestFromCtx(ctx).Response.Writeln(status)
+	//status, err := service.Ping().GetStatus(ctx, 1)
+	//if err != nil {
+	//	return res, err
+	//}
+	//g.RequestFromCtx(ctx).Response.Writeln(status)
 	return
 }

+ 29 - 7
internal/logic/node/node.go

@@ -32,23 +32,34 @@ func (c *sNode) Create(ctx context.Context, input model.NodeCreateInput) error {
 			Port:     input.Port,
 			Url:      input.Url,
 			PingType: input.PingType,
+			NodeMs:   0,
 		}).Insert()
 		return err
 	})
 }
 
+// UpdateNodeMs 更新节点延迟1
+func (c *sNode) UpdateNodeMs(ctx context.Context, input model.NodeUpdateInput) error {
+	_, err := dao.Node.Ctx(ctx).Where(g.Map{
+		"id": input.ServerId,
+	}).Update(g.Map{
+		"node_ms": input.NodeMs,
+	})
+	return err
+}
+
 // Del 删除节点
 func (c *sNode) Del(ctx context.Context, input model.NodeDelInput) error {
 	_, err := dao.Node.Ctx(ctx).Where(g.Map{
-		"host": input.Host,
+		"id": input.Id,
 	}).Delete()
 	return err
 }
 
 // IsExist 节点是否存在
-func (c *sNode) IsExist(ctx context.Context, input model.NodeDelInput) (bool, error) {
+func (c *sNode) IsExist(ctx context.Context, host string) (bool, error) {
 	count, err := dao.Node.Ctx(ctx).Where(g.Map{
-		"host": input.Host,
+		"host": host,
 	}).Count()
 	if err != nil {
 		return false, err
@@ -57,9 +68,9 @@ func (c *sNode) IsExist(ctx context.Context, input model.NodeDelInput) (bool, er
 }
 
 // UpdateNode 更新指定节点
-func (c *sNode) UpdateNode(ctx context.Context, input model.NodeCreateInput) error {
+func (c *sNode) UpdateNode(ctx context.Context, id int, input model.NodeCreateInput) error {
 	_, err := dao.Node.Ctx(ctx).Where(g.Map{
-		"host": input.Host,
+		"id": id,
 	}).Update(g.Map{
 		"host":      input.Host,
 		"name":      input.Name,
@@ -77,10 +88,21 @@ func (c *sNode) GetNode(ctx context.Context) ([]*entity.Node, error) {
 	return nodeList, err
 }
 
+// GetNodePingStatus 获取节点监控结果
+func (c *sNode) GetNodePingStatus(ctx context.Context) ([]*model.NodeItme, error) {
+	var nodeList []*model.NodeItme
+	//g.Model("node").With()
+	err := dao.Node.Ctx(ctx).With(dao.Pinglog).Scan(&nodeList)
+	if err != nil {
+		return nil, err
+	}
+	return nodeList, nil
+}
+
 // FindNode 获取指定节点数据
-func (c *sNode) FindNode(ctx context.Context, host string) (*entity.Node, error) {
+func (c *sNode) FindNode(ctx context.Context, id int) (*entity.Node, error) {
 	var nodeList *entity.Node
-	err := dao.Node.Ctx(ctx).Where("host = ?", host).Scan(&nodeList)
+	err := dao.Node.Ctx(ctx).Where("id = ?", id).Scan(&nodeList)
 	return nodeList, err
 }
 

+ 10 - 5
internal/logic/pinglog/pinglog.go

@@ -25,22 +25,22 @@ func New() *sPing {
 }
 
 // Create 创建延迟日志
-func (c *sPing) Create(ctx context.Context, ping model.PingSt, host string) error {
+func (c *sPing) Create(ctx context.Context, ping model.PingSt, setverid int) error {
 	return dao.Pinglog.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
 		_, err := dao.Pinglog.Ctx(ctx).Data(do.Pinglog{
 			Maxdelay: ping.MaxDelay,
 			Mindelay: ping.MinDelay,
 			Avgdelay: ping.AvgDelay,
 			Losspk:   ping.LossPk,
-			Host:     host,
+			Serverid: setverid,
 		}).Insert()
 		return err
 	})
 }
 
 // GetStatus 查询节点状态
-// SELECT *  FROM pinglog WHERE create_at >= DATE_SUB(NOW(),INTERVAL 10 MINUTE) and avgdelay = 0  and losspk >= 0 and maxdelay = 0 and `host` = 'kdvkr-04.xyz'
-func (c *sPing) GetStatus(ctx context.Context, host string) (bool, error) {
+// SELECT *  FROM pinglog WHERE create_at >= DATE_SUB(NOW(),INTERVAL 10 MINUTE) and avgdelay = 0  and losspk >= 0 and maxdelay = 0 and `serverid` = '1'
+func (c *sPing) GetStatus(ctx context.Context, serverid int) (bool, error) {
 	//查询的数据超过3次就是不ok了
 	startTime, err := g.Cfg().Get(ctx, "node.startTime")
 	if err != nil {
@@ -55,7 +55,12 @@ func (c *sPing) GetStatus(ctx context.Context, host string) (bool, error) {
 	}
 
 	timeStartStr := time.Unix(time.Now().Unix()-startTime.Int64(), 0)
-	count, err := dao.Pinglog.Ctx(ctx).Where("create_at > ?", timeStartStr).Where("avgdelay = 0").Where("losspk > ?", loos.Int()).Where("maxdelay = 0 ").Where("host = ?", host).Count()
+	count, err := dao.Pinglog.Ctx(ctx).Where("create_at > ?", timeStartStr).Where("avgdelay = 0").Where("losspk > ?", loos.Int()).Where("maxdelay = 0 ").Where("serverid = ?", serverid).Count()
 
 	return count >= 3, err
 }
+
+func (c *sPing) GetPingLog(ctx context.Context) (list []model.NodeItme, err error) {
+	//err = dao.Pinglog.Ctx(ctx).With(dao.Node{})
+	return
+}

+ 14 - 1
internal/model/node.go

@@ -1,5 +1,7 @@
 package model
 
+import "nodeMonitor/internal/model/entity"
+
 type NodeCreateInput struct {
 	Name      string
 	Host      string
@@ -10,5 +12,16 @@ type NodeCreateInput struct {
 }
 
 type NodeDelInput struct {
-	Host string
+	Id int
+}
+
+type NodeUpdateInput struct {
+	ServerId int
+	NodeMs   int
+}
+
+// UserDetail *UserDetail   `orm:"with:uid=id"`
+// //	 UserScores []*UserScores `orm:"with:uid=id"`
+type NodeItme struct {
+	PingList []*entity.Pinglog `orm:"with:serverid=id"`
 }

+ 14 - 6
internal/task/ping.go

@@ -24,14 +24,14 @@ func Ping(ctx context.Context) {
 	for _, target := range nodeList {
 		wg.Add(1)
 		//glog.Debug(ctx, target)
-		go PingTask(ctx, target.Host, &wg, target.PingType, target.Port)
+		go PingTask(ctx, target.Host, &wg, target.PingType, target.Port, target.Id)
 	}
 	wg.Wait()
 
 	go CheckNodeStatus(ctx)
 }
 
-func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, hostPort int) {
+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")
@@ -95,12 +95,20 @@ func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, h
 	}
 
 	//添加到数据库
-	AddPingLog(ctx, stat, t)
+	AddPingLog(ctx, stat, t, serverid)
 	wg.Done()
 }
 
-func AddPingLog(ctx context.Context, pingres model.PingSt, addr string) {
-	err := service.Ping().Create(ctx, pingres, addr)
+func AddPingLog(ctx context.Context, pingres model.PingSt, addr string, serverid int) {
+	err := service.Ping().Create(ctx, pingres, serverid)
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return
+	}
+	err = service.Node().UpdateNodeMs(ctx, model.NodeUpdateInput{
+		ServerId: serverid,
+		NodeMs:   pingres.AvgDelay,
+	})
 	if err != nil {
 		glog.Debug(ctx, err.Error())
 		return
@@ -118,7 +126,7 @@ func CheckNodeStatus(ctx context.Context) {
 	for _, target := range nodeList {
 		glog.Debug(ctx, "start url req .....")
 		//获取不通的IP进程url请求
-		status, err := service.Ping().GetStatus(ctx, target.Host)
+		status, err := service.Ping().GetStatus(ctx, target.Id)
 		if err != nil {
 			glog.Error(ctx, err.Error())
 			return