-
Notifications
You must be signed in to change notification settings - Fork 277
/
database.go
405 lines (371 loc) · 11.4 KB
/
database.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
// Licensed to LinDB under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. LinDB licenses this file to you 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 tsdb
import (
"context"
"fmt"
"io"
"runtime"
"sync"
"time"
"go.uber.org/atomic"
"github.com/lindb/lindb/internal/concurrent"
"github.com/lindb/lindb/internal/linmetric"
"github.com/lindb/lindb/kv"
"github.com/lindb/lindb/metrics"
"github.com/lindb/lindb/models"
"github.com/lindb/lindb/pkg/logger"
"github.com/lindb/lindb/pkg/option"
"github.com/lindb/lindb/tsdb/metadb"
"github.com/lindb/lindb/tsdb/tblstore/tagkeymeta"
)
//go:generate mockgen -source=./database.go -destination=./database_mock.go -package=tsdb
// Database represents an abstract time series database
type Database interface {
// Name returns time series database's name
Name() string
// NumOfShards returns number of families in time series database
NumOfShards() int
// GetConfig return the configuration of database.
GetConfig() *models.DatabaseConfig
// GetOption returns the database options
GetOption() *option.DatabaseOption
// CreateShards creates families for data partition
CreateShards(shardIDs []models.ShardID) error
// GetShard returns shard by given shard id
GetShard(shardID models.ShardID) (Shard, bool)
// ExecutorPool returns the pool for querying tasks
ExecutorPool() *ExecutorPool
// Closer closes database's underlying resource
io.Closer
// Metadata returns the metadata include metric/tag
Metadata() metadb.Metadata
// FlushMeta flushes meta to disk
FlushMeta() error
// WaitFlushMetaCompleted waits flush metadata job completed.
WaitFlushMetaCompleted()
// Flush flushes memory data of all families to disk
Flush() error
// Drop drops current database include all data.
Drop() error
// TTL expires the data of each shard base on time to live.
TTL()
// EvictSegment evicts segment which long term no read operation.
EvictSegment()
// SetLimits sets database's limits.
SetLimits(limits *models.Limits)
// GetLimits returns database's limits.
GetLimits() *models.Limits
}
// database implements Database for storing families,
// each shard represents a time series storage
type database struct {
name string // database-name
dir string
config *models.DatabaseConfig // meta configuration
executorPool *ExecutorPool // executor pool for querying task
mutex sync.Mutex // mutex for creating families
shardSet shardSet // atomic value
metadata metadb.Metadata // underlying metric metadata
metaStore kv.Store // underlying meta kv store
isFlushing atomic.Bool // restrict flusher concurrency
flushCondition *sync.Cond // flush condition
limits atomic.Value // store models.Limits
statistics *metrics.DatabaseStatistics
flushChecker DataFlushChecker
}
// newDatabase creates the database instance
func newDatabase(
databaseName string,
cfg *models.DatabaseConfig,
limits *models.Limits,
flushChecker DataFlushChecker,
) (Database, error) {
if err := cfg.Option.Validate(); err != nil {
return nil, fmt.Errorf("database option is invalid, err: %s", err)
}
db := &database{
name: databaseName,
flushChecker: flushChecker,
config: cfg,
shardSet: *newShardSet(),
executorPool: &ExecutorPool{
Filtering: concurrent.NewPool(
databaseName+"-filtering-pool",
runtime.GOMAXPROCS(-1), /*nRoutines*/
time.Second*5,
metrics.NewConcurrentStatistics(databaseName+"-filtering", linmetric.StorageRegistry),
),
Grouping: concurrent.NewPool(
databaseName+"-grouping-pool",
runtime.GOMAXPROCS(-1), /*nRoutines*/
time.Second*5,
metrics.NewConcurrentStatistics(databaseName+"-grouping", linmetric.StorageRegistry),
),
Scanner: concurrent.NewPool(
databaseName+"-scanner-pool",
runtime.GOMAXPROCS(-1), /*nRoutines*/
time.Second*5,
metrics.NewConcurrentStatistics(databaseName+"-scanner", linmetric.StorageRegistry),
),
},
isFlushing: *atomic.NewBool(false),
flushCondition: sync.NewCond(&sync.Mutex{}),
statistics: metrics.NewDatabaseStatistics(databaseName),
}
dbPath, err0 := createDatabasePath(databaseName)
if err0 != nil {
return nil, err0
}
db.dir = dbPath
if err := db.dumpDatabaseConfig(cfg); err != nil {
return nil, err
}
if err := db.initMetadata(); err != nil {
return nil, err
}
var err error
defer func() {
if err != nil && db.metadata != nil {
if e := db.metadata.Close(); e != nil {
engineLogger.Error("close metadata err will create database",
logger.Error(e), logger.String("db", databaseName))
}
}
}()
db.limits.Store(limits)
// load families if engine is existed
var shard Shard
if len(db.config.ShardIDs) > 0 {
for _, shardID := range db.config.ShardIDs {
shard, err = newShardFunc(db, shardID)
if err != nil {
return nil, fmt.Errorf("cannot create shard[%d] of database[%s] with error: %s",
shardID, databaseName, err)
}
db.shardSet.InsertShard(shardID, shard)
}
}
return db, nil
}
// SetLimits sets database's limits.
func (db *database) SetLimits(limits *models.Limits) {
db.limits.Store(limits)
db.mutex.Lock()
defer db.mutex.Unlock()
shards := db.shardSet.Entries()
for _, shard := range shards {
shard.shard.notifyLimitsChange()
}
}
// GetLimits returns database's limits.
func (db *database) GetLimits() *models.Limits {
return db.limits.Load().(*models.Limits)
}
// Metadata returns the metadata include metric/tag
func (db *database) Metadata() metadb.Metadata {
return db.metadata
}
// Name returns time series database's name
func (db *database) Name() string {
return db.name
}
// NumOfShards returns number of families in time series database
func (db *database) NumOfShards() int {
return db.shardSet.GetShardNum()
}
// GetConfig return the configuration of database.
func (db *database) GetConfig() *models.DatabaseConfig {
return db.config
}
// GetOption returns the database options
func (db *database) GetOption() *option.DatabaseOption {
return db.config.Option
}
// CreateShards creates families for data partition
func (db *database) CreateShards(
shardIDs []models.ShardID,
) error {
if len(shardIDs) == 0 {
return fmt.Errorf("shardIDs list is empty")
}
for _, shardID := range shardIDs {
if _, ok := db.GetShard(shardID); ok {
continue
}
if err := db.createShard(shardID); err != nil {
return err
}
}
return nil
}
// createShard creates a new shard based on option
func (db *database) createShard(shardID models.ShardID) error {
// be careful need do mutex unlock
db.mutex.Lock()
defer db.mutex.Unlock()
// double check
if _, ok := db.GetShard(shardID); ok {
return nil
}
// new shard
createdShard, err := newShardFunc(
db,
shardID)
if err != nil {
return fmt.Errorf("create shard[%d] for engine[%s] with error: %s", shardID, db.name, err)
}
// using new engine option
newCfg := &models.DatabaseConfig{Option: db.config.Option, ShardIDs: db.config.ShardIDs}
// add new shard id
newCfg.ShardIDs = append(newCfg.ShardIDs, shardID)
if err := db.dumpDatabaseConfig(newCfg); err != nil {
// TODO if dump config err, need close shard??
return err
}
db.shardSet.InsertShard(shardID, createdShard)
return nil
}
// GetShard returns shard by given shard id,
func (db *database) GetShard(shardID models.ShardID) (Shard, bool) {
return db.shardSet.GetShard(shardID)
}
// ExecutorPool returns the query task execute pool
func (db *database) ExecutorPool() *ExecutorPool {
return db.executorPool
}
// Close closes database's underlying resource
func (db *database) Close() error {
// wait previous flush job completed
db.WaitFlushMetaCompleted()
if err := db.metadata.Close(); err != nil {
return err
}
if err := kv.GetStoreManager().CloseStore(db.metaStore.Name()); err != nil {
return err
}
for _, shardEntry := range db.shardSet.Entries() {
thisShard := shardEntry.shard
if err := thisShard.Close(); err != nil {
engineLogger.Error(fmt.Sprintf(
"close shard[%d] of database[%s]", shardEntry.shardID, db.name), logger.Error(err))
}
}
return nil
}
// TTL expires the data of each shard base on time to live.
func (db *database) TTL() {
for _, shardEntry := range db.shardSet.Entries() {
thisShard := shardEntry.shard
thisShard.TTL()
}
}
// EvictSegment evicts segment which long term no read operation.
func (db *database) EvictSegment() {
for _, shardEntry := range db.shardSet.Entries() {
thisShard := shardEntry.shard
thisShard.EvictSegment()
}
}
// dumpDatabaseConfig persists option info to OPTIONS file
func (db *database) dumpDatabaseConfig(newConfig *models.DatabaseConfig) error {
cfgPath := optionsPath(db.name)
// write store info using toml format
if err := encodeToml(cfgPath, newConfig); err != nil {
return fmt.Errorf("write engine options to file[%s] error:%s", cfgPath, err)
}
db.config = newConfig
return nil
}
// initMetadata initializes metadata backend storage
func (db *database) initMetadata() error {
// FIXME: close kv store if err??
metaStore, err := kv.GetStoreManager().CreateStore(tagMetaIndicator(db.name), kv.DefaultStoreOption())
if err != nil {
return err
}
tagMetaFamily, err := metaStore.CreateFamily(
tagValueDir,
kv.FamilyOption{
CompactThreshold: 0,
Merger: string(tagkeymeta.MergerName)})
if err != nil {
return err
}
db.metaStore = metaStore
metadata, err := newMetadataFunc(context.TODO(), db.name, metricsMetaPath(db.name), tagMetaFamily)
if err != nil {
return err
}
db.metadata = metadata
return nil
}
// FlushMeta flushes meta to disk.
func (db *database) FlushMeta() (err error) {
// another flush process is running
if !db.isFlushing.CAS(false, true) {
return nil
}
start := time.Now()
defer func() {
db.flushCondition.L.Lock()
db.isFlushing.Store(false)
db.flushCondition.L.Unlock()
db.flushCondition.Broadcast()
db.statistics.MetaDBFlushDuration.UpdateSince(start)
}()
if err := db.metadata.Flush(); err != nil {
db.statistics.MetaDBFlushFailures.Incr()
return err
}
return nil
}
// WaitFlushMetaCompleted waits flush metadata job completed.
func (db *database) WaitFlushMetaCompleted() {
db.flushCondition.L.Lock()
if db.isFlushing.Load() {
db.flushCondition.Wait()
}
db.flushCondition.L.Unlock()
}
// Flush flushes memory data of all families to disk.
func (db *database) Flush() error {
for _, shardEntry := range db.shardSet.Entries() {
shard := shardEntry.shard
db.flushChecker.requestFlushJob(&flushRequest{
db: db,
shards: map[models.ShardID]*flushShard{
shard.ShardID(): {
shard: shard,
families: GetFamilyManager().GetFamiliesByShard(shard),
},
},
global: false,
})
}
return nil
}
// Drop drops current database include all data.
func (db *database) Drop() error {
if err := db.Close(); err != nil {
return err
}
if err := removeDir(db.dir); err != nil {
return err
}
return nil
}