Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3fc3c860bc | ||
|
|
22e13c9c0d | ||
|
|
4e66d187a7 |
95
.github/workflows/release.yml
vendored
Normal file
95
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
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 }}
|
||||||
373
README.md
373
README.md
@@ -1,40 +1,35 @@
|
|||||||
# go-alived
|
# go-alived
|
||||||
|
|
||||||
A lightweight, dependency-free VRRP (Virtual Router Redundancy Protocol) implementation in Go, designed as a simple alternative to keepalived.
|
A lightweight VRRP (Virtual Router Redundancy Protocol) implementation in Go, designed as a simple alternative to keepalived.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
✅ **Phase 1: Core VRRP Functionality (Completed)**
|
- **VRRP Protocol**: RFC 3768/5798 compliant implementation
|
||||||
- VRRP protocol implementation (RFC 3768/5798)
|
- **High Availability**: Automatic failover with priority-based master election
|
||||||
- Virtual IP management (add/remove VIPs)
|
- **Health Checking**: TCP, HTTP/HTTPS, ICMP ping, and script-based checks
|
||||||
- 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
|
||||||
|
|
||||||
### Build from source
|
### Download Binary
|
||||||
|
|
||||||
|
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
|
||||||
@@ -42,190 +37,246 @@ 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 Your Environment
|
### 1. Test Environment
|
||||||
|
|
||||||
Before deployment, test if your environment supports VRRP:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Basic test (auto-detect network interface)
|
# Check if your environment supports VRRP
|
||||||
sudo ./go-alived test
|
sudo go-alived test
|
||||||
|
|
||||||
# Test specific interface
|
# Test with 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. Run the Service
|
### 2. Configure
|
||||||
|
|
||||||
|
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
|
||||||
# Run with minimal config
|
# Systemd
|
||||||
sudo ./go-alived run -c config.mini.yaml -d
|
sudo systemctl daemon-reload
|
||||||
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
### 4. Verify
|
||||||
|
|
||||||
### Commands
|
```bash
|
||||||
|
# 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
|
||||||
|
|
||||||
### Minimal Configuration
|
### Two-Node HA Setup Example
|
||||||
|
|
||||||
|
**Node 1 (Primary)**:
|
||||||
```yaml
|
```yaml
|
||||||
# config.mini.yaml - VRRP only
|
|
||||||
global:
|
global:
|
||||||
router_id: "node1"
|
router_id: "node1"
|
||||||
|
|
||||||
vrrp_instances:
|
vrrp_instances:
|
||||||
- name: "VI_1"
|
- name: "VI_1"
|
||||||
interface: "eth0"
|
interface: "eth0"
|
||||||
state: "BACKUP"
|
state: "MASTER"
|
||||||
virtual_router_id: 51
|
virtual_router_id: 51
|
||||||
priority: 100
|
priority: 100 # Higher priority
|
||||||
advert_interval: 1
|
advert_interval: 1
|
||||||
auth_type: "PASS"
|
auth_type: "PASS"
|
||||||
auth_pass: "secret123"
|
auth_pass: "secret"
|
||||||
virtual_ips:
|
virtual_ips:
|
||||||
- "192.168.1.100/24"
|
- "192.168.1.100/24"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Full Configuration Example
|
**Node 2 (Backup)**:
|
||||||
|
```yaml
|
||||||
|
global:
|
||||||
|
router_id: "node2"
|
||||||
|
|
||||||
See `config.example.yaml` for complete configuration with health checking.
|
vrrp_instances:
|
||||||
|
- name: "VI_1"
|
||||||
|
interface: "eth0"
|
||||||
|
state: "BACKUP"
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
### Signals
|
### Health Checking
|
||||||
|
|
||||||
- `SIGHUP`: Reload configuration
|
```yaml
|
||||||
- `SIGINT/SIGTERM`: Graceful shutdown
|
vrrp_instances:
|
||||||
|
- name: "VI_1"
|
||||||
|
# ... other settings ...
|
||||||
|
track_scripts:
|
||||||
|
- "check_nginx" # Reference to health checker
|
||||||
|
|
||||||
## Architecture
|
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/
|
go-alived [command]
|
||||||
├── main.go # Application entry point
|
|
||||||
├── internal/
|
Available Commands:
|
||||||
│ ├── cmd/ # Cobra commands
|
run Run the VRRP service
|
||||||
│ │ ├── root.go # Root command
|
test Test environment for VRRP support
|
||||||
│ │ ├── run.go # Run service command
|
install Install go-alived as a system service (alias: i)
|
||||||
│ │ └── test.go # Environment test command
|
help Help about any command
|
||||||
│ ├── vrrp/ # VRRP implementation
|
|
||||||
│ │ ├── packet.go # VRRP packet structure & marshaling
|
Flags:
|
||||||
│ │ ├── socket.go # Raw socket operations
|
-h, --help help for go-alived
|
||||||
│ │ ├── state.go # State machine & timers
|
-v, --version version for go-alived
|
||||||
│ │ ├── arp.go # Gratuitous ARP
|
```
|
||||||
│ │ ├── instance.go # VRRP instance logic
|
|
||||||
│ │ └── manager.go # Instance manager
|
### run
|
||||||
│ └── health/ # Health check system
|
|
||||||
│ ├── checker.go # Checker interface & state
|
```bash
|
||||||
│ ├── monitor.go # Health check scheduler
|
go-alived run [flags]
|
||||||
│ ├── tcp.go # TCP health checker
|
|
||||||
│ ├── http.go # HTTP/HTTPS health checker
|
Flags:
|
||||||
│ ├── ping.go # ICMP ping checker
|
-c, --config string Path to config file (default "/etc/go-alived/config.yaml")
|
||||||
│ ├── script.go # Script checker
|
-d, --debug Enable debug mode
|
||||||
│ └── factory.go # Checker factory
|
```
|
||||||
├── pkg/
|
|
||||||
│ ├── config/ # Configuration loading & validation
|
### test
|
||||||
│ ├── logger/ # Logging system
|
|
||||||
│ └── netif/ # Network interface management
|
```bash
|
||||||
└── deployment/ # Deployment files
|
go-alived test [flags]
|
||||||
├── go-alived.service # Systemd service file
|
|
||||||
├── install.sh # Installation script
|
Flags:
|
||||||
├── uninstall.sh # Uninstallation script
|
-i, --interface string Network interface to test
|
||||||
├── check-env.sh # Environment check script
|
-v, --vip string Test VIP address (e.g., 192.168.1.100/24)
|
||||||
├── 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
|
||||||
|
|
||||||
### ✅ Fully Supported
|
| Environment | Support | Notes |
|
||||||
- Physical servers
|
|-------------|---------|-------|
|
||||||
- KVM/QEMU virtual machines
|
| Physical servers | Full | |
|
||||||
- Proxmox VE
|
| KVM/QEMU/Proxmox | Full | |
|
||||||
- VMware ESXi (with promiscuous mode)
|
| VMware ESXi | Full | Enable promiscuous mode |
|
||||||
- VirtualBox (with bridged network + promiscuous mode)
|
| VirtualBox | Full | Bridged network + promiscuous mode |
|
||||||
|
| Docker | Limited | Requires `--privileged --net=host` |
|
||||||
|
| OpenWrt/iStoreOS | Full | Use `--method service` for install |
|
||||||
|
| AWS/Aliyun/Azure | None | Multicast disabled |
|
||||||
|
|
||||||
### ⚠️ Limited Support
|
> **Note**: VRRP requires multicast support (224.0.0.18). Most public clouds disable multicast at the network layer. Use cloud-native HA solutions instead.
|
||||||
- Private cloud (depends on network configuration)
|
|
||||||
- Docker containers (requires `--privileged` and `--net=host`)
|
|
||||||
- Kubernetes (requires hostNetwork mode)
|
|
||||||
|
|
||||||
### ❌ Not Supported
|
## Troubleshooting
|
||||||
- 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.
|
### Common Issues
|
||||||
|
|
||||||
**Alternative**: Use cloud-native solutions like Elastic IP (AWS), SLB/HaVip (Aliyun), Load Balancer (Azure/GCP).
|
**1. "permission denied" or "operation not permitted"**
|
||||||
|
```bash
|
||||||
|
# VRRP requires root privileges
|
||||||
|
sudo go-alived run -c /etc/go-alived/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
See [deployment/COMPATIBILITY.md](deployment/COMPATIBILITY.md) for detailed compatibility information.
|
**2. "authentication failed"**
|
||||||
|
- Ensure `auth_pass` matches on all nodes
|
||||||
|
- Password is limited to 8 characters
|
||||||
|
|
||||||
## Requirements
|
**3. Both nodes become MASTER (split-brain)**
|
||||||
|
- Check network connectivity between nodes
|
||||||
|
- Verify `virtual_router_id` matches
|
||||||
|
- Ensure multicast traffic is allowed
|
||||||
|
|
||||||
- Go 1.21+ (for building)
|
**4. VIP not pingable after failover**
|
||||||
- Linux/macOS with root privileges (for raw sockets and interface management)
|
- Gratuitous ARP may be blocked
|
||||||
- Network interface with IPv4 address
|
- Check switch/router ARP cache timeout
|
||||||
- Multicast support (for VRRP)
|
|
||||||
|
|
||||||
## Dependencies
|
### Debug Mode
|
||||||
|
|
||||||
Minimal external dependencies:
|
```bash
|
||||||
- `github.com/vishvananda/netlink` - Network interface management
|
sudo go-alived run -c /etc/go-alived/config.yaml -d
|
||||||
- `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
|
|
||||||
|
|
||||||
## Documentation
|
|
||||||
|
|
||||||
- [USAGE.md](USAGE.md) - Detailed usage guide
|
|
||||||
- [TESTING.md](TESTING.md) - Testing guide
|
|
||||||
- [deployment/README.md](deployment/README.md) - Deployment guide
|
|
||||||
- [deployment/COMPATIBILITY.md](deployment/COMPATIBILITY.md) - Environment compatibility
|
|
||||||
- [roadmap.md](roadmap.md) - Implementation roadmap
|
|
||||||
|
|
||||||
## Roadmap
|
|
||||||
|
|
||||||
See [roadmap.md](roadmap.md) for detailed implementation plan.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
466
internal/cmd/install.go
Normal file
466
internal/cmd/install.go
Normal file
@@ -0,0 +1,466 @@
|
|||||||
|
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()
|
||||||
|
}
|
||||||
@@ -6,12 +6,14 @@ 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() {
|
||||||
@@ -21,5 +23,6 @@ func Execute() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
rootCmd.Version = Version
|
||||||
rootCmd.CompletionOptions.DisableDefaultCmd = true
|
rootCmd.CompletionOptions.DisableDefaultCmd = true
|
||||||
}
|
}
|
||||||
@@ -58,6 +58,7 @@ 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()
|
||||||
@@ -100,6 +101,27 @@ 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()
|
||||||
|
|
||||||
|
|||||||
89
internal/vrrp/notify.go
Normal file
89
internal/vrrp/notify.go
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
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)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user