Update roles/pips/files/cpu_usage.py

This commit is contained in:
2025-12-03 19:45:13 +01:00
parent 2d911cee99
commit b4637ccf89
+33 -43
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env python3 #!/usr/bin/env python3.11
"""Nagios plugin: report current memory usage. """Nagios plugin: report current memory usage.
Outputs a one-line status and perfdata and uses Nagios exit codes: Outputs a one-line status and perfdata and uses Nagios exit codes:
@@ -11,53 +11,43 @@ import argparse
import sys import sys
import psutil import psutil
def human_mb(bytes_val):
return bytes_val / (1024 * 1024)
def main(): def main():
parser = argparse.ArgumentParser(description="Nagios memory usage check") parser = argparse.ArgumentParser(description="Nagios memory usage check")
parser.add_argument("-w", "--warning", type=int, default=80, parser.add_argument("-w", "--warning", type=int, default=80,
help="warning threshold (percent used)") help="warning threshold (percent used)")
parser.add_argument("-c", "--critical", type=int, default=90, parser.add_argument("-c", "--critical", type=int, default=90,
help="critical threshold (percent used)") help="critical threshold (percent used)")
args = parser.parse_args() args = parser.parse_args()
if args.warning >= args.critical: if args.warning >= args.critical:
print("UNKNOWN - warning threshold must be less than critical") print("UNKNOWN - warning threshold must be less than critical")
sys.exit(3) sys.exit(3)
try: try:
cpu = psutil.cpu_percent(interval=1,percpu=True) cpu = psutil.cpu_percent(interval=5,percpu=True)
except Exception as e: except Exception as e:
print(f"UNKNOWN - failed to read cpu's: {e}") print(f"UNKNOWN - failed to read cpu's: {e}")
sys.exit(3) sys.exit(3)
#total_mb = human_mb(vm.total) status = 0
#used_mb = human_mb(vm.total - vm.available) cpu_list = ""
#percent_used = vm.percent cpu_print = ""
cpu_num = 0
status_str = "OK"
for percent_used in cpu:
if percent_used >= args.critical:
status = 2
status_str = "CRITICAL"
elif percent_used >= args.warning:
status = 1
status_str = "WARNING"
cpu_list += f"cpu{cpu_num}={percent_used:.1f};;;0; "
cpu_print += f"{percent_used:.1f}% "
cpu_num += 1
status = 0 print(f"CPU {status_str} {cpu_print} | {cpu_list} ")
status_str = "OK" sys.exit(status)
for percent_used in cpu:
if percent_used >= args.critical:
status = 2
status_str = "CRITICAL"
elif percent_used >= args.warning:
status = 1
status_str = "WARNING"
# Perfdata: used and total in MiB, and percent
perf = (
f"used={used_mb:.1f}MiB;{args.warning};{args.critical};0;{total_mb:.1f}"
f" total={total_mb:.1f}MiB"
)
print(f"CPU {status_str} - {used_mb:.1f}MiB used of {total_mb:.1f}MiB ({percent_used:.1f}%) | {perf}")
sys.exit(status)
if __name__ == "__main__": if __name__ == "__main__":
main() main()