forked from couchbase/cbgt
/
gocb_helper.go
315 lines (259 loc) · 7.68 KB
/
gocb_helper.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
// Copyright (c) 2018 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 cbgt
import (
"fmt"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/couchbase/cbauth"
"github.com/couchbase/gocb"
"gopkg.in/couchbase/gocbcore.v7"
)
// ----------------------------------------------------------------
type gocbAgentMap struct {
// Mutex to serialize access to entries
m sync.Mutex
// Map of gocbcore.Agent instances by bucket <name>:<uuid>
entries map[string]*gocbcore.Agent
}
var agentMap *gocbAgentMap
func init() {
agentMap = &gocbAgentMap{
entries: make(map[string]*gocbcore.Agent),
}
}
// Fetches a gocbcore agent instance for the bucket (name:uuid),
// if not found creates a new instance and stashes it in the map.
func (am *gocbAgentMap) fetchAgent(name, uuid, params, server string,
options map[string]string) (*gocbcore.Agent, error) {
am.m.Lock()
defer am.m.Unlock()
key := name + ":" + uuid
if _, exists := am.entries[key]; !exists {
agent, err := newAgent(name, uuid, params, server, options)
if err != nil {
return nil, err
}
am.entries[key] = agent
}
return am.entries[key], nil
}
// Closes and removes the gocbcore Agent instance with the uuid.
func (am *gocbAgentMap) closeAgent(name, uuid string) {
am.m.Lock()
defer am.m.Unlock()
key := name + ":" + uuid
if _, exists := am.entries[key]; exists {
am.entries[key].Close()
delete(am.entries, key)
}
}
// ----------------------------------------------------------------
func newAgent(sourceName, sourceUUID, sourceParams, serverIn string,
options map[string]string) (*gocbcore.Agent, error) {
server, _, bucketName :=
CouchbaseParseSourceName(serverIn, "default", sourceName)
config := &gocbcore.AgentConfig{
UserString: "stats",
BucketName: bucketName,
ConnectTimeout: 60000 * time.Millisecond,
ServerConnectTimeout: 7000 * time.Millisecond,
NmvRetryDelay: 100 * time.Millisecond,
UseKvErrorMaps: true,
Auth: &Authenticator{},
}
svrs := strings.Split(server, ";")
if len(svrs) <= 0 {
return nil, fmt.Errorf("gocb_helper: newAgent, no servers provided")
}
err := config.FromConnStr(svrs[0])
if err != nil {
return nil, err
}
return gocbcore.CreateAgent(config)
}
// ----------------------------------------------------------------
// CBPartitions parses a sourceParams for a couchbase
// data-source/feed.
func CBPartitions(sourceType, sourceName, sourceUUID, sourceParams,
serverIn string, options map[string]string) (
partitions []string, err error) {
agent, err := agentMap.fetchAgent(sourceName, sourceUUID,
sourceParams, serverIn, options)
if err != nil {
return nil, err
}
numVBuckets := agent.NumVbuckets()
rv := make([]string, numVBuckets)
for i := 0; i < numVBuckets; i++ {
rv[i] = strconv.Itoa(i)
}
return rv, nil
}
// ----------------------------------------------------------------
// CBPartitionSeqs returns a map keyed by partition/vbucket ID
// with values of each vbucket's UUID / high_seqno. It implements the
// FeedPartitionsFunc func signature.
func CBPartitionSeqs(sourceType, sourceName, sourceUUID,
sourceParams, serverIn string,
options map[string]string) (
map[string]UUIDSeq, error) {
agent, err := agentMap.fetchAgent(sourceName, sourceUUID,
sourceParams, serverIn, options)
if err != nil {
return nil, err
}
rv := map[string]UUIDSeq{}
signal := make(chan error, 1)
op, err := agent.StatsEx(gocbcore.StatsOptions{Key: "vbucket-details"},
func(resp *gocbcore.StatsResult, er error) {
if resp == nil || er != nil {
signal <- er
return
}
stats := resp.Servers
for _, nodeStats := range stats {
if nodeStats.Error != nil || len(nodeStats.Stats) <= 0 {
continue
}
for _, vbid := range vbucketIdStrings {
stateVal, ok := nodeStats.Stats["vb_"+vbid]
if !ok || stateVal != "active" {
continue
}
uuid, ok := nodeStats.Stats["vb_"+vbid+":uuid"]
if !ok {
continue
}
seqStr, ok := nodeStats.Stats["vb_"+vbid+":high_seqno"]
if !ok {
continue
}
seq, err := strconv.ParseUint(seqStr, 10, 64)
if err == nil {
rv[vbid] = UUIDSeq{
UUID: uuid,
Seq: seq,
}
}
}
}
signal <- nil
})
if err != nil {
return nil, err
}
timeoutTmr := gocbcore.AcquireTimer(30 * time.Second)
select {
case err := <-signal:
gocbcore.ReleaseTimer(timeoutTmr, false)
return rv, err
case <-timeoutTmr.C:
gocbcore.ReleaseTimer(timeoutTmr, true)
if !op.Cancel() {
err := <-signal
return rv, err
}
return nil, gocb.ErrTimeout
}
}
// ----------------------------------------------------------------
// CBStats returns a map of aggregated ("aggStats") and
// per-node stats ("nodesStats"). It implements the FeedStatsFunc
// func signature.
func CBStats(sourceType, sourceName, sourceUUID,
sourceParams, serverIn string,
options map[string]string, statsKind string) (
map[string]interface{}, error) {
agent, err := agentMap.fetchAgent(sourceName, sourceUUID,
sourceParams, serverIn, options)
if err != nil {
return nil, err
}
signal := make(chan error, 1)
var rv map[string]interface{}
op, err := agent.StatsEx(gocbcore.StatsOptions{Key: statsKind},
func(resp *gocbcore.StatsResult, er error) {
if resp == nil || er != nil {
signal <- er
return
}
stats := resp.Servers
aggStats := map[string]int64{} // Calculate aggregates.
for _, nodeStats := range stats {
if nodeStats.Error != nil {
continue
}
for k, v := range nodeStats.Stats {
iv, err := strconv.ParseInt(v, 10, 64)
if err == nil {
aggStats[k] += iv
}
}
}
rv = map[string]interface{}{
"aggStats": aggStats,
"nodesStats": stats,
}
if statsKind == "" {
rv["docCount"] = aggStats["curr_items"]
}
signal <- nil
})
if err != nil {
return nil, err
}
timeoutTmr := gocbcore.AcquireTimer(30 * time.Second)
select {
case err := <-signal:
gocbcore.ReleaseTimer(timeoutTmr, false)
return rv, err
case <-timeoutTmr.C:
gocbcore.ReleaseTimer(timeoutTmr, true)
if !op.Cancel() {
err := <-signal
return rv, err
}
return nil, gocb.ErrTimeout
}
}
// ----------------------------------------------------------------
// CBVBucketLookUp looks up the source vBucketID for a given
// document ID and index.
func CBVBucketLookUp(docID, serverIn string,
sourceDetails *IndexDef, req *http.Request) (string, error) {
var config gocbcore.AgentConfig
agent, err := gocbcore.CreateAgent(&config)
if err != nil {
return "", err
}
defer agent.Close()
vb := agent.KeyToVbucket([]byte(docID))
return strconv.Itoa(int(vb)), nil
}
// ----------------------------------------------------------------
type Authenticator struct{}
func (a *Authenticator) Credentials(req gocbcore.AuthCredsRequest) ([]gocbcore.UserPassPair, error) {
endpoint := req.Endpoint
// get rid of the http:// or https:// prefix from the endpoint
endpoint = strings.TrimPrefix(strings.TrimPrefix(endpoint, "http://"), "https://")
username, password, err := cbauth.GetMemcachedServiceAuth(endpoint)
if err != nil {
return []gocbcore.UserPassPair{{}}, err
}
return []gocbcore.UserPassPair{{
Username: username,
Password: password,
}}, nil
}