@@ -2,7 +2,7 @@ package pyroscope
22
33import (
44 "bytes"
5- "fmt "
5+ "errors "
66 "io"
77 "time"
88
@@ -50,12 +50,14 @@ func newEvent(typ eventType) event {
5050
5151func (e event ) send (c chan <- event ) error {
5252 c <- e
53+
5354 return <- e .done
5455}
5556
5657func newStartEvent (w io.Writer ) event {
5758 e := newEvent (startEvent )
5859 e .w = w
60+
5961 return e
6062}
6163
@@ -66,6 +68,7 @@ func newCPUProfileCollector(
6668 period time.Duration ,
6769) * cpuProfileCollector {
6870 buf := bytes .NewBuffer (make ([]byte , 0 , 1 << 10 ))
71+
6972 return & cpuProfileCollector {
7073 name : name ,
7174 dur : period ,
@@ -105,6 +108,7 @@ func (c *cpuProfileCollector) Start() {
105108 d = c .dur
106109 }
107110 t .Reset (d )
111+
108112 continue
109113 }
110114 t .Reset (c .dur )
@@ -125,6 +129,7 @@ func (c *cpuProfileCollector) Start() {
125129 c .collector .StopCPUProfile ()
126130 c .upload ()
127131 close (c .done )
132+
128133 return
129134
130135 case e := <- c .events :
@@ -145,7 +150,7 @@ func (c *cpuProfileCollector) handleEvent(e event) {
145150 if c .started { // Misuse.
146151 // Just to avoid interruption of the background
147152 // profiling that will fail immediately.
148- err = fmt . Errorf ( "cpu profiling already started" )
153+ err = errAlreadyStarted
149154 } else {
150155 err = c .reset (e .w )
151156 c .started = err == nil
@@ -161,7 +166,7 @@ func (c *cpuProfileCollector) handleEvent(e event) {
161166 if c .started {
162167 // Flush can't be done if StartCPUProfile is called,
163168 // as we'd need stopping the foreground collector first.
164- err = fmt . Errorf ( "flush rejected: cpu profiling is in progress" )
169+ err = errFlushRejected
165170 } else {
166171 err = c .reset (nil )
167172 }
@@ -184,6 +189,7 @@ func (c *cpuProfileCollector) Stop() {
184189
185190func (c * cpuProfileCollector ) StartCPUProfile (w io.Writer ) error {
186191 c .logger .Debugf ("cpu profile collector interrupted with StartCPUProfile" )
192+
187193 return newStartEvent (w ).send (c .events )
188194}
189195
@@ -206,12 +212,15 @@ func (c *cpuProfileCollector) reset(w io.Writer) error {
206212 d = io .MultiWriter (d , w )
207213 }
208214 c .timeStarted = time .Now ()
215+
209216 if err := c .collector .StartCPUProfile (d ); err != nil {
210217 c .logger .Errorf ("failed to start CPU profiling: %v" , err )
211218 c .timeStarted = time.Time {}
212219 c .buf .Reset ()
220+
213221 return err
214222 }
223+
215224 return nil
216225}
217226
@@ -236,3 +245,8 @@ func (c *cpuProfileCollector) upload() {
236245 })
237246 c .buf .Reset ()
238247}
248+
249+ var (
250+ errAlreadyStarted = errors .New ("cpu profiling already started" )
251+ errFlushRejected = errors .New ("flush rejected: cpu profiling is in progress" )
252+ )
0 commit comments