-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
394 lines (328 loc) · 9.37 KB
/
config.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
// 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 n1fty
import (
"fmt"
"os"
"path"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/couchbase/cbgt"
"github.com/couchbase/n1fty/util"
"github.com/couchbase/query/datastore"
"github.com/couchbase/query/errors"
"github.com/couchbase/query/logging"
)
const backfillSpaceDir = "query_tmpspace_dir"
const backfillSpaceLimit = "query_tmpspace_limit"
const searchTimeoutMS = "searchTimeoutMS"
const metakvMetaDir = "/fts/cbgt/cfg/"
// 5120 is the default tmp space limit shared between gsi/n1fty
var defaultBackfillLimit = int64(5120 / 2)
var defaultSearchTimeoutMS = int64(120000) // 2min
const backfillPrefix = "search-results"
// ftsConfig is the metakv config listener which helps the
// n1fty indexer to refresh it's config information like
// index/node definitions.
type ftsConfig struct {
cfg cbgt.Cfg
eventCh chan cbgt.CfgEvent
version uint64 // version for the metakv config changes
m sync.RWMutex
subscribers map[string]datastore.Indexer
m1 sync.RWMutex
indexDefs *cbgt.IndexDefs
nodeDefs *cbgt.NodeDefs
}
var once sync.Once
var srvConfig *ftsConfig
func init() {
var err error
srvConfig = &ftsConfig{
eventCh: make(chan cbgt.CfgEvent),
subscribers: make(map[string]datastore.Indexer),
version: 1,
}
cbgt.CfgMetaKvPrefix = "/fts/cbgt/cfg/"
srvConfig.cfg, err = cbgt.NewCfgMetaKv("", make(map[string]string))
if err != nil {
logging.Errorf("n1fty: ftsConfig err: %v", err)
}
srvConfig.cfg.Subscribe(cbgt.INDEX_DEFS_KEY, srvConfig.eventCh)
srvConfig.cfg.Subscribe(cbgt.CfgNodeDefsKey(cbgt.NODE_DEFS_KNOWN), srvConfig.eventCh)
go srvConfig.Listen()
}
var nodeDefsKnownKey = cbgt.CfgNodeDefsKey(cbgt.NODE_DEFS_KNOWN)
func (c *ftsConfig) Listen() {
for {
select {
case ev := <-c.eventCh:
// first bump the version so that the subscribers can
// verify the updated version with their cached one.
c.bumpVersion()
if ev.Key == nodeDefsKnownKey {
nodeDefs, _, err := cbgt.CfgGetNodeDefs(c.cfg, "known")
if err != nil {
logging.Infof("n1fty: ftsConfig CfgGetNodeDefs, err: %v", err)
// reset the node defs so that the clients shall
// fetch it directly from metakv.
nodeDefs = nil
}
c.m1.Lock()
c.nodeDefs = nodeDefs
c.m1.Unlock()
err = ftsClientInst.updateConnPools(topologyChange)
if err != nil {
logging.Errorf("n1fty: failed to update connection pools "+
"on TopologyChange, err: %v", err)
}
}
if ev.Key == cbgt.INDEX_DEFS_KEY {
indexDefs, _, err := cbgt.CfgGetIndexDefs(c.cfg)
if err != nil {
logging.Infof("n1fty: ftsConfig CfgGetIndexDefs, err: %v", err)
// reset the index defs so that the clients shall
// fetch it directly from metakv.
indexDefs = nil
}
c.m1.Lock()
c.indexDefs = indexDefs
c.m1.Unlock()
}
// clear mappingsCache (used during Verify/Eval) to
// remove any stale entries; the following refresh(..)
// on every indexer will add the latest entries into
// the cache.
util.ClearMappingsCache()
c.m.Lock()
for _, i := range c.subscribers {
if indexer, ok := i.(*FTSIndexer); ok {
indexer.refresh(true)
}
}
c.m.Unlock()
}
}
}
func (c *ftsConfig) subscribe(key string, i datastore.Indexer) {
c.m.Lock()
c.subscribeLOCKED(key, i)
c.m.Unlock()
}
func (c *ftsConfig) subscribeLOCKED(key string, i datastore.Indexer) {
c.subscribers[key] = i
}
func (c *ftsConfig) unSubscribe(key string) {
c.m.Lock()
delete(c.subscribers, key)
c.m.Unlock()
}
func (c *ftsConfig) getVersion() uint64 {
return atomic.LoadUint64(&c.version)
}
func (c *ftsConfig) bumpVersion() {
atomic.AddUint64(&c.version, 1)
}
type Cfg interface {
datastore.IndexConfig
GetConfig() map[string]interface{}
}
// clientConfig is used by the query to pass on the configs values
// related to the backfill.
var clientConfig n1ftyConfig
// n1ftyConfig implementation of datastore.IndexConfig interface
type n1ftyConfig struct {
config atomic.Value
}
func GetConfig() (datastore.IndexConfig, errors.Error) {
return &clientConfig, nil
}
func setConfig(nf *n1ftyConfig, conf map[string]interface{}) errors.Error {
err := nf.validateConfig(conf)
if err != nil {
return err
}
nf.processConfig(conf)
// make local copy so caller doesn't accidentally modify
newConf := nf.GetConfig()
if newConf == nil {
newConf = make(map[string]interface{})
}
for k, v := range conf {
newConf[k] = v
}
nf.config.Store(newConf)
return nil
}
func (c *n1ftyConfig) SetConfig(conf map[string]interface{}) errors.Error {
return setConfig(c, conf)
}
// SetParam should not be called concurrently with SetConfig
func (c *n1ftyConfig) SetParam(name string, val interface{}) errors.Error {
conf := c.config.Load().(map[string]interface{})
if conf != nil {
tempconf := make(map[string]interface{})
tempconf[name] = val
err := c.validateConfig(tempconf)
if err != nil {
return err
}
c.processConfig(tempconf)
logging.Infof("n1fty: Config - Setting param %v %v", name, val)
conf[name] = val
} else {
conf = make(map[string]interface{})
conf[name] = val
return c.SetConfig(conf)
}
return nil
}
func (c *n1ftyConfig) validateConfig(conf map[string]interface{}) errors.Error {
if conf == nil {
return nil
}
if v, ok := conf[backfillSpaceDir]; ok {
if _, ok1 := v.(string); !ok1 {
err := fmt.Errorf("n1fty: Invalid Config.. key: %v, val: %v",
backfillSpaceDir, v)
return util.N1QLError(err, err.Error())
}
}
if v, ok := conf[backfillSpaceLimit]; ok {
if _, ok1 := v.(int64); !ok1 {
err := fmt.Errorf("n1fty: Invalid Config.. key: %v, val: %v",
backfillSpaceLimit, v)
return util.N1QLError(err, err.Error())
}
}
if v, ok := conf[searchTimeoutMS]; ok {
if _, ok1 := v.(int64); !ok1 {
err := fmt.Errorf("n1fty: Invalid Config.. key: %v, val: %v",
searchTimeoutMS, v)
return util.N1QLError(err, err.Error())
}
}
return nil
}
func (c *n1ftyConfig) processConfig(conf map[string]interface{}) {
var olddir interface{}
var newdir interface{}
if conf != nil {
newdir, _ = conf[backfillSpaceDir]
}
prevconf := clientConfig.GetConfig()
if prevconf != nil {
olddir, _ = prevconf[backfillSpaceDir]
}
if olddir == nil {
olddir = getDefaultTmpDir()
}
// cleanup any stale files
if olddir != newdir {
cleanupTmpFiles(olddir.(string))
if newdir != nil {
cleanupTmpFiles(newdir.(string))
}
}
}
// best effort cleanup as tmpdir may change during restart
func cleanupTmpFiles(olddir string) {
files, err := os.ReadDir(olddir)
if err != nil {
return
}
searchTimeout := defaultSearchTimeoutMS
conf := clientConfig.GetConfig()
if conf != nil {
if val, ok := conf[searchTimeoutMS]; ok {
searchTimeout = val.(int64)
}
}
for _, file := range files {
if fInfo, err := file.Info(); err == nil {
fname := path.Join(olddir, file.Name())
mtime := fInfo.ModTime()
since := (time.Since(mtime).Seconds() * 1000) * 2 // twice the long search
if (strings.Contains(fname, backfillPrefix)) &&
int64(since) > searchTimeout {
logging.Infof("n1fty: removing old file %v, last modified @ %v",
fname, mtime)
os.Remove(fname)
}
}
}
}
func (c *n1ftyConfig) GetConfig() map[string]interface{} {
conf := c.config.Load()
if conf != nil {
return conf.(map[string]interface{})
}
return nil
}
func getDefaultTmpDir() string {
file, err := os.CreateTemp("", backfillPrefix)
if err != nil {
return ""
}
defaultDir := path.Dir(file.Name())
os.Remove(file.Name())
return defaultDir
}
// GetIndexDefs gets the latest indexDefs from configs
func GetIndexDefs(srvConfig *ftsConfig) (*cbgt.IndexDefs, error) {
srvConfig.m1.RLock()
rv := srvConfig.indexDefs
srvConfig.m1.RUnlock()
if rv != nil {
return rv, nil
}
// fetch it from metakv only when the local cache is empty.
indexDefs, _, err := cbgt.CfgGetIndexDefs(srvConfig.cfg)
if err != nil {
return nil, fmt.Errorf("indexDefs err: %v", err)
}
srvConfig.m1.Lock()
srvConfig.indexDefs = indexDefs
srvConfig.m1.Unlock()
return indexDefs, nil
}
// GetNodeDefs gets the latest nodeDefs from configs
func GetNodeDefs(srvConfig *ftsConfig) (*cbgt.NodeDefs, error) {
srvConfig.m1.RLock()
rv := srvConfig.nodeDefs
srvConfig.m1.RUnlock()
if rv != nil {
return rv, nil
}
// fetch it from metakv only when the local cache is empty.
nodeDefs, _, err := cbgt.CfgGetNodeDefs(srvConfig.cfg, "known")
if err != nil {
return nil, fmt.Errorf("nodeDefs err: %v", err)
}
srvConfig.m1.Lock()
srvConfig.nodeDefs = nodeDefs
srvConfig.m1.Unlock()
return nodeDefs, nil
}
// -----------------------------------------------------------------------------
// Atomic updates to variable to determine if system is
// in serverless mode or not - can take values 0 or 1 only.
var serverlessMode uint32
// SetDeploymentModel lets n1fty know the mode of operation.
func SetDeploymentModel(deploymentModel string) {
if deploymentModel == datastore.DEPLOYMENT_MODEL_SERVERLESS {
atomic.StoreUint32(&serverlessMode, 1)
} else {
atomic.StoreUint32(&serverlessMode, 0)
}
}
func IsServerlessMode() bool {
return atomic.LoadUint32(&serverlessMode) == 1
}