utils.sh.in 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #! /bin/sh
  2. STATE_OK=0
  3. STATE_WARNING=1
  4. STATE_CRITICAL=2
  5. STATE_UNKNOWN=3
  6. STATE_DEPENDENT=4
  7. print_revision() {
  8. echo "$1 v$2 (@PACKAGE@ @VERSION@)"
  9. printf '%b' "@WARRANTY@"
  10. }
  11. support() {
  12. printf '%b' "@SUPPORT@"
  13. }
  14. #
  15. # check_range takes a value and a range string, returning successfully if an
  16. # alert should be raised based on the range. Range values are inclusive.
  17. # Values may be integers or floats.
  18. #
  19. # Example usage:
  20. #
  21. # Generating an exit code of 1:
  22. # check_range 5 2:8
  23. #
  24. # Generating an exit code of 0:
  25. # check_range 1 2:8
  26. #
  27. check_range() {
  28. local v range yes no err decimal start end cmp match
  29. v="$1"
  30. range="$2"
  31. # whether to raise an alert or not
  32. yes=0
  33. no=1
  34. err=2
  35. # regex to match a decimal number
  36. decimal="-?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)"
  37. # compare numbers (including decimals), returning true/false
  38. cmp() { awk "BEGIN{ if ($1) exit(0); exit(1)}"; }
  39. # returns successfully if the string in the first argument matches the
  40. # regex in the second
  41. match() { echo "$1" | grep -E -q -- "$2"; }
  42. # make sure value is valid
  43. if ! match "$v" "^$decimal$"; then
  44. echo "${0##*/}: check_range: invalid value" >&2
  45. unset -f cmp match
  46. return "$err"
  47. fi
  48. # make sure range is valid
  49. if ! match "$range" "^@?(~|$decimal)(:($decimal)?)?$"; then
  50. echo "${0##*/}: check_range: invalid range" >&2
  51. unset -f cmp match
  52. return "$err"
  53. fi
  54. # check for leading @ char, which negates the range
  55. if match $range '^@'; then
  56. range=${range#@}
  57. yes=1
  58. no=0
  59. fi
  60. # parse the range string
  61. if ! match "$range" ':'; then
  62. start=0
  63. end="$range"
  64. else
  65. start="${range%%:*}"
  66. end="${range#*:}"
  67. fi
  68. # do the comparison, taking positive ("") and negative infinity ("~")
  69. # into account
  70. if [ "$start" != "~" ] && [ "$end" != "" ]; then
  71. if cmp "$start <= $v" && cmp "$v <= $end"; then
  72. unset -f cmp match
  73. return "$no"
  74. else
  75. unset -f cmp match
  76. return "$yes"
  77. fi
  78. elif [ "$start" != "~" ] && [ "$end" = "" ]; then
  79. if cmp "$start <= $v"; then
  80. unset -f cmp match
  81. return "$no"
  82. else
  83. unset -f cmp match
  84. return "$yes"
  85. fi
  86. elif [ "$start" = "~" ] && [ "$end" != "" ]; then
  87. if cmp "$v <= $end"; then
  88. unset -f cmp match
  89. return "$no"
  90. else
  91. unset -f cmp match
  92. return "$yes"
  93. fi
  94. else
  95. unset -f cmp match
  96. return "$no"
  97. fi
  98. }