Skip to content

Commit

Permalink
Merge pull request #4 from p00rt/master
Browse files Browse the repository at this point in the history
Add a check to watch for available RAM and a test for this check
  • Loading branch information
blackandred committed May 16, 2019
2 parents 46cb9d2 + a5e62dc commit 2a2c7cf
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/checks-tests/free_ram_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

echo " >> Assert that 2GB free (3/5GB used) is ok when max usage is 70%"
MOCK_FREE_RAM=3000 MOCK_TOTAL_RAM=5000 MAX_RAM_PERCENTAGE=70 ../checks/free_ram.py
[[ $? == 1 ]] && echo " .. Test failed." && exit 1
[[ $? == 127 ]] && echo " .. Test lacking a parameter." && exit 127

echo " >> Assert that 2GB free (8/10GB used) is too much when max usage is 60%"
MOCK_FREE_RAM=2000 MOCK_TOTAL_RAM=10000 MAX_RAM_PERCENTAGE=60 ../checks/free_ram.py
[[ $? == 0 ]] && echo " .. Test failed." && exit 0
[[ $? == 127 ]] && echo " .. Test lacking a parameter." && exit 127

echo " >> Assert that 5/10GB used is ok when max usage is 60%"
MOCK_FREE_RAM=5000 MOCK_TOTAL_RAM=10000 MAX_RAM_PERCENTAGE=60 ../checks/free_ram.py
[[ $? == 1 ]] && echo " .. Test failed." && exit 1
[[ $? == 127 ]] && echo " .. Test lacking a parameter." && exit 127

exit 0
29 changes: 29 additions & 0 deletions app/checks/free_ram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#!/usr/bin/env python3

import re
from os import environ
from sys import stderr

if 'MAX_RAM_PERCENTAGE' not in environ:
print("Missing MAX_RAM_PERCENTAGE parameter.\nUsage ./free_ram.py.", file=stderr)
exit(127)

def check_ram(meminfopath, maxPercent):
meminfo = open(meminfopath).read()
memTotalreg = re.compile("MemTotal:\s+(\d+)")
memAvailreg = re.compile("MemAvailable:\s+(\d+)")
memTotal = float( memTotalreg.split(meminfo)[1] )
memAvail = float( memAvailreg.split(meminfo)[1] )
if "MOCK_FREE_RAM" in environ and "MOCK_TOTAL_RAM" in environ:
memAvail = float(environ["MOCK_FREE_RAM"]) * 1024
memTotal = float(environ["MOCK_TOTAL_RAM"]) * 1024
memUsed = memTotal - memAvail
memUsedPercent = memUsed/memTotal * 100
if memUsed/memTotal * 100 > maxPercent:
print("RAM usage too high: {0:.0f}MiB/{1:.0f}MiB ({2:.0f}% used, {3:.0f}MiB left. Max usage allowed: {4:.0f}% ({5:.0f}MiB)".format(memUsed/1024, memTotal/1024, memUsedPercent, memAvail/1024, maxPercent, maxPercent/100.0 * memTotal/1024 ))
return 1
print("RAM usage OK: {0:.0f}MiB/{1:.0f}MiB ({2:.0f}% used, {3:.0f}MiB left. Max usage allowed: {4:.0f}% ({5:.0f}MiB)".format(memUsed/1024, memTotal/1024, memUsedPercent, memAvail/1024, maxPercent, maxPercent/100.0 * memTotal/1024 ))
return 0


exit(check_ram("/proc/meminfo", float(environ["MAX_RAM_PERCENTAGE"])))

0 comments on commit 2a2c7cf

Please sign in to comment.