2019-12-08 03:59:58 -05:00
|
|
|
package rpc
|
2019-12-07 05:14:40 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-12-09 03:02:49 -05:00
|
|
|
"log"
|
2020-10-24 09:29:05 -04:00
|
|
|
"time"
|
2019-12-07 05:14:40 -05:00
|
|
|
|
2020-11-10 21:07:45 -05:00
|
|
|
"github.com/naiba/nezha/model"
|
|
|
|
pb "github.com/naiba/nezha/proto"
|
|
|
|
"github.com/naiba/nezha/service/dao"
|
2019-12-07 05:14:40 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
// NezhaHandler ..
|
|
|
|
type NezhaHandler struct {
|
|
|
|
Auth *AuthHandler
|
|
|
|
}
|
|
|
|
|
|
|
|
// ReportState ..
|
|
|
|
func (s *NezhaHandler) ReportState(c context.Context, r *pb.State) (*pb.Receipt, error) {
|
2021-01-08 08:04:50 -05:00
|
|
|
var clientID uint64
|
2019-12-09 05:14:31 -05:00
|
|
|
var err error
|
|
|
|
if clientID, err = s.Auth.Check(c); err != nil {
|
2019-12-07 05:14:40 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
2019-12-13 04:56:14 -05:00
|
|
|
state := model.PB2State(r)
|
2019-12-10 04:57:57 -05:00
|
|
|
dao.ServerLock.RLock()
|
|
|
|
defer dao.ServerLock.RUnlock()
|
2020-10-24 09:29:05 -04:00
|
|
|
dao.ServerList[clientID].LastActive = time.Now()
|
2019-12-13 04:56:14 -05:00
|
|
|
dao.ServerList[clientID].State = &state
|
2019-12-07 05:14:40 -05:00
|
|
|
return &pb.Receipt{Proced: true}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Heartbeat ..
|
|
|
|
func (s *NezhaHandler) Heartbeat(r *pb.Beat, stream pb.NezhaService_HeartbeatServer) error {
|
2021-01-08 08:04:50 -05:00
|
|
|
var clientID uint64
|
2019-12-09 05:14:31 -05:00
|
|
|
var err error
|
|
|
|
defer log.Printf("Heartbeat exit server:%v err:%v", clientID, err)
|
|
|
|
if clientID, err = s.Auth.Check(stream.Context()); err != nil {
|
2019-12-07 05:14:40 -05:00
|
|
|
return err
|
|
|
|
}
|
2019-12-13 01:51:51 -05:00
|
|
|
// 放入在线服务器列表
|
2019-12-10 04:57:57 -05:00
|
|
|
dao.ServerLock.RLock()
|
|
|
|
closeCh := make(chan error)
|
|
|
|
dao.ServerList[clientID].StreamClose = closeCh
|
|
|
|
dao.ServerList[clientID].Stream = stream
|
2019-12-11 01:41:12 -05:00
|
|
|
dao.ServerLock.RUnlock()
|
2019-12-10 04:57:57 -05:00
|
|
|
select {
|
|
|
|
case err = <-closeCh:
|
|
|
|
return err
|
2019-12-09 03:02:49 -05:00
|
|
|
}
|
2019-12-07 05:14:40 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Register ..
|
|
|
|
func (s *NezhaHandler) Register(c context.Context, r *pb.Host) (*pb.Receipt, error) {
|
2021-01-08 08:04:50 -05:00
|
|
|
var clientID uint64
|
2019-12-09 05:14:31 -05:00
|
|
|
var err error
|
|
|
|
if clientID, err = s.Auth.Check(c); err != nil {
|
2019-12-07 05:14:40 -05:00
|
|
|
return nil, err
|
|
|
|
}
|
2019-12-13 04:56:14 -05:00
|
|
|
host := model.PB2Host(r)
|
2019-12-10 04:57:57 -05:00
|
|
|
dao.ServerLock.RLock()
|
|
|
|
defer dao.ServerLock.RUnlock()
|
2019-12-13 04:56:14 -05:00
|
|
|
dao.ServerList[clientID].Host = &host
|
2019-12-07 05:14:40 -05:00
|
|
|
return &pb.Receipt{Proced: true}, nil
|
|
|
|
}
|