nezha/cmd/dashboard/rpc/rpc.go

59 lines
1.2 KiB
Go
Raw Normal View History

2019-12-08 03:59:58 -05:00
package rpc
import (
2019-12-10 05:05:02 -05:00
"fmt"
"log"
2019-12-08 03:59:58 -05:00
"net"
"time"
2019-12-08 03:59:58 -05:00
"google.golang.org/grpc"
"github.com/naiba/nezha/model"
2020-11-10 21:07:45 -05:00
pb "github.com/naiba/nezha/proto"
"github.com/naiba/nezha/service/dao"
2020-11-10 21:07:45 -05:00
rpcService "github.com/naiba/nezha/service/rpc"
2019-12-08 03:59:58 -05:00
)
2019-12-10 05:05:02 -05:00
func ServeRPC(port uint) {
2019-12-08 03:59:58 -05:00
server := grpc.NewServer()
pb.RegisterNezhaServiceServer(server, &rpcService.NezhaHandler{
2019-12-09 05:14:31 -05:00
Auth: &rpcService.AuthHandler{},
2019-12-08 03:59:58 -05:00
})
2019-12-10 05:05:02 -05:00
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
2019-12-08 03:59:58 -05:00
if err != nil {
panic(err)
}
server.Serve(listen)
}
func DispatchTask(duration time.Duration) {
var index uint64 = 0
for {
var tasks []model.Monitor
var hasAliveAgent bool
dao.DB.Find(&tasks)
dao.ServerLock.RLock()
for i := 0; i < len(tasks); i++ {
if index >= uint64(len(dao.SortedServerList)) {
index = 0
if !hasAliveAgent {
break
}
hasAliveAgent = false
}
if dao.SortedServerList[index].TaskStream == nil {
i--
index++
continue
}
hasAliveAgent = true
log.Println("DispatchTask 确认派发 >>>>>", i, index)
dao.SortedServerList[index].TaskStream.Send(tasks[i].PB())
log.Println("DispatchTask 确认派发 <<<<<", i, index)
index++
}
dao.ServerLock.RUnlock()
time.Sleep(duration)
}
}