Skip to content

Commit

Permalink
move derp.go to derp module
Browse files Browse the repository at this point in the history
Signed-off-by: Kristoffer Dalby <[email protected]>
  • Loading branch information
kradalby committed Jun 8, 2023
1 parent 2289a2a commit 8c4c4c8
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 56 deletions.
48 changes: 34 additions & 14 deletions hscontrol/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/juanfont/headscale"
v1 "github.com/juanfont/headscale/gen/go/headscale/v1"
"github.com/juanfont/headscale/hscontrol/db"
"github.com/juanfont/headscale/hscontrol/derp"
"github.com/juanfont/headscale/hscontrol/policy"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/juanfont/headscale/hscontrol/util"
Expand Down Expand Up @@ -59,18 +60,12 @@ var (
)

const (
AuthPrefix = "Bearer "
updateInterval = 5000
HTTPReadTimeout = 30 * time.Second
HTTPShutdownTimeout = 3 * time.Second
privateKeyFileMode = 0o600
AuthPrefix = "Bearer "
updateInterval = 5000
privateKeyFileMode = 0o600

registerCacheExpiration = time.Minute * 15
registerCacheCleanup = time.Minute * 20

DisabledClientAuth = "disabled"
RelaxedClientAuth = "relaxed"
EnforcedClientAuth = "enforced"
)

// Headscale represents the base app of the service.
Expand Down Expand Up @@ -241,6 +236,31 @@ func (h *Headscale) expireExpiredMachines(milliSeconds int64) {
}
}

// scheduledDERPMapUpdateWorker refreshes the DERPMap stored on the global object
// at a set interval
func (h *Headscale) scheduledDERPMapUpdateWorker(cancelChan <-chan struct{}) {
log.Info().
Dur("frequency", h.cfg.DERP.UpdateFrequency).
Msg("Setting up a DERPMap update worker")
ticker := time.NewTicker(h.cfg.DERP.UpdateFrequency)

for {
select {
case <-cancelChan:
return

case <-ticker.C:
log.Info().Msg("Fetching DERPMap updates")
h.DERPMap = derp.GetDERPMap(h.cfg.DERP)
if h.cfg.DERP.ServerEnabled {
h.DERPMap.Regions[h.DERPServer.region.RegionID] = &h.DERPServer.region
}

h.setLastStateChangeToNow()
}
}
}

func (h *Headscale) failoverSubnetRoutes(milliSeconds int64) {
ticker := time.NewTicker(time.Duration(milliSeconds) * time.Millisecond)
for range ticker.C {
Expand Down Expand Up @@ -455,7 +475,7 @@ func (h *Headscale) Serve() error {
var err error

// Fetch an initial DERP Map before we start serving
h.DERPMap = GetDERPMap(h.cfg.DERP)
h.DERPMap = derp.GetDERPMap(h.cfg.DERP)

if h.cfg.DERP.ServerEnabled {
// When embedded DERP is enabled we always need a STUN server
Expand Down Expand Up @@ -615,7 +635,7 @@ func (h *Headscale) Serve() error {
httpServer := &http.Server{
Addr: h.cfg.Addr,
Handler: router,
ReadTimeout: HTTPReadTimeout,
ReadTimeout: types.HTTPReadTimeout,
// Go does not handle timeouts in HTTP very well, and there is
// no good way to handle streaming timeouts, therefore we need to
// keep this at unlimited and be careful to clean up connections
Expand Down Expand Up @@ -645,7 +665,7 @@ func (h *Headscale) Serve() error {
promHTTPServer := &http.Server{
Addr: h.cfg.MetricsAddr,
Handler: promMux,
ReadTimeout: HTTPReadTimeout,
ReadTimeout: types.HTTPReadTimeout,
WriteTimeout: 0,
}

Expand Down Expand Up @@ -709,7 +729,7 @@ func (h *Headscale) Serve() error {
// Gracefully shut down servers
ctx, cancel := context.WithTimeout(
context.Background(),
HTTPShutdownTimeout,
types.HTTPShutdownTimeout,
)
if err := promHTTPServer.Shutdown(ctx); err != nil {
log.Error().Err(err).Msg("Failed to shutdown prometheus http")
Expand Down Expand Up @@ -792,7 +812,7 @@ func (h *Headscale) getTLSSettings() (*tls.Config, error) {
server := &http.Server{
Addr: h.cfg.TLS.LetsEncrypt.Listen,
Handler: certManager.HTTPHandler(http.HandlerFunc(h.redirect)),
ReadTimeout: HTTPReadTimeout,
ReadTimeout: types.HTTPReadTimeout,
}

go func() {
Expand Down
30 changes: 3 additions & 27 deletions hscontrol/derp.go → hscontrol/derp/derp.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package hscontrol
package derp

import (
"context"
Expand All @@ -7,7 +7,6 @@ import (
"net/http"
"net/url"
"os"
"time"

"github.com/juanfont/headscale/hscontrol/types"
"github.com/rs/zerolog/log"
Expand All @@ -32,7 +31,7 @@ func loadDERPMapFromPath(path string) (*tailcfg.DERPMap, error) {
}

func loadDERPMapFromURL(addr url.URL) (*tailcfg.DERPMap, error) {
ctx, cancel := context.WithTimeout(context.Background(), HTTPReadTimeout)
ctx, cancel := context.WithTimeout(context.Background(), types.HTTPReadTimeout)
defer cancel()

req, err := http.NewRequestWithContext(ctx, http.MethodGet, addr.String(), nil)
Expand All @@ -41,7 +40,7 @@ func loadDERPMapFromURL(addr url.URL) (*tailcfg.DERPMap, error) {
}

client := http.Client{
Timeout: HTTPReadTimeout,
Timeout: types.HTTPReadTimeout,
}

resp, err := client.Do(req)
Expand Down Expand Up @@ -133,26 +132,3 @@ func GetDERPMap(cfg types.DERPConfig) *tailcfg.DERPMap {

return derpMap
}

func (h *Headscale) scheduledDERPMapUpdateWorker(cancelChan <-chan struct{}) {
log.Info().
Dur("frequency", h.cfg.DERP.UpdateFrequency).
Msg("Setting up a DERPMap update worker")
ticker := time.NewTicker(h.cfg.DERP.UpdateFrequency)

for {
select {
case <-cancelChan:
return

case <-ticker.C:
log.Info().Msg("Fetching DERPMap updates")
h.DERPMap = GetDERPMap(h.cfg.DERP)
if h.cfg.DERP.ServerEnabled {
h.DERPMap.Regions[h.DERPServer.region.RegionID] = &h.DERPServer.region
}

h.setLastStateChangeToNow()
}
}
}
5 changes: 3 additions & 2 deletions hscontrol/noise.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"net/http"

"github.com/gorilla/mux"
"github.com/juanfont/headscale/hscontrol/types"
"github.com/rs/zerolog/log"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
Expand Down Expand Up @@ -100,12 +101,12 @@ func (h *Headscale) NoiseUpgradeHandler(
router.HandleFunc("/machine/map", noiseServer.NoisePollNetMapHandler)

server := http.Server{
ReadTimeout: HTTPReadTimeout,
ReadTimeout: types.HTTPReadTimeout,
}

noiseServer.httpBaseConfig = &http.Server{
Handler: router,
ReadHeaderTimeout: HTTPReadTimeout,
ReadHeaderTimeout: types.HTTPReadTimeout,
}
noiseServer.http2Server = &http2.Server{}

Expand Down
6 changes: 0 additions & 6 deletions hscontrol/types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,6 @@ import (
)

const (
TlsALPN01ChallengeType = "TLS-ALPN-01"
Http01ChallengeType = "HTTP-01"

JSONLogFormat = "json"
TextLogFormat = "text"

defaultOIDCExpiryTime = 180 * 24 * time.Hour // 180 Days
maxDuration time.Duration = 1<<63 - 1
)
Expand Down
16 changes: 16 additions & 0 deletions hscontrol/types/const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package types

import "time"

const (
HTTPReadTimeout = 30 * time.Second
HTTPShutdownTimeout = 3 * time.Second
TlsALPN01ChallengeType = "TLS-ALPN-01"
Http01ChallengeType = "HTTP-01"

JSONLogFormat = "json"
TextLogFormat = "text"

KeepAliveInterval = 60 * time.Second
MaxHostnameLength = 255
)
8 changes: 1 addition & 7 deletions hscontrol/types/machine.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@ import (
"tailscale.com/types/key"
)

const (
// TODO(kradalby): Move out of here when we got circdeps under control.
keepAliveInterval = 60 * time.Second
MaxHostnameLength = 255
)

var (
ErrMachineAddressesInvalid = errors.New("failed to parse machine addresses")
ErrHostnameTooLong = errors.New("hostname too long")
Expand Down Expand Up @@ -160,7 +154,7 @@ func (machine *Machine) IsOnline() bool {
return false
}

return machine.LastSeen.After(time.Now().Add(-keepAliveInterval))
return machine.LastSeen.After(time.Now().Add(-KeepAliveInterval))
}

// IsEphemeral returns if the machine is registered as an Ephemeral node.
Expand Down

0 comments on commit 8c4c4c8

Please sign in to comment.