You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

netstat.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2020 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package procfs
  14. import (
  15. "bufio"
  16. "os"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. )
  21. // NetStat contains statistics for all the counters from one file.
  22. type NetStat struct {
  23. Stats map[string][]uint64
  24. Filename string
  25. }
  26. // NetStat retrieves stats from `/proc/net/stat/`.
  27. func (fs FS) NetStat() ([]NetStat, error) {
  28. statFiles, err := filepath.Glob(fs.proc.Path("net/stat/*"))
  29. if err != nil {
  30. return nil, err
  31. }
  32. var netStatsTotal []NetStat
  33. for _, filePath := range statFiles {
  34. procNetstat, err := parseNetstat(filePath)
  35. if err != nil {
  36. return nil, err
  37. }
  38. procNetstat.Filename = filepath.Base(filePath)
  39. netStatsTotal = append(netStatsTotal, procNetstat)
  40. }
  41. return netStatsTotal, nil
  42. }
  43. // parseNetstat parses the metrics from `/proc/net/stat/` file
  44. // and returns a NetStat structure.
  45. func parseNetstat(filePath string) (NetStat, error) {
  46. netStat := NetStat{
  47. Stats: make(map[string][]uint64),
  48. }
  49. file, err := os.Open(filePath)
  50. if err != nil {
  51. return netStat, err
  52. }
  53. defer file.Close()
  54. scanner := bufio.NewScanner(file)
  55. scanner.Scan()
  56. // First string is always a header for stats
  57. var headers []string
  58. headers = append(headers, strings.Fields(scanner.Text())...)
  59. // Other strings represent per-CPU counters
  60. for scanner.Scan() {
  61. for num, counter := range strings.Fields(scanner.Text()) {
  62. value, err := strconv.ParseUint(counter, 16, 64)
  63. if err != nil {
  64. return NetStat{}, err
  65. }
  66. netStat.Stats[headers[num]] = append(netStat.Stats[headers[num]], value)
  67. }
  68. }
  69. return netStat, nil
  70. }