-
Notifications
You must be signed in to change notification settings - Fork 28
/
grpc_server.go
388 lines (334 loc) · 12.2 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Copyright 2019-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package cbft
import (
"fmt"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/blevesearch/bleve/v2"
"github.com/blevesearch/bleve/v2/search"
"github.com/blevesearch/bleve/v2/search/query"
pb "github.com/couchbase/cbft/protobuf"
"github.com/couchbase/cbgt"
log "github.com/couchbase/clog"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var FeatureGRPC = "protocol:gRPC"
// atomic counter that keep track of the number of gRPC searches
var totRemoteGrpc uint64
var totRemoteGrpcSsl uint64
// totGrpcQueryRejectOnNotEnoughQuota tracks the number of rejected
// gRPC search requests on hitting the memory threshold for query
var totGrpcQueryRejectOnNotEnoughQuota uint64
// SearchService is an implementation for the SearchSrvServer
// gRPC search interface
type SearchService struct {
mgr *cbgt.Manager
}
func (s *SearchService) SetManager(mgr *cbgt.Manager) {
s.mgr = mgr
}
func (s *SearchService) Check(ctx context.Context,
in *pb.HealthCheckRequest) (*pb.HealthCheckResponse, error) {
if in.Service == "" || in.Service == "Search" ||
in.Service == "DocCount" {
return &pb.HealthCheckResponse{
Status: pb.HealthCheckResponse_SERVING,
}, nil
}
return nil, status.Error(codes.NotFound, "unknown service")
}
func (s *SearchService) DocCount(ctx context.Context,
req *pb.DocCountRequest) (*pb.DocCountResult, error) {
pindex := s.mgr.GetPIndex(req.IndexName)
if pindex == nil {
return &pb.DocCountResult{DocCount: 0}, fmt.Errorf("grpc_server: "+
"CountPIndex, no pindex, pindexName: %s", req.IndexName)
}
if pindex.Dest == nil {
return &pb.DocCountResult{DocCount: 0}, fmt.Errorf("grpc_server: "+
"CountPIndex, no pindex.Dest, pindexName: %s", req.IndexName)
}
if req.IndexUUID != "" && pindex.UUID != req.IndexUUID {
return &pb.DocCountResult{DocCount: 0}, fmt.Errorf("grpc_server: "+
"CountPIndex, wrong pindexUUID: %s, pindex.UUID: %s, pindexName: %s",
req.IndexUUID, pindex.UUID, req.IndexName)
}
count, err := pindex.Dest.Count(pindex, nil)
if err != nil {
return &pb.DocCountResult{DocCount: 0}, fmt.Errorf("grpc_server: "+
"CountPIndex, pindexName: %s, req: %#v, err: %v",
req.IndexName, req, err)
}
return &pb.DocCountResult{DocCount: int64(count)}, nil
}
func (s *SearchService) Search(req *pb.SearchRequest,
stream pb.SearchService_SearchServer) (err error) {
startTime := time.Now()
if req == nil {
return status.Error(codes.FailedPrecondition,
"grpc_server: Search empty search request")
}
defer func() {
updateRpcFocusStats(startTime, s.mgr, req, stream.Context(), err)
}()
err = verifyRPCAuth(stream.Context(), req.IndexName, req)
if err != nil {
return status.Errorf(codes.PermissionDenied,
"grpc_server: Search err: %v", err)
}
queryCtlParams := cbgt.QueryCtlParams{
Ctl: cbgt.QueryCtl{
Timeout: cbgt.QUERY_CTL_DEFAULT_TIMEOUT_MS,
},
}
if req.QueryCtlParams != nil {
err = UnmarshalJSON(req.QueryCtlParams, &queryCtlParams)
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search parsing queryCtlParams, err: %v", err)
}
}
queryPIndexes := QueryPIndexes{}
if req.QueryPIndexes != nil {
err = UnmarshalJSON(req.QueryPIndexes, &queryPIndexes)
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search parsing queryPIndexes, err: %v", err)
}
}
var sr *SearchRequest
err = UnmarshalJSON(req.Contents, &sr)
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search parsing searchRequest, err: %v", err)
}
if string(sr.Q) == "null" {
sr.Q = nil
}
var searchRequest *bleve.SearchRequest
searchRequest, err = sr.ConvertToBleveSearchRequest()
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search processing searchRequest, err: %v", err)
}
// pre process the query if applicable
var undecoratedQuery query.Query
var coordinatingNode bool
if strings.Compare(cbgt.CfgAppVersion, "7.0.0") >= 0 {
hv, _ := extractMetaHeader(stream.Context(), rpcClusterActionKey)
if hv != clusterActionScatterGather {
coordinatingNode = true
undecoratedQuery, searchRequest.Query = sr.decorateQuery(req.IndexName,
searchRequest.Query, nil)
}
}
if queryCtlParams.Ctl.Consistency != nil {
err = ValidateConsistencyParams(queryCtlParams.Ctl.Consistency)
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search validating consistency, err: %v", err)
}
}
// always check for bleveMaxResultWindow, as there is a
// third case of TopN and Streamed results.
if v := s.mgr.GetOption("bleveMaxResultWindow"); len(v) > 0 {
var bleveMaxResultWindow int
bleveMaxResultWindow, err = strconv.Atoi(v)
if err != nil {
return status.Errorf(codes.InvalidArgument,
"grpc_server: Search atoi: %v, err: %v", v, err)
}
if searchRequest.From+searchRequest.Size > bleveMaxResultWindow ||
(searchRequest.Size > bleveMaxResultWindow &&
(searchRequest.SearchAfter != nil || searchRequest.SearchBefore != nil)) {
err = status.Errorf(codes.InvalidArgument,
"Validating request, err: %v",
fmt.Errorf("grpc_server: Search bleveMaxResultWindow exceeded,"+
" from: %d, size: %d, bleveMaxResultWindow: %d",
searchRequest.From, searchRequest.Size,
bleveMaxResultWindow))
return err
}
}
// phase 1 - set up timeouts, wait for local consistency reqiurements
// to be satisfied, could return err 412
// create a context with the appropriate timeout
ctx, cancel, cancelCh := setupContextAndCancelCh(queryCtlParams, nil)
// defer a call to cancel, this ensures that goroutine from
// setupContextAndCancelCh always exits
defer cancel()
var onlyPIndexes map[string]bool
if len(queryPIndexes.PIndexNames) > 0 {
onlyPIndexes = cbgt.StringsToMap(queryPIndexes.PIndexNames)
}
// check if current scatter gather is a presearch
if isPreSearch(stream.Context()) {
ctx = context.WithValue(ctx, search.PreSearchKey, true)
}
alias, remoteClients, numPIndexes, er := bleveIndexAlias(s.mgr, req.IndexName,
req.IndexUUID, true, queryCtlParams.Ctl.Consistency, cancelCh, true,
onlyPIndexes, queryCtlParams.Ctl.PartitionSelection, addGrpcClients)
if er != nil {
if _, ok := er.(*cbgt.ErrorLocalPIndexHealth); !ok {
err = status.Errorf(codes.Unavailable,
"grpc_server: Search bleveIndexAlias, err: %v", er)
return err
}
}
var sh *streamer
var handlerMaker search.MakeDocumentMatchHandler
// check if the client requested streamed results/hits.
if req.Stream {
sh = newStreamHandler(req.IndexName, searchRequest, stream)
handlerMaker = sh.MakeDocumentMatchHandler
ctx = context.WithValue(ctx, search.MakeDocumentMatchHandlerKey,
handlerMaker)
for _, rc := range remoteClients {
if gc, ok := rc.(RemoteClient); ok {
gc.SetStreamHandler(sh)
}
}
}
// estimate memory needed for merging search results from all
// the pindexes
mergeEstimate := uint64(numPIndexes) * bleve.MemoryNeededForSearchResult(searchRequest)
err = fireQueryEvent(0, EventQueryStart, 0, mergeEstimate)
if err != nil {
atomic.AddUint64(&totGrpcQueryRejectOnNotEnoughQuota, 1)
return status.Errorf(codes.ResourceExhausted,
"grpc_server: Search query reject on not enough quota: %v", err)
}
defer fireQueryEvent(0, EventQueryEnd, 0, mergeEstimate)
// set query start/end callbacks
ctx = context.WithValue(ctx, bleve.SearchQueryStartCallbackKey,
bleve.SearchQueryStartCallbackFn(bleveCtxQueryStartCallback))
ctx = context.WithValue(ctx, bleve.SearchQueryEndCallbackKey,
bleve.SearchQueryEndCallbackFn(bleveCtxQueryEndCallback))
ctx = context.WithValue(ctx, search.SearcherStartCallbackKey,
search.SearcherStartCallbackFn(bleveCtxSearcherStartCallback))
ctx = context.WithValue(ctx, search.SearcherEndCallbackKey,
search.SearcherEndCallbackFn(bleveCtxSearcherEndCallback))
if coordinatingNode {
// register with the QuerySupervisor only on the coordinating node.
id := querySupervisor.AddEntry(&QuerySupervisorContext{
Query: searchRequest.Query,
Cancel: cancel,
Size: searchRequest.Size,
From: searchRequest.From,
Timeout: queryCtlParams.Ctl.Timeout,
IndexName: req.IndexName,
})
defer querySupervisor.DeleteEntry(id)
}
var searchResult *bleve.SearchResult
searchResult, err = alias.SearchInContext(ctx, searchRequest)
if searchResult != nil {
// if the query decoration happens for collection targeted or docID
// queries for multi collection indexes, then restore the original
// user query in the search response, if the search request was echo'd
// back in the search result.
// Note: searchResult.Request will be non nil only when searchRequest.Explain is true
// and its a bleve level setting
if undecoratedQuery != nil && searchResult.Request != nil {
searchResult.Request.Query = undecoratedQuery
}
err1 := processSearchResult(&queryCtlParams, req.IndexName, searchResult,
remoteClients, err, er)
if err1 != nil {
err = status.Error(codes.DeadlineExceeded,
fmt.Sprintf("grpc_server: Search searchInContext err: %v", err1))
return err
}
if searchResult.Status != nil &&
len(searchResult.Status.Errors) > 0 &&
queryCtlParams.Ctl.Consistency != nil &&
queryCtlParams.Ctl.Consistency.Results == "complete" {
// complete results expected, do not propagate partial results
return fmt.Errorf("grpc_server: results weren't retrieved from some"+
" index partitions: %d", len(searchResult.Status.Errors))
}
response, er2 := MarshalJSON(searchResult)
if er2 != nil {
err = status.Errorf(codes.Internal,
"grpc_server: Search response marshal err: %v", er2)
return err
}
rv := &pb.StreamSearchResults{
Contents: &pb.StreamSearchResults_SearchResult{
SearchResult: response,
}}
if err = stream.Send(rv); err != nil {
return status.Errorf(codes.Internal,
"grpc_server: Search stream send, err: %v", err)
}
}
return err
}
// TODO chaining of unary & stream interceptors can be done
// if neeeded for more stats/request tracking or debugging.
// eg: https://github.com/grpc-ecosystem/go-grpc-middleware
/*
func serverInterceptor(ctx context.Context, req interface{},
info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
start := time.Now()
response, err := handler(ctx, req)
log.Printf("grpc_server: invoke server method: %s duration: %f sec err: %v",
info.FullMethod, time.Since(start).Seconds(), err)
return response, err
}*/
// wrappedServerStream is a thin wrapper around
// grpc.ServerStream that allows modifying context.
type wrappedServerStream struct {
grpc.ServerStream
// WrappedContext is the wrapper's own Context. You can assign it.
wrappedContext context.Context
}
// Context returns the wrapper's wrappedContext,
// overwriting the nested grpc.ServerStream.Context()
func (w *wrappedServerStream) Context() context.Context {
return w.wrappedContext
}
// wrapServerStream returns a ServerStream that has
// the ability to overwrite context.
func wrapServerStream(stream grpc.ServerStream) *wrappedServerStream {
if existing, ok := stream.(*wrappedServerStream); ok {
return existing
}
return &wrappedServerStream{ServerStream: stream,
wrappedContext: stream.Context()}
}
func AddServerInterceptor() grpc.ServerOption {
return grpc.StreamInterceptor(serverInterceptor)
}
func serverInterceptor(
req interface{},
ss grpc.ServerStream,
info *grpc.StreamServerInfo,
handler grpc.StreamHandler) (err error) {
// skip the authCallbacks wrapping/authentication for scatter gather calls,
// as the user is already authenticated at the original node.
if _, err = extractMetaHeader(ss.Context(), rpcClusterActionKey); err == nil {
w := wrapServerStream(ss)
w.wrappedContext = ss.Context()
return handler(req, w)
}
nctx, err := wrapAuthCallbacks(req, ss.Context(), info.FullMethod)
if err != nil {
log.Errorf("grpc_server: authenticate err: %+v", err)
return err
}
w := wrapServerStream(ss)
w.wrappedContext = nctx
return handler(req, w)
}