2020-06-14 15:58:35 +02:00
|
|
|
package commands
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
|
|
|
|
"github.com/hamburghammer/gstat/args"
|
|
|
|
"github.com/shirou/gopsutil/mem"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Mem holds the memory usage for the json transformation
|
|
|
|
type Mem struct {
|
2020-06-29 14:02:06 +02:00
|
|
|
ReadVirtualMemoryStat func() (*mem.VirtualMemoryStat, error)
|
2020-06-14 15:58:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewMem is a constructor for the Mem struct
|
|
|
|
func NewMem() Mem {
|
2020-06-29 14:02:06 +02:00
|
|
|
return Mem{mem.VirtualMemory}
|
2020-06-14 15:58:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Exec gets the mem value and maps it to the executiondata struct
|
|
|
|
func (m Mem) Exec(args args.Arguments) ([]byte, error) {
|
2021-01-02 18:10:16 +01:00
|
|
|
usage, err := m.PureExec(args)
|
2020-06-14 15:58:35 +02:00
|
|
|
if err != nil {
|
|
|
|
return []byte{}, err
|
|
|
|
}
|
|
|
|
|
2020-11-09 21:27:18 +01:00
|
|
|
data := struct {
|
|
|
|
Mem Memory `json:"mem"`
|
|
|
|
}{usage}
|
2020-06-14 15:58:35 +02:00
|
|
|
return json.Marshal(data)
|
|
|
|
}
|
|
|
|
|
2021-01-02 18:10:16 +01:00
|
|
|
func (m Mem) PureExec(args args.Arguments) (Memory, error) {
|
|
|
|
if !args.Mem {
|
|
|
|
return Memory{}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
mem, err := m.ReadVirtualMemoryStat()
|
|
|
|
if err != nil {
|
|
|
|
return Memory{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
memory := Memory{Used: bytesToMegaByte(mem.Used), Total: bytesToMegaByte(mem.Total)}
|
|
|
|
return memory, nil
|
|
|
|
}
|
|
|
|
|
2020-06-14 15:58:35 +02:00
|
|
|
func bytesToMegaByte(bytes uint64) uint64 {
|
|
|
|
kb := bytes / 1024
|
|
|
|
mb := kb / 1024
|
|
|
|
return mb
|
|
|
|
}
|