github.com/mackerelio/mackerel-agent-plugins@v0.89.3/mackerel-plugin-conntrack/lib/conntrack.go (about) 1 package mpconntrack 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "strconv" 8 ) 9 10 // ConntrackCountPaths is paths to conntrack_count files. 11 var ConntrackCountPaths = []string{ 12 "/proc/sys/net/netfilter/nf_conntrack_count", 13 "/proc/sys/net/ipv4/netfilter/ip_conntrack_count", 14 } 15 16 // ConntrackMaxPaths is paths to conntrack_max files. 17 var ConntrackMaxPaths = []string{ 18 "/proc/sys/net/nf_conntrack_max", 19 "/proc/sys/net/netfilter/nf_conntrack_max", 20 "/proc/sys/net/ipv4/ip_conntrack_max", 21 "/proc/sys/net/ipv4/netfilter/ip_conntrack_max", 22 } 23 24 // Exists returns whether file exists or not. 25 func Exists(f string) bool { 26 _, err := os.Stat(f) 27 return err == nil 28 } 29 30 // FindFile returns a first matching file path to search multiple paths. 31 func FindFile(paths []string) (f string, err error) { 32 for _, f := range paths { 33 if Exists(f) { 34 return f, nil 35 } 36 } 37 38 return "", fmt.Errorf("Cannot find files %s", paths) // nolint 39 } 40 41 // CurrentValue returns a value from a file. 42 func CurrentValue(paths []string) (n uint64, err error) { 43 // Get a path. 44 path, err := FindFile(paths) 45 if err != nil { 46 return 0, err 47 } 48 49 // Check whether a file is open. 50 file, err := os.Open(path) 51 if err != nil { 52 return 0, err 53 } 54 defer file.Close() 55 56 // Read a value from file. 57 cnt := "" 58 scanner := bufio.NewScanner(file) 59 for scanner.Scan() { 60 cnt = scanner.Text() 61 } 62 if err := scanner.Err(); err != nil { 63 return 0, err 64 } 65 66 // Convert to uint64. 67 return strconv.ParseUint(cnt, 10, 64) 68 }