...

Source file src/github.com/prometheus/procfs/loadavg.go

Documentation: github.com/prometheus/procfs

     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  
    14  package procfs
    15  
    16  import (
    17  	"fmt"
    18  	"strconv"
    19  	"strings"
    20  
    21  	"github.com/prometheus/procfs/internal/util"
    22  )
    23  
    24  // LoadAvg represents an entry in /proc/loadavg.
    25  type LoadAvg struct {
    26  	Load1  float64
    27  	Load5  float64
    28  	Load15 float64
    29  }
    30  
    31  // LoadAvg returns loadavg from /proc.
    32  func (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.
    43  func 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("%w: Malformed line %q", ErrFileParse, 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("%s: Cannot parse load: %f: %w", ErrFileParse, loads[i], err)
    55  		}
    56  	}
    57  	return &LoadAvg{
    58  		Load1:  loads[0],
    59  		Load5:  loads[1],
    60  		Load15: loads[2],
    61  	}, nil
    62  }
    63  

View as plain text