Skip to content

Instantly share code, notes, and snippets.

@gabesullice
Created January 6, 2023 11:16
Show Gist options
  • Save gabesullice/5d59a899466601253f78c89059e84fea to your computer and use it in GitHub Desktop.
Save gabesullice/5d59a899466601253f78c89059e84fea to your computer and use it in GitHub Desktop.
Graph /proc/meminfo with Go and Graphite
package main
import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"strconv"
"time"
)
const meminfo = "/proc/meminfo"
const (
ErrOpen = iota + 2
ErrConv
)
func main() {
for {
f, err := os.Open(meminfo)
if err != nil {
os.Exit(ErrOpen)
}
s := bufio.NewScanner(f)
for s.Scan() {
parts := bytes.Split(s.Bytes(), []byte(":"))
k := string(bytes.Trim(bytes.ToLower(bytes.Map(parensToUnderscores, parts[0])), "_"))
v := bytes.Trim(parts[1], " ")
if v[0] == byte('0') {
continue
}
kb, err := strconv.Atoi(string(bytes.Split(v, []byte(" "))[0]))
if err != nil {
log.Println(err)
os.Exit(ErrConv)
}
fmt.Printf("memmon.%s %d %d\n", k, kb/1024, time.Now().Unix())
}
f.Close()
time.Sleep(time.Second)
}
}
func parensToUnderscores(r rune) rune {
if r == '(' || r == ')' {
return '_'
}
return r
}
#!/bin/bash
go run meminfo.go | nc localhost 2003
#/bin/bash
docker run --rm -d --name graphite -p 8080:80 -p 2003-2004:2003-2004 -p 2023-2024:2023-2024 -p 8125:8125/udp -p 8126:8126 graphiteapp/graphite-statsd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment