@@ -11,6 +11,7 @@ import (
1111 "github.com/juanfont/headscale/hscontrol/types"
1212 "github.com/juanfont/headscale/hscontrol/util"
1313 xmaps "golang.org/x/exp/maps"
14+ "tailscale.com/net/tsaddr"
1415 "tailscale.com/util/set"
1516)
1617
@@ -74,18 +75,12 @@ func (pr *PrimaryRoutes) updatePrimaryLocked() bool {
7475 // If the current primary is not available, select a new one.
7576 for prefix , nodes := range allPrimaries {
7677 if node , ok := pr .primaries [prefix ]; ok {
77- if len (nodes ) < 2 {
78- delete (pr .primaries , prefix )
79- changed = true
80- continue
81- }
82-
8378 // If the current primary is still available, continue.
8479 if slices .Contains (nodes , node ) {
8580 continue
8681 }
8782 }
88- if len (nodes ) >= 2 {
83+ if len (nodes ) >= 1 {
8984 pr .primaries [prefix ] = nodes [0 ]
9085 changed = true
9186 }
@@ -107,12 +102,16 @@ func (pr *PrimaryRoutes) updatePrimaryLocked() bool {
107102 return changed
108103}
109104
110- func (pr * PrimaryRoutes ) SetRoutes (node types.NodeID , prefix ... netip.Prefix ) bool {
105+ // SetRoutes sets the routes for a given Node ID and recalculates the primary routes
106+ // of the headscale.
107+ // It returns true if there was a change in primary routes.
108+ // All exit routes are ignored as they are not used in primary route context.
109+ func (pr * PrimaryRoutes ) SetRoutes (node types.NodeID , prefixes ... netip.Prefix ) bool {
111110 pr .mu .Lock ()
112111 defer pr .mu .Unlock ()
113112
114113 // If no routes are being set, remove the node from the routes map.
115- if len (prefix ) == 0 {
114+ if len (prefixes ) == 0 {
116115 if _ , ok := pr .routes [node ]; ok {
117116 delete (pr .routes , node )
118117 return pr .updatePrimaryLocked ()
@@ -121,12 +120,17 @@ func (pr *PrimaryRoutes) SetRoutes(node types.NodeID, prefix ...netip.Prefix) bo
121120 return false
122121 }
123122
124- if _ , ok := pr .routes [node ]; ! ok {
125- pr .routes [node ] = make (set.Set [netip.Prefix ], len (prefix ))
123+ rs := make (set.Set [netip.Prefix ], len (prefixes ))
124+ for _ , prefix := range prefixes {
125+ if ! tsaddr .IsExitRoute (prefix ) {
126+ rs .Add (prefix )
127+ }
126128 }
127129
128- for _ , p := range prefix {
129- pr .routes [node ].Add (p )
130+ if rs .Len () != 0 {
131+ pr .routes [node ] = rs
132+ } else {
133+ delete (pr .routes , node )
130134 }
131135
132136 return pr .updatePrimaryLocked ()
@@ -153,6 +157,7 @@ func (pr *PrimaryRoutes) PrimaryRoutes(id types.NodeID) []netip.Prefix {
153157 }
154158 }
155159
160+ tsaddr .SortPrefixes (routes )
156161 return routes
157162}
158163
0 commit comments