netstat.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. file, err := os.Open(filePath)
  35. if err != nil {
  36. return nil, err
  37. }
  38. netStatFile := NetStat{
  39. Filename: filepath.Base(filePath),
  40. Stats: make(map[string][]uint64),
  41. }
  42. scanner := bufio.NewScanner(file)
  43. scanner.Scan()
  44. // First string is always a header for stats
  45. var headers []string
  46. headers = append(headers, strings.Fields(scanner.Text())...)
  47. // Other strings represent per-CPU counters
  48. for scanner.Scan() {
  49. for num, counter := range strings.Fields(scanner.Text()) {
  50. value, err := strconv.ParseUint(counter, 16, 64)
  51. if err != nil {
  52. return nil, err
  53. }
  54. netStatFile.Stats[headers[num]] = append(netStatFile.Stats[headers[num]], value)
  55. }
  56. }
  57. netStatsTotal = append(netStatsTotal, netStatFile)
  58. }
  59. return netStatsTotal, nil
  60. }