wip v1.0.0
This commit is contained in:
72
internal/vrrp/arp.go
Normal file
72
internal/vrrp/arp.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
"github.com/mdlayher/arp"
|
||||
)
|
||||
|
||||
type ARPSender struct {
|
||||
client *arp.Client
|
||||
iface *net.Interface
|
||||
}
|
||||
|
||||
func NewARPSender(ifaceName string) (*ARPSender, error) {
|
||||
iface, err := net.InterfaceByName(ifaceName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get interface %s: %w", ifaceName, err)
|
||||
}
|
||||
|
||||
client, err := arp.Dial(iface)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create ARP client: %w", err)
|
||||
}
|
||||
|
||||
return &ARPSender{
|
||||
client: client,
|
||||
iface: iface,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *ARPSender) SendGratuitousARP(ip net.IP) error {
|
||||
if ip4 := ip.To4(); ip4 == nil {
|
||||
return fmt.Errorf("invalid IPv4 address: %s", ip)
|
||||
}
|
||||
|
||||
addr, err := netip.ParseAddr(ip.String())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to parse IP: %w", err)
|
||||
}
|
||||
|
||||
pkt, err := arp.NewPacket(
|
||||
arp.OperationRequest,
|
||||
a.iface.HardwareAddr,
|
||||
addr,
|
||||
net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
|
||||
addr,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create ARP packet: %w", err)
|
||||
}
|
||||
|
||||
if err := a.client.WriteTo(pkt, net.HardwareAddr{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}); err != nil {
|
||||
return fmt.Errorf("failed to send gratuitous ARP: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ARPSender) SendGratuitousARPForIPs(ips []net.IP) error {
|
||||
for _, ip := range ips {
|
||||
if err := a.SendGratuitousARP(ip); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ARPSender) Close() error {
|
||||
return a.client.Close()
|
||||
}
|
||||
427
internal/vrrp/instance.go
Normal file
427
internal/vrrp/instance.go
Normal file
@@ -0,0 +1,427 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/loveuer/go-alived/pkg/logger"
|
||||
"github.com/loveuer/go-alived/pkg/netif"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
Name string
|
||||
VirtualRouterID uint8
|
||||
Priority uint8
|
||||
AdvertInterval uint8
|
||||
Interface string
|
||||
VirtualIPs []net.IP
|
||||
AuthType uint8
|
||||
AuthPass string
|
||||
TrackScripts []string
|
||||
|
||||
state *StateMachine
|
||||
priorityCalc *PriorityCalculator
|
||||
history *StateHistory
|
||||
socket *Socket
|
||||
arpSender *ARPSender
|
||||
netInterface *netif.Interface
|
||||
|
||||
advertTimer *Timer
|
||||
masterDownTimer *Timer
|
||||
|
||||
running bool
|
||||
stopCh chan struct{}
|
||||
wg sync.WaitGroup
|
||||
mu sync.RWMutex
|
||||
|
||||
log *logger.Logger
|
||||
|
||||
onMaster func()
|
||||
onBackup func()
|
||||
onFault func()
|
||||
}
|
||||
|
||||
func NewInstance(
|
||||
name string,
|
||||
vrID uint8,
|
||||
priority uint8,
|
||||
advertInt uint8,
|
||||
iface string,
|
||||
vips []string,
|
||||
authType string,
|
||||
authPass string,
|
||||
trackScripts []string,
|
||||
log *logger.Logger,
|
||||
) (*Instance, error) {
|
||||
if vrID < 1 || vrID > 255 {
|
||||
return nil, fmt.Errorf("invalid virtual router ID: %d", vrID)
|
||||
}
|
||||
|
||||
if priority < 1 || priority > 255 {
|
||||
return nil, fmt.Errorf("invalid priority: %d", priority)
|
||||
}
|
||||
|
||||
virtualIPs := make([]net.IP, 0, len(vips))
|
||||
for _, vip := range vips {
|
||||
ip, _, err := net.ParseCIDR(vip)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid VIP %s: %w", vip, err)
|
||||
}
|
||||
virtualIPs = append(virtualIPs, ip)
|
||||
}
|
||||
|
||||
var authTypeNum uint8
|
||||
switch authType {
|
||||
case "NONE", "":
|
||||
authTypeNum = AuthTypeNone
|
||||
case "PASS":
|
||||
authTypeNum = AuthTypeSimpleText
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported auth type: %s", authType)
|
||||
}
|
||||
|
||||
netInterface, err := netif.GetInterface(iface)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get interface: %w", err)
|
||||
}
|
||||
|
||||
inst := &Instance{
|
||||
Name: name,
|
||||
VirtualRouterID: vrID,
|
||||
Priority: priority,
|
||||
AdvertInterval: advertInt,
|
||||
Interface: iface,
|
||||
VirtualIPs: virtualIPs,
|
||||
AuthType: authTypeNum,
|
||||
AuthPass: authPass,
|
||||
TrackScripts: trackScripts,
|
||||
state: NewStateMachine(StateInit),
|
||||
priorityCalc: NewPriorityCalculator(priority),
|
||||
history: NewStateHistory(100),
|
||||
netInterface: netInterface,
|
||||
stopCh: make(chan struct{}),
|
||||
log: log,
|
||||
}
|
||||
|
||||
inst.advertTimer = NewTimer(time.Duration(advertInt)*time.Second, inst.onAdvertTimer)
|
||||
inst.masterDownTimer = NewTimer(CalculateMasterDownInterval(advertInt), inst.onMasterDownTimer)
|
||||
|
||||
inst.state.OnStateChange(func(old, new State) {
|
||||
inst.history.Add(old, new, "state transition")
|
||||
inst.log.Info("[%s] state changed: %s -> %s", inst.Name, old, new)
|
||||
inst.handleStateChange(old, new)
|
||||
})
|
||||
|
||||
return inst, nil
|
||||
}
|
||||
|
||||
func (inst *Instance) Start() error {
|
||||
inst.mu.Lock()
|
||||
if inst.running {
|
||||
inst.mu.Unlock()
|
||||
return fmt.Errorf("instance %s already running", inst.Name)
|
||||
}
|
||||
inst.running = true
|
||||
inst.mu.Unlock()
|
||||
|
||||
var err error
|
||||
inst.socket, err = NewSocket(inst.Interface)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create socket: %w", err)
|
||||
}
|
||||
|
||||
inst.arpSender, err = NewARPSender(inst.Interface)
|
||||
if err != nil {
|
||||
inst.socket.Close()
|
||||
return fmt.Errorf("failed to create ARP sender: %w", err)
|
||||
}
|
||||
|
||||
inst.log.Info("[%s] starting VRRP instance (VRID=%d, Priority=%d, Interface=%s)",
|
||||
inst.Name, inst.VirtualRouterID, inst.Priority, inst.Interface)
|
||||
|
||||
inst.state.SetState(StateBackup)
|
||||
inst.masterDownTimer.Start()
|
||||
|
||||
inst.wg.Add(1)
|
||||
go inst.receiveLoop()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (inst *Instance) Stop() {
|
||||
inst.mu.Lock()
|
||||
if !inst.running {
|
||||
inst.mu.Unlock()
|
||||
return
|
||||
}
|
||||
inst.running = false
|
||||
inst.mu.Unlock()
|
||||
|
||||
inst.log.Info("[%s] stopping VRRP instance", inst.Name)
|
||||
|
||||
close(inst.stopCh)
|
||||
inst.wg.Wait()
|
||||
|
||||
inst.advertTimer.Stop()
|
||||
inst.masterDownTimer.Stop()
|
||||
|
||||
if inst.state.GetState() == StateMaster {
|
||||
inst.removeVIPs()
|
||||
}
|
||||
|
||||
if inst.socket != nil {
|
||||
inst.socket.Close()
|
||||
}
|
||||
|
||||
if inst.arpSender != nil {
|
||||
inst.arpSender.Close()
|
||||
}
|
||||
|
||||
inst.state.SetState(StateInit)
|
||||
}
|
||||
|
||||
func (inst *Instance) receiveLoop() {
|
||||
defer inst.wg.Done()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-inst.stopCh:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
pkt, srcIP, err := inst.socket.Receive()
|
||||
if err != nil {
|
||||
inst.log.Debug("[%s] failed to receive packet: %v", inst.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if pkt.VirtualRtrID != inst.VirtualRouterID {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := pkt.Validate(inst.AuthPass); err != nil {
|
||||
inst.log.Warn("[%s] packet validation failed: %v", inst.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
inst.handleAdvertisement(pkt, srcIP)
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) handleAdvertisement(pkt *VRRPPacket, srcIP net.IP) {
|
||||
currentState := inst.state.GetState()
|
||||
localPriority := inst.priorityCalc.GetPriority()
|
||||
|
||||
inst.log.Debug("[%s] received advertisement from %s (priority=%d, state=%s)",
|
||||
inst.Name, srcIP, pkt.Priority, currentState)
|
||||
|
||||
switch currentState {
|
||||
case StateBackup:
|
||||
if pkt.Priority == 0 {
|
||||
inst.masterDownTimer.SetDuration(CalculateSkewTime(localPriority))
|
||||
inst.masterDownTimer.Reset()
|
||||
} else if !ShouldBecomeMaster(localPriority, pkt.Priority, inst.socket.localIP.String(), srcIP.String()) {
|
||||
inst.masterDownTimer.Reset()
|
||||
}
|
||||
|
||||
case StateMaster:
|
||||
if ShouldBecomeMaster(pkt.Priority, localPriority, srcIP.String(), inst.socket.localIP.String()) {
|
||||
inst.log.Warn("[%s] received higher priority advertisement, stepping down", inst.Name)
|
||||
inst.state.SetState(StateBackup)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) onAdvertTimer() {
|
||||
if inst.state.GetState() == StateMaster {
|
||||
inst.sendAdvertisement()
|
||||
inst.advertTimer.Start()
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) onMasterDownTimer() {
|
||||
if inst.state.GetState() == StateBackup {
|
||||
inst.log.Info("[%s] master down timer expired, becoming master", inst.Name)
|
||||
inst.state.SetState(StateMaster)
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) sendAdvertisement() error {
|
||||
priority := inst.priorityCalc.GetPriority()
|
||||
|
||||
pkt := NewAdvertisement(
|
||||
inst.VirtualRouterID,
|
||||
priority,
|
||||
inst.AdvertInterval,
|
||||
inst.VirtualIPs,
|
||||
inst.AuthType,
|
||||
inst.AuthPass,
|
||||
)
|
||||
|
||||
if err := inst.socket.Send(pkt); err != nil {
|
||||
inst.log.Error("[%s] failed to send advertisement: %v", inst.Name, err)
|
||||
return err
|
||||
}
|
||||
|
||||
inst.log.Debug("[%s] sent advertisement (priority=%d)", inst.Name, priority)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (inst *Instance) handleStateChange(old, new State) {
|
||||
switch new {
|
||||
case StateMaster:
|
||||
inst.becomeMaster()
|
||||
case StateBackup:
|
||||
inst.becomeBackup(old)
|
||||
case StateFault:
|
||||
inst.becomeFault()
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) becomeMaster() {
|
||||
inst.log.Info("[%s] transitioning to MASTER state", inst.Name)
|
||||
|
||||
if err := inst.addVIPs(); err != nil {
|
||||
inst.log.Error("[%s] failed to add VIPs: %v", inst.Name, err)
|
||||
inst.state.SetState(StateFault)
|
||||
return
|
||||
}
|
||||
|
||||
if err := inst.arpSender.SendGratuitousARPForIPs(inst.VirtualIPs); err != nil {
|
||||
inst.log.Error("[%s] failed to send gratuitous ARP: %v", inst.Name, err)
|
||||
}
|
||||
|
||||
inst.masterDownTimer.Stop()
|
||||
inst.advertTimer.Start()
|
||||
|
||||
inst.sendAdvertisement()
|
||||
|
||||
if inst.onMaster != nil {
|
||||
inst.onMaster()
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) becomeBackup(oldState State) {
|
||||
inst.log.Info("[%s] transitioning to BACKUP state", inst.Name)
|
||||
|
||||
inst.advertTimer.Stop()
|
||||
|
||||
if oldState == StateMaster {
|
||||
if err := inst.removeVIPs(); err != nil {
|
||||
inst.log.Error("[%s] failed to remove VIPs: %v", inst.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
inst.masterDownTimer.Reset()
|
||||
|
||||
if inst.onBackup != nil {
|
||||
inst.onBackup()
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) becomeFault() {
|
||||
inst.log.Error("[%s] transitioning to FAULT state", inst.Name)
|
||||
|
||||
inst.advertTimer.Stop()
|
||||
inst.masterDownTimer.Stop()
|
||||
|
||||
if err := inst.removeVIPs(); err != nil {
|
||||
inst.log.Error("[%s] failed to remove VIPs: %v", inst.Name, err)
|
||||
}
|
||||
|
||||
if inst.onFault != nil {
|
||||
inst.onFault()
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) addVIPs() error {
|
||||
inst.log.Info("[%s] adding virtual IPs", inst.Name)
|
||||
|
||||
for _, vipStr := range inst.getVIPsWithCIDR() {
|
||||
if err := inst.netInterface.AddIP(vipStr); err != nil {
|
||||
inst.log.Error("[%s] failed to add VIP %s: %v", inst.Name, vipStr, err)
|
||||
return err
|
||||
}
|
||||
inst.log.Info("[%s] added VIP %s", inst.Name, vipStr)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (inst *Instance) removeVIPs() error {
|
||||
inst.log.Info("[%s] removing virtual IPs", inst.Name)
|
||||
|
||||
for _, vipStr := range inst.getVIPsWithCIDR() {
|
||||
has, _ := inst.netInterface.HasIP(vipStr)
|
||||
if !has {
|
||||
continue
|
||||
}
|
||||
|
||||
if err := inst.netInterface.DeleteIP(vipStr); err != nil {
|
||||
inst.log.Error("[%s] failed to remove VIP %s: %v", inst.Name, vipStr, err)
|
||||
return err
|
||||
}
|
||||
inst.log.Info("[%s] removed VIP %s", inst.Name, vipStr)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (inst *Instance) getVIPsWithCIDR() []string {
|
||||
result := make([]string, len(inst.VirtualIPs))
|
||||
for i, ip := range inst.VirtualIPs {
|
||||
result[i] = ip.String() + "/32"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (inst *Instance) GetState() State {
|
||||
return inst.state.GetState()
|
||||
}
|
||||
|
||||
func (inst *Instance) OnMaster(callback func()) {
|
||||
inst.onMaster = callback
|
||||
}
|
||||
|
||||
func (inst *Instance) OnBackup(callback func()) {
|
||||
inst.onBackup = callback
|
||||
}
|
||||
|
||||
func (inst *Instance) OnFault(callback func()) {
|
||||
inst.onFault = callback
|
||||
}
|
||||
|
||||
func (inst *Instance) AdjustPriority(delta int) {
|
||||
inst.mu.Lock()
|
||||
defer inst.mu.Unlock()
|
||||
|
||||
oldPriority := inst.priorityCalc.GetPriority()
|
||||
|
||||
if delta < 0 {
|
||||
inst.priorityCalc.DecreasePriority(uint8(-delta))
|
||||
}
|
||||
|
||||
newPriority := inst.priorityCalc.GetPriority()
|
||||
|
||||
if oldPriority != newPriority {
|
||||
inst.log.Info("[%s] priority adjusted: %d -> %d (delta=%d)",
|
||||
inst.Name, oldPriority, newPriority, delta)
|
||||
}
|
||||
}
|
||||
|
||||
func (inst *Instance) ResetPriority() {
|
||||
inst.mu.Lock()
|
||||
defer inst.mu.Unlock()
|
||||
|
||||
oldPriority := inst.priorityCalc.GetPriority()
|
||||
inst.priorityCalc.ResetPriority()
|
||||
newPriority := inst.priorityCalc.GetPriority()
|
||||
|
||||
if oldPriority != newPriority {
|
||||
inst.log.Info("[%s] priority reset: %d -> %d",
|
||||
inst.Name, oldPriority, newPriority)
|
||||
}
|
||||
}
|
||||
116
internal/vrrp/manager.go
Normal file
116
internal/vrrp/manager.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/loveuer/go-alived/pkg/config"
|
||||
"github.com/loveuer/go-alived/pkg/logger"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
instances map[string]*Instance
|
||||
mu sync.RWMutex
|
||||
log *logger.Logger
|
||||
}
|
||||
|
||||
func NewManager(log *logger.Logger) *Manager {
|
||||
return &Manager{
|
||||
instances: make(map[string]*Instance),
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) LoadFromConfig(cfg *config.Config) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
for _, vrrpCfg := range cfg.VRRP {
|
||||
inst, err := NewInstance(
|
||||
vrrpCfg.Name,
|
||||
uint8(vrrpCfg.VirtualRouterID),
|
||||
uint8(vrrpCfg.Priority),
|
||||
uint8(vrrpCfg.AdvertInterval),
|
||||
vrrpCfg.Interface,
|
||||
vrrpCfg.VirtualIPs,
|
||||
vrrpCfg.AuthType,
|
||||
vrrpCfg.AuthPass,
|
||||
vrrpCfg.TrackScripts,
|
||||
m.log,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create instance %s: %w", vrrpCfg.Name, err)
|
||||
}
|
||||
|
||||
m.instances[vrrpCfg.Name] = inst
|
||||
m.log.Info("loaded VRRP instance: %s", vrrpCfg.Name)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) StartAll() error {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
for name, inst := range m.instances {
|
||||
if err := inst.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start instance %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
m.log.Info("started %d VRRP instance(s)", len(m.instances))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) StopAll() {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
for _, inst := range m.instances {
|
||||
inst.Stop()
|
||||
}
|
||||
|
||||
m.log.Info("stopped all VRRP instances")
|
||||
}
|
||||
|
||||
func (m *Manager) GetInstance(name string) (*Instance, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
inst, ok := m.instances[name]
|
||||
return inst, ok
|
||||
}
|
||||
|
||||
func (m *Manager) GetAllInstances() []*Instance {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
result := make([]*Instance, 0, len(m.instances))
|
||||
for _, inst := range m.instances {
|
||||
result = append(result, inst)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *Manager) Reload(cfg *config.Config) error {
|
||||
m.log.Info("reloading VRRP configuration...")
|
||||
|
||||
m.StopAll()
|
||||
|
||||
m.mu.Lock()
|
||||
m.instances = make(map[string]*Instance)
|
||||
m.mu.Unlock()
|
||||
|
||||
if err := m.LoadFromConfig(cfg); err != nil {
|
||||
return fmt.Errorf("failed to load config: %w", err)
|
||||
}
|
||||
|
||||
if err := m.StartAll(); err != nil {
|
||||
return fmt.Errorf("failed to start instances: %w", err)
|
||||
}
|
||||
|
||||
m.log.Info("VRRP configuration reloaded successfully")
|
||||
return nil
|
||||
}
|
||||
184
internal/vrrp/packet.go
Normal file
184
internal/vrrp/packet.go
Normal file
@@ -0,0 +1,184 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
const (
|
||||
VRRPVersion = 2
|
||||
VRRPProtocolNumber = 112
|
||||
)
|
||||
|
||||
type VRRPPacket struct {
|
||||
Version uint8
|
||||
Type uint8
|
||||
VirtualRtrID uint8
|
||||
Priority uint8
|
||||
CountIPAddrs uint8
|
||||
AuthType uint8
|
||||
AdvertInt uint8
|
||||
Checksum uint16
|
||||
IPAddresses []net.IP
|
||||
AuthData [8]byte
|
||||
}
|
||||
|
||||
const (
|
||||
VRRPTypeAdvertisement = 1
|
||||
)
|
||||
|
||||
const (
|
||||
AuthTypeNone = 0
|
||||
AuthTypeSimpleText = 1
|
||||
AuthTypeIPAH = 2
|
||||
)
|
||||
|
||||
func NewAdvertisement(vrID uint8, priority uint8, advertInt uint8, ips []net.IP, authType uint8, authPass string) *VRRPPacket {
|
||||
pkt := &VRRPPacket{
|
||||
Version: VRRPVersion,
|
||||
Type: VRRPTypeAdvertisement,
|
||||
VirtualRtrID: vrID,
|
||||
Priority: priority,
|
||||
CountIPAddrs: uint8(len(ips)),
|
||||
AuthType: authType,
|
||||
AdvertInt: advertInt,
|
||||
IPAddresses: ips,
|
||||
}
|
||||
|
||||
if authType == AuthTypeSimpleText && authPass != "" {
|
||||
copy(pkt.AuthData[:], authPass)
|
||||
}
|
||||
|
||||
return pkt
|
||||
}
|
||||
|
||||
func (p *VRRPPacket) Marshal() ([]byte, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
versionType := (p.Version << 4) | p.Type
|
||||
if err := binary.Write(buf, binary.BigEndian, versionType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.VirtualRtrID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.Priority); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.CountIPAddrs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.AuthType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.AdvertInt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, uint16(0)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, ip := range p.IPAddresses {
|
||||
ip4 := ip.To4()
|
||||
if ip4 == nil {
|
||||
return nil, fmt.Errorf("invalid IPv4 address: %s", ip)
|
||||
}
|
||||
if err := binary.Write(buf, binary.BigEndian, ip4); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, p.AuthData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := buf.Bytes()
|
||||
|
||||
checksum := calculateChecksum(data)
|
||||
binary.BigEndian.PutUint16(data[6:8], checksum)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func Unmarshal(data []byte) (*VRRPPacket, error) {
|
||||
if len(data) < 20 {
|
||||
return nil, fmt.Errorf("packet too short: %d bytes", len(data))
|
||||
}
|
||||
|
||||
pkt := &VRRPPacket{}
|
||||
|
||||
versionType := data[0]
|
||||
pkt.Version = versionType >> 4
|
||||
pkt.Type = versionType & 0x0F
|
||||
pkt.VirtualRtrID = data[1]
|
||||
pkt.Priority = data[2]
|
||||
pkt.CountIPAddrs = data[3]
|
||||
pkt.AuthType = data[4]
|
||||
pkt.AdvertInt = data[5]
|
||||
pkt.Checksum = binary.BigEndian.Uint16(data[6:8])
|
||||
|
||||
offset := 8
|
||||
pkt.IPAddresses = make([]net.IP, pkt.CountIPAddrs)
|
||||
for i := 0; i < int(pkt.CountIPAddrs); i++ {
|
||||
if offset+4 > len(data) {
|
||||
return nil, fmt.Errorf("packet too short for IP addresses")
|
||||
}
|
||||
pkt.IPAddresses[i] = net.IPv4(data[offset], data[offset+1], data[offset+2], data[offset+3])
|
||||
offset += 4
|
||||
}
|
||||
|
||||
if offset+8 > len(data) {
|
||||
return nil, fmt.Errorf("packet too short for auth data")
|
||||
}
|
||||
copy(pkt.AuthData[:], data[offset:offset+8])
|
||||
|
||||
return pkt, nil
|
||||
}
|
||||
|
||||
func calculateChecksum(data []byte) uint16 {
|
||||
sum := uint32(0)
|
||||
|
||||
for i := 0; i < len(data)-1; i += 2 {
|
||||
sum += uint32(data[i])<<8 | uint32(data[i+1])
|
||||
}
|
||||
|
||||
if len(data)%2 == 1 {
|
||||
sum += uint32(data[len(data)-1]) << 8
|
||||
}
|
||||
|
||||
for sum > 0xFFFF {
|
||||
sum = (sum & 0xFFFF) + (sum >> 16)
|
||||
}
|
||||
|
||||
return uint16(^sum)
|
||||
}
|
||||
|
||||
func (p *VRRPPacket) Validate(authPass string) error {
|
||||
if p.Version != VRRPVersion {
|
||||
return fmt.Errorf("unsupported VRRP version: %d", p.Version)
|
||||
}
|
||||
|
||||
if p.Type != VRRPTypeAdvertisement {
|
||||
return fmt.Errorf("unsupported VRRP type: %d", p.Type)
|
||||
}
|
||||
|
||||
if p.AuthType == AuthTypeSimpleText {
|
||||
if authPass != "" {
|
||||
var expectedAuth [8]byte
|
||||
copy(expectedAuth[:], authPass)
|
||||
if !bytes.Equal(p.AuthData[:], expectedAuth[:]) {
|
||||
return fmt.Errorf("authentication failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
141
internal/vrrp/socket.go
Normal file
141
internal/vrrp/socket.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/net/ipv4"
|
||||
)
|
||||
|
||||
const (
|
||||
VRRPMulticastAddr = "224.0.0.18"
|
||||
)
|
||||
|
||||
type Socket struct {
|
||||
conn *ipv4.RawConn
|
||||
iface *net.Interface
|
||||
localIP net.IP
|
||||
groupIP net.IP
|
||||
}
|
||||
|
||||
func NewSocket(ifaceName string) (*Socket, error) {
|
||||
iface, err := net.InterfaceByName(ifaceName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get interface %s: %w", ifaceName, err)
|
||||
}
|
||||
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get addresses for %s: %w", ifaceName, err)
|
||||
}
|
||||
|
||||
var localIP net.IP
|
||||
for _, addr := range addrs {
|
||||
if ipNet, ok := addr.(*net.IPNet); ok {
|
||||
if ipv4 := ipNet.IP.To4(); ipv4 != nil {
|
||||
localIP = ipv4
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if localIP == nil {
|
||||
return nil, fmt.Errorf("no IPv4 address found on interface %s", ifaceName)
|
||||
}
|
||||
|
||||
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, VRRPProtocolNumber)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create raw socket: %w", err)
|
||||
}
|
||||
|
||||
if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
|
||||
syscall.Close(fd)
|
||||
return nil, fmt.Errorf("failed to set SO_REUSEADDR: %w", err)
|
||||
}
|
||||
|
||||
file := os.NewFile(uintptr(fd), "vrrp-socket")
|
||||
defer file.Close()
|
||||
|
||||
packetConn, err := net.FilePacketConn(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create packet connection: %w", err)
|
||||
}
|
||||
|
||||
rawConn, err := ipv4.NewRawConn(packetConn)
|
||||
if err != nil {
|
||||
packetConn.Close()
|
||||
return nil, fmt.Errorf("failed to create raw connection: %w", err)
|
||||
}
|
||||
|
||||
groupIP := net.ParseIP(VRRPMulticastAddr).To4()
|
||||
if groupIP == nil {
|
||||
rawConn.Close()
|
||||
return nil, fmt.Errorf("invalid multicast address: %s", VRRPMulticastAddr)
|
||||
}
|
||||
|
||||
if err := rawConn.JoinGroup(iface, &net.IPAddr{IP: groupIP}); err != nil {
|
||||
rawConn.Close()
|
||||
return nil, fmt.Errorf("failed to join multicast group: %w", err)
|
||||
}
|
||||
|
||||
if err := rawConn.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil {
|
||||
rawConn.Close()
|
||||
return nil, fmt.Errorf("failed to set control message: %w", err)
|
||||
}
|
||||
|
||||
return &Socket{
|
||||
conn: rawConn,
|
||||
iface: iface,
|
||||
localIP: localIP,
|
||||
groupIP: groupIP,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Socket) Send(pkt *VRRPPacket) error {
|
||||
data, err := pkt.Marshal()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal packet: %w", err)
|
||||
}
|
||||
|
||||
header := &ipv4.Header{
|
||||
Version: ipv4.Version,
|
||||
Len: ipv4.HeaderLen,
|
||||
TOS: 0xC0,
|
||||
TotalLen: ipv4.HeaderLen + len(data),
|
||||
TTL: 255,
|
||||
Protocol: VRRPProtocolNumber,
|
||||
Dst: s.groupIP,
|
||||
Src: s.localIP,
|
||||
}
|
||||
|
||||
if err := s.conn.WriteTo(header, data, nil); err != nil {
|
||||
return fmt.Errorf("failed to send packet: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Socket) Receive() (*VRRPPacket, net.IP, error) {
|
||||
buf := make([]byte, 1500)
|
||||
|
||||
header, payload, _, err := s.conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to receive packet: %w", err)
|
||||
}
|
||||
|
||||
pkt, err := Unmarshal(payload)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("failed to unmarshal packet: %w", err)
|
||||
}
|
||||
|
||||
return pkt, header.Src, nil
|
||||
}
|
||||
|
||||
func (s *Socket) Close() error {
|
||||
if err := s.conn.LeaveGroup(s.iface, &net.IPAddr{IP: s.groupIP}); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.conn.Close()
|
||||
}
|
||||
258
internal/vrrp/state.go
Normal file
258
internal/vrrp/state.go
Normal file
@@ -0,0 +1,258 @@
|
||||
package vrrp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type State int
|
||||
|
||||
const (
|
||||
StateInit State = iota
|
||||
StateBackup
|
||||
StateMaster
|
||||
StateFault
|
||||
)
|
||||
|
||||
func (s State) String() string {
|
||||
switch s {
|
||||
case StateInit:
|
||||
return "INIT"
|
||||
case StateBackup:
|
||||
return "BACKUP"
|
||||
case StateMaster:
|
||||
return "MASTER"
|
||||
case StateFault:
|
||||
return "FAULT"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
type StateMachine struct {
|
||||
currentState State
|
||||
previousState State
|
||||
mu sync.RWMutex
|
||||
stateChangeCallbacks []func(old, new State)
|
||||
}
|
||||
|
||||
func NewStateMachine(initialState State) *StateMachine {
|
||||
return &StateMachine{
|
||||
currentState: initialState,
|
||||
previousState: StateInit,
|
||||
stateChangeCallbacks: make([]func(old, new State), 0),
|
||||
}
|
||||
}
|
||||
|
||||
func (sm *StateMachine) GetState() State {
|
||||
sm.mu.RLock()
|
||||
defer sm.mu.RUnlock()
|
||||
return sm.currentState
|
||||
}
|
||||
|
||||
func (sm *StateMachine) SetState(newState State) {
|
||||
sm.mu.Lock()
|
||||
oldState := sm.currentState
|
||||
sm.previousState = oldState
|
||||
sm.currentState = newState
|
||||
callbacks := sm.stateChangeCallbacks
|
||||
sm.mu.Unlock()
|
||||
|
||||
for _, callback := range callbacks {
|
||||
callback(oldState, newState)
|
||||
}
|
||||
}
|
||||
|
||||
func (sm *StateMachine) OnStateChange(callback func(old, new State)) {
|
||||
sm.mu.Lock()
|
||||
defer sm.mu.Unlock()
|
||||
sm.stateChangeCallbacks = append(sm.stateChangeCallbacks, callback)
|
||||
}
|
||||
|
||||
type Timer struct {
|
||||
duration time.Duration
|
||||
timer *time.Timer
|
||||
callback func()
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewTimer(duration time.Duration, callback func()) *Timer {
|
||||
return &Timer{
|
||||
duration: duration,
|
||||
callback: callback,
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Timer) Start() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.timer != nil {
|
||||
t.timer.Stop()
|
||||
}
|
||||
|
||||
t.timer = time.AfterFunc(t.duration, t.callback)
|
||||
}
|
||||
|
||||
func (t *Timer) Stop() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.timer != nil {
|
||||
t.timer.Stop()
|
||||
t.timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Timer) Reset() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
if t.timer != nil {
|
||||
t.timer.Stop()
|
||||
}
|
||||
|
||||
t.timer = time.AfterFunc(t.duration, t.callback)
|
||||
}
|
||||
|
||||
func (t *Timer) SetDuration(duration time.Duration) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.duration = duration
|
||||
}
|
||||
|
||||
type PriorityCalculator struct {
|
||||
basePriority uint8
|
||||
currentPriority uint8
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewPriorityCalculator(basePriority uint8) *PriorityCalculator {
|
||||
return &PriorityCalculator{
|
||||
basePriority: basePriority,
|
||||
currentPriority: basePriority,
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PriorityCalculator) GetPriority() uint8 {
|
||||
pc.mu.RLock()
|
||||
defer pc.mu.RUnlock()
|
||||
return pc.currentPriority
|
||||
}
|
||||
|
||||
func (pc *PriorityCalculator) DecreasePriority(amount uint8) {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
|
||||
if pc.currentPriority > amount {
|
||||
pc.currentPriority -= amount
|
||||
} else {
|
||||
pc.currentPriority = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PriorityCalculator) ResetPriority() {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
pc.currentPriority = pc.basePriority
|
||||
}
|
||||
|
||||
func (pc *PriorityCalculator) SetBasePriority(priority uint8) {
|
||||
pc.mu.Lock()
|
||||
defer pc.mu.Unlock()
|
||||
pc.basePriority = priority
|
||||
pc.currentPriority = priority
|
||||
}
|
||||
|
||||
func ShouldBecomeMaster(localPriority, remotePriority uint8, localIP, remoteIP string) bool {
|
||||
if localPriority > remotePriority {
|
||||
return true
|
||||
}
|
||||
|
||||
if localPriority == remotePriority {
|
||||
return localIP > remoteIP
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func CalculateMasterDownInterval(advertInt uint8) time.Duration {
|
||||
return time.Duration(3*int(advertInt)) * time.Second
|
||||
}
|
||||
|
||||
func CalculateSkewTime(priority uint8) time.Duration {
|
||||
skew := float64(256-int(priority)) / 256.0
|
||||
return time.Duration(skew * float64(time.Second))
|
||||
}
|
||||
|
||||
type StateTransition struct {
|
||||
From State
|
||||
To State
|
||||
Timestamp time.Time
|
||||
Reason string
|
||||
}
|
||||
|
||||
type StateHistory struct {
|
||||
transitions []StateTransition
|
||||
maxSize int
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewStateHistory(maxSize int) *StateHistory {
|
||||
return &StateHistory{
|
||||
transitions: make([]StateTransition, 0, maxSize),
|
||||
maxSize: maxSize,
|
||||
}
|
||||
}
|
||||
|
||||
func (sh *StateHistory) Add(from, to State, reason string) {
|
||||
sh.mu.Lock()
|
||||
defer sh.mu.Unlock()
|
||||
|
||||
transition := StateTransition{
|
||||
From: from,
|
||||
To: to,
|
||||
Timestamp: time.Now(),
|
||||
Reason: reason,
|
||||
}
|
||||
|
||||
sh.transitions = append(sh.transitions, transition)
|
||||
|
||||
if len(sh.transitions) > sh.maxSize {
|
||||
sh.transitions = sh.transitions[1:]
|
||||
}
|
||||
}
|
||||
|
||||
func (sh *StateHistory) GetRecent(n int) []StateTransition {
|
||||
sh.mu.RLock()
|
||||
defer sh.mu.RUnlock()
|
||||
|
||||
if n > len(sh.transitions) {
|
||||
n = len(sh.transitions)
|
||||
}
|
||||
|
||||
start := len(sh.transitions) - n
|
||||
result := make([]StateTransition, n)
|
||||
copy(result, sh.transitions[start:])
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (sh *StateHistory) String() string {
|
||||
sh.mu.RLock()
|
||||
defer sh.mu.RUnlock()
|
||||
|
||||
if len(sh.transitions) == 0 {
|
||||
return "No state transitions"
|
||||
}
|
||||
|
||||
result := "State transition history:\n"
|
||||
for _, t := range sh.transitions {
|
||||
result += fmt.Sprintf(" %s: %s -> %s (%s)\n",
|
||||
t.Timestamp.Format("2006-01-02 15:04:05"),
|
||||
t.From, t.To, t.Reason)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user