cpu_usage 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/perl
  2. #
  3. # Copyright 2014 Pierre Mavro <deimos@deimos.fr>
  4. # Copyright 2014 Vivien Didelot <vivien@didelot.org>
  5. # Copyright 2014 Andreas Guldstrand <andreas.guldstrand@gmail.com>
  6. #
  7. # Licensed under the terms of the GNU GPL v3, or any later version.
  8. use strict;
  9. use warnings;
  10. use utf8;
  11. use Getopt::Long;
  12. # default values
  13. my $t_warn = $ENV{T_WARN} // 50;
  14. my $t_crit = $ENV{T_CRIT} // 80;
  15. my $cpu_usage = -1;
  16. my $decimals = $ENV{DECIMALS} // 2;
  17. my $label = $ENV{LABEL} // "";
  18. sub help {
  19. print "Usage: cpu_usage [-w <warning>] [-c <critical>] [-d <decimals>]\n";
  20. print "-w <percent>: warning threshold to become yellow\n";
  21. print "-c <percent>: critical threshold to become red\n";
  22. print "-d <decimals>: Use <decimals> decimals for percentage (default is $decimals) \n";
  23. exit 0;
  24. }
  25. GetOptions("help|h" => \&help,
  26. "w=i" => \$t_warn,
  27. "c=i" => \$t_crit,
  28. "d=i" => \$decimals,
  29. );
  30. # Get CPU usage
  31. $ENV{LC_ALL}="en_US"; # if mpstat is not run under en_US locale, things may break, so make sure it is
  32. open (MPSTAT, 'mpstat 1 1 |') or die;
  33. while (<MPSTAT>) {
  34. if (/^.*\s+(\d+\.\d+)[\s\x00]?$/) {
  35. $cpu_usage = 100 - $1; # 100% - %idle
  36. last;
  37. }
  38. }
  39. close(MPSTAT);
  40. $cpu_usage eq -1 and die 'Can\'t find CPU information';
  41. # Print short_text, full_text
  42. print "${label}";
  43. printf "%.${decimals}f%%\n", $cpu_usage;
  44. print "${label}";
  45. printf "%.${decimals}f%%\n", $cpu_usage;
  46. # Print color, if needed
  47. if ($cpu_usage >= $t_crit) {
  48. print "#FF0000\n";
  49. exit 33;
  50. } elsif ($cpu_usage >= $t_warn) {
  51. print "#FFFC00\n";
  52. }
  53. exit 0;