forked from couchbase/cbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remote.go
410 lines (335 loc) · 10.5 KB
/
remote.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright (c) 2014 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
package cbft
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/blevesearch/bleve"
"github.com/blevesearch/bleve/document"
"github.com/blevesearch/bleve/index"
"github.com/blevesearch/bleve/index/store"
"github.com/blevesearch/bleve/mapping"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
)
const RemoteRequestOverhead = 500 * time.Millisecond
var HttpTransportDialContextTimeout = 30 * time.Second // Go's default is 30 secs.
var HttpTransportDialContextKeepAlive = 30 * time.Second // Go's default is 30 secs.
var HttpTransportMaxIdleConns = 300 // Go's default is 100 (0 means no limit).
var HttpTransportMaxIdleConnsPerHost = 100 // Go's default is 2.
var HttpTransportIdleConnTimeout = 90 * time.Second // Go's default is 90 secs.
var HttpTransportTLSHandshakeTimeout = 10 * time.Second // Go's default is 10 secs.
var HttpTransportExpectContinueTimeout = 1 * time.Second // Go's default is 1 secs.
var HttpClient = http.DefaultClient // Overridable for testability / advanced needs.
// Overridable for testability / advanced needs.
var HttpPost = func(client *http.Client,
url string, bodyType string, body io.Reader) (*http.Response, error) {
return client.Post(url, bodyType, body)
}
// Overridable for testability / advanced needs.
var HttpGet = func(client *http.Client, url string) (*http.Response, error) {
return client.Get(url)
}
var indexClientUnimplementedErr = errors.New("unimplemented")
// IndexClient implements the Search() and DocCount() subset of the
// bleve.Index interface by accessing a remote cbft server via REST
// protocol. This allows callers to add a IndexClient as a target of
// a bleve.IndexAlias, and implements cbft protocol features like
// query consistency and auth.
//
// TODO: Implement propagating auth info in IndexClient.
type IndexClient struct {
mgr *cbgt.Manager
name string
HostPort string
IndexName string
IndexUUID string
PIndexNames []string
QueryURL string
CountURL string
Consistency *cbgt.ConsistencyParams
httpClient *http.Client
lastMutex sync.RWMutex
lastSearchStatus int
lastErrBody []byte
}
func (r *IndexClient) GetLast() (int, []byte) {
r.lastMutex.RLock()
defer r.lastMutex.RUnlock()
return r.lastSearchStatus, r.lastErrBody
}
func (r *IndexClient) Name() string {
return r.name
}
func (r *IndexClient) SetName(name string) {
r.name = name
}
func (r *IndexClient) Index(id string, data interface{}) error {
return indexClientUnimplementedErr
}
func (r *IndexClient) Delete(id string) error {
return indexClientUnimplementedErr
}
func (r *IndexClient) Batch(b *bleve.Batch) error {
return indexClientUnimplementedErr
}
func (r *IndexClient) Document(id string) (*document.Document, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) DocCount() (uint64, error) {
if r.CountURL == "" {
return 0, fmt.Errorf("remote: no CountURL provided")
}
u, err := UrlWithAuth(r.AuthType(), r.CountURL)
if err != nil {
return 0, fmt.Errorf("remote: auth for count,"+
" countURL: %s, authType: %s, err: %v",
r.CountURL, r.AuthType(), err)
}
resp, err := HttpGet(r.httpClient, u)
if err != nil {
return 0, err
}
defer resp.Body.Close()
respBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, fmt.Errorf("remote: count error reading resp.Body,"+
" countURL: %s, resp: %#v, err: %v", r.CountURL, resp, err)
}
if resp.StatusCode != 200 {
return 0, fmt.Errorf("remote: count got status code: %d,"+
" countURL: %s, resp: %#v", resp.StatusCode, r.CountURL, resp)
}
rv := struct {
Status string `json:"status"`
Count uint64 `json:"count"`
}{}
err = UnmarshalJSON(respBuf, &rv)
if err != nil {
return 0, fmt.Errorf("remote: count error parsing respBuf: %s,"+
" countURL: %s, resp: %#v, err: %v",
respBuf, r.CountURL, resp, err)
}
return rv.Count, nil
}
func (r *IndexClient) Search(req *bleve.SearchRequest) (
*bleve.SearchResult, error) {
return r.SearchInContext(context.Background(), req)
}
func (r *IndexClient) SearchInContext(ctx context.Context,
req *bleve.SearchRequest) (*bleve.SearchResult, error) {
if req == nil {
return nil, fmt.Errorf("remote: no req provided")
}
if r.QueryURL == "" {
return nil, fmt.Errorf("remote: no QueryURL provided")
}
queryCtlParams := &cbgt.QueryCtlParams{
Ctl: cbgt.QueryCtl{
Consistency: r.Consistency,
},
}
queryPIndexes := &QueryPIndexes{
PIndexNames: r.PIndexNames,
}
// if timeout was set, compute time remaining
if deadline, ok := ctx.Deadline(); ok {
remaining := deadline.Sub(time.Now())
// FIXME arbitrarily reducing the timeout, to increase the liklihood
// that a live system replies via HTTP round-trip before we give up
// on the request externally
remaining -= RemoteRequestOverhead
if remaining <= 0 {
// not enough time left
return nil, context.DeadlineExceeded
}
queryCtlParams.Ctl.Timeout = int64(remaining / time.Millisecond)
}
buf, err := MarshalJSON(struct {
*cbgt.QueryCtlParams
*QueryPIndexes
*bleve.SearchRequest
}{
queryCtlParams,
queryPIndexes,
req,
})
if err != nil {
return nil, err
}
resultCh := make(chan *bleve.SearchResult, 1)
go func() {
respBuf, err := r.Query(buf)
if err != nil {
resultCh <- makeSearchResultErr(req, r.PIndexNames, err)
return
}
rv := &bleve.SearchResult{
Status: &bleve.SearchStatus{
Errors: make(map[string]error),
},
}
err = UnmarshalJSON(respBuf, rv)
if err != nil {
resultCh <- makeSearchResultErr(req, r.PIndexNames,
fmt.Errorf("remote: search error parsing respBuf: %s,"+
" queryURL: %s, err: %v", respBuf, r.QueryURL, err))
return
}
resultCh <- rv
}()
select {
case <-ctx.Done():
return makeSearchResultErr(req, r.PIndexNames, ctx.Err()), nil
case rv := <-resultCh:
return rv, nil
}
}
func (r *IndexClient) Fields() ([]string, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) FieldDict(field string) (index.FieldDict, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) FieldDictRange(field string,
startTerm []byte, endTerm []byte) (index.FieldDict, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) FieldDictPrefix(field string,
termPrefix []byte) (index.FieldDict, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) DumpAll() chan interface{} {
return nil
}
func (r *IndexClient) DumpDoc(id string) chan interface{} {
return nil
}
func (r *IndexClient) DumpFields() chan interface{} {
return nil
}
func (r *IndexClient) Close() error {
return indexClientUnimplementedErr
}
func (r *IndexClient) Mapping() mapping.IndexMapping {
return nil
}
func (r *IndexClient) NewBatch() *bleve.Batch {
return nil
}
func (r *IndexClient) Stats() *bleve.IndexStat {
return nil
}
func (r *IndexClient) StatsMap() map[string]interface{} {
return nil
}
func (r *IndexClient) GetInternal(key []byte) ([]byte, error) {
return nil, indexClientUnimplementedErr
}
func (r *IndexClient) SetInternal(key, val []byte) error {
return indexClientUnimplementedErr
}
func (r *IndexClient) DeleteInternal(key []byte) error {
return indexClientUnimplementedErr
}
// -----------------------------------------------------
func (r *IndexClient) Count() (uint64, error) {
return r.DocCount()
}
func (r *IndexClient) Query(buf []byte) ([]byte, error) {
u, err := UrlWithAuth(r.AuthType(), r.QueryURL)
if err != nil {
return nil, fmt.Errorf("remote: auth for query,"+
" queryURL: %s, authType: %s, err: %v",
r.QueryURL, r.AuthType(), err)
}
req, err := http.NewRequest("POST", u, bytes.NewReader(buf))
if err != nil {
return nil, err
}
req.Header.Add(rest.CLUSTER_ACTION, "fts/scatter-gather")
req.Header.Add("Content-Type", "application/json")
resp, err := r.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("remote: query error reading resp.Body,"+
" queryURL: %s, resp: %#v, err: %v", r.QueryURL, resp, err)
}
r.lastMutex.Lock()
defer r.lastMutex.Unlock()
r.lastSearchStatus = resp.StatusCode
if resp.StatusCode != http.StatusOK {
r.lastErrBody = respBuf
return nil, fmt.Errorf("remote: query got status code: %d,"+
" queryURL: %s, buf: %s, resp: %#v, err: %v",
resp.StatusCode, r.QueryURL, buf, resp, err)
}
return respBuf, err
}
func (r *IndexClient) Advanced() (index.Index, store.KVStore, error) {
return nil, nil, indexClientUnimplementedErr
}
// -----------------------------------------------------
func (r *IndexClient) AuthType() string {
if r.mgr != nil {
return r.mgr.Options()["authType"]
}
return ""
}
// -----------------------------------------------------
// GroupIndexClientsByHostPort groups the index clients by their
// HostPort, merging the pindexNames. This is an enabler to allow
// scatter/gather to use fewer REST requests/connections.
func GroupIndexClientsByHostPort(clients []*IndexClient) (rv []*IndexClient, err error) {
m := map[string]*IndexClient{}
for _, client := range clients {
groupByKey := client.HostPort +
"/" + client.IndexName + "/" + client.IndexUUID
c, exists := m[groupByKey]
if !exists {
prefix := ""
if client.mgr != nil {
prefix = client.mgr.Options()["urlPrefix"]
}
proto := "http://"
if strings.Contains(client.QueryURL, "https") {
proto = "https://"
}
baseURL := proto + client.HostPort +
prefix + "/api/index/" + client.IndexName
c = &IndexClient{
mgr: client.mgr,
name: groupByKey,
HostPort: client.HostPort,
IndexName: client.IndexName,
IndexUUID: client.IndexUUID,
QueryURL: baseURL + "/query",
CountURL: baseURL + "/count",
Consistency: client.Consistency,
httpClient: client.httpClient,
}
m[groupByKey] = c
rv = append(rv, c)
}
c.PIndexNames = append(c.PIndexNames, client.PIndexNames...)
}
return rv, nil
}