Browse Source

init

master
Lars Hoogestraat 12 months ago
commit
e597c8fbac
6 changed files with 908 additions and 0 deletions
  1. +14
    -0
      LICENCE
  2. +231
    -0
      README.md
  3. +64
    -0
      THIRDPARTY
  4. +5
    -0
      go.mod
  5. +18
    -0
      go.sum
  6. +576
    -0
      main.go

+ 14
- 0
LICENCE View File

@ -0,0 +1,14 @@
The MIT License (MIT)
Copyright (c) 2020 Lars Hoogestraat
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 231
- 0
README.md View File

@ -0,0 +1,231 @@
## Description
check_netapp is a command line tool to request information about the health of your NetApp e.g. for icinga.
This tool offers ability to check the used space of volumes, failed disk, gathering the product version and firmware version.
## Usage
./check_netapp (version|fw|fansfailed|elecfailed|diskfailed)
### Examples
**Available disk space**
List all available volumes (same if you walk over OID: .1.3.6.1.4.1.789.1.5.4.1.2.):
```
./check_netapp df -H netapp.example.com -C public -l
```
returns the following
```
SNMPv2-SMI::enterprises.789.1.5.4.1.2.1046 = STRING: "/vol/datastore01"
SNMPv2-SMI::enterprises.789.1.5.4.1.2.1047 = STRING: "/vol/datastore02"
SNMPv2-SMI::enterprises.789.1.5.4.1.2.1048 = STRING: "/vol/datastore03"
```
Check the used disk space of volume 1047 (/vol/datastore02)
```
./check_netapp df -H netapp.example.com -C public -i 1047
```
the following text is returned:
```
Space of volume /vol/datastore02 has usage of 26.54%. Space total: 18.0 TB - Space available: 13.3 TB - Space used: 4.8 TB
```
You can use the name of the volume. It needs to walks over all volumes.
```
./check_netapp df -H netapp.example.com -C public -p /vol/datastore02.
```
You can set simple thresholds, -c for critcal (exit code 1) and -w for warnings (exit code 2)
```
./check_netapp df -H netapp.example.com -C public -i 1047 -c 90 -w 80
```
would be exited with code 1, if usage is above 90% and if usage is between 80-90% it returns with exit code 2.
**Fan failures**
Check for failures of the fans
```
./check_netapp fansfailed -H netapp.example.com -C public
```
**Disk failures**
Check for failures of the disks
```
./check_netapp diskfailed -H netapp.example.com -C public
```
**Electronic failures**
Check for failures of the electronic
```
./check_netapp elecfailed -H netapp.example.com -C public
```
**Firmware information**
Returns the current firmware information
```
./check_netapp fw -C public
```
## Example usage with icinga
**Command configuration**
```
object CheckCommand "check-netapp-electronic" {
command = [ PluginDir + "/check_netapp" ]
arguments = {
"elecfailed" = {
order = -1
required = true
}
"-H" = "$address$"
}
}
object CheckCommand "check-netapp-version" {
command = [ PluginDir + "/check_netapp" ]
arguments = {
"version" = {
order = -1
required = true
}
"-H" = "$address$"
}
}
object CheckCommand "check-netapp-firmware" {
command = [ PluginDir + "/check_netapp" ]
arguments = {
"fw" = {
order = -1
required = true
}
"-H" = "$address$"
}
}
object CheckCommand "check-netapp-diskfailed" {
command = [ PluginDir + "/check_netapp" ]
arguments = {
"diskfailed" = {
order = -1
required = true
}
"-H" = "$address$"
"-c" = "1"
}
}
```
**Host configuration**
It uses the group "netapp" to apply checks on host.
```
object Host "netapp" {
import "generic-host"
address = "xxx.xxx.xxx.xxx"
display_name = "NetApp
groups += ["netapp"]
vars.volumes["datastore02"] = {
id = 1047
critical = 99
warning = 97
}
}
```
**Service configuration**
```
apply Service "check-netapp-df-" for (identifier => volume in host.vars.volumes) {
import "generic-service"
check_command ="check-netapp-df"
vars.volumeID = volume.id
vars.critical = volume.critical
vars.warning = volume.warning
display_name = identifier
assign where "netapp" in host.groups
}
apply Service "check-netapp-version" {
import "generic-service"
check_command = "check-netapp-version"
vars.host.name = host.name
vars.host.address = host.address
assign where "netapp" in host.groups
}
apply Service "check-netapp-firmware" {
import "generic-service"
check_command = "check-netapp-firmware"
vars.host.name = host.name
vars.host.address = host.address
assign where "netapp" in host.groups
}
apply Service "check-netapp-fans" {
import "generic-service"
check_command = "check-netapp-fans"
vars.host.name = host.name
assign where "netapp" in host.groups
}
apply Service "check-netapp-electronic" {
import "generic-service"
check_command = "check-netapp-electronic"
vars.host.name = host.name
vars.host.address = host.address
assign where "netapp" in host.groups
}
apply Service "check-netapp-diskfailed" {
import "generic-service"
check_command = "check-netapp-diskfailed"
vars.host.name = host.name
assign where "netapp" in host.groups
}
```
### Info
* SNMP library from soniah is not maintained since 8th July 2020. [https://github.com/soniah/gosnmp](https://github.com/soniah/gosnmp)

+ 64
- 0
THIRDPARTY View File

@ -0,0 +1,64 @@
================================================================================
gosnmp by soniah
Github:
https://github.com/soniah/gosnmp
================================================================================
Copyright 2012-2020 The GoSNMP Authors. All rights reserved. Use of this
rights reserved. Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Parts of the gosnmp code are from GoLang ASN.1 Library
(as marked in the source code).
For those part of code the following license applies:
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 5
- 0
go.mod View File

@ -0,0 +1,5 @@
module git.hoogi.eu/snafu/check_netapp
go 1.14
require github.com/soniah/gosnmp v1.27.0

+ 18
- 0
go.sum View File

@ -0,0 +1,18 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/soniah/gosnmp v1.27.0 h1:nfmGlwMe/VvpRE5U2Llnt7ytaqT+qIzDzWbm/C75MjQ=
github.com/soniah/gosnmp v1.27.0/go.mod h1:nD71O9B+i/ueeBWp44G03aIY1Y4GJhF/gKK/KyaTzxU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=

+ 576
- 0
main.go View File

@ -0,0 +1,576 @@
// Copyright 2020 Lars Hoogestraat
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"flag"
"fmt"
"math"
"os"
"strconv"
"strings"
"github.com/soniah/gosnmp"
)
type status int
const (
ok = iota
warning
critical
unknown
)
const (
productVersion = "1.3.6.1.4.1.789.1.1.2.0"
productFirmwareVersion = "1.3.6.1.4.1.789.1.1.6.0"
dfFileSys = "1.3.6.1.4.1.789.1.5.4.1.2"
dfPerCentKBytesCapacity = "1.3.6.1.4.1.789.1.5.4.1.6"
df64TotalKBytes = "1.3.6.1.4.1.789.1.5.4.1.29"
df64UsedKBytes = "1.3.6.1.4.1.789.1.5.4.1.30"
df64AvailKBytes = "1.3.6.1.4.1.789.1.5.4.1.31"
diskActiveCount = "1.3.6.1.4.1.789.1.6.4.2"
diskReconstructingCount = "1.3.6.1.4.1.789.1.6.4.3"
diskReconstructingParityCount = "1.3.6.1.4.1.789.1.6.4.4"
diskVerifyingParityCount = "1.3.6.1.4.1.789.1.6.4.5"
diskScrubbingCount = "1.3.6.1.4.1.789.1.6.4.6"
diskFailedCount = "1.3.6.1.4.1.789.1.6.4.7.0"
diskSpareCount = "1.3.6.1.4.1.789.1.6.4.8"
diskAddingSpareCount = "1.3.6.1.4.1.789.1.6.4.9"
diskFailedMessage = "1.3.6.1.4.1.789.1.6.4.10"
diskPrefailedCount = "1.3.6.1.4.1.789.1.6.4.11"
enclFansFailed = "1.3.6.1.4.1.789.1.21.1.2.1.18"
enclElectronicsFailed = "1.3.6.1.4.1.789.1.21.1.2.1.33"
)
type genericFlags struct {
host string
community string
}
type diskfailedFlags struct {
critical int
warning int
}
type dfFlags struct {
volumeID int
volume string
listVolumes bool
critical int
warning int
}
func usage() {
fmt.Println("check_netapp is a command line tool to check SNMP values from NetApp for e.g. icinga")
fmt.Println("Usage:")
fmt.Println("\t ./check_netapp (version|fw|fansfailed|elecfailed|diskfailed)")
}
func main() {
stat := ok
defer func() {
os.Exit(stat)
}()
genericFlags := genericFlags{}
dfFlags := dfFlags{}
version := flag.NewFlagSet("version", flag.ExitOnError)
version.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
version.StringVar(&genericFlags.community, "C", "public", "The community to connect")
fw := flag.NewFlagSet("fw", flag.ExitOnError)
fw.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
fw.StringVar(&genericFlags.community, "C", "public", "The community to connect")
fansFailed := flag.NewFlagSet("fansfailed", flag.ExitOnError)
fansFailed.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
fansFailed.StringVar(&genericFlags.community, "C", "public", "The community to connect")
elecFailed := flag.NewFlagSet("elecfailed", flag.ExitOnError)
elecFailed.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
elecFailed.StringVar(&genericFlags.community, "C", "public", "The community to connect")
df := flag.NewFlagSet("df", flag.ExitOnError)
df.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
df.StringVar(&genericFlags.community, "C", "public", "The community to connect")
df.IntVar(&dfFlags.volumeID, "i", -1, "The ID of the volume. The last digits returned by the volume list of e.g. .1.3.6.1.4.1.789.1.5.4.1.2.1135 the id would be 1135.")
df.StringVar(&dfFlags.volume, "p", "", "The path of the volume to monitor. Could be slow, walks over all volumes")
df.BoolVar(&dfFlags.listVolumes, "l", false, "List all volumes reported by SNMP")
df.IntVar(&dfFlags.critical, "c", -1, "Percentage of space used before going critical")
df.IntVar(&dfFlags.warning, "w", -1, "Percentage of space used before sending a warning")
diskfailedFlags := diskfailedFlags{}
diskfailed := flag.NewFlagSet("diskfailed", flag.ExitOnError)
diskfailed.StringVar(&genericFlags.host, "H", "localhost", "The host to connect")
diskfailed.StringVar(&genericFlags.community, "C", "public", "The community to connect")
diskfailed.IntVar(&diskfailedFlags.critical, "c", -1, "number of failed disks before going critical")
diskfailed.IntVar(&diskfailedFlags.warning, "w", -1, "number of failed disks before sending a warning")
if len(os.Args) < 2 {
usage()
stat = unknown
return
}
switch os.Args[1] {
case "df":
df.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
stat = unknown
return
}
defer gosnmp.Default.Conn.Close()
status, err := dfFlags.diskSpaceUsage()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
os.Exit(int(status))
case "version":
version.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
stat = unknown
return
}
status, err := genericFlags.getVersion()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
stat = int(status)
return
case "fw":
fw.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
stat = unknown
return
}
status, err := genericFlags.getFirmwareVersion()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
stat = int(status)
return
case "diskfailed":
diskfailed.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
stat = unknown
return
}
status, err := diskfailedFlags.getDiskFailed()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
stat = int(status)
return
case "elecfailed":
elecFailed.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
stat = unknown
return
}
status, err := genericFlags.getElectronicFailed()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
stat = int(status)
return
case "fansfailed":
fansFailed.Parse(os.Args[2:])
err := genericFlags.connect()
if err != nil {
fmt.Println(err)
os.Exit(critical)
}
status, err := genericFlags.getFansFailed()
if err != nil {
fmt.Println(err)
stat = int(status)
return
}
stat = int(status)
return
default:
usage()
stat = unknown
return
}
}
// connect established connection with the snmp host
func (f genericFlags) connect() error {
gosnmp.Default.Target = f.host
gosnmp.Default.Community = f.community
err := gosnmp.Default.Connect()
if err != nil {
fmt.Printf("error: Connect(): %v", err)
os.Exit(unknown)
}
return nil
}
//getVersion returns the version of the NetApp (OID .1.3.6.1.4.1.789.1.1.2.0)
func (f genericFlags) getVersion() (status, error) {
version, err := gosnmp.Default.Get([]string{productVersion})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", productVersion, err)
}
if err = checkType(version.Variables[0]); err != nil {
return unknown, err
}
fmt.Print(string(version.Variables[0].Value.([]uint8)))
return ok, nil
}
func (f genericFlags) getElectronicFailed() (status, error) {
elecFailed, err := gosnmp.Default.WalkAll(enclElectronicsFailed)
if err != nil {
return unknown, fmt.Errorf("WalkAll(%s) err: %v", enclElectronicsFailed, err)
}
elecFailedMsg := ""
for _, v := range elecFailed {
if err = checkType(v); err != nil {
return unknown, err
}
if string(v.Value.([]uint8)) != "" {
elecFailedMsg += fmt.Sprintf("%s\n", v.Value.([]uint8))
}
}
if elecFailedMsg != "" {
return critical, errors.New(elecFailedMsg)
}
fmt.Print("Electronic is ok")
return ok, nil
}
func (f genericFlags) getFansFailed() (status, error) {
fansFailed, err := gosnmp.Default.WalkAll(enclFansFailed)
if err != nil {
return unknown, fmt.Errorf("WalkAll(%s) err: %v", enclElectronicsFailed, err)
}
fansFailedMsg := ""
for _, v := range fansFailed {
if err = checkType(v); err != nil {
return unknown, err
}
if string(v.Value.([]uint8)) != "" {
fansFailedMsg += fmt.Sprintf("%s\n", v.Value.([]uint8))
}
}
if fansFailedMsg != "" {
return critical, errors.New(fansFailedMsg)
}
fmt.Print("Fans are ok")
return ok, nil
}
//getFirmwareVersion returns the firmware version of the NetApp (OID 1.3.6.1.4.1.789.1.1.6.0)
func (f genericFlags) getFirmwareVersion() (status, error) {
version, err := gosnmp.Default.Get([]string{productFirmwareVersion})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", productFirmwareVersion, err)
}
err = checkType(version.Variables[0])
if err != nil {
return unknown, err
}
fmt.Printf("Firmware version: %s", version.Variables[0].Value.([]uint8))
return ok, nil
}
//getDiskFailed returns the number of failed disk with the failure message if any
func (f diskfailedFlags) getDiskFailed() (status, error) {
failedDisk, err := gosnmp.Default.Get([]string{diskFailedCount})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", diskFailedCount, err)
}
err = checkType(failedDisk.Variables[0])
if err != nil {
return unknown, err
}
iFailedDisk := failedDisk.Variables[0].Value.(int)
failedDiskMsg, err := f.getDiskFailedMessage(iFailedDisk)
if err != nil {
return unknown, err
}
if f.critical > 0 && iFailedDisk >= f.critical {
return critical, fmt.Errorf(failedDiskMsg)
} else if f.warning > 0 && iFailedDisk >= f.warning {
return warning, fmt.Errorf(failedDiskMsg)
}
fmt.Print(failedDiskMsg)
return ok, nil
}
func (f diskfailedFlags) getDiskFailedMessage(failedDisks int) (string, error) {
failedDiskMsg := fmt.Sprintf("%d disk(s) has failures", failedDisks)
if failedDisks > 0 {
msg, err := gosnmp.Default.Get([]string{diskFailedMessage})
if err != nil {
return "", fmt.Errorf("Get(%s) err: %v", diskFailedMessage, err)
}
err = checkType(msg.Variables[0])
if err != nil {
return "", err
}
failedDiskMsg += fmt.Sprintf("\nDescription: %s", msg.Variables[0].Value.([]uint8))
}
return failedDiskMsg, nil
}
//diskSpaceUsage returns the percentage of used space of a volume
func (f dfFlags) diskSpaceUsage() (status, error) {
volID := f.volumeID
if volID == -1 {
results, err := gosnmp.Default.WalkAll(dfFileSys)
if err != nil {
return unknown, fmt.Errorf("WalkAll(%s): %v", dfFileSys, err)
}
if f.listVolumes {
for _, v := range results {
fmt.Printf("%s %s\n", v.Name, v.Value.([]uint8))
}
return ok, nil
}
volID, err = getVolumeID(f.volume, results)
if err != nil {
return unknown, err
}
}
volName, err := gosnmp.Default.Get([]string{dfFileSys + "." + strconv.Itoa(volID)})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", dfFileSys+"."+strconv.Itoa(volID), err)
}
err = checkType(volName.Variables[0])
if err != nil {
return unknown, err
}
strVolName := string(volName.Variables[0].Value.([]uint8))
//Get total space
total, err := gosnmp.Default.Get([]string{df64TotalKBytes + "." + strconv.Itoa(volID)})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", df64TotalKBytes+"."+strconv.Itoa(volID), err)
}
err = checkType(total.Variables[0])
if err != nil {
return unknown, err
}
//Get used space
used, err := gosnmp.Default.Get([]string{df64UsedKBytes + "." + strconv.Itoa(volID)})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", df64UsedKBytes+"."+strconv.Itoa(volID), err)
}
err = checkType(used.Variables[0])
if err != nil {
return unknown, err
}
//Get available space
available, err := gosnmp.Default.Get([]string{df64AvailKBytes + "." + strconv.Itoa(volID)})
if err != nil {
return unknown, fmt.Errorf("Get(%s) err: %v", df64AvailKBytes+"."+strconv.Itoa(volID), err)
}
err = checkType(available.Variables[0])
if err != nil {
return unknown, err
}
iused := used.Variables[0].Value.(uint64)
itotal := total.Variables[0].Value.(uint64)
iavailable := available.Variables[0].Value.(uint64)
percUsed := 100 / float64(itotal) * float64(iused)
if int(percUsed) >= f.critical && f.critical > 0 {
return critical, fmt.Errorf("Space of volume %s has usage of %.2f%%. Space total: %s - Space available: %s - Space used: %s", strVolName, percUsed, hr(itotal), hr(iavailable), hr(iused))
}
if int(percUsed) >= f.warning && f.warning > 0 {
return warning, fmt.Errorf("Space of volume %s has usage of %.2f%%. Space total: %s - Space available: %s - Space used: %s", strVolName, percUsed, hr(itotal), hr(iavailable), hr(iused))
}
fmt.Printf("Space of volume %s has usage of %.2f%%. Space total: %s - Space available: %s - Space used: %s", strVolName, percUsed, hr(itotal), hr(iavailable), hr(iused))
return ok, nil
}
func getVolumeID(volName string, in []gosnmp.SnmpPDU) (int, error) {
for _, v := range in {
value := string(v.Value.([]uint8))
if value == volName {
pos := strings.LastIndex(v.Name, ".")
if pos == -1 {
return -1, fmt.Errorf("error: unexpected snmp response %s, please check via snmpget", v.Name)
}
volID, err := strconv.Atoi(v.Name[pos+1:])
if err != nil {
return -1, fmt.Errorf("error: could not convert unexpected value %s into integer", v.Name[pos+1:])
}
return volID, nil
}
}
return -1, fmt.Errorf("error: volume %s not found", volName)
}
func checkType(pdu gosnmp.SnmpPDU) error {
if pdu.Type == gosnmp.NoSuchInstance {
return fmt.Errorf("no such instance, requested object instance with OID %s could not be returned", pdu.Name)
} else if pdu.Type == gosnmp.NoSuchObject {
return fmt.Errorf("no such object, requested object instance with OID %s could not be returned", pdu.Name)
} else if pdu.Type == gosnmp.UnknownType {
return fmt.Errorf("unknown type, object instance with OID %s contained an unknown type", pdu.Name)
}
return nil
}
// hr fs input in kilobyte - returns a human readable filesize
func hr(fs uint64) string {
if fs == 0 {
return "0"
}
sizes := []string{"B", "KB", "MB", "GB", "TB"}
exp := math.Floor(math.Log(float64(fs)) / math.Log(1024))
if exp > 4 {
exp = 4
}
s := sizes[int(exp)+1]
if exp == 0 {
return fmt.Sprintf("%d %s", fs, s)
}
val := float64(fs) / float64(math.Pow(1024, exp))
return fmt.Sprintf("%.1f %s", math.Ceil(float64(val)*10)/10, s)
}

Loading…
Cancel
Save