-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapturer.go
100 lines (88 loc) · 1.88 KB
/
capturer.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
package pprofs
import (
"fmt"
"io"
"log"
"sync"
"time"
)
type capturer struct {
profiles []profile
trigger Trigger
storage Storage
logger Logger
}
func defaultCapturer() *capturer {
return &capturer{
profiles: []profile{
CpuProfile(),
HeapProfile(),
},
trigger: NewRandomIntervalTrigger(15*time.Second, 2*time.Minute),
storage: NewFileStorageFromEnv(),
logger: log.New(io.Discard, "", 0),
}
}
func newCapturer(opts ...Option) (*capturer, error) {
c := defaultCapturer()
for _, v := range opts {
v(c)
}
if err := c.validate(); err != nil {
return nil, err
}
return c, nil
}
func (c *capturer) run() {
for {
if err := c.trigger.Wait(); err != nil {
c.logger.Printf("wait: %v", err)
continue
}
wg := &sync.WaitGroup{}
wg.Add(len(c.profiles))
now := time.Now()
for _, p := range c.profiles {
go func(p profile) {
defer wg.Done()
name := p.name()
w, err := c.storage.WriteCloser(name, now)
if err != nil {
c.logger.Printf("new writer for %v %v: %v", name, now, err)
return
}
defer w.Close()
if err := p.capture(w); err != nil {
c.logger.Printf("capture %v at %v: %v", name, now, err)
}
}(p)
}
wg.Wait()
}
}
func (c *capturer) validate() error {
if len(c.profiles) == 0 {
return fmt.Errorf("%w: empty profiles", ErrInvalidOption)
}
exists := map[string]struct{}{}
for _, v := range c.profiles {
if v == nil {
return fmt.Errorf("%w: nil profile", ErrInvalidOption)
}
name := v.name()
if _, ok := exists[name]; ok {
return fmt.Errorf("%w: duplicated profile %v", ErrInvalidOption, name)
}
exists[v.name()] = struct{}{}
}
if c.trigger == nil {
return fmt.Errorf("%w: nil trigger", ErrInvalidOption)
}
if c.storage == nil {
return fmt.Errorf("%w: nil storage", ErrInvalidOption)
}
if c.logger == nil {
return fmt.Errorf("%w: nil logger", ErrInvalidOption)
}
return nil
}