blob: 0cce190ec22bf47d482be61e6ce1ee75b1fea5ad [file] [log] [blame]
khenaidood948f772021-08-11 17:49:24 -04001// 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 "fmt"
18 "strconv"
19 "strings"
20
21 "github.com/prometheus/procfs/internal/util"
22)
23
24// LoadAvg represents an entry in /proc/loadavg
25type LoadAvg struct {
26 Load1 float64
27 Load5 float64
28 Load15 float64
29}
30
31// LoadAvg returns loadavg from /proc.
32func (fs FS) LoadAvg() (*LoadAvg, error) {
33 path := fs.proc.Path("loadavg")
34
35 data, err := util.ReadFileNoStat(path)
36 if err != nil {
37 return nil, err
38 }
39 return parseLoad(data)
40}
41
42// Parse /proc loadavg and return 1m, 5m and 15m.
43func parseLoad(loadavgBytes []byte) (*LoadAvg, error) {
44 loads := make([]float64, 3)
45 parts := strings.Fields(string(loadavgBytes))
46 if len(parts) < 3 {
47 return nil, fmt.Errorf("malformed loadavg line: too few fields in loadavg string: %q", string(loadavgBytes))
48 }
49
50 var err error
51 for i, load := range parts[0:3] {
52 loads[i], err = strconv.ParseFloat(load, 64)
53 if err != nil {
54 return nil, fmt.Errorf("could not parse load %q: %w", load, err)
55 }
56 }
57 return &LoadAvg{
58 Load1: loads[0],
59 Load5: loads[1],
60 Load15: loads[2],
61 }, nil
62}