lux/host/lux_host.go

80 lines
1.6 KiB
Go

package host
import (
"lux/crypto"
"lux/net"
"lux/proto"
)
// interface to get data for options. may be blocking
type LuxOptionProvider interface {
Provide() (LuxOption, error)
}
type LuxHost struct {
hostname string
router net.LuxRouter
providers []LuxOptionProvider
}
func NewLuxHost(hostname string, hostKey crypto.LuxKey, ks crypto.LuxKeyStore) LuxHost {
return LuxHost{
hostname: hostname,
router: net.NewLuxRouter(hostKey, ks),
providers: make([]LuxOptionProvider, 0),
}
}
func (host *LuxHost) AddNode(node proto.LuxID, udpAddr string) error {
return host.router.AddOutboundRoute(node, net.LuxRouteFromSource, net.LuxChannelExterior, udpAddr)
}
func (host *LuxHost) AddOptionProvider(provider LuxOptionProvider) {
host.providers = append(host.providers, provider)
}
func (host *LuxHost) GetRouter() *net.LuxRouter {
return &host.router
}
func (host *LuxHost) CaptureState() (LuxState, error) {
state := LuxState{
Hostname: host.hostname,
Options: make(map[LuxOptionType]LuxOption),
}
for _, provider := range host.providers {
opt, err := provider.Provide()
if err != nil {
return state, err
}
state.Options[opt.Type()] = opt
}
return state, nil
}
func (host *LuxHost) Heartbeat() error {
state, err := host.CaptureState()
if err != nil {
return err
}
packet := net.LuxPacket{
Target: host.router.GetThisKey().Id,
Type: net.LuxPacketTypeHeartbeat,
Buffer: proto.NewLuxBuffer(),
}
state.Write(&packet.Buffer)
return host.router.Multicast(packet, proto.LuxTypeNode)
}
func (host *LuxHost) Start() {
host.router.Start()
}
func (host *LuxHost) Stop() {
host.router.Stop()
}