From 1ecd0d7ca4a9ef453ec3f2a67349f954b8c47d54 Mon Sep 17 00:00:00 2001 From: Juan Font Date: Thu, 2 Sep 2021 16:57:26 +0200 Subject: [PATCH] Added DB SharedNode model to support sharing nodes --- db.go | 5 +++++ sharing_nodes.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 sharing_nodes.go diff --git a/db.go b/db.go index 06302523..4435f048 100644 --- a/db.go +++ b/db.go @@ -44,6 +44,11 @@ func (h *Headscale) initDB() error { return err } + err = db.AutoMigrate(&SharedNode{}) + if err != nil { + return err + } + err = h.setValue("db_version", dbVersion) return err } diff --git a/sharing_nodes.go b/sharing_nodes.go new file mode 100644 index 00000000..b52b900c --- /dev/null +++ b/sharing_nodes.go @@ -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 +}