2019-12-08 03:59:58 -05:00
|
|
|
package rpc
|
|
|
|
|
|
|
|
import (
|
2019-12-10 05:05:02 -05:00
|
|
|
"fmt"
|
2019-12-08 03:59:58 -05:00
|
|
|
"net"
|
|
|
|
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
|
2021-06-21 09:30:42 -04:00
|
|
|
"github.com/naiba/nezha/model"
|
2020-11-10 21:07:45 -05:00
|
|
|
pb "github.com/naiba/nezha/proto"
|
2021-01-15 11:45:49 -05:00
|
|
|
"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)
|
|
|
|
}
|
2021-01-15 11:45:49 -05:00
|
|
|
|
2021-09-02 11:45:21 -04:00
|
|
|
func DispatchTask(serviceSentinelDispatchBus <-chan model.Monitor) {
|
|
|
|
workedServerIndex := 0
|
|
|
|
for task := range serviceSentinelDispatchBus {
|
|
|
|
round := 0
|
2021-09-02 20:52:45 -04:00
|
|
|
endIndex := workedServerIndex
|
2021-01-17 09:18:36 -05:00
|
|
|
dao.SortedServerLock.RLock()
|
2021-09-02 20:52:45 -04:00
|
|
|
// 如果已经轮了一整圈又轮到自己,没有合适机器去请求,跳出循环
|
|
|
|
for round < 1 || workedServerIndex < endIndex {
|
2021-09-02 11:45:21 -04:00
|
|
|
// 如果到了圈尾,再回到圈头,圈数加一,游标重置
|
2021-10-10 11:52:25 -04:00
|
|
|
if workedServerIndex >= len(dao.SortedServerList) {
|
2021-09-02 11:45:21 -04:00
|
|
|
workedServerIndex = 0
|
|
|
|
round++
|
|
|
|
continue
|
2021-01-15 11:45:49 -05:00
|
|
|
}
|
2021-09-02 11:45:21 -04:00
|
|
|
// 如果服务器不在线,跳过这个服务器
|
|
|
|
if dao.SortedServerList[workedServerIndex].TaskStream == nil {
|
|
|
|
workedServerIndex++
|
2021-06-21 09:30:42 -04:00
|
|
|
continue
|
|
|
|
}
|
2021-09-02 11:45:21 -04:00
|
|
|
// 如果此任务不可使用此服务器请求,跳过这个服务器(有些 IPv6 only 开了 NAT64 的机器请求 IPv4 总会出问题)
|
|
|
|
if (task.Cover == model.MonitorCoverAll && task.SkipServers[dao.SortedServerList[workedServerIndex].ID]) ||
|
|
|
|
(task.Cover == model.MonitorCoverIgnoreAll && !task.SkipServers[dao.SortedServerList[workedServerIndex].ID]) {
|
|
|
|
workedServerIndex++
|
2021-01-15 11:45:49 -05:00
|
|
|
continue
|
|
|
|
}
|
2021-09-02 11:45:21 -04:00
|
|
|
// 找到合适机器执行任务,跳出循环
|
|
|
|
dao.SortedServerList[workedServerIndex].TaskStream.Send(task.PB())
|
|
|
|
workedServerIndex++
|
|
|
|
break
|
2021-01-15 11:45:49 -05:00
|
|
|
}
|
2021-01-17 09:18:36 -05:00
|
|
|
dao.SortedServerLock.RUnlock()
|
2021-01-15 11:45:49 -05:00
|
|
|
}
|
|
|
|
}
|