262 lines
7.2 KiB
Go
262 lines
7.2 KiB
Go
// Package services manages service registrations from Wild Cloud, Wild Works,
|
|
// and manual entries. Services register with Central to get DNS, gateway
|
|
// routing, TLS certificates, and optional public exposure via DDNS.
|
|
//
|
|
// Each registration is keyed by its domain — one registration per domain.
|
|
// Central registers its own UI domain here on startup (source: "central").
|
|
package services
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// BackendType describes how the gateway handles traffic for this service.
|
|
type BackendType string
|
|
|
|
const (
|
|
BackendTCPPassthrough BackendType = "tcp-passthrough" // L4 SNI passthrough (k8s)
|
|
BackendHTTP BackendType = "http" // L7 HTTP reverse proxy
|
|
)
|
|
|
|
// TLSMode describes how TLS is handled for the service.
|
|
type TLSMode string
|
|
|
|
const (
|
|
TLSTerminate TLSMode = "terminate" // Central terminates TLS
|
|
TLSPassthrough TLSMode = "passthrough" // Backend handles TLS (k8s traefik)
|
|
)
|
|
|
|
// Backend describes the target for a service.
|
|
type Backend struct {
|
|
Address string `yaml:"address" json:"address"` // host:port
|
|
Type BackendType `yaml:"type" json:"type"` // tcp-passthrough or http
|
|
Health string `yaml:"health,omitempty" json:"health,omitempty"`
|
|
}
|
|
|
|
// Service represents a registered service. The Domain is the unique key.
|
|
type Service struct {
|
|
Domain string `yaml:"domain" json:"domain"` // FQDN — unique key
|
|
Source string `yaml:"source,omitempty" json:"source,omitempty"` // who registered: wild-cloud, wild-works, manual
|
|
Backend Backend `yaml:"backend" json:"backend"` // where to route
|
|
Subdomains bool `yaml:"subdomains,omitempty" json:"subdomains,omitempty"` // also match *.domain
|
|
Public bool `yaml:"public,omitempty" json:"public,omitempty"` // true = internet-visible (DDNS + external), false = LAN only
|
|
TLS TLSMode `yaml:"tls,omitempty" json:"tls,omitempty"` // passthrough or terminate
|
|
}
|
|
|
|
// Manager handles service registration CRUD and triggers networking reconciliation.
|
|
type Manager struct {
|
|
dataDir string
|
|
mu sync.RWMutex
|
|
reconcileFn func()
|
|
}
|
|
|
|
// NewManager creates a new service registration manager.
|
|
func NewManager(dataDir string) *Manager {
|
|
servicesDir := filepath.Join(dataDir, "services")
|
|
if err := os.MkdirAll(servicesDir, 0755); err != nil {
|
|
slog.Warn("failed to create services directory", "path", servicesDir, "error", err)
|
|
}
|
|
return &Manager{dataDir: dataDir}
|
|
}
|
|
|
|
// SetReconcileFn sets the function called after service changes to update networking.
|
|
func (m *Manager) SetReconcileFn(fn func()) {
|
|
m.reconcileFn = fn
|
|
}
|
|
|
|
func (m *Manager) servicesDir() string {
|
|
return filepath.Join(m.dataDir, "services")
|
|
}
|
|
|
|
// domainToFilename converts a domain to a filesystem-safe filename.
|
|
func domainToFilename(domain string) string {
|
|
return strings.ReplaceAll(domain, ".", "_") + ".yaml"
|
|
}
|
|
|
|
func (m *Manager) servicePath(domain string) string {
|
|
return filepath.Join(m.servicesDir(), domainToFilename(domain))
|
|
}
|
|
|
|
// Register creates or updates a service registration.
|
|
func (m *Manager) Register(svc Service) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
if svc.Domain == "" {
|
|
return fmt.Errorf("domain is required")
|
|
}
|
|
if svc.Backend.Address == "" {
|
|
return fmt.Errorf("backend address is required")
|
|
}
|
|
if svc.Backend.Type == "" {
|
|
return fmt.Errorf("backend type is required")
|
|
}
|
|
// Public field is a bool — no validation needed (defaults to false)
|
|
|
|
// Default TLS mode based on backend type
|
|
if svc.TLS == "" {
|
|
if svc.Backend.Type == BackendTCPPassthrough {
|
|
svc.TLS = TLSPassthrough
|
|
} else {
|
|
svc.TLS = TLSTerminate
|
|
}
|
|
}
|
|
|
|
// Default source
|
|
if svc.Source == "" {
|
|
svc.Source = "manual"
|
|
}
|
|
|
|
data, err := yaml.Marshal(svc)
|
|
if err != nil {
|
|
return fmt.Errorf("marshaling service: %w", err)
|
|
}
|
|
|
|
if err := os.WriteFile(m.servicePath(svc.Domain), data, 0644); err != nil {
|
|
return fmt.Errorf("writing service file: %w", err)
|
|
}
|
|
|
|
slog.Info("service registered", "domain", svc.Domain, "public", svc.Public, "source", svc.Source, "subdomains", svc.Subdomains)
|
|
|
|
if m.reconcileFn != nil {
|
|
go m.reconcileFn()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Deregister removes a service registration by domain.
|
|
func (m *Manager) Deregister(domain string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
|
|
path := m.servicePath(domain)
|
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
|
return fmt.Errorf("service %q not found", domain)
|
|
}
|
|
|
|
if err := os.Remove(path); err != nil {
|
|
return fmt.Errorf("removing service file: %w", err)
|
|
}
|
|
|
|
slog.Info("service deregistered", "domain", domain)
|
|
|
|
if m.reconcileFn != nil {
|
|
go m.reconcileFn()
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Get retrieves a service registration by domain.
|
|
func (m *Manager) Get(domain string) (*Service, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
|
|
data, err := os.ReadFile(m.servicePath(domain))
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("service %q not found", domain)
|
|
}
|
|
return nil, fmt.Errorf("reading service file: %w", err)
|
|
}
|
|
|
|
var svc Service
|
|
if err := yaml.Unmarshal(data, &svc); err != nil {
|
|
return nil, fmt.Errorf("parsing service file: %w", err)
|
|
}
|
|
|
|
return &svc, nil
|
|
}
|
|
|
|
// List returns all registered services.
|
|
func (m *Manager) List() ([]Service, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
|
|
entries, err := os.ReadDir(m.servicesDir())
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return nil, nil
|
|
}
|
|
return nil, fmt.Errorf("reading services directory: %w", err)
|
|
}
|
|
|
|
var services []Service
|
|
for _, entry := range entries {
|
|
if entry.IsDir() || filepath.Ext(entry.Name()) != ".yaml" {
|
|
continue
|
|
}
|
|
|
|
data, err := os.ReadFile(filepath.Join(m.servicesDir(), entry.Name()))
|
|
if err != nil {
|
|
slog.Warn("failed to read service file", "file", entry.Name(), "error", err)
|
|
continue
|
|
}
|
|
|
|
var svc Service
|
|
if err := yaml.Unmarshal(data, &svc); err != nil {
|
|
slog.Warn("failed to parse service file", "file", entry.Name(), "error", err)
|
|
continue
|
|
}
|
|
|
|
services = append(services, svc)
|
|
}
|
|
|
|
return services, nil
|
|
}
|
|
|
|
// DeregisterBySource removes all registrations from a given source that match
|
|
// a backend address. Used by consumers to clean up before re-registering.
|
|
func (m *Manager) DeregisterBySource(source, backendAddress string) error {
|
|
svcs, err := m.List()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, svc := range svcs {
|
|
if svc.Source == source && svc.Backend.Address == backendAddress {
|
|
if err := m.Deregister(svc.Domain); err != nil {
|
|
slog.Warn("failed to deregister service during cleanup", "domain", svc.Domain, "error", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Update applies partial updates to a service registration.
|
|
func (m *Manager) Update(domain string, updates map[string]any) error {
|
|
svc, err := m.Get(domain)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if public, ok := updates["public"].(bool); ok {
|
|
svc.Public = public
|
|
}
|
|
if sub, ok := updates["subdomains"].(bool); ok {
|
|
svc.Subdomains = sub
|
|
}
|
|
if backend, ok := updates["backend"].(map[string]any); ok {
|
|
if addr, ok := backend["address"].(string); ok {
|
|
svc.Backend.Address = addr
|
|
}
|
|
if typ, ok := backend["type"].(string); ok {
|
|
svc.Backend.Type = BackendType(typ)
|
|
}
|
|
if health, ok := backend["health"].(string); ok {
|
|
svc.Backend.Health = health
|
|
}
|
|
}
|
|
|
|
return m.Register(*svc)
|
|
}
|