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.
 
 

90 lines
2.2 KiB

  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. "fmt"
  18. "strconv"
  19. "strings"
  20. "github.com/prometheus/procfs/internal/util"
  21. )
  22. // Swap represents an entry in /proc/swaps.
  23. type Swap struct {
  24. Filename string
  25. Type string
  26. Size int
  27. Used int
  28. Priority int
  29. }
  30. // Swaps returns a slice of all configured swap devices on the system.
  31. func (fs FS) Swaps() ([]*Swap, error) {
  32. data, err := util.ReadFileNoStat(fs.proc.Path("swaps"))
  33. if err != nil {
  34. return nil, err
  35. }
  36. return parseSwaps(data)
  37. }
  38. func parseSwaps(info []byte) ([]*Swap, error) {
  39. swaps := []*Swap{}
  40. scanner := bufio.NewScanner(bytes.NewReader(info))
  41. scanner.Scan() // ignore header line
  42. for scanner.Scan() {
  43. swapString := scanner.Text()
  44. parsedSwap, err := parseSwapString(swapString)
  45. if err != nil {
  46. return nil, err
  47. }
  48. swaps = append(swaps, parsedSwap)
  49. }
  50. err := scanner.Err()
  51. return swaps, err
  52. }
  53. func parseSwapString(swapString string) (*Swap, error) {
  54. var err error
  55. swapFields := strings.Fields(swapString)
  56. swapLength := len(swapFields)
  57. if swapLength < 5 {
  58. return nil, fmt.Errorf("too few fields in swap string: %s", swapString)
  59. }
  60. swap := &Swap{
  61. Filename: swapFields[0],
  62. Type: swapFields[1],
  63. }
  64. swap.Size, err = strconv.Atoi(swapFields[2])
  65. if err != nil {
  66. return nil, fmt.Errorf("invalid swap size: %s", swapFields[2])
  67. }
  68. swap.Used, err = strconv.Atoi(swapFields[3])
  69. if err != nil {
  70. return nil, fmt.Errorf("invalid swap used: %s", swapFields[3])
  71. }
  72. swap.Priority, err = strconv.Atoi(swapFields[4])
  73. if err != nil {
  74. return nil, fmt.Errorf("invalid swap priority: %s", swapFields[4])
  75. }
  76. return swap, nil
  77. }