headplane/agent/internal/tsnet/server.go

58 lines
1.3 KiB
Go
Raw Normal View History

package tsnet
import (
"context"
2025-04-08 14:51:28 -04:00
"github.com/tale/headplane/agent/internal/config"
"github.com/tale/headplane/agent/internal/util"
"tailscale.com/client/tailscale"
"tailscale.com/tsnet"
)
// Wrapper type so we can add methods to the server.
type TSAgent struct {
*tsnet.Server
Lc *tailscale.LocalClient
ID string
}
// Creates a new tsnet agent and returns an instance of the server.
2025-04-08 14:51:28 -04:00
func NewAgent(cfg *config.Config) *TSAgent {
server := &tsnet.Server{
Hostname: cfg.Hostname,
ControlURL: cfg.TSControlURL,
AuthKey: cfg.TSAuthKey,
Logf: func(string, ...interface{}) {}, // Disabled by default
}
2025-04-08 14:51:28 -04:00
if cfg.Debug {
log := util.GetLogger()
server.Logf = log.Debug
}
2025-04-08 14:51:28 -04:00
return &TSAgent{server, nil, ""}
}
// Starts the tsnet agent and sets the node ID.
2025-04-08 14:51:28 -04:00
func (s *TSAgent) Connect() {
log := util.GetLogger()
// Waits until the agent is up and running.
status, err := s.Up(context.Background())
if err != nil {
2025-04-08 14:51:28 -04:00
log.Fatal("Failed to connect to Tailnet: %s", err)
}
s.Lc, err = s.LocalClient()
if err != nil {
2025-04-08 14:51:28 -04:00
log.Fatal("Failed to initialize local Tailscale client: %s", err)
}
2025-04-08 14:51:28 -04:00
log.Info("Connected to Tailnet (PublicKey: %s)", status.Self.PublicKey)
s.ID = string(status.Self.ID)
}
// Shuts down the tsnet agent.
func (s *TSAgent) Shutdown() {
s.Close()
}