-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc_server.go
272 lines (252 loc) · 6.84 KB
/
grpc_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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package zongzi
import (
"context"
"net"
"sync"
"time"
"google.golang.org/grpc"
"github.com/logbn/zongzi/internal"
)
type grpcServer struct {
internal.UnimplementedInternalServer
agent *Agent
server *grpc.Server
listenAddr string
serverOpts []grpc.ServerOption
}
func newGrpcServer(listenAddr string, opts ...grpc.ServerOption) *grpcServer {
return &grpcServer{
listenAddr: listenAddr,
serverOpts: opts,
}
}
func (s *grpcServer) Ping(ctx context.Context, req *internal.PingRequest) (res *internal.PingResponse, err error) {
return &internal.PingResponse{}, nil
}
func (s *grpcServer) Probe(ctx context.Context, req *internal.ProbeRequest) (res *internal.ProbeResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Probe: %#v`, req)
return &internal.ProbeResponse{
GossipAdvertiseAddress: s.agent.hostConfig.Gossip.AdvertiseAddress,
}, nil
}
func (s *grpcServer) Info(ctx context.Context, req *internal.InfoRequest) (res *internal.InfoResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Info: %#v`, req)
return &internal.InfoResponse{
HostId: s.agent.hostID(),
ReplicaId: s.agent.replicaConfig.ReplicaID,
}, nil
}
func (s *grpcServer) Members(ctx context.Context, req *internal.MembersRequest) (res *internal.MembersResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Members: %#v`, req)
return &internal.MembersResponse{
Members: s.agent.members,
}, nil
}
func (s *grpcServer) Join(ctx context.Context, req *internal.JoinRequest) (res *internal.JoinResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Join: %#v`, req)
res = &internal.JoinResponse{}
if s.agent.Status() != AgentStatus_Ready {
err = ErrAgentNotReady
return
}
res.Value, err = s.agent.joinPrimeReplica(req.HostId, s.agent.replicaConfig.ShardID, req.IsNonVoting)
return
}
func (s *grpcServer) Add(ctx context.Context, req *internal.AddRequest) (res *internal.AddResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Join: %#v`, req)
res = &internal.AddResponse{}
if s.agent.Status() != AgentStatus_Ready {
err = ErrAgentNotReady
return
}
res.Value, err = s.agent.joinShardReplica(req.HostId, req.ShardId, req.ReplicaId, req.IsNonVoting)
return
}
var emptyCommitResponse = &internal.CommitResponse{}
func (s *grpcServer) Commit(ctx context.Context, req *internal.CommitRequest) (res *internal.CommitResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Propose: %#v`, req)
if !s.agent.hostConfig.NotifyCommit {
s.agent.log.Warningf(`%v`, ErrNotifyCommitDisabled)
}
if s.agent.Status() != AgentStatus_Ready {
err = ErrAgentNotReady
return
}
rs, err := s.agent.host.Propose(s.agent.host.GetNoOPSession(req.ShardId), req.Data, raftTimeout)
if err != nil {
return
}
defer rs.Release()
for {
select {
case r := <-rs.ResultC():
if r.Committed() {
res = emptyCommitResponse
} else if r.Aborted() {
err = ErrAborted
} else if r.Dropped() {
err = ErrShardNotReady
} else if r.Rejected() {
err = ErrRejected
} else if r.Terminated() {
err = ErrShardClosed
} else if r.Timeout() {
err = ErrTimeout
}
case <-ctx.Done():
if ctx.Err() == context.Canceled {
err = ErrCanceled
} else if ctx.Err() == context.DeadlineExceeded {
err = ErrTimeout
}
}
if err != nil || res != nil {
break
}
}
return
}
func (s *grpcServer) Apply(ctx context.Context, req *internal.ApplyRequest) (res *internal.ApplyResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Propose: %#v`, req)
if s.agent.Status() != AgentStatus_Ready {
err = ErrAgentNotReady
return
}
rs, err := s.agent.host.Propose(s.agent.host.GetNoOPSession(req.ShardId), req.Data, raftTimeout)
if err != nil {
return
}
defer rs.Release()
for {
select {
case r := <-rs.ResultC():
if r.Completed() {
res = &internal.ApplyResponse{
Value: r.GetResult().Value,
Data: r.GetResult().Data,
}
} else if r.Aborted() {
err = ErrAborted
} else if r.Dropped() {
err = ErrShardNotReady
} else if r.Rejected() {
err = ErrRejected
} else if r.Terminated() {
err = ErrShardClosed
} else if r.Timeout() {
err = ErrTimeout
}
case <-ctx.Done():
if ctx.Err() == context.Canceled {
err = ErrCanceled
} else if ctx.Err() == context.DeadlineExceeded {
err = ErrTimeout
}
}
if err != nil || res != nil {
break
}
}
return
}
func (s *grpcServer) Index(ctx context.Context, req *internal.IndexRequest) (res *internal.IndexResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Query: %#v`, req)
res = &internal.IndexResponse{}
err = s.agent.index(ctx, req.ShardId)
return
}
func (s *grpcServer) Read(ctx context.Context, req *internal.ReadRequest) (res *internal.ReadResponse, err error) {
// s.agent.log.Debugf(`gRPC Req Query: %#v`, req)
res = &internal.ReadResponse{}
query := getLookupQuery()
query.ctx = ctx
query.data = req.Data
defer query.Release()
var r any
if req.Stale {
r, err = s.agent.host.StaleRead(req.ShardId, query)
} else {
ctx, cancel := context.WithTimeout(ctx, raftTimeout)
defer cancel()
r, err = s.agent.host.SyncRead(ctx, req.ShardId, query)
}
if result, ok := r.(*Result); ok && result != nil {
res.Value = result.Value
res.Data = result.Data
ReleaseResult(result)
}
return
}
func (s *grpcServer) Watch(req *internal.WatchRequest, srv internal.Internal_WatchServer) (err error) {
// s.agent.log.Debugf(`gRPC Req Query: %#v`, req)
query := getWatchQuery()
query.ctx = srv.Context()
query.data = req.Data
query.result = make(chan *Result)
defer query.Release()
var done = make(chan bool)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case result := <-query.result:
err := srv.Send(&internal.WatchResponse{
Value: result.Value,
Data: result.Data,
})
if err != nil {
s.agent.log.Errorf(`Error sending watch response: %s`, err.Error())
}
ReleaseResult(result)
case <-done:
return
}
}
}()
if req.Stale {
_, err = s.agent.host.StaleRead(req.ShardId, query)
} else {
_, err = s.agent.host.SyncRead(srv.Context(), req.ShardId, query)
}
close(done)
wg.Wait()
return
}
func (s *grpcServer) Start(a *Agent) error {
// a.log.Errorf("Starting gRPC server on %s", s.listenAddr)
s.agent = a
lis, err := net.Listen("tcp", s.listenAddr)
if err != nil {
return err
}
// https://github.com/grpc/grpc-go/tree/master/examples/features/authentication
// opts = append(opts, grpc.UnaryInterceptor(ensureValidToken))
s.server = grpc.NewServer(s.serverOpts...)
internal.RegisterInternalServer(s.server, s)
var done = make(chan bool)
go func() {
err = s.server.Serve(lis)
close(done)
}()
select {
case <-a.ctx.Done():
case <-done:
}
return err
}
func (s *grpcServer) Stop() {
if s.server != nil {
var ch = make(chan bool)
go func() {
s.server.GracefulStop()
close(ch)
}()
select {
case <-ch:
case <-time.After(5 * time.Second):
s.server.Stop()
}
}
}