Refactor machine.go, and move functionality to routes.go + unit tests

Port routes tests to new model

Mark as primary the first instance of subnet + tests

In preparation for subnet failover, mark the initial occurrence of a subnet as the primary one.
This commit is contained in:
Juan Font 2022-11-24 16:00:40 +00:00 committed by Kristoffer Dalby
parent ac8bff716d
commit b62acff2e3
6 changed files with 275 additions and 98 deletions

View file

@ -11,6 +11,11 @@ const (
ErrRouteIsNotAvailable = Error("route is not available")
)
var (
ExitRouteV4 = netip.MustParsePrefix("0.0.0.0/0")
ExitRouteV6 = netip.MustParsePrefix("::/0")
)
type Route struct {
gorm.Model
@ -37,6 +42,18 @@ func (rs Routes) toPrefixes() []netip.Prefix {
return prefixes
}
// isUniquePrefix returns if there is another machine providing the same route already
func (h *Headscale) isUniquePrefix(route Route) bool {
var count int64
h.db.
Model(&Route{}).
Where("prefix = ? AND machine_id != ? AND advertised = ? AND enabled = ?",
route.Prefix,
route.MachineID,
true, true).Count(&count)
return count == 0
}
// getMachinePrimaryRoutes returns the routes that are enabled and marked as primary (for subnet failover)
// Exit nodes are not considered for this, as they are never marked as Primary
func (h *Headscale) getMachinePrimaryRoutes(m *Machine) ([]Route, error) {