/
table_manager.go
246 lines (200 loc) · 6.06 KB
/
table_manager.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
package uploads
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sync"
"time"
"github.com/cortexproject/cortex/pkg/chunk"
"github.com/cortexproject/cortex/pkg/chunk/local"
chunk_util "github.com/cortexproject/cortex/pkg/chunk/util"
pkg_util "github.com/cortexproject/cortex/pkg/util"
"github.com/cortexproject/cortex/pkg/util/spanlogger"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
)
type Config struct {
Uploader string
IndexDir string
UploadInterval time.Duration
}
type TableManager struct {
cfg Config
boltIndexClient BoltDBIndexClient
storageClient StorageClient
metrics *metrics
tables map[string]*Table
tablesMtx sync.RWMutex
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewTableManager(cfg Config, boltIndexClient BoltDBIndexClient, storageClient StorageClient, registerer prometheus.Registerer) (*TableManager, error) {
ctx, cancel := context.WithCancel(context.Background())
tm := TableManager{
cfg: cfg,
boltIndexClient: boltIndexClient,
storageClient: storageClient,
metrics: newMetrics(registerer),
ctx: ctx,
cancel: cancel,
}
tables, err := tm.loadTables()
if err != nil {
return nil, err
}
tm.tables = tables
go tm.loop()
return &tm, nil
}
func (tm *TableManager) loop() {
tm.wg.Add(1)
defer tm.wg.Done()
syncTicker := time.NewTicker(tm.cfg.UploadInterval)
defer syncTicker.Stop()
for {
select {
case <-syncTicker.C:
err := tm.uploadTables(context.Background())
if err != nil {
level.Error(pkg_util.Logger).Log("msg", "error uploading local boltdb files to the storage", "err", err)
}
case <-tm.ctx.Done():
return
}
}
}
func (tm *TableManager) Stop() {
level.Info(pkg_util.Logger).Log("msg", "stopping table manager")
tm.cancel()
tm.wg.Wait()
err := tm.uploadTables(context.Background())
if err != nil {
level.Error(pkg_util.Logger).Log("msg", "error uploading local boltdb files to the storage before stopping", "err", err)
}
}
func (tm *TableManager) QueryPages(ctx context.Context, queries []chunk.IndexQuery, callback chunk_util.Callback) error {
return chunk_util.DoParallelQueries(ctx, tm.query, queries, callback)
}
func (tm *TableManager) query(ctx context.Context, query chunk.IndexQuery, callback chunk_util.Callback) error {
tm.tablesMtx.RLock()
defer tm.tablesMtx.RUnlock()
log, ctx := spanlogger.New(ctx, "Shipper.Uploads.Query")
defer log.Span.Finish()
table, ok := tm.tables[query.TableName]
if !ok {
return nil
}
return table.Query(ctx, query, callback)
}
func (tm *TableManager) BatchWrite(ctx context.Context, batch chunk.WriteBatch) error {
boltWriteBatch, ok := batch.(*local.BoltWriteBatch)
if !ok {
return errors.New("invalid write batch")
}
for tableName, tableWrites := range boltWriteBatch.Writes {
table, err := tm.getOrCreateTable(tableName)
if err != nil {
return err
}
err = table.Write(ctx, tableWrites)
if err != nil {
return err
}
}
return nil
}
func (tm *TableManager) getOrCreateTable(tableName string) (*Table, error) {
tm.tablesMtx.RLock()
table, ok := tm.tables[tableName]
tm.tablesMtx.RUnlock()
if !ok {
tm.tablesMtx.Lock()
defer tm.tablesMtx.Unlock()
table, ok = tm.tables[tableName]
if !ok {
var err error
table, err = NewTable(filepath.Join(tm.cfg.IndexDir, tableName), tm.cfg.Uploader, tm.storageClient, tm.boltIndexClient)
if err != nil {
return nil, err
}
tm.tables[tableName] = table
}
}
return table, nil
}
func (tm *TableManager) uploadTables(ctx context.Context) (err error) {
tm.tablesMtx.RLock()
defer tm.tablesMtx.RUnlock()
level.Info(pkg_util.Logger).Log("msg", "uploading tables")
defer func() {
status := statusSuccess
if err != nil {
status = statusFailure
}
tm.metrics.tablesUploadOperationTotal.WithLabelValues(status).Inc()
}()
for _, table := range tm.tables {
err := table.Upload(ctx)
if err != nil {
return err
}
// cleanup unwanted dbs from the table
err = table.Cleanup()
if err != nil {
// we do not want to stop uploading of dbs due to failures in cleaning them up so logging just the error here.
level.Error(pkg_util.Logger).Log("msg", "failed to cleanup uploaded dbs past their retention period", "table", table.name, "err", err)
}
}
return
}
func (tm *TableManager) loadTables() (map[string]*Table, error) {
localTables := make(map[string]*Table)
filesInfo, err := ioutil.ReadDir(tm.cfg.IndexDir)
if err != nil {
return nil, err
}
// regex matching table name patters, i.e prefix+period_number
re, err := regexp.Compile(`.+[0-9]+$`)
if err != nil {
return nil, err
}
for _, fileInfo := range filesInfo {
if !re.MatchString(fileInfo.Name()) {
continue
}
// since we are moving to keeping files for same table in a folder, if current element is a file we need to move it inside a directory with the same name
// i.e file index_123 would be moved to path index_123/index_123.
if !fileInfo.IsDir() {
level.Info(pkg_util.Logger).Log("msg", fmt.Sprintf("found a legacy file %s, moving it to folder with same name", fileInfo.Name()))
filePath := filepath.Join(tm.cfg.IndexDir, fileInfo.Name())
// create a folder with .temp suffix since we can't create a directory with same name as file.
tempDirPath := filePath + ".temp"
if err := chunk_util.EnsureDirectory(tempDirPath); err != nil {
return nil, err
}
// move the file to temp dir.
if err := os.Rename(filePath, filepath.Join(tempDirPath, fileInfo.Name())); err != nil {
return nil, err
}
// rename the directory to name of the file
if err := os.Rename(tempDirPath, filePath); err != nil {
return nil, err
}
}
level.Info(pkg_util.Logger).Log("msg", fmt.Sprintf("loading table %s", fileInfo.Name()))
table, err := LoadTable(filepath.Join(tm.cfg.IndexDir, fileInfo.Name()), tm.cfg.Uploader, tm.storageClient, tm.boltIndexClient)
if err != nil {
return nil, err
}
if table == nil {
continue
}
localTables[fileInfo.Name()] = table
}
return localTables, nil
}