getwtxt/svc/db.go

110 lines
2.2 KiB
Go
Raw Normal View History

2019-07-11 04:57:06 +00:00
/*
Copyright (c) 2019 Ben Morrison (gbmor)
This file is part of Getwtxt.
Getwtxt is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Getwtxt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Getwtxt. If not, see <https://www.gnu.org/licenses/>.
*/
package svc // import "git.sr.ht/~gbmor/getwtxt/svc"
2019-06-04 22:14:24 +00:00
import (
"log"
"time"
2019-06-04 22:14:24 +00:00
"github.com/syndtr/goleveldb/leveldb"
2019-06-10 09:09:51 +00:00
"golang.org/x/sys/unix"
2019-06-04 22:14:24 +00:00
)
// Everything in this file is database-agnostic.
// Functions and types related to specific kinds
// of databases will be in their own respective
// files, such as:
// - leveldb.go
// - sqlite.go
// Abstraction to allow several different
// databases to be used interchangeably.
type dbase interface {
push() error
pull()
delUser(string) error
}
// Opens a new connection to the specified
// database, then reads it into memory.
2019-06-06 05:23:44 +00:00
func initDatabase() {
var db dbase
confObj.Mu.RLock()
dbpath := confObj.DBPath
confObj.Mu.RUnlock()
2019-06-06 05:23:44 +00:00
switch confObj.DBType {
case "leveldb":
lvl, err := leveldb.OpenFile(dbpath, nil)
2019-06-06 22:26:16 +00:00
errFatal("", err)
2019-06-06 05:23:44 +00:00
db = &dbLevel{db: lvl}
case "sqlite":
2019-06-06 22:26:16 +00:00
db = initSqlite()
2019-06-06 05:23:44 +00:00
}
dbChan <- db
2019-06-06 06:20:38 +00:00
pullDB()
2019-06-06 05:23:44 +00:00
}
// Close the database connection.
func killDB() {
db := <-dbChan
switch dbType := db.(type) {
case *dbLevel:
errLog("", dbType.db.Close())
case *dbSqlite:
errLog("", dbType.db.Close())
}
2019-06-04 22:14:24 +00:00
}
// Pushes the registry's cache data
// to a local database for safe keeping.
2019-06-06 06:20:38 +00:00
func pushDB() error {
2019-06-04 22:14:24 +00:00
db := <-dbChan
err := db.push()
2019-06-04 22:14:24 +00:00
dbChan <- db
2019-06-10 09:09:51 +00:00
unix.Sync()
return err
2019-06-04 22:14:24 +00:00
}
// Reads the database from disk into memory.
2019-06-06 06:20:38 +00:00
func pullDB() {
start := time.Now()
2019-06-04 22:14:24 +00:00
db := <-dbChan
db.pull()
dbChan <- db
log.Printf("Database pull took: %v\n", time.Since(start))
2019-06-04 22:14:24 +00:00
}
func delUser(userURL string) error {
db := <-dbChan
err := db.delUser(userURL)
dbChan <- db
if err != nil {
return err
}
return twtxtCache.DelUser(userURL)
}