github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/metrics/disk_linux.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // Contains the Linux implementation of process disk IO counter retrieval.
    19  
    20  package metrics
    21  
    22  import (
    23  	"bufio"
    24  	"fmt"
    25  	"io"
    26  	"os"
    27  	"strconv"
    28  	"strings"
    29  )
    30  
    31  // ReadDiskStats retrieves the disk IO stats belonging to the current process.
    32  func ReadDiskStats(stats *DiskStats) error {
    33  	// Open the process disk IO counter file
    34  	inf, err := os.Open(fmt.Sprintf("/proc/%d/io", os.Getpid()))
    35  	if err != nil {
    36  		return err
    37  	}
    38  	defer inf.Close()
    39  	in := bufio.NewReader(inf)
    40  
    41  	// Iterate over the IO counter, and extract what we need
    42  	for {
    43  		// Read the next line and split to key and value
    44  		line, err := in.ReadString('\n')
    45  		if err != nil {
    46  			if err == io.EOF {
    47  				return nil
    48  			}
    49  			return err
    50  		}
    51  		parts := strings.Split(line, ":")
    52  		if len(parts) != 2 {
    53  			continue
    54  		}
    55  		key := strings.TrimSpace(parts[0])
    56  		value, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
    57  		if err != nil {
    58  			return err
    59  		}
    60  
    61  		// Update the counter based on the key
    62  		switch key {
    63  		case "syscr":
    64  			stats.ReadCount = value
    65  		case "syscw":
    66  			stats.WriteCount = value
    67  		case "rchar":
    68  			stats.ReadBytes = value
    69  		case "wchar":
    70  			stats.WriteBytes = value
    71  		}
    72  	}
    73  }