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