github.com/demonoid81/containerd@v1.3.4/sys/proc.go (about)

     1  // +build linux
     2  
     3  /*
     4     Copyright The containerd Authors.
     5  
     6     Licensed under the Apache License, Version 2.0 (the "License");
     7     you may not use this file except in compliance with the License.
     8     You may obtain a copy of the License at
     9  
    10         http://www.apache.org/licenses/LICENSE-2.0
    11  
    12     Unless required by applicable law or agreed to in writing, software
    13     distributed under the License is distributed on an "AS IS" BASIS,
    14     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15     See the License for the specific language governing permissions and
    16     limitations under the License.
    17  */
    18  
    19  package sys
    20  
    21  import (
    22  	"bufio"
    23  	"fmt"
    24  	"os"
    25  	"strconv"
    26  	"strings"
    27  
    28  	"github.com/opencontainers/runc/libcontainer/system"
    29  )
    30  
    31  const nanoSecondsPerSecond = 1e9
    32  
    33  var clockTicksPerSecond = uint64(system.GetClockTicks())
    34  
    35  // GetSystemCPUUsage returns the host system's cpu usage in
    36  // nanoseconds. An error is returned if the format of the underlying
    37  // file does not match.
    38  //
    39  // Uses /proc/stat defined by POSIX. Looks for the cpu
    40  // statistics line and then sums up the first seven fields
    41  // provided. See `man 5 proc` for details on specific field
    42  // information.
    43  func GetSystemCPUUsage() (uint64, error) {
    44  	var line string
    45  	f, err := os.Open("/proc/stat")
    46  	if err != nil {
    47  		return 0, err
    48  	}
    49  	bufReader := bufio.NewReaderSize(nil, 128)
    50  	defer func() {
    51  		bufReader.Reset(nil)
    52  		f.Close()
    53  	}()
    54  	bufReader.Reset(f)
    55  	err = nil
    56  	for err == nil {
    57  		line, err = bufReader.ReadString('\n')
    58  		if err != nil {
    59  			break
    60  		}
    61  		parts := strings.Fields(line)
    62  		switch parts[0] {
    63  		case "cpu":
    64  			if len(parts) < 8 {
    65  				return 0, fmt.Errorf("bad format of cpu stats")
    66  			}
    67  			var totalClockTicks uint64
    68  			for _, i := range parts[1:8] {
    69  				v, err := strconv.ParseUint(i, 10, 64)
    70  				if err != nil {
    71  					return 0, fmt.Errorf("error parsing cpu stats")
    72  				}
    73  				totalClockTicks += v
    74  			}
    75  			return (totalClockTicks * nanoSecondsPerSecond) /
    76  				clockTicksPerSecond, nil
    77  		}
    78  	}
    79  	return 0, fmt.Errorf("bad stats format")
    80  }