Skip to content

Instantly share code, notes, and snippets.

@ayush--s
Created March 13, 2020 06:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayush--s/57f6db6a88e720d728fb389c88e68c2f to your computer and use it in GitHub Desktop.
Save ayush--s/57f6db6a88e720d728fb389c88e68c2f to your computer and use it in GitHub Desktop.
kill executables of a name over memory usage percentage
package main
import (
"fmt"
"log"
"log/syslog"
"strings"
"github.com/shirou/gopsutil/process"
)
// MemoryPercentKillThreshold set max percentage for process
const MemoryPercentKillThreshold float32 = 18.0
// ProcessType set process to match to kill, if it exceeds memory usage
const ProcessType string = "uwsgi"
func main() {
sysLog, err := syslog.New(syslog.LOG_WARNING, "killer")
if err != nil {
log.Fatal(err)
}
ps, _ := process.Processes()
for _, p := range ps {
cmd, err := p.Cmdline()
if err != nil {
}
if strings.Contains(cmd, ProcessType) {
mem, _ := p.MemoryPercent()
if mem > MemoryPercentKillThreshold {
err := p.Terminate()
if err != nil {
sysLog.Crit(fmt.Sprint("process:", p.Pid, " counldn't be killed: ", err))
} else {
sysLog.Alert(fmt.Sprint("process:", p.Pid, " got killed due to high memory usage: ", mem))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment