cauto 2 years ago
parent
commit
3ed0427276

+ 1 - 1
api/v1/hello.go

@@ -10,5 +10,5 @@ type HelloReq struct {
 }
 type HelloRes struct {
 	g.Meta   `mime:"application/json" example:"json"`
-	NodeItme []*model.NodeItme
+	NodeItme []*model.UserItem
 }

+ 20 - 0
api/v1/node.go

@@ -3,6 +3,7 @@ package v1
 import (
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/os/gcron"
+	"nodeMonitor/internal/model"
 	"nodeMonitor/internal/model/entity"
 )
 
@@ -19,6 +20,18 @@ type NodeRes struct {
 	//g.Meta `mime:"application/json"`
 
 }
+type NodeEditReq struct {
+	g.Meta    `path:"/edit" tags:"edit" method:"post" summary:"编辑"`
+	Id        int    `p:"id" v:"required#节点ID不能为空"`
+	Name      string `p:"name" v:"required#节点名称不能为空"`
+	Host      string `p:"host" v:"required#节点不能为空"`
+	Port      int    `p:"port"`
+	Url       string `p:"url"`
+	PingType  int    `p:"pingType"`
+	UrlStatus int    `p:"urlstatus"`
+}
+type NodeEditRes struct {
+}
 
 type NodeDelReq struct {
 	g.Meta `path:"/del" tags:"del" method:"post" summary:"删除节点"`
@@ -70,3 +83,10 @@ type NodeCronStatusRes struct {
 	RetEntry     []*gcron.Entry
 	RetCronCount int
 }
+
+type NodeStatusReq struct {
+	g.Meta `path:"/nodestatus" tags:"nodestatus" method:"get" summary:"查看任务状态"`
+}
+type NodeStatusRes struct {
+	NodeItme []*model.UserItem
+}

+ 52 - 28
db/nodeMonitor.sql

@@ -1,30 +1,54 @@
-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;
+/*
+ Navicat Premium Data Transfer
 
-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;
+ Source Server         : localhost
+ Source Server Type    : MySQL
+ Source Server Version : 50734
+ Source Host           : localhost:3306
+ Source Schema         : nodeMonitor
 
+ Target Server Type    : MySQL
+ Target Server Version : 50734
+ File Encoding         : 65001
+
+ Date: 07/11/2022 14:51:21
+*/
+
+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是否执行完成',
+  `nodeMs` int(11) DEFAULT NULL COMMENT ' 服务器延迟',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=30 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 '创建时间',
+  `serverid` int(11) DEFAULT NULL COMMENT '服务器ID',
+  PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=343 DEFAULT CHARSET=utf8mb4;
+
+SET FOREIGN_KEY_CHECKS = 1;

+ 1 - 0
go.mod

@@ -13,5 +13,6 @@ require (
 	github.com/miekg/dns v1.1.50
 	github.com/rivo/uniseg v0.4.2 // indirect
 	go.opentelemetry.io/otel/sdk v1.11.1 // indirect
+	golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
 	golang.org/x/net v0.1.0
 )

+ 2 - 0
go.sum

@@ -128,6 +128,7 @@ go.opentelemetry.io/otel/trace v1.11.1/go.mod h1:f/Q9G7vzk5u91PhbmKbg1Qn0rzH1LJ4
 golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
 golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
@@ -184,6 +185,7 @@ golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
 golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
 golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
 golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
 golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=

+ 10 - 0
hack/config.yaml

@@ -2,6 +2,16 @@
 # CLI tool, only in development environment.
 # https://goframe.org/pages/viewpage.action?pageId=3673173
 gfcli:
+  build:
+    name: "nodeMonitor"
+    arch: "amd64"
+    system: "linux"
+    mod: "none"
+    cgo: 0
+    pack: ""
+    version: ""
+    output: "./bin"
+    extra: ""
   gen:
     dao:
       - link: "mysql:root:123456@tcp(127.0.0.1:3306)/nodeMonitor"

+ 5 - 0
internal/cmd/cmd.go

@@ -45,3 +45,8 @@ func enhanceOpenAPIDoc(s *ghttp.Server) {
 		},
 	}
 }
+
+func StartPingStart(ctx context.Context) string {
+
+	return ""
+}

+ 56 - 0
internal/controller/Node.go

@@ -49,12 +49,31 @@ func (c *sNode) Del(ctx context.Context, req *v1.NodeDelReq) (res *v1.NodeDelRes
 	return
 }
 
+func (c *sNode) Edit(ctx context.Context, req *v1.NodeEditReq) (res *v1.NodeEditRes, err error) {
+	err = service.Node().UpdateNode(ctx, model.NodeEditInput{
+		Id:        req.Id,
+		Name:      req.Name,
+		Host:      req.Host,
+		Port:      req.Port,
+		Url:       req.Url,
+		PingType:  req.PingType,
+		UrlStatus: req.UrlStatus,
+	})
+	return
+}
+
 func (c *sNode) All(ctx context.Context, req *v1.NodeAllReq) (res *v1.NodeALlRes, err error) {
 	res = new(v1.NodeALlRes)
 	res.NodeList, err = service.Node().GetNode(ctx)
 	return
 }
 
+func (c *sNode) NodeStatus(ctx context.Context, req *v1.NodeStatusReq) (res *v1.NodeStatusRes, err error) {
+	res = new(v1.NodeStatusRes)
+	res.NodeItme, err = service.Node().GetNodePingStatus(ctx)
+	return
+}
+
 func (c *sNode) Start(ctx context.Context, req *v1.NodeCronStartReq) (res *v1.NodeCronStartRes, err error) {
 	res = new(v1.NodeCronStartRes)
 	StartTime := req.StartTime
@@ -82,6 +101,30 @@ func (c *sNode) Start(ctx context.Context, req *v1.NodeCronStartReq) (res *v1.No
 		res.Status = true
 	}
 
+	//taskStatusName, err := g.Cfg().Get(ctx, "node.ping_status_task")
+	//if err != nil {
+	//	glog.Debug(ctx, err.Error())
+	//	return
+	//}
+	//search_status := gcron.Search(taskStatusName.String())
+	//if search_status != nil {
+	//	gcron.Stop(taskStatusName.String())
+	//	gcron.Start(taskStatusName.String())
+	//	glog.Debug(ctx, "task -- ", gcron.Size())
+	//	res.RetEntry = gcron.Entries()
+	//	res.RetCronCount = gcron.Size()
+	//	res.Status = true
+	//} else {
+	//	s := fmt.Sprintf("*/%d * * * * *", 120)
+	//	_, err = gcron.AddSingleton(ctx, s, func(ctx context.Context) {
+	//		go task.PingStatus(ctx)
+	//	}, taskStatusName.String())
+	//	res.RetEntry = gcron.Entries()
+	//	res.RetCronCount = gcron.Size()
+	//	res.Status = true
+	//
+	//}
+
 	return
 }
 
@@ -93,15 +136,28 @@ func (c *sNode) Stop(ctx context.Context, req *v1.NodeCronStopReq) (res *v1.Node
 		glog.Debug(ctx, err.Error())
 		return
 	}
+
+	//taskStatusName, err := g.Cfg().Get(ctx, "node.ping_status_task")
+	//if err != nil {
+	//	glog.Debug(ctx, err.Error())
+	//	return
+	//}
+
 	gcron.Stop(taskName.String())
+	//gcron.Stop(taskStatusName.String())
 	if remove {
 		gcron.Remove(taskName.String())
+		//gcron.Remove(taskStatusName.String())
 	}
 
 	search := gcron.Search(taskName.String())
 	if search == nil {
 		res.Status = false
 	}
+	//search_status := gcron.Search(taskStatusName.String())
+	//if search_status == nil {
+	//	res.Status = false
+	//}
 	res.RetCronCount = gcron.Size()
 
 	return

+ 3 - 2
internal/controller/hello.go

@@ -4,7 +4,6 @@ import (
 	"context"
 	"nodeMonitor/api/v1"
 	"nodeMonitor/internal/service"
-	"time"
 )
 
 var (
@@ -18,10 +17,12 @@ func (c *cHello) Hello(ctx context.Context, req *v1.HelloReq) (res *v1.HelloRes,
 	res = new(v1.HelloRes)
 	//t1 := time.Now()
 
+	//g.Model("node").With(&res.NodeItme, "Node")
+
 	res.NodeItme, err = service.Node().GetNodePingStatus(ctx)
 
 	//Format("2006-01-02 15:04")
-	g.RequestFromCtx(ctx).Response.Writeln(time.Now())
+	//g.RequestFromCtx(ctx).Response.Writeln(time.Now())
 
 	//status, err := service.Ping().GetStatus(ctx, 1)
 	//if err != nil {

+ 28 - 12
internal/logic/node/node.go

@@ -3,12 +3,15 @@ package node
 import (
 	"github.com/gogf/gf/v2/database/gdb"
 	"github.com/gogf/gf/v2/frame/g"
+	"github.com/gogf/gf/v2/os/glog"
+	"github.com/gogf/gf/v2/os/gtime"
 	"golang.org/x/net/context"
 	"nodeMonitor/internal/dao"
 	"nodeMonitor/internal/model"
 	"nodeMonitor/internal/model/do"
 	"nodeMonitor/internal/model/entity"
 	"nodeMonitor/internal/service"
+	"time"
 )
 
 type (
@@ -68,15 +71,16 @@ func (c *sNode) IsExist(ctx context.Context, host string) (bool, error) {
 }
 
 // UpdateNode 更新指定节点
-func (c *sNode) UpdateNode(ctx context.Context, id int, input model.NodeCreateInput) error {
+func (c *sNode) UpdateNode(ctx context.Context, input model.NodeEditInput) error {
 	_, err := dao.Node.Ctx(ctx).Where(g.Map{
-		"id": id,
+		"id": input.Id,
 	}).Update(g.Map{
-		"host":      input.Host,
-		"name":      input.Name,
-		"port":      input.Port,
-		"url":       input.Url,
-		"ping_type": input.PingType,
+		"host":       input.Host,
+		"name":       input.Name,
+		"port":       input.Port,
+		"url":        input.Url,
+		"ping_type":  input.PingType,
+		"url_status": input.UrlStatus,
 	})
 	return err
 }
@@ -84,18 +88,30 @@ func (c *sNode) UpdateNode(ctx context.Context, id int, input model.NodeCreateIn
 // GetNode 获取全部数据
 func (c *sNode) GetNode(ctx context.Context) ([]*entity.Node, error) {
 	var nodeList []*entity.Node
-	err := dao.Node.Ctx(ctx).Scan(&nodeList)
+	err := dao.Node.Ctx(ctx).OrderDesc("create_at").Scan(&nodeList)
 	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)
+func (c *sNode) GetNodePingStatus(ctx context.Context) ([]*model.UserItem, error) {
+	//查询10分钟内的数据
+	startTime, err := g.Cfg().Get(ctx, "node.startTime")
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return nil, err
+	}
+	var nodeList []*model.UserItem
+	timeStartStr := gtime.Now().Add(-startTime.Duration() * time.Second).String()
+	err = dao.Node.Ctx(ctx).OrderDesc("create_at").ScanList(&nodeList, "Node")
 	if err != nil {
 		return nil, err
 	}
+	err = dao.Pinglog.Ctx(ctx).Where("serverid", gdb.ListItemValuesUnique(nodeList, "Node", "Id")).Where("create_at > ?", timeStartStr).OrderDesc("create_at").ScanList(&nodeList, "PingLog", "Node", "serverid=id")
+	glog.Debug(ctx, timeStartStr)
+	if err != nil {
+		return nil, err
+	}
+
 	return nodeList, nil
 }
 

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

@@ -4,6 +4,7 @@ import (
 	"github.com/gogf/gf/v2/database/gdb"
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/os/glog"
+	"github.com/gogf/gf/v2/os/gtime"
 	"golang.org/x/net/context"
 	"nodeMonitor/internal/dao"
 	"nodeMonitor/internal/model"
@@ -39,28 +40,23 @@ func (c *sPing) Create(ctx context.Context, ping model.PingSt, setverid int) err
 }
 
 // GetStatus 查询节点状态
-// SELECT *  FROM pinglog WHERE create_at >= DATE_SUB(NOW(),INTERVAL 10 MINUTE) and avgdelay = 0  and losspk >= 0 and maxdelay = 0 and `serverid` = '1'
+// SELECT *  FROM pinglog WHERE create_at >= DATE_SUB(NOW(),INTERVAL 10 MINUTE) and avgdelay = 0  and losspk >= 0 and maxdelay = 0 and `serverid` = '1'gf
 func (c *sPing) GetStatus(ctx context.Context, serverid int) (bool, error) {
-	//查询的数据超过3次就是不ok了
+	//查询10分钟内的数据
 	startTime, err := g.Cfg().Get(ctx, "node.startTime")
 	if err != nil {
 		glog.Debug(ctx, err.Error())
 		return false, err
 	}
-
+	//查询的数据超过3次就是不ok了
 	loos, err := g.Cfg().Get(ctx, "node.loos")
 	if err != nil {
 		glog.Debug(ctx, err.Error())
 		return false, err
 	}
 
-	timeStartStr := time.Unix(time.Now().Unix()-startTime.Int64(), 0)
+	timeStartStr := gtime.Now().Add(-startTime.Duration() * time.Second).String()
 	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
-}

+ 34 - 5
internal/model/node.go

@@ -1,6 +1,9 @@
 package model
 
-import "nodeMonitor/internal/model/entity"
+import (
+	"github.com/gogf/gf/v2/os/gtime"
+	"github.com/gogf/gf/v2/util/gmeta"
+)
 
 type NodeCreateInput struct {
 	Name      string
@@ -11,6 +14,16 @@ type NodeCreateInput struct {
 	UrlStatus int
 }
 
+type NodeEditInput struct {
+	Id        int
+	Name      string
+	Host      string
+	Port      int
+	Url       string
+	PingType  int
+	UrlStatus int
+}
+
 type NodeDelInput struct {
 	Id int
 }
@@ -20,8 +33,24 @@ type NodeUpdateInput struct {
 	NodeMs   int
 }
 
-// UserDetail *UserDetail   `orm:"with:uid=id"`
-// //	 UserScores []*UserScores `orm:"with:uid=id"`
-type NodeItme struct {
-	PingList []*entity.Pinglog `orm:"with:serverid=id"`
+// EntityNodePingLog PINGLOGN表
+type EntityNodePingLog struct {
+	gmeta.Meta `orm:"table:pinglog"`
+	Serverid   int         `json:"serverid"`
+	Avgdelay   string      `json:"avgdelay"`                    // 平均延迟
+	CreateAt   *gtime.Time `json:"createAt" description:"创建时间"` // 创建时间
+}
+
+// EntityNodeInfo 组合模型,用户信息
+type EntityNodeInfo struct {
+	gmeta.Meta `orm:"table:node"`
+	Id         int    `orm:"id" json:"id"`
+	Name       string `orm:"name"`
+	Host       string `orm:"host"`
+}
+
+// 组合模型,用户信息
+type UserItem struct {
+	Node    *EntityNodeInfo
+	PingLog []*EntityNodePingLog
 }

+ 1 - 0
internal/router/router.go

@@ -9,6 +9,7 @@ func BindController(group *ghttp.RouterGroup) {
 	group.Group("/api/v1", func(group *ghttp.RouterGroup) {
 		group.Middleware(ghttp.MiddlewareHandlerResponse)
 		//group.Middleware(middleware.Middleware().CORS)
+		//group.Middleware(ghttp.MiddlewareCORS())
 		NodeRouter(group)
 		DomeRouter(group)
 	})

+ 91 - 29
internal/task/ping.go

@@ -1,11 +1,14 @@
 package task
 
 import (
+	"fmt"
 	"github.com/gogf/gf/v2/frame/g"
 	"github.com/gogf/gf/v2/os/glog"
+	"golang.org/x/crypto/ssh"
 	"golang.org/x/net/context"
 	"net"
 	"nodeMonitor/internal/model"
+	"nodeMonitor/internal/model/entity"
 	"nodeMonitor/internal/service"
 	"nodeMonitor/library/nettools"
 	"sync"
@@ -26,9 +29,22 @@ func Ping(ctx context.Context) {
 		//glog.Debug(ctx, target)
 		go PingTask(ctx, target.Host, &wg, target.PingType, target.Port, target.Id)
 	}
+
 	wg.Wait()
+	go PingStatus(ctx)
+}
+
+func PingStatus(ctx context.Context) {
+
+	nodeList, err := service.Node().GetNode(ctx)
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return
+	}
+	for _, target := range nodeList {
+		CheckNodeStatus(ctx, target)
+	}
 
-	go CheckNodeStatus(ctx)
 }
 
 func PingTask(ctx context.Context, t string, wg *sync.WaitGroup, pingType int, hostPort int, serverid int) {
@@ -70,7 +86,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
@@ -83,7 +99,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
@@ -91,7 +107,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")
 	}
 
 	//添加到数据库
@@ -116,43 +132,89 @@ func AddPingLog(ctx context.Context, pingres model.PingSt, addr string, serverid
 	return
 }
 
-func CheckNodeStatus(ctx context.Context) {
+func CheckNodeStatus(ctx context.Context, target *entity.Node) {
 
-	nodeList, err := service.Node().GetNode(ctx)
+	glog.Debug(ctx, "start url req .....")
+	//获取不通的IP进程url请求
+	status, err := service.Ping().GetStatus(ctx, target.Id)
 	if err != nil {
-		glog.Debug(ctx, err.Error())
+		glog.Error(ctx, err.Error())
 		return
 	}
-	for _, target := range nodeList {
-		glog.Debug(ctx, "start url req .....")
-		//获取不通的IP进程url请求
-		status, err := service.Ping().GetStatus(ctx, target.Id)
+	if status {
+
+		if target.UrlStatus == 200 {
+			return
+		}
+		client := g.Client()
+		client.SetTimeout(30 * time.Second)
+		r, err := client.Get(ctx, target.Url)
 		if err != nil {
-			glog.Error(ctx, err.Error())
+			glog.Debug(ctx, err.Error())
+			SSHTaskCommand(ctx, target.Host, target.Port)
 			return
 		}
-		if status {
-
-			if target.UrlStatus == 200 {
-				return
-			}
-
-			r, err := g.Client().Get(ctx, target.Url)
+		defer r.Close()
+		glog.Debug(ctx, "req :", target.Url, "status :", r.Status)
+		if r.StatusCode == 200 {
+			err := service.Node().UpdateNodeUrlStatus(ctx, model.NodeCreateInput{Host: target.Host, UrlStatus: r.StatusCode})
 			if err != nil {
-				glog.Error(ctx, err.Error())
+				glog.Debug(ctx, err.Error())
 				return
 			}
-			defer r.Close()
-			glog.Debug(ctx, "req :", target.Url, "status :", r.Status)
-			if r.StatusCode == 200 {
-				err := service.Node().UpdateNodeUrlStatus(ctx, model.NodeCreateInput{Host: target.Host, UrlStatus: r.StatusCode})
-				if err != nil {
-					glog.Debug(ctx, err.Error())
-					return
-				}
-			}
+		} else {
+			SSHTaskCommand(ctx, target.Host, target.Port)
 		}
+	}
+
+}
+
+func SSHTaskCommand(ctx context.Context, host string, port int) {
+
+	sshPassword, err := g.Cfg().Get(ctx, "node.sshPassword")
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return
+	}
+	sshUsername, err := g.Cfg().Get(ctx, "node.sshUsername")
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return
+	}
+
+	sshCommand, err := g.Cfg().Get(ctx, "node.sshCommand")
+	if err != nil {
+		glog.Debug(ctx, err.Error())
+		return
+	}
+	s2 := fmt.Sprintf("%s:%d\n", host, port)
+	// 建立SSH客户端连接
+	client, err := ssh.Dial("tcp", s2, &ssh.ClientConfig{
+		User:            sshUsername.String(),
+		Auth:            []ssh.AuthMethod{ssh.Password(sshPassword.String())},
+		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
+	})
+	if err != nil {
+		//log.Fatalf("SSH dial error: %s", err.Error())
+		glog.Debug(ctx, "SSH dial error:", err.Error())
+		return
+	}
 
+	// 建立新会话
+	session, err := client.NewSession()
+	defer session.Close()
+	if err != nil {
+		//log.Fatalf("new session error: %s", err.Error())
+		glog.Debug(ctx, "new session error:", err.Error())
+		return
 	}
 
+	result, err := session.Output(sshCommand.String())
+	if err != nil {
+		//fmt.Fprintf(os.Stdout, "Failed to run command, Err:%s", err.Error())
+		//os.Exit(0)
+		glog.Debug(ctx, err.Error())
+		return
+	}
+	glog.Debug(ctx, result)
 }

+ 6 - 2
manifest/config/config.yaml

@@ -31,12 +31,12 @@ database:
     Path: "resource/log/sql"
 
   default:
-    link: "mysql:root:123456@tcp(127.0.0.1:3306)/nodeMonitor"
+    link: "mysql:nodeMonitor:NNmeANyDyftp2Nan@tcp(47.243.54.62:8366)/nodemonitor?loc=Local&parseTime=true"
     debug: true
     charset: "utf8mb4" #数据库编码
     dryRun: false #空跑
     maxIdle: 10 #连接池最大闲置的连接数
-    maxOpen: 10 #连接池最大打开的连接数
+    maxOpen: 30 #连接池最大打开的连接数
     maxLifetime: 30 #(单位秒)连接对象可重复使用的时间长度
 
 node:
@@ -45,6 +45,10 @@ node:
   startTime: 900 #用于查询15分钟内的数据
   loos: 30 #用于丢包率检测 如果丢包率>当前值就是坏了
   taskName: "ping_task" #任务名称
+  taskStatusName: "ping_status_task" #任务名称
+  sshCommand: "" #用于执行ssh 命令
+  sshPassword: "" #ssh密码
+  sshUsername: "root"
 #gfToken:
 #  cacheKey: "gfToken_"
 #  timeOut: 10800