-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
646 lines (506 loc) · 13.5 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// Copyright (c) 2020, 2022-2024 D. Bohdan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
tsize "github.com/kopoli/go-terminal-size"
"github.com/mitchellh/go-wordwrap"
"github.com/shirou/gopsutil/v4/process"
)
const (
defaultDumpPath = ""
defaultLength = 20
defaultMemFormat = "%.1f"
defaultNewlines = false
defaultOutputPath = "-"
defaultQuiet = false
defaultRecordTime = 1000 // ms
defaultSampleTime = 200 // ms
defaultTimeFormat = "%d:%02d:%04.1f"
defaultVerbose = false
defaultWait = -1
sparklineLowMaximum = 10000
usageDivisor = 1 << 20 // Report memory usage in binary megabytes.
version = "0.9.1"
)
var sparklineTicks = []rune{'▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'}
type config struct {
arguments []string
command string
dumpPath string
length int
memFormat string
newlines bool
outputPath string
quiet bool
record int
sample int
timeFormat string
wait int
}
type MemoryTracker struct {
timestamps []int64
values []int64
maximum int64
mu sync.RWMutex
}
func (mt *MemoryTracker) AddRecord(timestamp int64, value int64) {
mt.mu.Lock()
defer mt.mu.Unlock()
mt.timestamps = append(mt.timestamps, timestamp)
mt.values = append(mt.values, value)
if value > mt.maximum {
mt.maximum = value
}
}
func (mt *MemoryTracker) History(count int) ([]int64, []int64, int64) {
mt.mu.RLock()
defer mt.mu.RUnlock()
if count < 0 || count > len(mt.values) {
count = len(mt.values)
}
timestampsCopy := make([]int64, count)
copy(timestampsCopy, mt.timestamps[len(mt.timestamps)-count:])
valuesCopy := make([]int64, count)
copy(valuesCopy, mt.values[len(mt.values)-count:])
return timestampsCopy, valuesCopy, mt.maximum
}
func wrapForTerm(s string) string {
size, err := tsize.GetSize()
if err != nil {
return s
}
return wordwrap.WrapString(s, uint(size.Width))
}
func usage(w io.Writer) {
s := fmt.Sprintf(
`Usage: %s [-h] [-v] [-d path] [-l n] [-m fmt] [-n] [-o path] [-q] [-t fmt] [-w ms] [--] command [arg ...]`,
filepath.Base(os.Args[0]),
)
fmt.Fprintln(w, wrapForTerm(s))
}
func help() {
usage(os.Stdout)
s := fmt.Sprintf(`
Track the RAM usage (resident set size) of a process and its descendants in real time.
Arguments:
command
Command to run
[arg ...]
Arguments to the command
Options:
-h, --help
Print this help message and exit
-v, --version
Print the version number and exit
-d, --dump path
File to append full memory usage history to when finished
-l, --length n
Sparkline length (default: %d)
-m, --mem-format fmt
Format string for memory amounts (default: '%v')
-n, --newlines
Print new sparkline on new line instead of over previous
-o, --output path
Output file to append to ('%v' for standard error)
-q, --quiet
Do not print sparklines, only final report
-r, --record ms
How frequently to record/report memory usage in ms (default: %d)
-s, --sample ms
How frequently to sample memory usage in ms (default: %d)
-t, --time-format fmt
Format string for run time (default: '%v')
-w, --wait ms
Set '--sample' and '--record' time simultaneously (that both options override)
`,
defaultLength,
defaultMemFormat,
defaultOutputPath,
defaultRecordTime,
defaultSampleTime,
defaultTimeFormat,
)
fmt.Print(wrapForTerm(s))
}
func parseArgs() config {
cfg := config{
dumpPath: defaultDumpPath,
length: defaultLength,
memFormat: defaultMemFormat,
outputPath: defaultOutputPath,
record: defaultRecordTime,
sample: defaultSampleTime,
timeFormat: defaultTimeFormat,
wait: defaultWait,
}
usageError := func(message string, badValue interface{}) {
usage(os.Stderr)
fmt.Fprintf(os.Stderr, "\nError: "+message+"\n", badValue)
os.Exit(2)
}
// Parse the command-line flags.
printHelp := false
printVersion := false
recondTimeSet := false
sampleTimeSet := false
waitTimeSet := false
var i int
nextArg := func(flag string) string {
i++
if i >= len(os.Args) {
usageError("no value for option: %s", flag)
}
return os.Args[i]
}
for i = 1; i < len(os.Args); i++ {
arg := os.Args[i]
if arg == "--" {
i++
break
}
if !strings.HasPrefix(arg, "-") {
break
}
switch arg {
case "-d", "--dump":
cfg.dumpPath = nextArg(arg)
case "-h", "--help":
printHelp = true
case "-l", "--length":
value := nextArg(arg)
length, err := strconv.Atoi(value)
if err != nil {
usageError("invalid length: %v", value)
}
cfg.length = length
case "-m", "--mem-format":
cfg.memFormat = nextArg(arg)
case "-n", "--newlines":
cfg.newlines = true
case "-o", "--output":
cfg.outputPath = nextArg(arg)
case "-q", "--quiet":
cfg.quiet = true
case "-r", "--record":
value := nextArg(arg)
record, err := strconv.Atoi(value)
if err != nil {
usageError("invalid record time: %v", value)
}
cfg.record = record
recondTimeSet = true
case "-s", "--sample":
value := nextArg(arg)
sample, err := strconv.Atoi(value)
if err != nil {
usageError("invalid sample time: %v", value)
}
cfg.sample = sample
sampleTimeSet = true
case "-t", "--time-format":
cfg.timeFormat = nextArg(arg)
case "-v", "--version":
printVersion = true
case "-w", "--wait":
value := nextArg(arg)
wait, err := strconv.Atoi(value)
if err != nil {
usageError("invalid wait time: %v", value)
}
cfg.wait = wait
waitTimeSet = true
default:
usageError("unknown option: %v", arg)
}
}
if printHelp {
help()
os.Exit(0)
}
if printVersion {
fmt.Println(version)
os.Exit(0)
}
// Ensure we have a command.
if i >= len(os.Args) {
usageError("command is required%v", "")
}
// Set the command and arguments.
cfg.command = os.Args[i]
if i+1 < len(os.Args) {
cfg.arguments = os.Args[i+1:]
} else {
cfg.arguments = []string{}
}
// Handle the wait option.
if waitTimeSet {
if !recondTimeSet {
cfg.record = cfg.wait
}
if !sampleTimeSet {
cfg.sample = cfg.wait
}
}
return cfg
}
func main() {
cfg := parseArgs()
if err := run(cfg); err != nil {
if cfg.outputPath == defaultOutputPath && !cfg.newlines {
fmt.Fprintln(os.Stderr)
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
os.Exit(exitErr.ExitCode())
}
fmt.Fprintln(os.Stderr, "Error: ", err)
os.Exit(1)
}
}
func run(cfg config) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Set up signal handling.
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
startTime := time.Now().UTC()
// Prepare stderr or file output.
output, err := getOutput(cfg.outputPath)
if err != nil {
return err
}
if output != os.Stderr {
defer output.Close()
}
// We use '\r' to print the sparklines on the same line by default.
coreFormat := "%s " + cfg.memFormat
sparklineFormat := "\r" + coreFormat
if cfg.newlines {
sparklineFormat = coreFormat + "\n"
}
// Start the command.
cmd := exec.CommandContext(ctx, cfg.command, cfg.arguments...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return fmt.Errorf("failed to start command: %w", err)
}
// Ensure we shut down the process.
defer func() {
if cmd.Process != nil {
cmd.Process.Kill()
}
}()
// Get the process.
proc, err := process.NewProcess(int32(cmd.Process.Pid))
if err != nil {
return fmt.Errorf("failed to get process: %w", err)
}
// Create the memory-tracking data structures and closures that append to them.
memTracker := &MemoryTracker{}
sample := []int64{}
addSample := func() error {
mem, err := getMemoryUsage(proc)
if err != nil {
return err
}
sample = append(sample, int64(mem))
return nil
}
addRecord := func() {
if len(sample) == 0 {
return
}
memTracker.AddRecord(time.Now().UnixNano(), slices.Max(sample))
if !cfg.quiet {
_, values, maximum := memTracker.History(cfg.length)
line := sparkline(maximum, values)
fmt.Fprintf(output, sparklineFormat, line, float64(maximum)/usageDivisor)
}
sample = []int64{}
}
// Start memory tracking by adding an initial record before we wait.
_ = addSample()
addRecord()
done := make(chan error, 1)
go func() {
sampleTicker := time.NewTicker(time.Duration(cfg.sample) * time.Millisecond)
defer sampleTicker.Stop()
recordTicker := time.NewTicker(time.Duration(cfg.record) * time.Millisecond)
defer recordTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-sampleTicker.C:
err := addSample()
if err != nil {
continue
}
case <-recordTicker.C:
addRecord()
}
}
}()
go func() {
done <- cmd.Wait()
}()
// Wait for either the command's completion or a signal.
select {
case err := <-done:
// Stop memory tracking.
cancel()
if err != nil {
return err
}
case sig := <-sigChan:
cancel()
return fmt.Errorf("received signal: %v", sig)
}
// Get the complete final stats.
timestamps, values, maximum := memTracker.History(-1)
endTime := time.Now().UTC()
if len(values) == 0 {
fmt.Fprintln(output, "no data collected")
} else {
if !cfg.newlines && !cfg.quiet {
fmt.Fprintln(output)
}
summary := summarize(values, maximum, startTime, endTime, cfg.memFormat, cfg.timeFormat)
fmt.Fprintln(output, summary)
}
// Dump the memory usage history if required.
if cfg.dumpPath != defaultDumpPath {
if err := dumpHistory(cfg.dumpPath, timestamps, values); err != nil {
return fmt.Errorf("failed to dump history: %w", err)
}
}
return nil
}
func getOutput(path string) (*os.File, error) {
if path == defaultOutputPath {
return os.Stderr, nil
}
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return nil, fmt.Errorf("failed to open output file: %w", err)
}
return file, nil
}
func getMemoryUsage(proc *process.Process) (int64, error) {
procs := []*process.Process{proc}
var total int64
for len(procs) > 0 {
current := procs[0]
procs = procs[1:]
if current == nil {
continue
}
children, err := current.Children()
if err != nil && err != process.ErrorNoChildren {
return 0, err
}
procs = append(procs, children...)
for _, child := range children {
mem, err := child.MemoryInfo()
// If we can't get memory info for a child, skip it.
if err != nil || mem == nil {
continue
}
total += int64(mem.RSS)
}
}
return total, nil
}
func summarize(values []int64, maximum int64, start, end time.Time, memFormat, timeFormat string) string {
avg := average(values)
result := strings.Builder{}
result.WriteString(" avg: ")
result.WriteString(fmt.Sprintf(memFormat, float64(avg)/usageDivisor))
result.WriteString("\n max: ")
result.WriteString(fmt.Sprintf(memFormat, float64(maximum)/usageDivisor))
result.WriteString("\ntime: ")
hours, minutes, seconds := hmsDelta(start, end)
result.WriteString(fmt.Sprintf(timeFormat, hours, minutes, seconds))
return result.String()
}
func average[T int64](values []T) T {
var sum T
for _, value := range values {
sum += value
}
if len(values) == 0 {
return T(0)
}
return sum / T(len(values))
}
func dumpHistory(path string, timestamps []int64, values []int64) error {
file, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
for i, timestamp := range timestamps {
_, err := fmt.Fprintf(writer, "%d %d\n", timestamp/1_000_000, values[i])
if err != nil {
return err
}
}
return writer.Flush()
}
func hmsDelta(start, end time.Time) (int, int, float64) {
delta := end.Sub(start)
totalMillis := int(delta / time.Millisecond)
hours := totalMillis / (60 * 60 * 1000)
remaining := totalMillis % (60 * 60 * 1000)
minutes := remaining / (60 * 1000)
remaining = remaining % (60 * 1000)
seconds := float64(remaining) / 1000.0
return hours, minutes, seconds
}
func sparkline(maximum int64, data []int64) string {
if maximum <= sparklineLowMaximum {
return strings.Repeat(string(sparklineTicks[0]), max(1, len(data)))
}
tickMax := int64(len(sparklineTicks) - 1)
result := strings.Builder{}
for _, x := range data {
tickIndex := int(tickMax * x / maximum)
result.WriteRune(sparklineTicks[tickIndex])
}
return result.String()
}