当用户提到以下关键词时激活此技能:
CmdNotify is a lightweight, resource-optimized command monitoring system written in Go. It allows you to:
Create a config.json file:
json
{
"commands": [
{
"name": "disk_usage",
"command": "df -h /",
"interval": "30s",
"timeout": "10s",
"notify_on": ["change"],
"max_history": 2
},
{
"name": "memory_check",
"command": "vm_stat | grep 'Pages free'",
"interval": "20s",
"timeout": "5s",
"notify_on": ["change"],
"notify_cmd": "echo '[ALERT] $CMD_NAME: $CMD_MESSAGE'",
"max_history": 2
}
]
}
bash
# Build
go build -o cmdnotify .
# Run with default config
./cmdnotify
# Run with custom config
./cmdnotify -config /path/to/config.json
FieldTypeDefaultDescriptionnamestringrequiredUnique identifier for the commandcommandstringrequiredShell command to executeintervalduration1sExecution interval (e.g., 30s, 5m, 1h)timeoutduration30sMaximum execution time per runnotify_on[]string[]Events to notify on: ["change"], ["error"], ["all"]``notify_cmdstring""Custom notification command (optional)max_historyint2Number of results to keep for change detectionworking_dirstring""Working directory for command execution
When no notify_cmd is specified, alerts are printed to stderr:
text
[disk_usage] Command 'disk_usage' output changed
Exit code: 0
Output:
Filesystem Size Used Avail Capacity
/dev/disk1s1 228Gi 180Gi 48Gi 79%
Set notify_cmd to integrate with external systems:
json
{
"notify_cmd": "curl -X POST -d '{\"text\":\"$CMD_MESSAGE\"}' https://hooks.slack.com/services/..."
}
Environment variables available in notify_cmd:
CMD_NAME - Command nameCMD_MESSAGE - Alert messageCmdNotify is designed for minimal resource consumption:
FeatureImplementationGoroutine PoolSemaphore-based concurrency limiting (default: CPU count, min 4)Timeout ControlPer-command context.WithTimeout prevents zombie processesMemory Reusebytes.Buffer for output; history limited to max_historyEfficient HashingSHA-256 of output + exit code for fast change detectionGraceful Shutdowncontext.Cancel + sync.WaitGroup ensures clean exit
text
CmdNotify/
├── config.go # Configuration loading & validation
├── config.json # Example configuration
├── executor.go # Command execution & change detection
├── scheduler.go # Scheduling engine with goroutine pool
├── main.go # Entry point
└── go.mod # Go module definition
json
{
"commands": [
{
"name": "api_health",
"command": "curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/health",
"interval": "10s",
"timeout": "5s",
"notify_on": ["change", "error"],
"notify_cmd": "echo '[$(date)] $CMD_NAME status changed: $CMD_MESSAGE' >> /var/log/alerts.log",
"max_history": 3
},
{
"name": "db_connection_count",
"command": "psql -c 'SELECT count(*) FROM pg_stat_activity;' -t",
"interval": "1m",
"timeout": "10s",
"notify_on": ["all"],
"working_dir": "/opt/monitoring"
}
]
}