-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
427 lines (339 loc) · 12.3 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright 2020 James Lee <jamesl33info@gmail.com>
//
// 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 database
import (
"database/sql"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/jamesl33/goamt/utils"
"github.com/jamesl33/goamt/utils/sqlite"
"github.com/jamesl33/goamt/value"
"github.com/jamesl33/goamt/version"
"github.com/apex/log"
_ "github.com/mattn/go-sqlite3" // SQLite database driver, unreferenced but required
"github.com/pkg/errors"
)
// Database - Represents a connection to a goamt SQLite database and exposes a thread safe interface.
type Database struct {
db *sql.DB
txns int
lock sync.Mutex
}
// Create - Create a new database, returning an error if an existing database already exists.
func Create(path string) (*Database, error) {
if utils.PathExists(path) {
return nil, &ErrAlreadyExists{what: "database", where: path}
}
db, err := sql.Open("sqlite3", path+"?_journal=wal&_mutex=full&_sync=extra&mode=rwc")
if err != nil {
return nil, errors.Wrap(err, "failed to open SQLite database")
}
err = sqlite.SetPragma(db, sqlite.PragmaUserVersion, version.DatabaseVersionCurrent)
if err != nil {
return nil, errors.Wrap(err, "failed to set 'user_version'")
}
err = sqlite.SetPragma(db, sqlite.PragmaForiegnKeys, "on")
if err != nil {
return nil, errors.Wrap(err, "failed to set 'foreign_keys'")
}
query := sqlite.Query{
Query: `
create table library (
id integer primary key autoincrement,
path text not null unique,
discovered integer not null,
transcoded integer,
hash integer unique,
unique (path, hash)
);`,
}
_, err = sqlite.ExecuteQuery(db, query)
if err != nil {
return nil, errors.Wrap(err, "failed to create library table")
}
query.Query = `
create table jobs (
id integer primary key autoincrement,
library_id integer not null unique,
start_time integer not null,
foreign key (library_id) references library (id)
);
`
_, err = sqlite.ExecuteQuery(db, query)
if err != nil {
return nil, errors.Wrap(err, "failed to create jobs table")
}
log.WithField("version", version.DatabaseVersionCurrent).Info("Created new database")
return &Database{db: db}, nil
}
// Open - Open an existing database returning an error if the provided database is missing or an unsupported version.
func Open(path string) (*Database, error) {
if !utils.PathExists(path) {
return nil, &ErrNotFound{what: "database", where: path}
}
db, err := sql.Open("sqlite3", path+"?_journal=wal&_mutex=full&_sync=extra&mode=rw")
if err != nil {
return nil, errors.Wrap(err, "failed to open SQLite database")
}
var userVersion uint32
err = sqlite.GetPragma(db, sqlite.PragmaUserVersion, &userVersion)
if err != nil {
return nil, errors.Wrap(err, "failed to get 'user_version'")
}
log.WithField("version", userVersion).Info("Opened existing database")
if !version.DatabaseVersion(userVersion).Supported() {
return nil, &ErrUnknownVersion{what: "database", where: path}
}
err = sqlite.SetPragma(db, sqlite.PragmaForiegnKeys, "on")
if err != nil {
return nil, errors.Wrap(err, "failed to set 'foreign_keys'")
}
database := &Database{db: db}
err = database.recoverIncompleteJobs()
if err != nil {
return nil, errors.Wrap(err, "failed to recover incomplete jobs")
}
return database, nil
}
// recoverIncompleteJobs - Scan then handle any in-progress transcode jobs; this will revert or complete jobs depending
// on their status.
func (d *Database) recoverIncompleteJobs() error {
callback := func(scan sqlite.ScanCallback) error {
var entry value.Entry
err := scan(&entry.ID, &entry.Path, &entry.Discovered, &entry.Transcoded, &entry.Hash)
if err != nil {
return errors.Wrap(err, "failed to scan incomplete job information")
}
log.WithFields(entry).Warn("Found incomplete job")
hash, err := utils.HashFile(entry.Path)
if (err == nil && hash != entry.Hash) || (!utils.PathExists(entry.Path) &&
utils.PathExists(utils.ReplaceExtension(entry.Path, value.TranscodingExtension))) {
return d.completeIncompleteJob(entry)
}
return d.rollbackIncompleteJob(entry)
}
query := sqlite.Query{
Query: `select library.id, path,discovered,transcoded,hash from jobs
inner join library on jobs.library_id = library.id`,
}
err := sqlite.QueryRows(d.db, query, callback)
if err != nil && !errors.Is(err, sqlite.ErrQueryReturnedNoRows) {
return errors.Wrap(err, "failed to query incomplete jobs")
}
return nil
}
// completeIncompleteJob - Complete the incomplete transcode job for the provided entry.
func (d *Database) completeIncompleteJob(entry value.Entry) error {
log.WithFields(entry).Info("Completing incomplete job")
err := os.Rename(
utils.ReplaceExtension(entry.Path, value.TranscodingExtension),
utils.ReplaceExtension(entry.Path, value.TargetExtension),
)
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to rename incomplete transcode file")
}
entry.Path = utils.ReplaceExtension(entry.Path, value.TargetExtension)
err = d.CompleteTranscoding(entry)
if err != nil {
return errors.Wrap(err, "failed to mark transcoding complete")
}
return nil
}
// rollbackIncompleteJob - Rollback the incomplete transcode job for the provided entry.
func (d *Database) rollbackIncompleteJob(entry value.Entry) error {
log.WithFields(entry).Info("Rolling back incomplete job")
err := os.Remove(strings.TrimSuffix(entry.Path, filepath.Ext(entry.Path)) + value.TranscodingExtension)
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to remove incomplete transcode file")
}
return d.cancelTranscoding(entry, false)
}
// addJob - Add a new job to the jobs table indicating the provided entry is going to be transcoded.
func (d *Database) addJob(db sqlite.Executable, entry value.Entry) error {
log.WithFields(entry).Debug("Added job for entry")
query := sqlite.Query{
Query: "insert into jobs (library_id, start_time) values (?, ?);",
Arguments: []interface{}{entry.ID, time.Now().Unix()},
}
_, err := sqlite.ExecuteQuery(db, query)
return err
}
// removeJob - Remove the job corresponding to the provided entry from the jobs table.
func (d *Database) removeJob(db sqlite.Executable, entry value.Entry) error {
log.WithFields(entry).Debug("Removing job for entry")
query := sqlite.Query{
Query: "delete from jobs where library_id = ?;",
Arguments: []interface{}{entry.ID},
}
_, err := sqlite.ExecuteQuery(db, query)
return err
}
// Close - Close the database, the database should not be used after it has been closed.
func (d *Database) Close() error {
d.lock.Lock()
defer d.lock.Unlock()
log.Info("Closing database")
defer func() {
d.db = nil
d.txns = 0
}()
return d.db.Close()
}
// Upsert - Update or insert the provided entry into the database; the entry will be updated in the event of a hash
// conflict.
func (d *Database) Upsert(entry value.Entry) error {
return d.wrapTransaction(func(tx *sql.Tx) error {
log.WithFields(entry).Info("Adding entry")
query := sqlite.Query{
Query: `insert or replace into library (path, discovered, transcoded, hash) values (?, ?, ?, ?)
on conflict(hash) do update set path=excluded.path where path != excluded.path;`,
Arguments: []interface{}{entry.Path, entry.Discovered, entry.Transcoded, entry.Hash},
}
_, err := sqlite.ExecuteQuery(tx, query)
if err != nil {
return errors.Wrap(err, "failed to execute query")
}
return nil
})
}
// Remove - Remove the provided entry from the database; this will also remove any incomplete jobs for the provided
// entry.
func (d *Database) Remove(entry value.Entry) error {
return d.wrapTransaction(func(tx *sql.Tx) error {
log.WithFields(entry).Info("Removing entry")
err := d.removeJob(tx, entry)
if err != nil {
return errors.Wrap(err, "failed to remove job")
}
query := sqlite.Query{
Query: "delete from library where id = ?;",
Arguments: []interface{}{entry.ID},
}
_, err = sqlite.ExecuteQuery(tx, query)
if err != nil {
return errors.Wrap(err, "failed to execute query")
}
return nil
})
}
// BeginTranscoding - Retrieve an untranscoded entry from the database, note that a job will be created for the provided
// entry which should be completed/cancelled (in the event of a failure, this will happen the next time the database is
// opened).
func (d *Database) BeginTranscoding() (value.Entry, error) {
var entry value.Entry
return entry, d.wrapTransaction(func(tx *sql.Tx) error {
query := sqlite.Query{
Query: "select library.id, path, hash from library where transcoded is null and " +
"id not in (select library_id from jobs) order by discovered asc limit 1;",
}
err := sqlite.QueryRow(tx, query, &entry.ID, &entry.Path, &entry.Hash)
if err != nil {
return errors.Wrap(err, "failed to query database")
}
log.WithFields(entry).Info("Scheduling job to transcode entry")
err = d.addJob(tx, entry)
if err != nil {
return errors.Wrap(err, "failed to add job")
}
return nil
})
}
// CompleteTranscoding - Rehash and mark the provided entry as having been transcoded.
func (d *Database) CompleteTranscoding(entry value.Entry) error {
hash, err := utils.HashFile(entry.Path)
if err != nil {
return errors.Wrap(err, "failed to hash file")
}
return d.wrapTransaction(func(tx *sql.Tx) error {
query := sqlite.Query{
Query: "update library set path = ?, transcoded = ?, hash = ? where id = ?;",
Arguments: []interface{}{entry.Path, utils.Int64P(time.Now().Unix()), hash, entry.ID},
}
_, err = sqlite.ExecuteQuery(tx, query)
if err != nil {
return errors.Wrap(err, "failed to update database")
}
log.WithFields(entry).Info("Completing job to transcode entry")
err = d.removeJob(tx, entry)
if err != nil {
return errors.Wrapf(err, "failed to remove job %d", entry.ID)
}
return nil
})
}
// CancelTranscoding - Cancel the job for the provided entry.
func (d *Database) CancelTranscoding(entry value.Entry) error {
return d.cancelTranscoding(entry, true)
}
// cancelTranscoding - Convenience function to conditionally log, then remove the job for the provided entry.
func (d *Database) cancelTranscoding(entry value.Entry, shouldLog bool) error {
return d.wrapTransaction(func(tx *sql.Tx) error {
if shouldLog {
log.WithFields(entry).Info("Cancelling job to transcode entry")
}
err := d.removeJob(tx, entry)
if err != nil {
return errors.Wrapf(err, "failed to remove job %d", entry.ID)
}
return nil
})
}
// wrapTransaction - Run the provided callback within a transaction (correctly handling the completion/rollback).
func (d *Database) wrapTransaction(callback func(tx *sql.Tx) error) error {
d.lock.Lock()
defer d.lock.Unlock()
tx, err := d.beginLOCKED()
if err != nil {
return errors.Wrap(err, "failed to begin transaction")
}
err = callback(tx)
if err == nil {
err = d.commitLOCKED(tx)
if err != nil {
return errors.Wrap(err, "failed to commit transaction")
}
return nil
}
if !errors.Is(err, sqlite.ErrQueryReturnedNoRows) {
log.WithError(err).Error("Unexpected error, rolling back transaction")
}
if err := d.rollbackLOCKED(tx); err != nil {
return errors.Wrap(err, "failed to rollback transaction")
}
return err
}
// beginLOCKED - Utility function to log and being a new transaction.
func (d *Database) beginLOCKED() (*sql.Tx, error) {
log.WithField("number", d.txns+1).Debug("Beginning transaction")
return d.db.Begin()
}
// commitLOCKED - Utility function to log and commit the provided transaction.
func (d *Database) commitLOCKED(tx *sql.Tx) error {
log.WithField("number", d.txns+1).Debug("Committing transaction")
defer func() {
d.txns++
}()
return tx.Commit()
}
// rollbackLOCKED - Utility function to log and rollback the provided transaction.
func (d *Database) rollbackLOCKED(tx *sql.Tx) error {
log.WithField("number", d.txns+1).Debug("Rolling back transaction")
defer func() {
d.txns++
}()
return tx.Rollback()
}