-
Notifications
You must be signed in to change notification settings - Fork 669
/
continuous.go
108 lines (90 loc) · 2.53 KB
/
continuous.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package profiler
import (
"fmt"
"time"
"golang.org/x/sync/errgroup"
"github.com/ava-labs/avalanchego/utils/filesystem"
)
// Config that is used to describe the options of the continuous profiler.
type Config struct {
Dir string `json:"dir"`
Enabled bool `json:"enabled"`
Freq time.Duration `json:"freq"`
MaxNumFiles int `json:"maxNumFiles"`
}
// ContinuousProfiler periodically captures CPU, memory, and lock profiles
type ContinuousProfiler interface {
Dispatch() error
Shutdown()
}
type continuousProfiler struct {
profiler *profiler
freq time.Duration
maxNumFiles int
// Dispatch returns when closer is closed
closer chan struct{}
}
func NewContinuous(dir string, freq time.Duration, maxNumFiles int) ContinuousProfiler {
return &continuousProfiler{
profiler: new(dir),
freq: freq,
maxNumFiles: maxNumFiles,
closer: make(chan struct{}),
}
}
func (p *continuousProfiler) Dispatch() error {
t := time.NewTicker(p.freq)
defer t.Stop()
for {
if err := p.start(); err != nil {
return err
}
select {
case <-p.closer:
return p.stop()
case <-t.C:
if err := p.stop(); err != nil {
return err
}
}
if err := p.rotate(); err != nil {
return err
}
}
}
func (p *continuousProfiler) start() error {
return p.profiler.StartCPUProfiler()
}
func (p *continuousProfiler) stop() error {
g := errgroup.Group{}
g.Go(p.profiler.StopCPUProfiler)
g.Go(p.profiler.MemoryProfile)
g.Go(p.profiler.LockProfile)
return g.Wait()
}
func (p *continuousProfiler) rotate() error {
g := errgroup.Group{}
g.Go(func() error { return rotate(p.profiler.cpuProfileName, p.maxNumFiles) })
g.Go(func() error { return rotate(p.profiler.memProfileName, p.maxNumFiles) })
g.Go(func() error { return rotate(p.profiler.lockProfileName, p.maxNumFiles) })
return g.Wait()
}
func (p *continuousProfiler) Shutdown() {
close(p.closer)
}
// Renames the file at [name] to [name].1, the file at [name].1 to [name].2, etc.
// Assumes that there is a file at [name].
func rotate(name string, maxNumFiles int) error {
for i := maxNumFiles - 1; i > 0; i-- {
sourceFilename := fmt.Sprintf("%s.%d", name, i)
destFilename := fmt.Sprintf("%s.%d", name, i+1)
if _, err := filesystem.RenameIfExists(sourceFilename, destFilename); err != nil {
return err
}
}
destFilename := fmt.Sprintf("%s.1", name)
_, err := filesystem.RenameIfExists(name, destFilename)
return err
}