github.com/ethanhsieh/snapd@v0.0.0-20210615102523-3db9b8e4edc5/osutil/meminfo.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2021 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program 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 General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package osutil
    21  
    22  import (
    23  	"bufio"
    24  	"fmt"
    25  	"os"
    26  	"strconv"
    27  	"strings"
    28  )
    29  
    30  var (
    31  	procMeminfo = "/proc/meminfo"
    32  )
    33  
    34  // TotalSystemMemory returns the total memory in the system in bytes.
    35  func TotalSystemMemory() (totalMem uint64, err error) {
    36  	f, err := os.Open(procMeminfo)
    37  	if err != nil {
    38  		return 0, err
    39  	}
    40  	defer f.Close()
    41  	s := bufio.NewScanner(f)
    42  	for {
    43  		if !s.Scan() {
    44  			break
    45  		}
    46  		l := strings.TrimSpace(s.Text())
    47  		if !strings.HasPrefix(l, "MemTotal:") {
    48  			continue
    49  		}
    50  		fields := strings.Fields(l)
    51  		if len(fields) != 3 || fields[2] != "kB" {
    52  			return 0, fmt.Errorf("cannot process unexpected meminfo entry %q", l)
    53  		}
    54  		totalMem, err = strconv.ParseUint(fields[1], 10, 64)
    55  		if err != nil {
    56  			return 0, fmt.Errorf("cannot convert memory size value: %v", err)
    57  		}
    58  		// got it
    59  		return totalMem * 1024, nil
    60  	}
    61  	if err := s.Err(); err != nil {
    62  		return 0, err
    63  	}
    64  	return 0, fmt.Errorf("cannot determine the total amount of memory in the system from %s", procMeminfo)
    65  }
    66  
    67  func MockProcMeminfo(newPath string) (restore func()) {
    68  	MustBeTestBinary("mocking can only be done from tests")
    69  	oldProcMeminfo := procMeminfo
    70  	procMeminfo = newPath
    71  	return func() {
    72  		procMeminfo = oldProcMeminfo
    73  	}
    74  }