2020-06-21 10:32:08 +00:00
|
|
|
package headscale
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
"github.com/jinzhu/gorm"
|
2021-04-24 15:26:50 +00:00
|
|
|
_ "github.com/jinzhu/gorm/dialects/postgres" // sql driver
|
2020-06-21 10:32:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const dbVersion = "1"
|
|
|
|
|
2021-02-23 19:11:30 +00:00
|
|
|
// KV is a key-value store in a psql table. For future use...
|
2020-06-21 10:32:08 +00:00
|
|
|
type KV struct {
|
|
|
|
Key string
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Headscale) initDB() error {
|
2021-05-02 18:47:36 +00:00
|
|
|
db, err := gorm.Open(h.dbType, h.dbString)
|
2020-06-21 10:32:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-05-02 18:47:36 +00:00
|
|
|
if h.dbType == "postgres" {
|
|
|
|
db.Exec("create extension if not exists \"uuid-ossp\";")
|
|
|
|
}
|
2020-06-21 10:32:08 +00:00
|
|
|
db.AutoMigrate(&Machine{})
|
|
|
|
db.AutoMigrate(&KV{})
|
2021-02-27 23:58:09 +00:00
|
|
|
db.AutoMigrate(&Namespace{})
|
2021-04-22 22:25:01 +00:00
|
|
|
db.AutoMigrate(&PreAuthKey{})
|
2020-06-21 10:32:08 +00:00
|
|
|
db.Close()
|
|
|
|
|
2021-04-24 15:41:29 +00:00
|
|
|
err = h.setValue("db_version", dbVersion)
|
|
|
|
return err
|
2020-06-21 10:32:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Headscale) db() (*gorm.DB, error) {
|
2021-05-02 18:47:36 +00:00
|
|
|
db, err := gorm.Open(h.dbType, h.dbString)
|
2020-06-21 10:32:08 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2021-05-02 18:47:36 +00:00
|
|
|
if h.dbDebug {
|
|
|
|
db.LogMode(true)
|
|
|
|
}
|
2020-06-21 10:32:08 +00:00
|
|
|
return db, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Headscale) getValue(key string) (string, error) {
|
|
|
|
db, err := h.db()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
var row KV
|
|
|
|
if db.First(&row, "key = ?", key).RecordNotFound() {
|
|
|
|
return "", errors.New("not found")
|
|
|
|
}
|
|
|
|
return row.Value, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Headscale) setValue(key string, value string) error {
|
|
|
|
kv := KV{
|
|
|
|
Key: key,
|
|
|
|
Value: value,
|
|
|
|
}
|
|
|
|
db, err := h.db()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer db.Close()
|
|
|
|
_, err = h.getValue(key)
|
|
|
|
if err == nil {
|
|
|
|
db.Model(&kv).Where("key = ?", key).Update("value", value)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
db.Create(kv)
|
|
|
|
return nil
|
|
|
|
}
|