This repository has been archived by the owner on Aug 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
storage_sqlite.go
474 lines (409 loc) · 9.98 KB
/
storage_sqlite.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// +build !rocksdb
/*
Copyright 2016 The Transicator Authors
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 storage
import (
"sort"
"database/sql"
"fmt"
"os"
"time"
"io"
"io/ioutil"
log "github.com/Sirupsen/logrus"
"github.com/apigee-labs/transicator/common"
sqlite3 "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
)
const (
driverName = "sqlite3"
backupPagesInStep = 512
)
/*
An SQL is a handle to a database.
*/
type SQL struct {
baseFile string
db *sql.DB
insert *sql.Stmt
readRange *sql.Stmt
readFirst *sql.Stmt
readLast *sql.Stmt
purgeByTime *sql.Stmt
}
type readResult struct {
lsn uint64
index uint32
data []byte
}
type readResults []readResult
/*
Open opens a SQLite database and makes it available for reads and writes.
Opened databases should be closed when done.
The "baseFile" parameter refers to the name of a directory where RocksDB can
store its data. SQLite will create a few inside this directory. To create
an empty database, make sure that it is empty.
*/
func Open(baseFile string) (*SQL, error) {
success := false
url, err := createDBDir(baseFile)
if err != nil {
return nil, err
}
log.Infof("Opening SQLite DB at %s\n", url)
db, err := sql.Open(driverName, url)
if err != nil {
return nil, err
}
defer func() {
if !success {
db.Close()
}
}()
_, err = db.Exec(createTableSQL)
if err != nil {
return nil, err
}
stor := &SQL{
baseFile: baseFile,
db: db,
}
stor.insert, err = db.Prepare(insertSQL)
if err == nil {
stor.readRange, err = db.Prepare(readRangeSQL)
}
if err == nil {
stor.readFirst, err = db.Prepare(readFirstSQL)
}
if err == nil {
stor.readLast, err = db.Prepare(readLastSQL)
}
if err == nil {
stor.purgeByTime, err = db.Prepare(purgeByTimeSQL)
}
if err != nil {
return nil, err
}
success = true
return stor, nil
}
// createDBDir ensures that "base" is a directory and returns the file name
func createDBDir(baseFile string) (string, error) {
st, err := os.Stat(baseFile)
if err != nil {
err = os.Mkdir(baseFile, 0775)
if err != nil {
return "", err
}
} else if !st.IsDir() {
return "", fmt.Errorf("Database location %s is not a directory", baseFile)
}
return fmt.Sprintf("%s/transicator", baseFile), err
}
/*
Close closes the database cleanly.
*/
func (s *SQL) Close() {
log.Infof("Closed DB in %s", s.baseFile)
s.db.Close()
}
/*
Delete deletes all the files used by the database.
*/
func (s *SQL) Delete() error {
return os.RemoveAll(s.baseFile)
}
/*
Put writes an entry to the database indexed by scope, lsn, and index in order
*/
func (s *SQL) Put(scope string, lsn uint64, index uint32, data []byte) error {
_, err := s.insert.Exec(scope, lsn, index, time.Now().UnixNano(), data)
return err
}
/*
PutBatch writes a whole bunch.
*/
func (s *SQL) PutBatch(entries []Entry) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
is := tx.Stmt(s.insert)
defer is.Close()
for _, entry := range entries {
_, err = is.Exec(
entry.Scope, entry.LSN, entry.Index,
time.Now().UnixNano(), entry.Data)
if err != nil {
return err
}
}
return tx.Commit()
}
/*
Get returns what was written by PutEntry. It's mainly used for testing.
*/
func (s *SQL) Get(scope string, lsn uint64, index uint32) ([]byte, error) {
row := s.db.QueryRow("select data from transicator_entries where scope = ? and lsn = ? and ix = ?",
scope, lsn, index)
var data []byte
err := row.Scan(&data)
if err == sql.ErrNoRows {
return nil, nil
} else if err == nil {
return data, nil
}
return nil, err
}
/*
Scan returns entries in sequence number order a list of scopes.
It also returns the sequences of the first and last records in the DB.
The first entry returned will be the first entry that matches the specified
startLSN and startIndex. No more than "limit" entries will be returned.
To retrieve the very next entry after an entry, simply increment the index
by 1. This method uses a snapshot to guarantee consistency even if data is
being inserted to the database -- as long as the data is being inserted
in LSN order!
The array returned is the array of entries (again, in "sequence" order).
*/
func (s *SQL) Scan(
scopes []string,
startLSN uint64, startIndex uint32,
limit int, filter func([]byte) bool) (final [][]byte, firstSeq common.Sequence, lastSeq common.Sequence, err error) {
// By doing this in a transaction we should get snapshot-level consistency
var tx *sql.Tx
tx, err = s.db.Begin()
if err != nil {
return
}
defer tx.Commit()
// Read first and last sequences
firstSeq, lastSeq, err = s.readLimits(tx)
if err != nil {
return
}
// Read range for each scope
var results readResults
for _, scope := range scopes {
var rr readResults
rr, err = s.readOneRange(scope, startLSN, startIndex, limit, tx, filter)
if err != nil {
return
}
results = append(results, rr...)
}
tx.Commit()
// Sort and then take limit
sort.Sort(results)
for count := 0; count < len(results) && count < limit; count++ {
final = append(final, results[count].data)
}
return
}
/*
Purge removes all entries older than the specified time.
*/
func (s *SQL) Purge(oldest time.Time) (uint64, error) {
res, err := s.purgeByTime.Exec(oldest.UnixNano())
if err != nil {
return 0, err
}
ra, _ := res.RowsAffected()
return uint64(ra), nil
}
/*
GetBackup creates a backup of the current database in a temp filename,
and write the persistent db file to the specified writer.
It's the caller's responsibility to close the writer, if needed.
*/
func (s *SQL) GetBackup(w io.Writer) (err error) {
tempDirURL, err := ioutil.TempDir("", "transicator_sqlite_backup")
if err != nil {
return
}
backupDirName := fmt.Sprintf("%s/backup", tempDirURL)
log.Debugf("Sqlite backup destination: %s", backupDirName)
// remove the temp backup file
defer os.RemoveAll(tempDirURL)
// create backup
bc := s.Backup(backupDirName)
for {
br := <-bc
log.Debugf("Backup %d remaining\n", br.PagesRemaining)
if err = br.Error; err != nil {
log.Error(err)
return
}
if br.Done {
break
}
}
// copy backup file to the writer
backupFileName := fmt.Sprintf("%s/transicator", backupDirName)
fileReader, err := os.Open(backupFileName)
defer fileReader.Close()
if err != nil {
log.Error(err)
return
}
_, err = io.Copy(w, fileReader)
if err != nil {
log.Error(err)
}
return
}
/*
Backup creates a backup of the current database in the specified file name,
and sends results using the supplied channel.
*/
func (s *SQL) Backup(dest string) <-chan BackupProgress {
pc := make(chan BackupProgress, 1000)
go s.runBackup(dest, pc)
return pc
}
func (s *SQL) runBackup(dest string, pc chan BackupProgress) {
// if the specified database file existed, return error
if _, err := os.Stat(dest); err == nil {
log.Error("dest dir existed")
pc <- BackupProgress{
PagesRemaining: -1,
Error: errors.New("dest dir existed"),
Done: false,
}
return
}
srcConn, err := s.openRawConnection(s.baseFile)
if err != nil {
returnBackupError(pc, err)
return
}
defer srcConn.Close()
dstConn, err := s.openRawConnection(dest)
if err != nil {
returnBackupError(pc, err)
return
}
defer dstConn.Close()
backup, err := dstConn.Backup("main", srcConn, "main")
if err != nil {
returnBackupError(pc, err)
return
}
defer backup.Close()
done := false
for i := 0; !done; i++ {
done, err = backup.Step(backupPagesInStep)
pc <- BackupProgress{
PagesRemaining: backup.Remaining(),
Error: err,
Done: done,
}
}
backup.Finish()
}
func returnBackupError(pc chan BackupProgress, err error) {
pc <- BackupProgress{
Done: true,
Error: err,
}
}
func (s *SQL) openRawConnection(baseFile string) (*sqlite3.SQLiteConn, error) {
url, err := createDBDir(baseFile)
if err != nil {
return nil, err
}
sqlConn, err := s.db.Driver().Open(url)
if err != nil {
return nil, err
}
return sqlConn.(*sqlite3.SQLiteConn), nil
}
func (s *SQL) readOneRange(scope string, startLSN uint64,
startIndex uint32, limit int, tx *sql.Tx,
filter func([]byte) bool) (results readResults, err error) {
var rows *sql.Rows
rrs := tx.Stmt(s.readRange)
defer rrs.Close()
rows, err = rrs.Query(scope, startLSN, startLSN, startIndex)
if err != nil {
return
}
defer rows.Close()
count := 0
for count < limit && rows.Next() {
var lsn uint64
var index uint32
var data []byte
err = rows.Scan(&lsn, &index, &data)
if err != nil {
return
}
if filter == nil || filter(data) {
result := readResult{
lsn: lsn,
index: index,
data: data,
}
results = append(results, result)
count++
}
}
return results, nil
}
func (s *SQL) readLimits(tx *sql.Tx) (firstSeq, lastSeq common.Sequence, err error) {
rfs := tx.Stmt(s.readFirst)
defer rfs.Close()
row := rfs.QueryRow()
var lsn uint64
var ix uint32
err = row.Scan(&lsn, &ix)
if err == sql.ErrNoRows {
err = nil
return
} else if err != nil {
return
}
firstSeq = common.MakeSequence(lsn, ix)
rls := tx.Stmt(s.readLast)
defer rls.Close()
row = rls.QueryRow()
err = row.Scan(&lsn, &ix)
if err == sql.ErrNoRows {
err = nil
lastSeq = firstSeq
return
} else if err != nil {
return
}
lastSeq = common.MakeSequence(lsn, ix)
return
}
// Needed to sort read results by LSN and index
func (r readResults) Len() int {
return len(r)
}
func (r readResults) Less(i, j int) bool {
if r[i].lsn < r[j].lsn {
return true
}
if r[i].lsn == r[j].lsn && r[i].index < r[j].index {
return true
}
return false
}
func (r readResults) Swap(i, j int) {
tmp := r[i]
r[i] = r[j]
r[j] = tmp
}