github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/runsc/sandbox/memory.go (about)

     1  // Copyright 2021 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package sandbox
    16  
    17  import (
    18  	"bufio"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  	"strconv"
    23  	"strings"
    24  )
    25  
    26  // totalSystemMemory extracts "MemTotal" from "/proc/meminfo".
    27  func totalSystemMemory() (uint64, error) {
    28  	f, err := os.Open("/proc/meminfo")
    29  	if err != nil {
    30  		return 0, err
    31  	}
    32  	defer f.Close()
    33  	return parseTotalSystemMemory(f)
    34  }
    35  
    36  func parseTotalSystemMemory(r io.Reader) (uint64, error) {
    37  	for scanner := bufio.NewScanner(r); scanner.Scan(); {
    38  		line := scanner.Text()
    39  		totalStr := strings.TrimPrefix(line, "MemTotal:")
    40  		if len(totalStr) < len(line) {
    41  			fields := strings.Fields(totalStr)
    42  			if len(fields) == 0 || len(fields) > 2 {
    43  				return 0, fmt.Errorf(`malformed "MemTotal": %q`, line)
    44  			}
    45  			totalStr = fields[0]
    46  			unit := ""
    47  			if len(fields) == 2 {
    48  				unit = fields[1]
    49  			}
    50  			mem, err := strconv.ParseUint(totalStr, 10, 64)
    51  			if err != nil {
    52  				return 0, err
    53  			}
    54  			switch unit {
    55  			case "":
    56  				// do nothing.
    57  			case "kB":
    58  				memKb := mem
    59  				mem = memKb * 1024
    60  				if mem < memKb {
    61  					return 0, fmt.Errorf(`"MemTotal" too large: %d`, memKb)
    62  				}
    63  			default:
    64  				return 0, fmt.Errorf("unknown unit %q: %q", unit, line)
    65  			}
    66  			return mem, nil
    67  		}
    68  	}
    69  	return 0, fmt.Errorf(`malformed "/proc/meminfo": "MemTotal" not found`)
    70  }