forked from afex/hystrix-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventstream.go
326 lines (278 loc) · 10.9 KB
/
eventstream.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
package hystrix
import (
"bytes"
"encoding/json"
"net/http"
"sync"
"time"
"github.com/lesha888/hystrix-go/hystrix/rolling"
)
const (
streamEventBufferSize = 10
)
// NewStreamHandler returns a server capable of exposing dashboard metrics via HTTP.
func NewStreamHandler() *StreamHandler {
return &StreamHandler{}
}
// StreamHandler publishes metrics for each command and each pool once a second to all connected HTTP client.
type StreamHandler struct {
requests map[*http.Request]chan []byte
mu sync.RWMutex
done chan struct{}
}
// Start begins watching the in-memory circuit breakers for metrics
func (sh *StreamHandler) Start() {
sh.requests = make(map[*http.Request]chan []byte)
sh.done = make(chan struct{})
go sh.loop()
}
// Stop shuts down the metric collection routine
func (sh *StreamHandler) Stop() {
close(sh.done)
}
var _ http.Handler = (*StreamHandler)(nil)
func (sh *StreamHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// Make sure that the writer supports flushing.
f, ok := rw.(http.Flusher)
if !ok {
http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError)
return
}
events := sh.register(req)
defer sh.unregister(req)
notify := rw.(http.CloseNotifier).CloseNotify()
rw.Header().Add("Content-Type", "text/event-stream")
rw.Header().Set("Cache-Control", "no-cache")
rw.Header().Set("Connection", "keep-alive")
for {
select {
case <-notify:
// client is gone
return
case event := <-events:
_, err := rw.Write(event)
if err != nil {
return
}
f.Flush()
}
}
}
func (sh *StreamHandler) loop() {
tick := time.Tick(1 * time.Second)
for {
select {
case <-tick:
circuitBreakersMutex.RLock()
for _, cb := range circuitBreakers {
sh.publishMetrics(cb)
sh.publishThreadPools(cb.executorPool)
}
circuitBreakersMutex.RUnlock()
case <-sh.done:
return
}
}
}
func (sh *StreamHandler) publishMetrics(cb *CircuitBreaker) error {
now := time.Now()
reqCount := cb.metrics.Requests().Sum(now)
errCount := cb.metrics.DefaultCollector().Errors().Sum(now)
errPct := cb.metrics.ErrorPercent(now)
eventBytes, err := json.Marshal(&streamCmdMetric{
Type: "HystrixCommand",
Name: cb.Name,
Group: cb.Name,
Time: currentTime(),
ReportingHosts: 1,
RequestCount: uint32(reqCount),
ErrorCount: uint32(errCount),
ErrorPct: uint32(errPct),
CircuitBreakerOpen: cb.IsOpen(),
RollingCountSuccess: uint32(cb.metrics.DefaultCollector().Successes().Sum(now)),
RollingCountFailure: uint32(cb.metrics.DefaultCollector().Failures().Sum(now)),
RollingCountThreadPoolRejected: uint32(cb.metrics.DefaultCollector().Rejects().Sum(now)),
RollingCountShortCircuited: uint32(cb.metrics.DefaultCollector().ShortCircuits().Sum(now)),
RollingCountTimeout: uint32(cb.metrics.DefaultCollector().Timeouts().Sum(now)),
RollingCountFallbackSuccess: uint32(cb.metrics.DefaultCollector().FallbackSuccesses().Sum(now)),
RollingCountFallbackFailure: uint32(cb.metrics.DefaultCollector().FallbackFailures().Sum(now)),
LatencyTotal: generateLatencyTimings(cb.metrics.DefaultCollector().TotalDuration()),
LatencyTotalMean: cb.metrics.DefaultCollector().TotalDuration().Mean(),
LatencyExecute: generateLatencyTimings(cb.metrics.DefaultCollector().RunDuration()),
LatencyExecuteMean: cb.metrics.DefaultCollector().RunDuration().Mean(),
// TODO: all hard-coded values should become configurable settings, per circuit
RollingStatsWindow: 10000,
ExecutionIsolationStrategy: "THREAD",
CircuitBreakerEnabled: true,
CircuitBreakerForceClosed: false,
CircuitBreakerForceOpen: cb.forceOpen,
CircuitBreakerErrorThresholdPercent: uint32(getSettings(cb.Name).ErrorPercentThreshold),
CircuitBreakerSleepWindow: uint32(getSettings(cb.Name).SleepWindow.Seconds() * 1000),
CircuitBreakerRequestVolumeThreshold: uint32(getSettings(cb.Name).RequestVolumeThreshold),
})
if err != nil {
return err
}
err = sh.writeToRequests(eventBytes)
if err != nil {
return err
}
return nil
}
func (sh *StreamHandler) publishThreadPools(pool *executorPool) error {
now := time.Now()
eventBytes, err := json.Marshal(&streamThreadPoolMetric{
Type: "HystrixThreadPool",
Name: pool.Name,
ReportingHosts: 1,
CurrentActiveCount: uint32(pool.ActiveCount()),
CurrentTaskCount: 0,
CurrentCompletedTaskCount: 0,
RollingCountThreadsExecuted: uint32(pool.Metrics.Executed.Sum(now)),
RollingMaxActiveThreads: uint32(pool.Metrics.MaxActiveRequests.Max(now)),
CurrentPoolSize: uint32(pool.Max),
CurrentCorePoolSize: uint32(pool.Max),
CurrentLargestPoolSize: uint32(pool.Max),
CurrentMaximumPoolSize: uint32(pool.Max),
RollingStatsWindow: 10000,
QueueSizeRejectionThreshold: 0,
CurrentQueueSize: 0,
})
if err != nil {
return err
}
err = sh.writeToRequests(eventBytes)
return nil
}
func (sh *StreamHandler) writeToRequests(eventBytes []byte) error {
var b bytes.Buffer
_, err := b.Write([]byte("data:"))
if err != nil {
return err
}
_, err = b.Write(eventBytes)
if err != nil {
return err
}
_, err = b.Write([]byte("\n\n"))
if err != nil {
return err
}
dataBytes := b.Bytes()
sh.mu.RLock()
for _, requestEvents := range sh.requests {
select {
case requestEvents <- dataBytes:
default:
}
}
sh.mu.RUnlock()
return nil
}
func (sh *StreamHandler) register(req *http.Request) <-chan []byte {
sh.mu.RLock()
events, ok := sh.requests[req]
sh.mu.RUnlock()
if ok {
return events
}
events = make(chan []byte, streamEventBufferSize)
sh.mu.Lock()
sh.requests[req] = events
sh.mu.Unlock()
return events
}
func (sh *StreamHandler) unregister(req *http.Request) {
sh.mu.Lock()
delete(sh.requests, req)
sh.mu.Unlock()
}
func generateLatencyTimings(r *rolling.Timing) streamCmdLatency {
return streamCmdLatency{
Timing0: r.Percentile(0),
Timing25: r.Percentile(25),
Timing50: r.Percentile(50),
Timing75: r.Percentile(75),
Timing90: r.Percentile(90),
Timing95: r.Percentile(95),
Timing99: r.Percentile(99),
Timing995: r.Percentile(99.5),
Timing100: r.Percentile(100),
}
}
type streamCmdMetric struct {
Type string `json:"type"`
Name string `json:"name"`
Group string `json:"group"`
Time int64 `json:"currentTime"`
ReportingHosts uint32 `json:"reportingHosts"`
// Health
RequestCount uint32 `json:"requestCount"`
ErrorCount uint32 `json:"errorCount"`
ErrorPct uint32 `json:"errorPercentage"`
CircuitBreakerOpen bool `json:"isCircuitBreakerOpen"`
RollingCountCollapsedRequests uint32 `json:"rollingCountCollapsedRequests"`
RollingCountExceptionsThrown uint32 `json:"rollingCountExceptionsThrown"`
RollingCountFailure uint32 `json:"rollingCountFailure"`
RollingCountFallbackFailure uint32 `json:"rollingCountFallbackFailure"`
RollingCountFallbackRejection uint32 `json:"rollingCountFallbackRejection"`
RollingCountFallbackSuccess uint32 `json:"rollingCountFallbackSuccess"`
RollingCountResponsesFromCache uint32 `json:"rollingCountResponsesFromCache"`
RollingCountSemaphoreRejected uint32 `json:"rollingCountSemaphoreRejected"`
RollingCountShortCircuited uint32 `json:"rollingCountShortCircuited"`
RollingCountSuccess uint32 `json:"rollingCountSuccess"`
RollingCountThreadPoolRejected uint32 `json:"rollingCountThreadPoolRejected"`
RollingCountTimeout uint32 `json:"rollingCountTimeout"`
CurrentConcurrentExecutionCount uint32 `json:"currentConcurrentExecutionCount"`
LatencyExecuteMean uint32 `json:"latencyExecute_mean"`
LatencyExecute streamCmdLatency `json:"latencyExecute"`
LatencyTotalMean uint32 `json:"latencyTotal_mean"`
LatencyTotal streamCmdLatency `json:"latencyTotal"`
// Properties
CircuitBreakerRequestVolumeThreshold uint32 `json:"propertyValue_circuitBreakerRequestVolumeThreshold"`
CircuitBreakerSleepWindow uint32 `json:"propertyValue_circuitBreakerSleepWindowInMilliseconds"`
CircuitBreakerErrorThresholdPercent uint32 `json:"propertyValue_circuitBreakerErrorThresholdPercentage"`
CircuitBreakerForceOpen bool `json:"propertyValue_circuitBreakerForceOpen"`
CircuitBreakerForceClosed bool `json:"propertyValue_circuitBreakerForceClosed"`
CircuitBreakerEnabled bool `json:"propertyValue_circuitBreakerEnabled"`
ExecutionIsolationStrategy string `json:"propertyValue_executionIsolationStrategy"`
ExecutionIsolationThreadTimeout uint32 `json:"propertyValue_executionIsolationThreadTimeoutInMilliseconds"`
ExecutionIsolationThreadInterruptOnTimeout bool `json:"propertyValue_executionIsolationThreadInterruptOnTimeout"`
ExecutionIsolationThreadPoolKeyOverride string `json:"propertyValue_executionIsolationThreadPoolKeyOverride"`
ExecutionIsolationSemaphoreMaxConcurrentRequests uint32 `json:"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests"`
FallbackIsolationSemaphoreMaxConcurrentRequests uint32 `json:"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests"`
RollingStatsWindow uint32 `json:"propertyValue_metricsRollingStatisticalWindowInMilliseconds"`
RequestCacheEnabled bool `json:"propertyValue_requestCacheEnabled"`
RequestLogEnabled bool `json:"propertyValue_requestLogEnabled"`
}
type streamCmdLatency struct {
Timing0 uint32 `json:"0"`
Timing25 uint32 `json:"25"`
Timing50 uint32 `json:"50"`
Timing75 uint32 `json:"75"`
Timing90 uint32 `json:"90"`
Timing95 uint32 `json:"95"`
Timing99 uint32 `json:"99"`
Timing995 uint32 `json:"99.5"`
Timing100 uint32 `json:"100"`
}
type streamThreadPoolMetric struct {
Type string `json:"type"`
Name string `json:"name"`
ReportingHosts uint32 `json:"reportingHosts"`
CurrentActiveCount uint32 `json:"currentActiveCount"`
CurrentCompletedTaskCount uint32 `json:"currentCompletedTaskCount"`
CurrentCorePoolSize uint32 `json:"currentCorePoolSize"`
CurrentLargestPoolSize uint32 `json:"currentLargestPoolSize"`
CurrentMaximumPoolSize uint32 `json:"currentMaximumPoolSize"`
CurrentPoolSize uint32 `json:"currentPoolSize"`
CurrentQueueSize uint32 `json:"currentQueueSize"`
CurrentTaskCount uint32 `json:"currentTaskCount"`
RollingMaxActiveThreads uint32 `json:"rollingMaxActiveThreads"`
RollingCountThreadsExecuted uint32 `json:"rollingCountThreadsExecuted"`
RollingStatsWindow uint32 `json:"propertyValue_metricsRollingStatisticalWindowInMilliseconds"`
QueueSizeRejectionThreshold uint32 `json:"propertyValue_queueSizeRejectionThreshold"`
}
func currentTime() int64 {
return time.Now().UnixNano() / int64(1000000)
}