Added DB SharedNode model to support sharing nodes

This commit is contained in:
Juan Font 2021-09-02 16:57:26 +02:00
parent 39c661d408
commit 1ecd0d7ca4
2 changed files with 42 additions and 0 deletions

5
db.go
View File

@ -44,6 +44,11 @@ func (h *Headscale) initDB() error {
return err return err
} }
err = db.AutoMigrate(&SharedNode{})
if err != nil {
return err
}
err = h.setValue("db_version", dbVersion) err = h.setValue("db_version", dbVersion)
return err return err
} }

37
sharing_nodes.go Normal file
View File

@ -0,0 +1,37 @@
package headscale
import "gorm.io/gorm"
const errorSameNamespace = Error("Destination namespace same as origin")
const errorNodeAlreadyShared = Error("Node already shared to this namespace")
// Sharing is a join table to support sharing nodes between namespaces
type SharedNode struct {
gorm.Model
MachineID uint64
Machine Machine
NamespaceID uint
Namespace Namespace
}
// ShareNodeInNamespace adds a machine as a shared node to a namespace
func (h *Headscale) ShareNodeInNamespace(m *Machine, ns *Namespace) error {
if m.NamespaceID == ns.ID {
return errorSameNamespace
}
sn := SharedNode{}
if err := h.db.Where("machine_id = ? AND namespace_id", m.ID, ns.ID).First(&sn).Error; err == nil {
return errorNodeAlreadyShared
}
sn = SharedNode{
MachineID: m.ID,
Machine: *m,
NamespaceID: ns.ID,
Namespace: *ns,
}
h.db.Save(&sn)
return nil
}