net_sockstat.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // Copyright 2019 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. "bytes"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "strings"
  21. "github.com/prometheus/procfs/internal/util"
  22. )
  23. // A NetSockstat contains the output of /proc/net/sockstat{,6} for IPv4 or IPv6,
  24. // respectively.
  25. type NetSockstat struct {
  26. // Used is non-nil for IPv4 sockstat results, but nil for IPv6.
  27. Used *int
  28. Protocols []NetSockstatProtocol
  29. }
  30. // A NetSockstatProtocol contains statistics about a given socket protocol.
  31. // Pointer fields indicate that the value may or may not be present on any
  32. // given protocol.
  33. type NetSockstatProtocol struct {
  34. Protocol string
  35. InUse int
  36. Orphan *int
  37. TW *int
  38. Alloc *int
  39. Mem *int
  40. Memory *int
  41. }
  42. // NetSockstat retrieves IPv4 socket statistics.
  43. func (fs FS) NetSockstat() (*NetSockstat, error) {
  44. return readSockstat(fs.proc.Path("net", "sockstat"))
  45. }
  46. // NetSockstat6 retrieves IPv6 socket statistics.
  47. //
  48. // If IPv6 is disabled on this kernel, the returned error can be checked with
  49. // os.IsNotExist.
  50. func (fs FS) NetSockstat6() (*NetSockstat, error) {
  51. return readSockstat(fs.proc.Path("net", "sockstat6"))
  52. }
  53. // readSockstat opens and parses a NetSockstat from the input file.
  54. func readSockstat(name string) (*NetSockstat, error) {
  55. // This file is small and can be read with one syscall.
  56. b, err := util.ReadFileNoStat(name)
  57. if err != nil {
  58. // Do not wrap this error so the caller can detect os.IsNotExist and
  59. // similar conditions.
  60. return nil, err
  61. }
  62. stat, err := parseSockstat(bytes.NewReader(b))
  63. if err != nil {
  64. return nil, fmt.Errorf("failed to read sockstats from %q: %w", name, err)
  65. }
  66. return stat, nil
  67. }
  68. // parseSockstat reads the contents of a sockstat file and parses a NetSockstat.
  69. func parseSockstat(r io.Reader) (*NetSockstat, error) {
  70. var stat NetSockstat
  71. s := bufio.NewScanner(r)
  72. for s.Scan() {
  73. // Expect a minimum of a protocol and one key/value pair.
  74. fields := strings.Split(s.Text(), " ")
  75. if len(fields) < 3 {
  76. return nil, fmt.Errorf("malformed sockstat line: %q", s.Text())
  77. }
  78. // The remaining fields are key/value pairs.
  79. kvs, err := parseSockstatKVs(fields[1:])
  80. if err != nil {
  81. return nil, fmt.Errorf("error parsing sockstat key/value pairs from %q: %w", s.Text(), err)
  82. }
  83. // The first field is the protocol. We must trim its colon suffix.
  84. proto := strings.TrimSuffix(fields[0], ":")
  85. switch proto {
  86. case "sockets":
  87. // Special case: IPv4 has a sockets "used" key/value pair that we
  88. // embed at the top level of the structure.
  89. used := kvs["used"]
  90. stat.Used = &used
  91. default:
  92. // Parse all other lines as individual protocols.
  93. nsp := parseSockstatProtocol(kvs)
  94. nsp.Protocol = proto
  95. stat.Protocols = append(stat.Protocols, nsp)
  96. }
  97. }
  98. if err := s.Err(); err != nil {
  99. return nil, err
  100. }
  101. return &stat, nil
  102. }
  103. // parseSockstatKVs parses a string slice into a map of key/value pairs.
  104. func parseSockstatKVs(kvs []string) (map[string]int, error) {
  105. if len(kvs)%2 != 0 {
  106. return nil, errors.New("odd number of fields in key/value pairs")
  107. }
  108. // Iterate two values at a time to gather key/value pairs.
  109. out := make(map[string]int, len(kvs)/2)
  110. for i := 0; i < len(kvs); i += 2 {
  111. vp := util.NewValueParser(kvs[i+1])
  112. out[kvs[i]] = vp.Int()
  113. if err := vp.Err(); err != nil {
  114. return nil, err
  115. }
  116. }
  117. return out, nil
  118. }
  119. // parseSockstatProtocol parses a NetSockstatProtocol from the input kvs map.
  120. func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol {
  121. var nsp NetSockstatProtocol
  122. for k, v := range kvs {
  123. // Capture the range variable to ensure we get unique pointers for
  124. // each of the optional fields.
  125. v := v
  126. switch k {
  127. case "inuse":
  128. nsp.InUse = v
  129. case "orphan":
  130. nsp.Orphan = &v
  131. case "tw":
  132. nsp.TW = &v
  133. case "alloc":
  134. nsp.Alloc = &v
  135. case "mem":
  136. nsp.Mem = &v
  137. case "memory":
  138. nsp.Memory = &v
  139. }
  140. }
  141. return nsp
  142. }