preventing multiple Starts and adding a Stop
JP Robinson
7 years ago
32 | 32 | |
33 | 33 | Start(reportInvterval time.Duration) error |
34 | 34 | Flush() |
35 | Stop() error | |
35 | 36 | } |
36 | 37 | |
37 | 38 | type emitter struct { |
38 | 39 | prefix string |
39 | 40 | |
40 | addr string | |
41 | tcp bool | |
42 | conn net.Conn | |
41 | addr string | |
42 | tcp bool | |
43 | conn net.Conn | |
44 | start sync.Once | |
45 | stop chan bool | |
43 | 46 | |
44 | 47 | mtx sync.Mutex |
45 | 48 | counters []*counter |
58 | 61 | return &emitter{ |
59 | 62 | addr: addr, |
60 | 63 | tcp: tcp, |
64 | stop: make(chan bool), | |
61 | 65 | prefix: metricsPrefix, |
62 | 66 | logger: logger, |
63 | 67 | } |
149 | 153 | // Start will kick off a background goroutine to |
150 | 154 | // call Flush once every interval. |
151 | 155 | func (e *emitter) Start(interval time.Duration) error { |
152 | err := e.dial() | |
153 | if err != nil { | |
154 | return err | |
155 | } | |
156 | go func() { | |
157 | for range time.Tick(interval) { | |
158 | e.Flush() | |
159 | } | |
160 | }() | |
161 | return nil | |
156 | var err error | |
157 | e.start.Do(func() { | |
158 | err = e.dial() | |
159 | if err != nil { | |
160 | return | |
161 | } | |
162 | go func() { | |
163 | t := time.Tick(interval) | |
164 | for { | |
165 | select { | |
166 | case <-t: | |
167 | e.Flush() | |
168 | case <-e.stop: | |
169 | return | |
170 | } | |
171 | } | |
172 | }() | |
173 | }) | |
174 | return err | |
175 | } | |
176 | ||
177 | // Stop will flush the current metrics and close the | |
178 | // current Graphite connection, if it exists. | |
179 | func (e *emitter) Stop() error { | |
180 | if e.conn == nil { | |
181 | return nil | |
182 | } | |
183 | // stop the ticking flush loop | |
184 | e.stop <- true | |
185 | // get one last flush in | |
186 | e.Flush() | |
187 | // close the connection | |
188 | return e.conn.Close() | |
162 | 189 | } |
163 | 190 | |
164 | 191 | // Flush will attempt to create a connection with the given address |