-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
245 lines (214 loc) · 5.18 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package main
import (
"flag"
"fmt"
"log"
"os"
"regexp"
"runtime"
"sort"
"strings"
"sync"
)
const (
CmdDisplayMax = 32
usage = `Usage: %s [OPTION...]
Simple, accurate RAM and swap reporting.
Options:
`
)
var (
filter string
memProfile string
cpuProfile string
showHeap bool
filterRE *regexp.Regexp
)
// store info about a command (group of processes), similar to how
// ps_mem works.
type CmdMemInfo struct {
PIDs []int
Name string
Pss float64
Shared float64
Heap float64
Swapped float64
}
type MapInfo struct {
Inode uint64
Name string
}
// mapLine is a line from /proc/$PID/maps, or one of the same header
// lines from smaps.
func NewMapInfo(mapLine []byte) MapInfo {
var mi MapInfo
var err error
pieces := splitSpaces(mapLine)
if len(pieces) == 6 {
mi.Name = string(pieces[5])
}
if len(pieces) < 5 {
panic(fmt.Sprintf("NewMapInfo(%d): `%s`",
len(pieces), string(mapLine)))
}
mi.Inode, err = ParseUint(pieces[4], 10, 64)
if err != nil {
panic(fmt.Sprintf("NewMapInfo: Atoi(%s): %s (%s)",
string(pieces[4]), err, string(mapLine)))
}
return mi
}
func (mi MapInfo) IsAnon() bool {
return mi.Inode == 0
}
// worker is executed in a new goroutine. Its sole purpose is to
// process requests for information about particular PIDs.
func worker(pidRequest chan int, wg *sync.WaitGroup, result chan *CmdMemInfo) {
for pid := range pidRequest {
var err error
cmi := new(CmdMemInfo)
cmi.PIDs = []int{pid}
cmi.Name, err = procName(pid)
if err != nil {
log.Printf("procName(%d): %s", pid, err)
wg.Done()
continue
} else if cmi.Name == "" {
// XXX: This happens with kernel
// threads. maybe warn? idk.
wg.Done()
continue
} else if filterRE != nil && !filterRE.MatchString(cmi.Name) {
wg.Done()
continue
}
cmi.Pss, cmi.Shared, cmi.Heap, cmi.Swapped, err = procMem(pid)
if err != nil {
log.Printf("procMem(%d): %s", pid, err)
wg.Done()
continue
}
result <- cmi
wg.Done()
}
}
type byPss []*CmdMemInfo
func (c byPss) Len() int { return len(c) }
func (c byPss) Less(i, j int) bool { return c[i].Pss < c[j].Pss }
func (c byPss) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage, os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&filter, "filter", "",
"regex to test process names against")
flag.StringVar(&memProfile, "memprofile", "",
"write memory profile to this file")
flag.StringVar(&cpuProfile, "cpuprofile", "",
"write cpu profile to this file")
flag.BoolVar(&showHeap, "heap", false, "show heap column")
flag.Parse()
if filter != "" {
filterRE = regexp.MustCompile(filter)
}
}
func main() {
prof, err := NewProf(memProfile, cpuProfile)
if err != nil {
log.Fatal(err)
}
// if -memprof or -cpuprof haven't been set on the command
// line, these are nops
prof.Start()
defer prof.Stop()
// need to be root to read map info for other user's
// processes.
if os.Geteuid() != 0 {
fmt.Printf("%s requires root privileges. (try 'sudo `which %s`)\n",
os.Args[0], os.Args[0])
return
}
pids, err := pidList()
if err != nil {
log.Printf("pidList: %s", err)
return
}
var wg sync.WaitGroup
work := make(chan int, len(pids))
result := make(chan *CmdMemInfo, len(pids))
// give us as much parallelism as possible
nCPU := runtime.NumCPU()
runtime.GOMAXPROCS(nCPU)
for i := 0; i < nCPU; i++ {
go worker(work, &wg, result)
}
wg.Add(len(pids))
for _, pid := range pids {
work <- pid
}
wg.Wait()
// aggregate similar processes by command name.
cmdMap := map[string]*CmdMemInfo{}
loop:
for {
// this only works correctly because we a channel
// where the buffer size >= the number of potential
// results.
select {
case c := <-result:
n := c.Name
if _, ok := cmdMap[n]; !ok {
cmdMap[n] = c
continue
}
cmdMap[n].PIDs = append(cmdMap[n].PIDs, c.PIDs...)
cmdMap[n].Pss += c.Pss
cmdMap[n].Shared += c.Shared
cmdMap[n].Swapped += c.Swapped
default:
break loop
}
}
// extract map values to a slice so we can sort them
cmds := make([]*CmdMemInfo, 0, len(cmdMap))
for _, c := range cmdMap {
cmds = append(cmds, c)
}
sort.Sort(byPss(cmds))
// keep track of total RAM and swap usage
var totPss, totSwap float64
headFmt := "%10s%10s%10s\t%s\n"
cols := []interface{}{"MB RAM", "SHARED", "SWAPPED", "PROCESS (COUNT)"}
totFmt := "#%9.1f%20.1f\tTOTAL USED BY PROCESSES\n"
if showHeap {
headFmt = "%10s" + headFmt
cols = []interface{}{"MB RAM", "SHARED", "HEAP", "SWAPPED", "PROCESS (COUNT)"}
totFmt = "#%9.1f%30.1f\tTOTAL USED BY PROCESSES\n"
}
fmt.Printf(headFmt, cols...)
for _, c := range cmds {
n := c.Name
if len(n) > CmdDisplayMax {
if n[0] == '[' {
n = n[:strings.IndexRune(n, ']')+1]
} else {
n = n[:CmdDisplayMax]
}
}
s := ""
if c.Swapped > 0 {
swap := c.Swapped / 1024.
totSwap += swap
s = fmt.Sprintf("%10.1f", swap)
}
pss := float64(c.Pss) / 1024.
if showHeap {
fmt.Printf("%10.1f%10.1f%10.1f%10s\t%s (%d)\n", pss, c.Shared/1024., c.Heap/1024., s, n, len(c.PIDs))
} else {
fmt.Printf("%10.1f%10.1f%10s\t%s (%d)\n", pss, c.Shared/1024., s, n, len(c.PIDs))
}
totPss += pss
}
fmt.Printf(totFmt, totPss, totSwap)
}