** Copyright (C) 2001-2025 Zabbix SIA
** This program is free software: you can redistribute it and/or modify it under the terms of
** the GNU Affero General Public License as published by the Free Software Foundation, version 3.
** This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
** without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU Affero General Public License for more details.
** You should have received a copy of the GNU Affero General Public License along with this program.
** If not, see <https://www.gnu.org/licenses/>.
// GetMemory reads /proc/meminfo file and returns and returns the value in bytes for the
// specific memory type. Returns an error if the value was not found, or if there is an issue
// with reading the file or parsing the value.
func GetMemory(memType string) (mem uint64, err error) {
meminfo, err := ReadAll("/proc/meminfo")
return mem, fmt.Errorf("cannot read meminfo file: %s", err.Error())
mem, found, err = ByteFromProcFileData(meminfo, memType)
return mem, fmt.Errorf("cannot get the memory amount for %s: %s", memType, err.Error())
return mem, fmt.Errorf("cannot get the memory amount for %s", memType)
// ReadAll reads all data from a file. Returns an error if there is an issue with reading the file or
func ReadAll(filename string) (data []byte, err error) {
fd, err := syscall.Open(filename, syscall.O_RDONLY, 0)
if n, err = syscall.Read(fd, b); err != nil {
if errors.Is(err, syscall.EINTR) {
if _, err = buf.Write(b[:n]); err != nil {
// ByteFromProcFileData returns the value in bytes of the provided value name from the provided
// process file data. Returns true if the value is found, and false if it is not or if there is an
// error. Returns an error if there is an issue with parsing values.
func ByteFromProcFileData(data []byte, valueName string) (uint64, bool, error) {
for _, line := range strings.Split(string(data), "\n") {
i := strings.Index(line, ":")