Created
March 13, 2020 06:59
-
-
Save ayush--s/57f6db6a88e720d728fb389c88e68c2f to your computer and use it in GitHub Desktop.
kill executables of a name over memory usage percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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