1
0
mirror of https://github.com/juanfont/headscale.git synced 2024-12-20 19:09:07 +01:00
juanfont.headscale/sharing.go

87 lines
2.1 KiB
Go
Raw Normal View History

package headscale
import "gorm.io/gorm"
2021-11-13 09:36:45 +01:00
const (
2021-11-15 17:33:16 +01:00
errSameNamespace = Error("Destination namespace same as origin")
errMachineAlreadyShared = Error("Node already shared to this namespace")
errMachineNotShared = Error("Machine not shared to this namespace")
2021-11-13 09:36:45 +01:00
)
2021-11-13 09:39:04 +01:00
// SharedMachine is a join table to support sharing nodes between namespaces.
2021-09-06 14:43:43 +02:00
type SharedMachine struct {
gorm.Model
MachineID uint64
Machine Machine
NamespaceID uint
Namespace Namespace
}
2021-11-13 09:39:04 +01:00
// AddSharedMachineToNamespace adds a machine as a shared node to a namespace.
func (h *Headscale) AddSharedMachineToNamespace(
machine *Machine,
namespace *Namespace,
) error {
if machine.NamespaceID == namespace.ID {
2021-11-15 17:33:16 +01:00
return errSameNamespace
}
sharedMachines := []SharedMachine{}
if err := h.db.Where("machine_id = ? AND namespace_id = ?", machine.ID, namespace.ID).Find(&sharedMachines).Error; err != nil {
return err
}
if len(sharedMachines) > 0 {
2021-11-15 17:33:16 +01:00
return errMachineAlreadyShared
}
sharedMachine := SharedMachine{
MachineID: machine.ID,
Machine: *machine,
NamespaceID: namespace.ID,
Namespace: *namespace,
}
h.db.Save(&sharedMachine)
return nil
}
2021-11-13 09:39:04 +01:00
// RemoveSharedMachineFromNamespace removes a shared machine from a namespace.
func (h *Headscale) RemoveSharedMachineFromNamespace(
machine *Machine,
namespace *Namespace,
) error {
if machine.NamespaceID == namespace.ID {
// Can't unshare from primary namespace
2021-11-15 17:33:16 +01:00
return errMachineNotShared
}
sharedMachine := SharedMachine{}
result := h.db.Where("machine_id = ? AND namespace_id = ?", machine.ID, namespace.ID).
2021-11-13 09:36:45 +01:00
Unscoped().
Delete(&sharedMachine)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
2021-11-15 17:33:16 +01:00
return errMachineNotShared
}
err := h.RequestMapUpdates(namespace.ID)
if err != nil {
return err
}
return nil
}
2021-11-13 09:39:04 +01:00
// RemoveSharedMachineFromAllNamespaces removes a machine as a shared node from all namespaces.
func (h *Headscale) RemoveSharedMachineFromAllNamespaces(machine *Machine) error {
sharedMachine := SharedMachine{}
if result := h.db.Where("machine_id = ?", machine.ID).Unscoped().Delete(&sharedMachine); result.Error != nil {
return result.Error
}
return nil
}