You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-stats-server/main.go

79 lines
1.6 KiB
Go

10 months ago
package main
import (
10 months ago
"bufio"
10 months ago
"fmt"
10 months ago
"log"
10 months ago
"net"
"os"
"os/exec"
"strings"
10 months ago
)
var commands = map[string]string{
"cpu": `top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | sed "s/^/100 - /" | bc`,
"memory": `free -m | awk '/Mem/{print $3 " " $2}'`,
"network": `cat /sys/class/net/[e]*/statistics/{r,t}x_bytes`,
"storage": `df -Ph | grep mmcblk0p5 | awk '{print $2 " " $3}' | sed 's/G//g'`,
"uptime": `cut -f1 -d. /proc/uptime`,
}
10 months ago
// executeCommand runs a system command and returns its output
func executeCommand(command string) string {
10 months ago
cmd := exec.Command("bash", "-c", command)
output, err := cmd.CombinedOutput()
if err != nil {
10 months ago
return err.Error()
10 months ago
}
10 months ago
10 months ago
return string(output)
}
// handleConnection handles one command per connection
10 months ago
func handleConnection(conn net.Conn) {
defer conn.Close()
10 months ago
scanner := bufio.NewScanner(conn)
if !scanner.Scan() {
log.Printf("Error reading from %s, %s", conn.RemoteAddr(), scanner.Err())
return
}
10 months ago
10 months ago
command := scanner.Text()
cmd, valid := commands[strings.TrimSpace(string(command))]
if !valid {
10 months ago
fmt.Fprintln(conn, "invalid command")
return
10 months ago
}
10 months ago
output := executeCommand(cmd)
fmt.Fprintln(conn, output)
10 months ago
}
func main() {
host, ok := os.LookupEnv("HOST")
if !ok {
host = ":12345"
}
ln, err := net.Listen("tcp", host)
10 months ago
if err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
defer ln.Close()
10 months ago
log.Printf("Listening on %s...", host)
10 months ago
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error:", err)
continue
}
10 months ago
log.Printf("Connection from %s", conn.RemoteAddr())
10 months ago
go handleConnection(conn)
}
}