nezha/service/rpc/nezha.go

71 lines
1.6 KiB
Go
Raw Normal View History

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"
2019-12-07 05:14:40 -05:00
2019-12-09 03:02:49 -05:00
"github.com/p14yground/nezha/model"
2019-12-07 05:14:40 -05:00
pb "github.com/p14yground/nezha/proto"
2019-12-09 05:14:31 -05:00
"github.com/p14yground/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) {
2019-12-09 05:14:31 -05:00
var clientID string
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()
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 {
2019-12-09 05:14:31 -05:00
var clientID string
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
// 默认连接后先上报10分钟
err = stream.Send(&pb.Command{
Type: model.MTReportState,
})
if err != nil {
return err
}
// 放入在线服务器列表
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) {
2019-12-09 05:14:31 -05:00
var clientID string
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
}