-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.go
70 lines (58 loc) · 1.88 KB
/
memory.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"fmt"
"runtime/debug"
"github.com/shirou/gopsutil/mem"
)
type MemorySample struct {
MemoryTotal float64 `json:"memoryTotalBytes"`
MemoryFree float64 `json:"memoryFreeBytes"`
MemoryUsed float64 `json:"memoryUsedBytes"`
MemoryFreePercent float64 `json:"memoryFreePercent"`
MemoryUsedPercent float64 `json:"memoryUsedPercent"`
MemoryCachedBytes float64 `json:"memoryCachedBytes"`
MemorySlabBytes float64 `json:"memorySlabBytes"`
MemorySharedBytes float64 `json:"memorySharedBytes"`
SwapTotal float64 `json:"swapTotalBytes"`
SwapFree float64 `json:"swapFreeBytes"`
SwapUsed float64 `json:"swapUsedBytes"`
}
type MemoryMonitor struct {
vmHarvest func() (*mem.VirtualMemoryStat, error)
}
func (mm *MemoryMonitor) Sample() (result *MemorySample, err error) {
defer func() {
if panicErr := recover(); panicErr != nil {
err = fmt.Errorf("Panic in MemoryMonitor.Sample: %v\nStack: %s", panicErr, debug.Stack())
}
}()
memory, err := mm.vmHarvest()
if err != nil {
return nil, err
}
swap, err := mem.SwapMemory()
if err != nil {
return nil, err
}
memoryFreePercent := float64(0)
memoryUsedPercent := float64(0)
if memory.Total > 0 {
memoryFreePercent = float64(memory.Available) / float64(memory.Total) * 100
memoryUsedPercent = 100.0 - memoryFreePercent
}
return &MemorySample{
MemoryTotal: float64(memory.Total),
MemoryFree: float64(memory.Available),
MemoryUsed: float64(memory.Used),
MemoryCachedBytes: float64(memory.Cached),
MemorySlabBytes: float64(memory.Slab),
MemorySharedBytes: float64(memory.Shared),
MemoryFreePercent: memoryFreePercent,
MemoryUsedPercent: memoryUsedPercent,
SwapTotal: float64(swap.Total),
SwapUsed: float64(swap.Used),
SwapFree: float64(swap.Free),
}, nil
}