-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
lrs_server.go
77 lines (63 loc) · 2.23 KB
/
lrs_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package server
import (
"log"
"sync"
gcpLoadStats "github.com/envoyproxy/go-control-plane/envoy/service/load_stats/v3"
"github.com/golang/protobuf/ptypes/duration"
)
// This is how often Envoy will send the load report
const StatsFrequencyInSeconds = 2
// Server handling Load Stats communication
type Server interface {
gcpLoadStats.LoadReportingServiceServer
HandleRequest(stream gcpLoadStats.LoadReportingService_StreamLoadStatsServer, request *gcpLoadStats.LoadStatsRequest)
}
func NewServer() Server {
return &server{nodesConnected: make(map[string]bool)}
}
type server struct {
// protects nodesConnected
mu sync.Mutex
// This cache stores nodes connected to the LRS server
nodesConnected map[string]bool
}
// Handles incoming stream connections and LoadStatsRequests
func (s *server) StreamLoadStats(stream gcpLoadStats.LoadReportingService_StreamLoadStatsServer) error {
for {
req, err := stream.Recv()
// input stream ended or errored out
if err != nil {
return err
}
s.HandleRequest(stream, req)
}
}
func (s *server) HandleRequest(stream gcpLoadStats.LoadReportingService_StreamLoadStatsServer, request *gcpLoadStats.LoadStatsRequest) {
nodeID := request.GetNode().GetId()
s.mu.Lock()
defer s.mu.Unlock()
// Check whether any Node has already connected or not.
// If not, add the NodeID to nodesConnected and enable Load Report with given frequency
// If yes, log stats
if _, exist := s.nodesConnected[nodeID]; !exist {
// Add NodeID to the nodesConnected
log.Printf("Adding new new node to cache `%s`", nodeID)
s.nodesConnected[nodeID] = true
// Initialize Load Reporting
err := stream.Send(&gcpLoadStats.LoadStatsResponse{
Clusters: []string{"local_service"},
LoadReportingInterval: &duration.Duration{Seconds: StatsFrequencyInSeconds},
ReportEndpointGranularity: true,
})
if err != nil {
log.Panicf("Unable to send response to node %s due to err: %s", nodeID, err)
}
return
}
// After Load Report is enabled, log the Load Report stats received
for _, clusterStats := range request.ClusterStats {
if len(clusterStats.UpstreamLocalityStats) > 0 {
log.Printf("Got stats from cluster `%s` node `%s` - %s", request.Node.Cluster, request.Node.Id, clusterStats)
}
}
}