1 Commits

Author SHA1 Message Date
loveuer bece440c47 wip v1.0.0 2025-12-08 22:23:45 +08:00
22 changed files with 473 additions and 1570 deletions
-95
View File
@@ -1,95 +0,0 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
build:
name: Build ${{ matrix.os }}-${{ matrix.arch }}
runs-on: ubuntu-latest
strategy:
matrix:
include:
- os: linux
arch: amd64
- os: linux
arch: arm64
- os: darwin
arch: amd64
- os: darwin
arch: arm64
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Get version
id: version
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Build binary
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
CGO_ENABLED: 0
run: |
mkdir -p dist
BINARY_NAME=go-alived-${{ matrix.os }}-${{ matrix.arch }}
if [ "${{ matrix.os }}" = "windows" ]; then
BINARY_NAME="${BINARY_NAME}.exe"
fi
go build -ldflags="-s -w -X github.com/loveuer/go-alived/internal/cmd.Version=${{ steps.version.outputs.VERSION }}" \
-o dist/${BINARY_NAME} .
# Create checksum
cd dist && sha256sum ${BINARY_NAME} > ${BINARY_NAME}.sha256
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: go-alived-${{ matrix.os }}-${{ matrix.arch }}
path: dist/
release:
name: Create Release
needs: build
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Prepare release files
run: |
mkdir -p release
find artifacts -type f -exec cp {} release/ \;
ls -la release/
- name: Get version
id: version
run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
- name: Create Release
uses: softprops/action-gh-release@v1
with:
name: Release ${{ steps.version.outputs.VERSION }}
draft: false
prerelease: ${{ contains(github.ref, '-rc') || contains(github.ref, '-beta') || contains(github.ref, '-alpha') }}
generate_release_notes: true
files: release/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-1
View File
@@ -4,4 +4,3 @@
dist dist
x-* x-*
go-alived
+154 -263
View File
@@ -1,36 +1,40 @@
# go-alived # go-alived
A lightweight VRRP (Virtual Router Redundancy Protocol) implementation in Go, designed as a simple alternative to keepalived. A lightweight, dependency-free VRRP (Virtual Router Redundancy Protocol) implementation in Go, designed as a simple alternative to keepalived.
## Features ## Features
- **VRRP Protocol**: RFC 3768/5798 compliant implementation **Phase 1: Core VRRP Functionality (Completed)**
- **High Availability**: Automatic failover with priority-based master election - VRRP protocol implementation (RFC 3768/5798)
- **Health Checking**: TCP, HTTP/HTTPS, ICMP ping, and script-based checks - Virtual IP management (add/remove VIPs)
- **Unicast Support**: Direct peer communication for restricted network environments (macvlan, cloud) - State machine (INIT/BACKUP/MASTER/FAULT)
- **Easy Deployment**: Built-in install command with systemd/init.d support - Priority-based master election
- **Hot Reload**: Configuration reload via SIGHUP without service restart - Gratuitous ARP for network updates
- **Zero Dependencies**: Single static binary, no runtime dependencies - Raw socket VRRP packet send/receive
- Timer management (advertisement & master-down timers)
- VRRP instance manager with multi-instance support
- Configuration hot-reload (SIGHUP)
**Phase 2: Health Checking (Completed)**
- Health checker interface with rise/fall logic
- TCP health checks
- HTTP/HTTPS health checks
- ICMP ping checks
- Script-based checks (custom commands)
- Periodic health check scheduling
- Health check integration with VRRP priority
- Track scripts: automatic priority adjustment on health changes
🚧 **Phase 3: Enhanced Features (Planned)**
- State transition scripts (notify_master/backup/fault)
- Email/Webhook notifications
- Sync groups
- Virtual MAC support
- Metrics export
## Installation ## Installation
### Download Binary ### Build from source
Download the latest release from [GitHub Releases](https://github.com/loveuer/go-alived/releases):
```bash
# Linux amd64
curl -LO https://github.com/loveuer/go-alived/releases/latest/download/go-alived-linux-amd64
chmod +x go-alived-linux-amd64
sudo mv go-alived-linux-amd64 /usr/local/bin/go-alived
# Linux arm64
curl -LO https://github.com/loveuer/go-alived/releases/latest/download/go-alived-linux-arm64
chmod +x go-alived-linux-arm64
sudo mv go-alived-linux-arm64 /usr/local/bin/go-alived
```
### Build from Source
```bash ```bash
git clone https://github.com/loveuer/go-alived.git git clone https://github.com/loveuer/go-alived.git
@@ -38,303 +42,190 @@ cd go-alived
go build -o go-alived . go build -o go-alived .
``` ```
### Quick Install (Recommended)
```bash
# Install as systemd service (default)
sudo ./go-alived install
# Install as init.d service (for OpenWrt/older systems)
sudo ./go-alived install --method service
```
## Quick Start ## Quick Start
### 1. Test Environment ### 1. Test Your Environment
Before deployment, test if your environment supports VRRP:
```bash ```bash
# Check if your environment supports VRRP # Basic test (auto-detect network interface)
sudo go-alived test sudo ./go-alived test
# Test with specific interface # Test specific interface
sudo go-alived test -i eth0 sudo ./go-alived test -i eth0
# Full test with VIP
sudo ./go-alived test -i eth0 -v 192.168.1.100/24
``` ```
### 2. Configure ### 2. Run the Service
Edit `/etc/go-alived/config.yaml`:
```yaml
global:
router_id: "node1"
vrrp_instances:
- name: "VI_1"
interface: "eth0" # Network interface
state: "BACKUP" # Initial state
virtual_router_id: 51 # VRID (1-255, must match on all nodes)
priority: 100 # Higher = more likely to be master
advert_interval: 1 # Advertisement interval in seconds
auth_type: "PASS" # Authentication type
auth_pass: "secret" # Password (max 8 chars)
virtual_ips:
- "192.168.1.100/24" # Virtual IP address(es)
```
### 3. Start Service
```bash ```bash
# Systemd # Run with minimal config
sudo systemctl daemon-reload sudo ./go-alived run -c config.mini.yaml -d
sudo systemctl enable go-alived
# Run with full config
sudo ./go-alived -c config.yaml
# Install as systemd service
sudo ./deployment/install.sh
sudo systemctl start go-alived sudo systemctl start go-alived
# Init.d
sudo /etc/init.d/go-alived start
``` ```
### 4. Verify ## Usage
```bash ### Commands
# Check service status
sudo systemctl status go-alived
# Check VIP
ip addr show eth0 | grep 192.168.1.100
# View logs
sudo journalctl -u go-alived -f
``` ```
go-alived # Run VRRP service (default)
go-alived run # Run VRRP service
go-alived test # Test environment for VRRP support
go-alived --help # Show help
go-alived --version # Show version
```
### Global Flags
```
-c, --config string Path to configuration file (default "/etc/go-alived/config.yaml")
-d, --debug Enable debug mode
-h, --help Show help
-v, --version Show version
```
### Test Command Flags
```
-i, --interface string Network interface to test (auto-detect if not specified)
-v, --vip string Test VIP address (e.g., 192.168.1.100/24)
```
See [USAGE.md](USAGE.md) for detailed usage documentation.
## Configuration ## Configuration
### Two-Node HA Setup Example ### Minimal Configuration
**Node 1 (Primary)**:
```yaml ```yaml
# config.mini.yaml - VRRP only
global: global:
router_id: "node1" router_id: "node1"
vrrp_instances:
- name: "VI_1"
interface: "eth0"
state: "MASTER"
virtual_router_id: 51
priority: 100 # Higher priority
advert_interval: 1
auth_type: "PASS"
auth_pass: "secret"
virtual_ips:
- "192.168.1.100/24"
```
**Node 2 (Backup)**:
```yaml
global:
router_id: "node2"
vrrp_instances: vrrp_instances:
- name: "VI_1" - name: "VI_1"
interface: "eth0" interface: "eth0"
state: "BACKUP" state: "BACKUP"
virtual_router_id: 51 virtual_router_id: 51
priority: 90 # Lower priority
advert_interval: 1
auth_type: "PASS"
auth_pass: "secret" # Must match
virtual_ips:
- "192.168.1.100/24" # Must match
```
### Unicast Configuration (for macvlan / cloud environments)
In environments where multicast is not available (macvlan networks, public clouds, etc.), use unicast to send VRRP advertisements directly to peer IPs:
**Node 1 (MASTER)**:
```yaml
global:
router_id: "node1"
vrrp_instances:
- name: "VI_1"
interface: "eth0"
state: "MASTER"
virtual_router_id: 51
priority: 100 priority: 100
advert_interval: 1 advert_interval: 1
auth_type: "PASS" auth_type: "PASS"
auth_pass: "secret123" auth_pass: "secret123"
virtual_ips: virtual_ips:
- "192.168.1.100/24" - "192.168.1.100/24"
unicast_src_ip: "192.168.1.10"
unicast_peers:
- "192.168.1.11"
``` ```
**Node 2 (BACKUP)**: ### Full Configuration Example
```yaml
global:
router_id: "node2"
vrrp_instances: See `config.example.yaml` for complete configuration with health checking.
- name: "VI_1"
interface: "eth0"
state: "BACKUP"
virtual_router_id: 51
priority: 50
advert_interval: 1
auth_type: "PASS"
auth_pass: "secret123"
virtual_ips:
- "192.168.1.100/24"
unicast_src_ip: "192.168.1.11"
unicast_peers:
- "192.168.1.10"
```
See `etc/config.unicast.yaml` for a complete unicast example. ### Signals
### Health Checking - `SIGHUP`: Reload configuration
- `SIGINT/SIGTERM`: Graceful shutdown
```yaml ## Architecture
vrrp_instances:
- name: "VI_1"
# ... other settings ...
track_scripts:
- "check_nginx" # Reference to health checker
health_checkers:
- name: "check_nginx"
type: "tcp"
interval: 3s
timeout: 2s
rise: 3 # Successes to mark healthy
fall: 2 # Failures to mark unhealthy
config:
host: "127.0.0.1"
port: 80
```
**Supported Health Check Types**:
| Type | Description | Config |
|------|-------------|--------|
| `tcp` | TCP port check | `host`, `port` |
| `http` | HTTP endpoint check | `url`, `method`, `expected_status` |
| `ping` | ICMP ping check | `host`, `count` |
| `script` | Custom script | `script`, `args` |
## Commands
``` ```
go-alived [command] go-alived/
├── main.go # Application entry point
Available Commands: ├── internal/
run Run the VRRP service │ ├── cmd/ # Cobra commands
test Test environment for VRRP support │ │ ├── root.go # Root command
install Install go-alived as a system service (alias: i) │ │ ├── run.go # Run service command
help Help about any command │ │ └── test.go # Environment test command
│ ├── vrrp/ # VRRP implementation
Flags: │ │ ├── packet.go # VRRP packet structure & marshaling
-h, --help help for go-alived │ │ ├── socket.go # Raw socket operations
-v, --version version for go-alived │ │ ├── state.go # State machine & timers
``` │ │ ├── arp.go # Gratuitous ARP
│ │ ├── instance.go # VRRP instance logic
### run │ │ └── manager.go # Instance manager
│ └── health/ # Health check system
```bash │ ├── checker.go # Checker interface & state
go-alived run [flags] │ ├── monitor.go # Health check scheduler
│ ├── tcp.go # TCP health checker
Flags: │ ├── http.go # HTTP/HTTPS health checker
-c, --config string Path to config file (default "/etc/go-alived/config.yaml") │ ├── ping.go # ICMP ping checker
-d, --debug Enable debug mode │ ├── script.go # Script checker
``` │ └── factory.go # Checker factory
├── pkg/
### test │ ├── config/ # Configuration loading & validation
│ ├── logger/ # Logging system
```bash │ └── netif/ # Network interface management
go-alived test [flags] └── deployment/ # Deployment files
├── go-alived.service # Systemd service file
Flags: ├── install.sh # Installation script
-i, --interface string Network interface to test ├── uninstall.sh # Uninstallation script
-v, --vip string Test VIP address (e.g., 192.168.1.100/24) ├── check-env.sh # Environment check script
``` ├── README.md # Deployment documentation
└── COMPATIBILITY.md # Environment compatibility guide
### install
```bash
go-alived install [flags]
Flags:
-m, --method string Installation method: systemd, service (default "systemd")
Aliases:
install, i
```
## Signals
| Signal | Action |
|--------|--------|
| `SIGHUP` | Reload configuration |
| `SIGINT` / `SIGTERM` | Graceful shutdown |
```bash
# Reload configuration
sudo kill -HUP $(pgrep go-alived)
``` ```
## Environment Compatibility ## Environment Compatibility
| Environment | Support | Notes | ### ✅ Fully Supported
|-------------|---------|-------| - Physical servers
| Physical servers | Full | | - KVM/QEMU virtual machines
| KVM/QEMU/Proxmox | Full | | - Proxmox VE
| VMware ESXi | Full | Enable promiscuous mode | - VMware ESXi (with promiscuous mode)
| VirtualBox | Full | Bridged network + promiscuous mode | - VirtualBox (with bridged network + promiscuous mode)
| Docker | Limited | Requires `--privileged --net=host` |
| OpenWrt/iStoreOS | Full | Use `--method service` for install |
| macvlan networks | Full | Use unicast mode |
| AWS/Aliyun/Azure/GCP | Limited | Use unicast mode |
> **Note**: VRRP defaults to multicast (224.0.0.18). In environments where multicast is disabled or unavailable (public clouds, macvlan networks), use **unicast mode** by configuring `unicast_src_ip` and `unicast_peers`. ### ⚠️ Limited Support
- Private cloud (depends on network configuration)
- Docker containers (requires `--privileged` and `--net=host`)
- Kubernetes (requires hostNetwork mode)
### ❌ Not Supported
- AWS EC2 (multicast disabled)
- Aliyun ECS (multicast disabled)
- Azure VM (requires special configuration)
- Google Cloud (multicast disabled by default)
**Why?** Public clouds typically disable multicast protocols (224.0.0.18) at the network virtualization layer.
**Alternative**: Use cloud-native solutions like Elastic IP (AWS), SLB/HaVip (Aliyun), Load Balancer (Azure/GCP).
See [deployment/COMPATIBILITY.md](deployment/COMPATIBILITY.md) for detailed compatibility information.
## Requirements ## Requirements
- Go 1.21+ (for building) - Go 1.21+ (for building)
- Linux/macOS with root privileges (for raw sockets and interface management) - Linux/macOS with root privileges (for raw sockets and interface management)
- Network interface with IPv4 address - Network interface with IPv4 address
- Multicast support (default mode) **or** unicast configuration (for restricted environments) - Multicast support (for VRRP)
## Troubleshooting ## Dependencies
### Common Issues Minimal external dependencies:
- `github.com/vishvananda/netlink` - Network interface management
- `github.com/mdlayher/arp` - ARP packet handling
- `github.com/spf13/cobra` - CLI framework
- `golang.org/x/net/ipv4` - IPv4 raw socket support
- `golang.org/x/net/icmp` - ICMP ping support
- `gopkg.in/yaml.v3` - YAML configuration parsing
**1. "permission denied" or "operation not permitted"** ## Documentation
```bash
# VRRP requires root privileges
sudo go-alived run -c /etc/go-alived/config.yaml
```
**2. "authentication failed"** - [USAGE.md](USAGE.md) - Detailed usage guide
- Ensure `auth_pass` matches on all nodes - [TESTING.md](TESTING.md) - Testing guide
- Password is limited to 8 characters - [deployment/README.md](deployment/README.md) - Deployment guide
- [deployment/COMPATIBILITY.md](deployment/COMPATIBILITY.md) - Environment compatibility
- [roadmap.md](roadmap.md) - Implementation roadmap
**3. Both nodes become MASTER (split-brain)** ## Roadmap
- Check network connectivity between nodes
- Verify `virtual_router_id` matches
- In multicast mode: ensure multicast traffic is allowed
- In unicast mode: verify `unicast_peers` and `unicast_src_ip` are correct
**4. VIP not pingable after failover** See [roadmap.md](roadmap.md) for detailed implementation plan.
- Gratuitous ARP may be blocked
- Check switch/router ARP cache timeout
### Debug Mode
```bash
sudo go-alived run -c /etc/go-alived/config.yaml -d
```
## License ## License
-31
View File
@@ -1,31 +0,0 @@
global:
router_id: "node1"
vrrp_instances:
# Example: VRRP with unicast peers for macvlan environments
# In macvlan networks, multicast between sub-interfaces of the same
# parent interface does not work. Use unicast to send VRRP advertisements
# directly to peer IP addresses.
- name: "VI_1"
interface: "eth0"
state: "BACKUP"
virtual_router_id: 51
priority: 100
advert_interval: 1
auth_type: "PASS"
auth_pass: "secret123"
virtual_ips:
- "192.168.1.100/24"
# Unicast source IP: the local IP address to use for sending VRRP packets.
# If omitted, the interface's primary IPv4 address is used automatically.
unicast_src_ip: "192.168.1.10"
# Unicast peer list: IP addresses of the other VRRP nodes.
# When configured, VRRP advertisements are sent directly to these IPs
# instead of using multicast (224.0.0.18).
# On each node, list the OTHER nodes' IPs here (not your own).
unicast_peers:
- "192.168.1.11"
# Add more peers for setups with more than two nodes:
# - "192.168.1.12"
+6 -9
View File
@@ -1,23 +1,20 @@
module github.com/loveuer/go-alived module github.com/loveuer/go-alived
go 1.24.0 go 1.25.0
require (
github.com/mdlayher/arp v0.0.0-20220512170110-6706a2966875
github.com/spf13/cobra v1.10.2
github.com/vishvananda/netlink v1.3.1
golang.org/x/net v0.47.0
gopkg.in/yaml.v3 v3.0.1
)
require ( require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/josharian/native v1.0.0 // indirect github.com/josharian/native v1.0.0 // indirect
github.com/mdlayher/arp v0.0.0-20220512170110-6706a2966875 // indirect
github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118 // indirect
github.com/mdlayher/packet v1.0.0 // indirect github.com/mdlayher/packet v1.0.0 // indirect
github.com/mdlayher/socket v0.2.1 // indirect github.com/mdlayher/socket v0.2.1 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.9 // indirect github.com/spf13/pflag v1.0.9 // indirect
github.com/vishvananda/netlink v1.3.1 // indirect
github.com/vishvananda/netns v0.0.5 // indirect github.com/vishvananda/netns v0.0.5 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/sys v0.38.0 // indirect golang.org/x/sys v0.38.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
) )
+2 -2
View File
@@ -1,6 +1,5 @@
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
@@ -26,6 +25,7 @@ github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZla
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY= golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU= golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
@@ -35,12 +35,12 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-466
View File
@@ -1,466 +0,0 @@
package cmd
import (
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"github.com/spf13/cobra"
)
const (
defaultBinaryPath = "/usr/local/bin/go-alived"
defaultConfigDir = "/etc/go-alived"
defaultConfigFile = "/etc/go-alived/config.yaml"
systemdServicePath = "/etc/systemd/system/go-alived.service"
initdScriptPath = "/etc/init.d/go-alived"
)
var (
installMethod string
)
var installCmd = &cobra.Command{
Use: "install",
Aliases: []string{"i"},
Short: "Install go-alived as a system service",
Long: `Install go-alived binary and configuration files to system paths.
Supported installation methods:
- systemd: Install as a systemd service (default, recommended for modern Linux)
- service: Install as a SysV init.d service (for older Linux distributions)
Examples:
sudo go-alived install
sudo go-alived install --method systemd
sudo go-alived i -m service`,
Run: runInstall,
}
func init() {
rootCmd.AddCommand(installCmd)
installCmd.Flags().StringVarP(&installMethod, "method", "m", "systemd",
"installation method: systemd, service")
}
func runInstall(cmd *cobra.Command, args []string) {
// Check root privileges
if os.Geteuid() != 0 {
fmt.Println("Error: This command requires root privileges")
fmt.Println("Please run with: sudo go-alived install")
os.Exit(1)
}
// Validate method
method := strings.ToLower(installMethod)
if method != "systemd" && method != "service" {
fmt.Printf("Error: Invalid installation method '%s'\n", installMethod)
fmt.Println("Supported methods: systemd, service")
os.Exit(1)
}
fmt.Println("=== Go-Alived Installation ===")
fmt.Println()
const totalSteps = 3
// Step 1: Copy binary
if err := installBinary(1, totalSteps); err != nil {
fmt.Printf("Error installing binary: %v\n", err)
os.Exit(1)
}
// Step 2: Create config directory and file
configCreated, err := installConfig(2, totalSteps)
if err != nil {
fmt.Printf("Error installing config: %v\n", err)
os.Exit(1)
}
// Step 3: Install service script
if err := installServiceScript(3, totalSteps, method); err != nil {
fmt.Printf("Error installing service script: %v\n", err)
os.Exit(1)
}
// Print completion message
printCompletionMessage(method, configCreated)
}
func installBinary(step, total int) error {
fmt.Printf("[%d/%d] Installing binary... ", step, total)
// Get current executable path
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
// Resolve symlinks
execPath, err = filepath.EvalSymlinks(execPath)
if err != nil {
return fmt.Errorf("failed to resolve symlinks: %w", err)
}
// Check if already installed at target path
if execPath == defaultBinaryPath {
fmt.Println("already installed")
return nil
}
// Open source file
src, err := os.Open(execPath)
if err != nil {
return fmt.Errorf("failed to open source binary: %w", err)
}
defer src.Close()
// Create destination file
dst, err := os.OpenFile(defaultBinaryPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
if err != nil {
return fmt.Errorf("failed to create destination binary: %w", err)
}
defer dst.Close()
// Copy binary
if _, err := io.Copy(dst, src); err != nil {
return fmt.Errorf("failed to copy binary: %w", err)
}
fmt.Printf("done (%s)\n", defaultBinaryPath)
return nil
}
func installConfig(step, total int) (bool, error) {
fmt.Printf("[%d/%d] Setting up configuration... ", step, total)
// Create config directory
if err := os.MkdirAll(defaultConfigDir, 0755); err != nil {
return false, fmt.Errorf("failed to create config directory: %w", err)
}
// Check if config file already exists
if _, err := os.Stat(defaultConfigFile); err == nil {
fmt.Println("config already exists")
return false, nil
}
// Generate config content
configContent := generateDefaultConfig()
// Write config file
if err := os.WriteFile(defaultConfigFile, []byte(configContent), 0644); err != nil {
return false, fmt.Errorf("failed to write config file: %w", err)
}
fmt.Printf("done (%s)\n", defaultConfigFile)
return true, nil
}
func installServiceScript(step, total int, method string) error {
switch method {
case "systemd":
return installSystemdService(step, total)
case "service":
return installInitdScript(step, total)
default:
return fmt.Errorf("unsupported method: %s", method)
}
}
func installSystemdService(step, total int) error {
fmt.Printf("[%d/%d] Installing systemd service... ", step, total)
serviceContent := generateSystemdService()
if err := os.WriteFile(systemdServicePath, []byte(serviceContent), 0644); err != nil {
return fmt.Errorf("failed to write service file: %w", err)
}
fmt.Printf("done (%s)\n", systemdServicePath)
return nil
}
func installInitdScript(step, total int) error {
fmt.Printf("[%d/%d] Installing init.d script... ", step, total)
scriptContent := generateInitdScript()
if err := os.WriteFile(initdScriptPath, []byte(scriptContent), 0755); err != nil {
return fmt.Errorf("failed to write init.d script: %w", err)
}
fmt.Printf("done (%s)\n", initdScriptPath)
return nil
}
func generateDefaultConfig() string {
// Auto-detect network interface
iface := detectNetworkInterface()
hostname, _ := os.Hostname()
if hostname == "" {
hostname = "node1"
}
return fmt.Sprintf(`# Go-Alived Configuration
# Generated by: go-alived install
# Documentation: https://github.com/loveuer/go-alived
global:
router_id: "%s"
vrrp_instances:
- name: "VI_1"
interface: "%s"
state: "BACKUP"
virtual_router_id: 51
priority: 100
advert_interval: 1
auth_type: "PASS"
auth_pass: "changeme" # TODO: Change this password
virtual_ips:
- "192.168.1.100/24" # TODO: Change to your VIP
# Optional: Health checkers
# health_checkers:
# - name: "check_nginx"
# type: "tcp"
# interval: 3s
# timeout: 2s
# rise: 3
# fall: 2
# config:
# host: "127.0.0.1"
# port: 80
`, hostname, iface)
}
func generateSystemdService() string {
return `[Unit]
Description=Go-Alived - VRRP High Availability Service
Documentation=https://github.com/loveuer/go-alived
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
Group=root
ExecStart=/usr/local/bin/go-alived run --config /etc/go-alived/config.yaml
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=go-alived
# Security settings
NoNewPrivileges=false
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/etc/go-alived
# Resource limits
LimitNOFILE=65535
LimitNPROC=512
# Capabilities required for VRRP operations
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
`
}
func generateInitdScript() string {
return `#!/bin/sh
### BEGIN INIT INFO
# Provides: go-alived
# Required-Start: $network $remote_fs $syslog
# Required-Stop: $network $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Go-Alived VRRP High Availability Service
# Description: Lightweight VRRP implementation for IP high availability
### END INIT INFO
NAME="go-alived"
DAEMON="/usr/local/bin/go-alived"
DAEMON_ARGS="run --config /etc/go-alived/config.yaml"
PIDFILE="/var/run/${NAME}.pid"
LOGFILE="/var/log/${NAME}.log"
[ -x "$DAEMON" ] || exit 5
start() {
if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
echo "$NAME is already running"
return 1
fi
echo -n "Starting $NAME... "
nohup $DAEMON $DAEMON_ARGS >> "$LOGFILE" 2>&1 &
echo $! > "$PIDFILE"
echo "done (PID: $(cat "$PIDFILE"))"
}
stop() {
if [ ! -f "$PIDFILE" ] || ! kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
echo "$NAME is not running"
return 1
fi
echo -n "Stopping $NAME... "
kill "$(cat "$PIDFILE")"
rm -f "$PIDFILE"
echo "done"
}
restart() {
stop
sleep 1
start
}
reload() {
if [ ! -f "$PIDFILE" ] || ! kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
echo "$NAME is not running"
return 1
fi
echo -n "Reloading $NAME configuration... "
kill -HUP "$(cat "$PIDFILE")"
echo "done"
}
status() {
if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
echo "$NAME is running (PID: $(cat "$PIDFILE"))"
else
echo "$NAME is not running"
[ -f "$PIDFILE" ] && rm -f "$PIDFILE"
return 1
fi
}
case "$1" in
start) start ;;
stop) stop ;;
restart) restart ;;
reload) reload ;;
status) status ;;
*)
echo "Usage: $0 {start|stop|restart|reload|status}"
exit 2
;;
esac
exit $?
`
}
func detectNetworkInterface() string {
interfaces, err := net.Interfaces()
if err != nil {
return "eth0"
}
for _, iface := range interfaces {
// Skip loopback and down interfaces
if iface.Flags&net.FlagLoopback != 0 {
continue
}
if iface.Flags&net.FlagUp == 0 {
continue
}
// Check if interface has IPv4 address
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok {
if ipv4 := ipNet.IP.To4(); ipv4 != nil && !ipv4.IsLoopback() {
return iface.Name
}
}
}
}
return "eth0"
}
func printCompletionMessage(method string, configCreated bool) {
fmt.Println()
fmt.Println("=== Installation Complete ===")
fmt.Println()
// Installed files summary
fmt.Println(">>> Installed Files:")
fmt.Printf(" Binary: %s\n", defaultBinaryPath)
fmt.Printf(" Config: %s\n", defaultConfigFile)
if method == "systemd" {
fmt.Printf(" Service: %s\n", systemdServicePath)
} else {
fmt.Printf(" Service: %s\n", initdScriptPath)
}
fmt.Println()
// What needs to be modified
fmt.Println(">>> Configuration Required:")
fmt.Printf(" Edit: %s\n", defaultConfigFile)
fmt.Println()
if configCreated {
fmt.Println(" Modify the following settings:")
fmt.Println(" - auth_pass: Change 'changeme' to a secure password")
fmt.Println(" - virtual_ips: Set your Virtual IP address(es)")
fmt.Println(" - interface: Verify the network interface is correct")
fmt.Println(" - priority: Adjust based on node role (higher = more likely master)")
} else {
fmt.Println(" Review your existing configuration")
}
fmt.Println()
// How to start
fmt.Println(">>> Next Steps:")
if method == "systemd" {
fmt.Println(" 1. Edit configuration:")
fmt.Printf(" sudo vim %s\n", defaultConfigFile)
fmt.Println()
fmt.Println(" 2. Reload systemd and start service:")
fmt.Println(" sudo systemctl daemon-reload")
fmt.Println(" sudo systemctl enable go-alived")
fmt.Println(" sudo systemctl start go-alived")
fmt.Println()
fmt.Println(" 3. Check service status:")
fmt.Println(" sudo systemctl status go-alived")
fmt.Println(" sudo journalctl -u go-alived -f")
} else {
fmt.Println(" 1. Edit configuration:")
fmt.Printf(" sudo vim %s\n", defaultConfigFile)
fmt.Println()
fmt.Println(" 2. Start service:")
fmt.Printf(" sudo %s start\n", initdScriptPath)
fmt.Println()
fmt.Println(" 3. Enable on boot (Debian/Ubuntu):")
fmt.Println(" sudo update-rc.d go-alived defaults")
fmt.Println()
fmt.Println(" 4. Check service status:")
fmt.Printf(" sudo %s status\n", initdScriptPath)
fmt.Printf(" tail -f /var/log/go-alived.log\n")
}
fmt.Println()
// Test environment
fmt.Println(">>> Test Environment (Optional):")
fmt.Printf(" sudo %s test\n", defaultBinaryPath)
fmt.Println()
}
+1 -4
View File
@@ -6,14 +6,12 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// Version can be set at build time via ldflags
var Version = "1.3.0"
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: "go-alived", Use: "go-alived",
Short: "Go-Alived - VRRP High Availability Service", Short: "Go-Alived - VRRP High Availability Service",
Long: `go-alived is a lightweight, dependency-free VRRP implementation in Go. Long: `go-alived is a lightweight, dependency-free VRRP implementation in Go.
It provides high availability for IP addresses with health checking support.`, It provides high availability for IP addresses with health checking support.`,
Version: "1.0.0",
} }
func Execute() { func Execute() {
@@ -23,6 +21,5 @@ func Execute() {
} }
func init() { func init() {
rootCmd.Version = Version
rootCmd.CompletionOptions.DisableDefaultCmd = true rootCmd.CompletionOptions.DisableDefaultCmd = true
} }
-22
View File
@@ -58,7 +58,6 @@ func runService(cmd *cobra.Command, args []string) {
os.Exit(1) os.Exit(1)
} }
setupNotifyScripts(vrrpMgr, cfg, log)
setupHealthTracking(vrrpMgr, healthMgr, log) setupHealthTracking(vrrpMgr, healthMgr, log)
healthMgr.StartAll() healthMgr.StartAll()
@@ -101,27 +100,6 @@ func cleanup(log *logger.Logger, vrrpMgr *vrrp.Manager, healthMgr *health.Manage
vrrpMgr.StopAll() vrrpMgr.StopAll()
} }
func setupNotifyScripts(vrrpMgr *vrrp.Manager, cfg *config.Config, log *logger.Logger) {
for _, vrrpCfg := range cfg.VRRP {
if vrrpCfg.NotifyMaster == "" && vrrpCfg.NotifyBackup == "" && vrrpCfg.NotifyFault == "" {
continue
}
inst, ok := vrrpMgr.GetInstance(vrrpCfg.Name)
if !ok {
continue
}
vrrp.SetupNotify(inst, &vrrp.NotifyConfig{
Name: vrrpCfg.Name,
NotifyMaster: vrrpCfg.NotifyMaster,
NotifyBackup: vrrpCfg.NotifyBackup,
NotifyFault: vrrpCfg.NotifyFault,
Log: log,
})
}
}
func setupHealthTracking(vrrpMgr *vrrp.Manager, healthMgr *health.Manager, log *logger.Logger) { func setupHealthTracking(vrrpMgr *vrrp.Manager, healthMgr *health.Manager, log *logger.Logger) {
instances := vrrpMgr.GetAllInstances() instances := vrrpMgr.GetAllInstances()
+1 -1
View File
@@ -367,7 +367,7 @@ func (t *EnvironmentTest) TestCloudEnvironment() {
if err == nil { if err == nil {
cloudDetected = true cloudDetected = true
t.AddResult("云环境", !test.isFatal, fmt.Sprintf("检测到%s环境", test.name), test.isFatal) t.AddResult("云环境", !test.isFatal, fmt.Sprintf("检测到%s环境", test.name), test.isFatal)
t.log.Warn("%s", test.solution) t.log.Warn(test.solution)
} }
} }
+2 -7
View File
@@ -8,13 +8,9 @@ import (
) )
func CreateChecker(cfg *config.HealthChecker) (Checker, error) { func CreateChecker(cfg *config.HealthChecker) (Checker, error) {
if cfg.Config == nil {
return nil, fmt.Errorf("missing config for checker %s", cfg.Name)
}
configMap, ok := cfg.Config.(map[string]interface{}) configMap, ok := cfg.Config.(map[string]interface{})
if !ok { if !ok {
return nil, fmt.Errorf("invalid config type for checker %s: expected map[string]interface{}", cfg.Name) return nil, fmt.Errorf("invalid config for checker %s", cfg.Name)
} }
switch cfg.Type { switch cfg.Type {
@@ -40,7 +36,6 @@ func LoadFromConfig(cfg *config.Config, log *logger.Logger) (*Manager, error) {
return nil, fmt.Errorf("failed to create checker %s: %w", healthCfg.Name, err) return nil, fmt.Errorf("failed to create checker %s: %w", healthCfg.Name, err)
} }
configMap, _ := healthCfg.Config.(map[string]interface{})
monitorCfg := &CheckerConfig{ monitorCfg := &CheckerConfig{
Name: healthCfg.Name, Name: healthCfg.Name,
Type: healthCfg.Type, Type: healthCfg.Type,
@@ -48,7 +43,7 @@ func LoadFromConfig(cfg *config.Config, log *logger.Logger) (*Manager, error) {
Timeout: healthCfg.Timeout, Timeout: healthCfg.Timeout,
Rise: healthCfg.Rise, Rise: healthCfg.Rise,
Fall: healthCfg.Fall, Fall: healthCfg.Fall,
Config: configMap, Config: healthCfg.Config.(map[string]interface{}),
} }
monitor := NewMonitor(checker, monitorCfg, log) monitor := NewMonitor(checker, monitorCfg, log)
-74
View File
@@ -1,74 +0,0 @@
package health
import (
"sync"
"github.com/loveuer/go-alived/pkg/logger"
)
// Manager manages multiple health check monitors.
type Manager struct {
monitors map[string]*Monitor
mu sync.RWMutex
log *logger.Logger
}
// NewManager creates a new health check Manager.
func NewManager(log *logger.Logger) *Manager {
return &Manager{
monitors: make(map[string]*Monitor),
log: log,
}
}
// AddMonitor adds a monitor to the manager.
func (m *Manager) AddMonitor(monitor *Monitor) {
m.mu.Lock()
defer m.mu.Unlock()
m.monitors[monitor.config.Name] = monitor
}
// GetMonitor retrieves a monitor by name.
func (m *Manager) GetMonitor(name string) (*Monitor, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
monitor, ok := m.monitors[name]
return monitor, ok
}
// StartAll starts all registered monitors.
func (m *Manager) StartAll() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, monitor := range m.monitors {
monitor.Start()
}
m.log.Info("started %d health check monitor(s)", len(m.monitors))
}
// StopAll stops all registered monitors.
func (m *Manager) StopAll() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, monitor := range m.monitors {
monitor.Stop()
}
m.log.Info("stopped all health check monitors")
}
// GetAllStates returns the current state of all monitors.
func (m *Manager) GetAllStates() map[string]*CheckerState {
m.mu.RLock()
defer m.mu.RUnlock()
states := make(map[string]*CheckerState)
for name, monitor := range m.monitors {
states[name] = monitor.GetState()
}
return states
}
+61 -10
View File
@@ -8,7 +8,6 @@ import (
"github.com/loveuer/go-alived/pkg/logger" "github.com/loveuer/go-alived/pkg/logger"
) )
// Monitor runs periodic health checks and tracks state.
type Monitor struct { type Monitor struct {
checker Checker checker Checker
config *CheckerConfig config *CheckerConfig
@@ -22,7 +21,6 @@ type Monitor struct {
mu sync.RWMutex mu sync.RWMutex
} }
// NewMonitor creates a new Monitor for the given checker.
func NewMonitor(checker Checker, config *CheckerConfig, log *logger.Logger) *Monitor { func NewMonitor(checker Checker, config *CheckerConfig, log *logger.Logger) *Monitor {
return &Monitor{ return &Monitor{
checker: checker, checker: checker,
@@ -37,7 +35,6 @@ func NewMonitor(checker Checker, config *CheckerConfig, log *logger.Logger) *Mon
} }
} }
// Start begins the health check loop.
func (m *Monitor) Start() { func (m *Monitor) Start() {
m.mu.Lock() m.mu.Lock()
if m.running { if m.running {
@@ -54,7 +51,6 @@ func (m *Monitor) Start() {
go m.checkLoop() go m.checkLoop()
} }
// Stop stops the health check loop.
func (m *Monitor) Stop() { func (m *Monitor) Stop() {
m.mu.Lock() m.mu.Lock()
if !m.running { if !m.running {
@@ -75,7 +71,6 @@ func (m *Monitor) checkLoop() {
ticker := time.NewTicker(m.config.Interval) ticker := time.NewTicker(m.config.Interval)
defer ticker.Stop() defer ticker.Stop()
// Perform initial check immediately
m.performCheck() m.performCheck()
for { for {
@@ -100,8 +95,7 @@ func (m *Monitor) performCheck() {
oldHealthy := m.state.Healthy oldHealthy := m.state.Healthy
stateChanged := m.state.Update(result, m.config.Rise, m.config.Fall) stateChanged := m.state.Update(result, m.config.Rise, m.config.Fall)
newHealthy := m.state.Healthy newHealthy := m.state.Healthy
callbacks := make([]StateChangeCallback, len(m.callbacks)) callbacks := m.callbacks
copy(callbacks, m.callbacks)
m.mu.Unlock() m.mu.Unlock()
m.log.Debug("[HealthCheck:%s] check completed: result=%s, duration=%s, healthy=%v", m.log.Debug("[HealthCheck:%s] check completed: result=%s, duration=%s, healthy=%v",
@@ -117,14 +111,12 @@ func (m *Monitor) performCheck() {
} }
} }
// OnStateChange registers a callback for health state changes.
func (m *Monitor) OnStateChange(callback StateChangeCallback) { func (m *Monitor) OnStateChange(callback StateChangeCallback) {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
m.callbacks = append(m.callbacks, callback) m.callbacks = append(m.callbacks, callback)
} }
// GetState returns a copy of the current checker state.
func (m *Monitor) GetState() *CheckerState { func (m *Monitor) GetState() *CheckerState {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
@@ -133,9 +125,68 @@ func (m *Monitor) GetState() *CheckerState {
return &stateCopy return &stateCopy
} }
// IsHealthy returns whether the checker is currently healthy.
func (m *Monitor) IsHealthy() bool { func (m *Monitor) IsHealthy() bool {
m.mu.RLock() m.mu.RLock()
defer m.mu.RUnlock() defer m.mu.RUnlock()
return m.state.Healthy return m.state.Healthy
} }
type Manager struct {
monitors map[string]*Monitor
mu sync.RWMutex
log *logger.Logger
}
func NewManager(log *logger.Logger) *Manager {
return &Manager{
monitors: make(map[string]*Monitor),
log: log,
}
}
func (m *Manager) AddMonitor(monitor *Monitor) {
m.mu.Lock()
defer m.mu.Unlock()
m.monitors[monitor.config.Name] = monitor
}
func (m *Manager) GetMonitor(name string) (*Monitor, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
monitor, ok := m.monitors[name]
return monitor, ok
}
func (m *Manager) StartAll() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, monitor := range m.monitors {
monitor.Start()
}
m.log.Info("started %d health check monitor(s)", len(m.monitors))
}
func (m *Manager) StopAll() {
m.mu.RLock()
defer m.mu.RUnlock()
for _, monitor := range m.monitors {
monitor.Stop()
}
m.log.Info("stopped all health check monitors")
}
func (m *Manager) GetAllStates() map[string]*CheckerState {
m.mu.RLock()
defer m.mu.RUnlock()
states := make(map[string]*CheckerState)
for name, monitor := range m.monitors {
states[name] = monitor.GetState()
}
return states
}
-95
View File
@@ -1,95 +0,0 @@
package vrrp
import (
"fmt"
"sync"
"time"
)
// StateTransition represents a single state transition event.
type StateTransition struct {
From State
To State
Timestamp time.Time
Reason string
}
// StateHistory maintains a bounded history of state transitions.
type StateHistory struct {
transitions []StateTransition
maxSize int
mu sync.RWMutex
}
// NewStateHistory creates a new StateHistory with the specified maximum size.
func NewStateHistory(maxSize int) *StateHistory {
return &StateHistory{
transitions: make([]StateTransition, 0, maxSize),
maxSize: maxSize,
}
}
// Add records a new state transition.
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)
// Maintain bounded size using ring buffer style
if len(sh.transitions) > sh.maxSize {
// Copy to new slice to allow garbage collection of old backing array
newTransitions := make([]StateTransition, len(sh.transitions)-1, sh.maxSize)
copy(newTransitions, sh.transitions[1:])
sh.transitions = newTransitions
}
}
// GetRecent returns the most recent n transitions.
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
}
// Len returns the number of recorded transitions.
func (sh *StateHistory) Len() int {
sh.mu.RLock()
defer sh.mu.RUnlock()
return len(sh.transitions)
}
// String returns a formatted string representation of the history.
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
}
+16 -92
View File
@@ -17,12 +17,9 @@ type Instance struct {
AdvertInterval uint8 AdvertInterval uint8
Interface string Interface string
VirtualIPs []net.IP VirtualIPs []net.IP
VirtualIPCIDRs []string // preserve original CIDR notation
AuthType uint8 AuthType uint8
AuthPass string AuthPass string
TrackScripts []string TrackScripts []string
UnicastSrcIP net.IP
UnicastPeers []net.IP
state *StateMachine state *StateMachine
priorityCalc *PriorityCalculator priorityCalc *PriorityCalculator
@@ -56,8 +53,6 @@ func NewInstance(
authType string, authType string,
authPass string, authPass string,
trackScripts []string, trackScripts []string,
unicastSrcIP string,
unicastPeers []string,
log *logger.Logger, log *logger.Logger,
) (*Instance, error) { ) (*Instance, error) {
if vrID < 1 || vrID > 255 { if vrID < 1 || vrID > 255 {
@@ -69,14 +64,12 @@ func NewInstance(
} }
virtualIPs := make([]net.IP, 0, len(vips)) virtualIPs := make([]net.IP, 0, len(vips))
virtualIPCIDRs := make([]string, 0, len(vips))
for _, vip := range vips { for _, vip := range vips {
ip, _, err := net.ParseCIDR(vip) ip, _, err := net.ParseCIDR(vip)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid VIP %s: %w", vip, err) return nil, fmt.Errorf("invalid VIP %s: %w", vip, err)
} }
virtualIPs = append(virtualIPs, ip) virtualIPs = append(virtualIPs, ip)
virtualIPCIDRs = append(virtualIPCIDRs, vip)
} }
var authTypeNum uint8 var authTypeNum uint8
@@ -94,28 +87,6 @@ func NewInstance(
return nil, fmt.Errorf("failed to get interface: %w", err) return nil, fmt.Errorf("failed to get interface: %w", err)
} }
var parsedSrcIP net.IP
var parsedPeers []net.IP
if len(unicastPeers) > 0 {
parsedPeers = make([]net.IP, 0, len(unicastPeers))
for _, peer := range unicastPeers {
ip := net.ParseIP(peer)
if ip == nil {
return nil, fmt.Errorf("invalid unicast peer IP: %s", peer)
}
parsedPeers = append(parsedPeers, ip.To4())
}
if unicastSrcIP != "" {
parsedSrcIP = net.ParseIP(unicastSrcIP)
if parsedSrcIP == nil {
return nil, fmt.Errorf("invalid unicast src IP: %s", unicastSrcIP)
}
parsedSrcIP = parsedSrcIP.To4()
}
}
inst := &Instance{ inst := &Instance{
Name: name, Name: name,
VirtualRouterID: vrID, VirtualRouterID: vrID,
@@ -123,12 +94,9 @@ func NewInstance(
AdvertInterval: advertInt, AdvertInterval: advertInt,
Interface: iface, Interface: iface,
VirtualIPs: virtualIPs, VirtualIPs: virtualIPs,
VirtualIPCIDRs: virtualIPCIDRs,
AuthType: authTypeNum, AuthType: authTypeNum,
AuthPass: authPass, AuthPass: authPass,
TrackScripts: trackScripts, TrackScripts: trackScripts,
UnicastSrcIP: parsedSrcIP,
UnicastPeers: parsedPeers,
state: NewStateMachine(StateInit), state: NewStateMachine(StateInit),
priorityCalc: NewPriorityCalculator(priority), priorityCalc: NewPriorityCalculator(priority),
history: NewStateHistory(100), history: NewStateHistory(100),
@@ -159,15 +127,7 @@ func (inst *Instance) Start() error {
inst.mu.Unlock() inst.mu.Unlock()
var err error var err error
if len(inst.UnicastPeers) > 0 { inst.socket, err = NewSocket(inst.Interface)
if inst.UnicastSrcIP != nil {
inst.socket, err = NewUnicastSocket(inst.Interface, inst.UnicastSrcIP)
} else {
inst.socket, err = NewSocket(inst.Interface)
}
} else {
inst.socket, err = NewSocket(inst.Interface)
}
if err != nil { if err != nil {
return fmt.Errorf("failed to create socket: %w", err) return fmt.Errorf("failed to create socket: %w", err)
} }
@@ -178,13 +138,8 @@ func (inst *Instance) Start() error {
return fmt.Errorf("failed to create ARP sender: %w", err) return fmt.Errorf("failed to create ARP sender: %w", err)
} }
if len(inst.UnicastPeers) > 0 { inst.log.Info("[%s] starting VRRP instance (VRID=%d, Priority=%d, Interface=%s)",
inst.log.Info("[%s] starting VRRP instance (VRID=%d, Priority=%d, Interface=%s, Mode=unicast, SrcIP=%s, Peers=%v)", inst.Name, inst.VirtualRouterID, inst.Priority, inst.Interface)
inst.Name, inst.VirtualRouterID, inst.Priority, inst.Interface, inst.socket.localIP, inst.UnicastPeers)
} else {
inst.log.Info("[%s] starting VRRP instance (VRID=%d, Priority=%d, Interface=%s, Mode=multicast)",
inst.Name, inst.VirtualRouterID, inst.Priority, inst.Interface)
}
inst.state.SetState(StateBackup) inst.state.SetState(StateBackup)
inst.masterDownTimer.Start() inst.masterDownTimer.Start()
@@ -237,15 +192,8 @@ func (inst *Instance) receiveLoop() {
default: default:
} }
// Set read deadline to allow periodic check of stop channel
inst.socket.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
pkt, srcIP, err := inst.socket.Receive() pkt, srcIP, err := inst.socket.Receive()
if err != nil { if err != nil {
// Check if it's a timeout error, which is expected
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
continue
}
inst.log.Debug("[%s] failed to receive packet: %v", inst.Name, err) inst.log.Debug("[%s] failed to receive packet: %v", inst.Name, err)
continue continue
} }
@@ -254,13 +202,6 @@ func (inst *Instance) receiveLoop() {
continue continue
} }
if len(inst.UnicastPeers) > 0 {
if !inst.isUnicastPeer(srcIP) {
inst.log.Debug("[%s] ignoring packet from non-peer %s", inst.Name, srcIP)
continue
}
}
if err := pkt.Validate(inst.AuthPass); err != nil { if err := pkt.Validate(inst.AuthPass); err != nil {
inst.log.Warn("[%s] packet validation failed: %v", inst.Name, err) inst.log.Warn("[%s] packet validation failed: %v", inst.Name, err)
continue continue
@@ -270,15 +211,6 @@ func (inst *Instance) receiveLoop() {
} }
} }
func (inst *Instance) isUnicastPeer(ip net.IP) bool {
for _, peer := range inst.UnicastPeers {
if peer.Equal(ip) {
return true
}
}
return false
}
func (inst *Instance) handleAdvertisement(pkt *VRRPPacket, srcIP net.IP) { func (inst *Instance) handleAdvertisement(pkt *VRRPPacket, srcIP net.IP) {
currentState := inst.state.GetState() currentState := inst.state.GetState()
localPriority := inst.priorityCalc.GetPriority() localPriority := inst.priorityCalc.GetPriority()
@@ -329,22 +261,12 @@ func (inst *Instance) sendAdvertisement() error {
inst.AuthPass, inst.AuthPass,
) )
if len(inst.UnicastPeers) > 0 { if err := inst.socket.Send(pkt); err != nil {
for _, peer := range inst.UnicastPeers { inst.log.Error("[%s] failed to send advertisement: %v", inst.Name, err)
if err := inst.socket.SendTo(pkt, peer); err != nil { return err
inst.log.Error("[%s] failed to send unicast advertisement to %s: %v", inst.Name, peer, err)
return err
}
}
inst.log.Debug("[%s] sent unicast advertisement (priority=%d, peers=%d)", inst.Name, priority, len(inst.UnicastPeers))
} else {
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 multicast advertisement (priority=%d)", inst.Name, priority)
} }
inst.log.Debug("[%s] sent advertisement (priority=%d)", inst.Name, priority)
return nil return nil
} }
@@ -449,7 +371,11 @@ func (inst *Instance) removeVIPs() error {
} }
func (inst *Instance) getVIPsWithCIDR() []string { func (inst *Instance) getVIPsWithCIDR() []string {
return inst.VirtualIPCIDRs result := make([]string, len(inst.VirtualIPs))
for i, ip := range inst.VirtualIPs {
result[i] = ip.String() + "/32"
}
return result
} }
func (inst *Instance) GetState() State { func (inst *Instance) GetState() State {
@@ -473,17 +399,15 @@ func (inst *Instance) AdjustPriority(delta int) {
defer inst.mu.Unlock() defer inst.mu.Unlock()
oldPriority := inst.priorityCalc.GetPriority() oldPriority := inst.priorityCalc.GetPriority()
if delta < 0 { if delta < 0 {
inst.priorityCalc.DecreasePriority(uint8(-delta)) inst.priorityCalc.DecreasePriority(uint8(-delta))
} else if delta > 0 {
inst.priorityCalc.IncreasePriority(uint8(delta))
} }
newPriority := inst.priorityCalc.GetPriority() newPriority := inst.priorityCalc.GetPriority()
if oldPriority != newPriority { if oldPriority != newPriority {
inst.log.Info("[%s] priority adjusted: %d -> %d (delta=%d)", inst.log.Info("[%s] priority adjusted: %d -> %d (delta=%d)",
inst.Name, oldPriority, newPriority, delta) inst.Name, oldPriority, newPriority, delta)
} }
} }
-2
View File
@@ -36,8 +36,6 @@ func (m *Manager) LoadFromConfig(cfg *config.Config) error {
vrrpCfg.AuthType, vrrpCfg.AuthType,
vrrpCfg.AuthPass, vrrpCfg.AuthPass,
vrrpCfg.TrackScripts, vrrpCfg.TrackScripts,
vrrpCfg.UnicastSrcIP,
vrrpCfg.UnicastPeers,
m.log, m.log,
) )
if err != nil { if err != nil {
-89
View File
@@ -1,89 +0,0 @@
package vrrp
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/loveuer/go-alived/pkg/logger"
)
const notifyTimeout = 60 * time.Second
// NotifyConfig holds the notify script configuration for a VRRP instance.
type NotifyConfig struct {
Name string
NotifyMaster string
NotifyBackup string
NotifyFault string
Log *logger.Logger
}
// SetupNotify registers notify scripts as state change callbacks on the instance.
func SetupNotify(inst *Instance, cfg *NotifyConfig) {
if cfg.NotifyMaster != "" {
script := cfg.NotifyMaster
inst.OnMaster(func() {
cfg.Log.Info("[%s] executing notify_master script", cfg.Name)
go runNotifyScript(cfg.Log, cfg.Name, "notify_master", script)
})
cfg.Log.Info("[%s] registered notify_master script", cfg.Name)
}
if cfg.NotifyBackup != "" {
script := cfg.NotifyBackup
inst.OnBackup(func() {
cfg.Log.Info("[%s] executing notify_backup script", cfg.Name)
go runNotifyScript(cfg.Log, cfg.Name, "notify_backup", script)
})
cfg.Log.Info("[%s] registered notify_backup script", cfg.Name)
}
if cfg.NotifyFault != "" {
script := cfg.NotifyFault
inst.OnFault(func() {
cfg.Log.Info("[%s] executing notify_fault script", cfg.Name)
go runNotifyScript(cfg.Log, cfg.Name, "notify_fault", script)
})
cfg.Log.Info("[%s] registered notify_fault script", cfg.Name)
}
}
func runNotifyScript(log *logger.Logger, instName, event, script string) {
ctx, cancel := context.WithTimeout(context.Background(), notifyTimeout)
defer cancel()
cmd := buildCommand(ctx, script)
cmd.Env = append(os.Environ(),
fmt.Sprintf("GO_ALIVED_INSTANCE=%s", instName),
fmt.Sprintf("GO_ALIVED_EVENT=%s", event),
)
output, err := cmd.CombinedOutput()
if err != nil {
log.Error("[%s] %s script failed: %v (output: %s)",
instName, event, err, strings.TrimSpace(string(output)))
return
}
if len(output) > 0 {
log.Info("[%s] %s script output: %s",
instName, event, strings.TrimSpace(string(output)))
}
log.Info("[%s] %s script completed successfully", instName, event)
}
func buildCommand(ctx context.Context, script string) *exec.Cmd {
script = strings.TrimSpace(script)
// If the script is a path to an existing executable file, run it directly
if info, err := os.Stat(script); err == nil && !info.IsDir() {
return exec.CommandContext(ctx, script)
}
// Otherwise treat as inline shell script
return exec.CommandContext(ctx, "sh", "-c", script)
}
-99
View File
@@ -1,99 +0,0 @@
package vrrp
import (
"sync"
"time"
)
// PriorityCalculator manages VRRP priority with support for dynamic adjustment.
type PriorityCalculator struct {
basePriority uint8
currentPriority uint8
mu sync.RWMutex
}
// NewPriorityCalculator creates a new PriorityCalculator with the specified base priority.
func NewPriorityCalculator(basePriority uint8) *PriorityCalculator {
return &PriorityCalculator{
basePriority: basePriority,
currentPriority: basePriority,
}
}
// GetPriority returns the current priority.
func (pc *PriorityCalculator) GetPriority() uint8 {
pc.mu.RLock()
defer pc.mu.RUnlock()
return pc.currentPriority
}
// DecreasePriority decreases the current priority by the specified amount.
// The priority will not go below 0.
func (pc *PriorityCalculator) DecreasePriority(amount uint8) {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.currentPriority > amount {
pc.currentPriority -= amount
} else {
pc.currentPriority = 0
}
}
// IncreasePriority increases the current priority by the specified amount.
// The priority will not exceed 255 or the base priority.
func (pc *PriorityCalculator) IncreasePriority(amount uint8) {
pc.mu.Lock()
defer pc.mu.Unlock()
newPriority := pc.currentPriority + amount
if newPriority > pc.basePriority {
newPriority = pc.basePriority
}
if newPriority < pc.currentPriority { // overflow check
newPriority = pc.basePriority
}
pc.currentPriority = newPriority
}
// ResetPriority resets the priority to the base value.
func (pc *PriorityCalculator) ResetPriority() {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.currentPriority = pc.basePriority
}
// SetBasePriority sets a new base priority and resets current priority to match.
func (pc *PriorityCalculator) SetBasePriority(priority uint8) {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.basePriority = priority
pc.currentPriority = priority
}
// ShouldBecomeMaster determines if the local node should become master
// based on priority comparison and IP address tie-breaking.
func ShouldBecomeMaster(localPriority, remotePriority uint8, localIP, remoteIP string) bool {
if localPriority > remotePriority {
return true
}
if localPriority == remotePriority {
return localIP > remoteIP
}
return false
}
// CalculateMasterDownInterval calculates the master down interval
// according to VRRP specification: (3 * Advertisement_Interval).
func CalculateMasterDownInterval(advertInt uint8) time.Duration {
return time.Duration(3*int(advertInt)) * time.Second
}
// CalculateSkewTime calculates the skew time for master down timer
// according to VRRP specification: ((256 - Priority) / 256).
func CalculateSkewTime(priority uint8) time.Duration {
skew := float64(256-int(priority)) / 256.0
return time.Duration(skew * float64(time.Second))
}
+31 -110
View File
@@ -5,7 +5,6 @@ import (
"net" "net"
"os" "os"
"syscall" "syscall"
"time"
"golang.org/x/net/ipv4" "golang.org/x/net/ipv4"
) )
@@ -15,11 +14,10 @@ const (
) )
type Socket struct { type Socket struct {
conn *ipv4.RawConn conn *ipv4.RawConn
packetConn net.PacketConn iface *net.Interface
iface *net.Interface localIP net.IP
localIP net.IP groupIP net.IP
groupIP net.IP
} }
func NewSocket(ifaceName string) (*Socket, error) { func NewSocket(ifaceName string) (*Socket, error) {
@@ -47,11 +45,30 @@ func NewSocket(ifaceName string) (*Socket, error) {
return nil, fmt.Errorf("no IPv4 address found on interface %s", ifaceName) return nil, fmt.Errorf("no IPv4 address found on interface %s", ifaceName)
} }
rawConn, packetConn, err := createRawConn() fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, VRRPProtocolNumber)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create raw socket: %w", err) 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() groupIP := net.ParseIP(VRRPMulticastAddr).To4()
if groupIP == nil { if groupIP == nil {
rawConn.Close() rawConn.Close()
@@ -69,79 +86,13 @@ func NewSocket(ifaceName string) (*Socket, error) {
} }
return &Socket{ return &Socket{
conn: rawConn, conn: rawConn,
packetConn: packetConn, iface: iface,
iface: iface, localIP: localIP,
localIP: localIP, groupIP: groupIP,
groupIP: groupIP,
}, nil }, nil
} }
func NewUnicastSocket(ifaceName string, srcIP net.IP) (*Socket, error) {
iface, err := net.InterfaceByName(ifaceName)
if err != nil {
return nil, fmt.Errorf("failed to get interface %s: %w", ifaceName, err)
}
rawConn, packetConn, err := createRawConn()
if err != nil {
return nil, err
}
// Bind to the specific interface and source IP so we receive unicast VRRP packets
bindAddr := &syscall.SockaddrInet4{}
copy(bindAddr.Addr[:], srcIP.To4())
fd, _ := rawConn.SyscallConn()
var bindErr error
fd.Control(func(fd uintptr) {
bindErr = syscall.Bind(int(fd), bindAddr)
})
if bindErr != nil {
rawConn.Close()
return nil, fmt.Errorf("failed to bind to %s: %w", srcIP, bindErr)
}
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,
packetConn: packetConn,
iface: iface,
localIP: srcIP,
groupIP: nil,
}, nil
}
func createRawConn() (*ipv4.RawConn, net.PacketConn, error) {
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, VRRPProtocolNumber)
if err != nil {
return nil, 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, nil, fmt.Errorf("failed to set SO_REUSEADDR: %w", err)
}
file := os.NewFile(uintptr(fd), "vrrp-socket")
packetConn, err := net.FilePacketConn(file)
file.Close()
if err != nil {
return nil, nil, fmt.Errorf("failed to create packet connection: %w", err)
}
rawConn, err := ipv4.NewRawConn(packetConn)
if err != nil {
packetConn.Close()
return nil, nil, fmt.Errorf("failed to create raw connection: %w", err)
}
return rawConn, packetConn, nil
}
func (s *Socket) Send(pkt *VRRPPacket) error { func (s *Socket) Send(pkt *VRRPPacket) error {
data, err := pkt.Marshal() data, err := pkt.Marshal()
if err != nil { if err != nil {
@@ -166,30 +117,6 @@ func (s *Socket) Send(pkt *VRRPPacket) error {
return nil return nil
} }
func (s *Socket) SendTo(pkt *VRRPPacket, dst net.IP) 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: dst,
Src: s.localIP,
}
if err := s.conn.WriteTo(header, data, nil); err != nil {
return fmt.Errorf("failed to send packet to %s: %w", dst, err)
}
return nil
}
func (s *Socket) Receive() (*VRRPPacket, net.IP, error) { func (s *Socket) Receive() (*VRRPPacket, net.IP, error) {
buf := make([]byte, 1500) buf := make([]byte, 1500)
@@ -206,15 +133,9 @@ func (s *Socket) Receive() (*VRRPPacket, net.IP, error) {
return pkt, header.Src, nil return pkt, header.Src, nil
} }
func (s *Socket) SetReadDeadline(t time.Time) error {
return s.packetConn.SetReadDeadline(t)
}
func (s *Socket) Close() error { func (s *Socket) Close() error {
if s.groupIP != nil { if err := s.conn.LeaveGroup(s.iface, &net.IPAddr{IP: s.groupIP}); err != nil {
if err := s.conn.LeaveGroup(s.iface, &net.IPAddr{IP: s.groupIP}); err != nil { return err
return err
}
} }
return s.conn.Close() return s.conn.Close()
} }
+199 -17
View File
@@ -1,8 +1,11 @@
package vrrp package vrrp
import "sync" import (
"fmt"
"sync"
"time"
)
// State represents the VRRP instance state.
type State int type State int
const ( const (
@@ -12,7 +15,6 @@ const (
StateFault StateFault
) )
// String returns the string representation of the state.
func (s State) String() string { func (s State) String() string {
switch s { switch s {
case StateInit: case StateInit:
@@ -28,39 +30,33 @@ func (s State) String() string {
} }
} }
// StateMachine manages VRRP state transitions with thread-safe callbacks.
type StateMachine struct { type StateMachine struct {
currentState State currentState State
mu sync.RWMutex previousState State
mu sync.RWMutex
stateChangeCallbacks []func(old, new State) stateChangeCallbacks []func(old, new State)
} }
// NewStateMachine creates a new StateMachine with the specified initial state.
func NewStateMachine(initialState State) *StateMachine { func NewStateMachine(initialState State) *StateMachine {
return &StateMachine{ return &StateMachine{
currentState: initialState, currentState: initialState,
previousState: StateInit,
stateChangeCallbacks: make([]func(old, new State), 0), stateChangeCallbacks: make([]func(old, new State), 0),
} }
} }
// GetState returns the current state.
func (sm *StateMachine) GetState() State { func (sm *StateMachine) GetState() State {
sm.mu.RLock() sm.mu.RLock()
defer sm.mu.RUnlock() defer sm.mu.RUnlock()
return sm.currentState return sm.currentState
} }
// SetState transitions to a new state and triggers registered callbacks.
func (sm *StateMachine) SetState(newState State) { func (sm *StateMachine) SetState(newState State) {
sm.mu.Lock() sm.mu.Lock()
oldState := sm.currentState oldState := sm.currentState
if oldState == newState { sm.previousState = oldState
sm.mu.Unlock()
return
}
sm.currentState = newState sm.currentState = newState
callbacks := make([]func(old, new State), len(sm.stateChangeCallbacks)) callbacks := sm.stateChangeCallbacks
copy(callbacks, sm.stateChangeCallbacks)
sm.mu.Unlock() sm.mu.Unlock()
for _, callback := range callbacks { for _, callback := range callbacks {
@@ -68,9 +64,195 @@ func (sm *StateMachine) SetState(newState State) {
} }
} }
// OnStateChange registers a callback to be invoked on state changes.
func (sm *StateMachine) OnStateChange(callback func(old, new State)) { func (sm *StateMachine) OnStateChange(callback func(old, new State)) {
sm.mu.Lock() sm.mu.Lock()
defer sm.mu.Unlock() defer sm.mu.Unlock()
sm.stateChangeCallbacks = append(sm.stateChangeCallbacks, callback) 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
}
-64
View File
@@ -1,64 +0,0 @@
package vrrp
import (
"sync"
"time"
)
// Timer provides a thread-safe timer with callback support.
type Timer struct {
duration time.Duration
timer *time.Timer
callback func()
mu sync.Mutex
}
// NewTimer creates a new Timer with the specified duration and callback.
func NewTimer(duration time.Duration, callback func()) *Timer {
return &Timer{
duration: duration,
callback: callback,
}
}
// Start starts or restarts the timer.
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)
}
// Stop stops the timer if it's running.
func (t *Timer) Stop() {
t.mu.Lock()
defer t.mu.Unlock()
if t.timer != nil {
t.timer.Stop()
t.timer = nil
}
}
// Reset stops the current timer and starts a new one with the same duration.
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)
}
// SetDuration updates the timer's duration for future starts.
func (t *Timer) SetDuration(duration time.Duration) {
t.mu.Lock()
defer t.mu.Unlock()
t.duration = duration
}
-17
View File
@@ -2,7 +2,6 @@ package config
import ( import (
"fmt" "fmt"
"net"
"os" "os"
"time" "time"
@@ -34,8 +33,6 @@ type VRRPInstance struct {
NotifyBackup string `yaml:"notify_backup"` NotifyBackup string `yaml:"notify_backup"`
NotifyFault string `yaml:"notify_fault"` NotifyFault string `yaml:"notify_fault"`
TrackScripts []string `yaml:"track_scripts"` TrackScripts []string `yaml:"track_scripts"`
UnicastSrcIP string `yaml:"unicast_src_ip"`
UnicastPeers []string `yaml:"unicast_peers"`
} }
type HealthChecker struct { type HealthChecker struct {
@@ -87,20 +84,6 @@ func validate(cfg *Config) error {
if len(vrrp.VirtualIPs) == 0 { if len(vrrp.VirtualIPs) == 0 {
return fmt.Errorf("vrrp_instances[%d].virtual_ips cannot be empty", i) return fmt.Errorf("vrrp_instances[%d].virtual_ips cannot be empty", i)
} }
if len(vrrp.UnicastPeers) > 0 {
for j, peer := range vrrp.UnicastPeers {
if ip := net.ParseIP(peer); ip == nil || ip.To4() == nil {
return fmt.Errorf("vrrp_instances[%d].unicast_peers[%d] is not a valid IPv4 address: %s", i, j, peer)
}
}
}
if vrrp.UnicastSrcIP != "" {
if ip := net.ParseIP(vrrp.UnicastSrcIP); ip == nil || ip.To4() == nil {
return fmt.Errorf("vrrp_instances[%d].unicast_src_ip is not a valid IPv4 address: %s", i, vrrp.UnicastSrcIP)
}
}
} }
return nil return nil