cubefs

Форк
0
124 строки · 3.3 Кб
1
package hystrix
2

3
import (
4
	"sync"
5
	"time"
6
)
7

8
var (
9
	// DefaultTimeout is how long to wait for command to complete, in milliseconds
10
	DefaultTimeout = 1000
11
	// DefaultMaxConcurrent is how many commands of the same type can run at the same time
12
	DefaultMaxConcurrent = 10
13
	// DefaultVolumeThreshold is the minimum number of requests needed before a circuit can be tripped due to health
14
	DefaultVolumeThreshold = 20
15
	// DefaultSleepWindow is how long, in milliseconds, to wait after a circuit opens before testing for recovery
16
	DefaultSleepWindow = 5000
17
	// DefaultErrorPercentThreshold causes circuits to open once the rolling measure of errors exceeds this percent of requests
18
	DefaultErrorPercentThreshold = 50
19
	// DefaultLogger is the default logger that will be used in the Hystrix package. By default prints nothing.
20
	DefaultLogger = NoopLogger{}
21
)
22

23
type Settings struct {
24
	Timeout                time.Duration
25
	MaxConcurrentRequests  int
26
	RequestVolumeThreshold uint64
27
	SleepWindow            time.Duration
28
	ErrorPercentThreshold  int
29
}
30

31
// CommandConfig is used to tune circuit settings at runtime
32
type CommandConfig struct {
33
	Timeout                int `json:"timeout"`
34
	MaxConcurrentRequests  int `json:"max_concurrent_requests"`
35
	RequestVolumeThreshold int `json:"request_volume_threshold"`
36
	SleepWindow            int `json:"sleep_window"`
37
	ErrorPercentThreshold  int `json:"error_percent_threshold"`
38
}
39

40
var circuitSettings map[string]*Settings
41
var settingsMutex *sync.RWMutex
42
var log logger
43

44
func init() {
45
	circuitSettings = make(map[string]*Settings)
46
	settingsMutex = &sync.RWMutex{}
47
	log = DefaultLogger
48
}
49

50
// Configure applies settings for a set of circuits
51
func Configure(cmds map[string]CommandConfig) {
52
	for k, v := range cmds {
53
		ConfigureCommand(k, v)
54
	}
55
}
56

57
// ConfigureCommand applies settings for a circuit
58
func ConfigureCommand(name string, config CommandConfig) {
59
	settingsMutex.Lock()
60
	defer settingsMutex.Unlock()
61

62
	timeout := DefaultTimeout
63
	if config.Timeout != 0 {
64
		timeout = config.Timeout
65
	}
66

67
	max := DefaultMaxConcurrent
68
	if config.MaxConcurrentRequests != 0 {
69
		max = config.MaxConcurrentRequests
70
	}
71

72
	volume := DefaultVolumeThreshold
73
	if config.RequestVolumeThreshold != 0 {
74
		volume = config.RequestVolumeThreshold
75
	}
76

77
	sleep := DefaultSleepWindow
78
	if config.SleepWindow != 0 {
79
		sleep = config.SleepWindow
80
	}
81

82
	errorPercent := DefaultErrorPercentThreshold
83
	if config.ErrorPercentThreshold != 0 {
84
		errorPercent = config.ErrorPercentThreshold
85
	}
86

87
	circuitSettings[name] = &Settings{
88
		Timeout:                time.Duration(timeout) * time.Millisecond,
89
		MaxConcurrentRequests:  max,
90
		RequestVolumeThreshold: uint64(volume),
91
		SleepWindow:            time.Duration(sleep) * time.Millisecond,
92
		ErrorPercentThreshold:  errorPercent,
93
	}
94
}
95

96
func getSettings(name string) *Settings {
97
	settingsMutex.RLock()
98
	s, exists := circuitSettings[name]
99
	settingsMutex.RUnlock()
100

101
	if !exists {
102
		ConfigureCommand(name, CommandConfig{})
103
		s = getSettings(name)
104
	}
105

106
	return s
107
}
108

109
func GetCircuitSettings() map[string]*Settings {
110
	copy := make(map[string]*Settings)
111

112
	settingsMutex.RLock()
113
	for key, val := range circuitSettings {
114
		copy[key] = val
115
	}
116
	settingsMutex.RUnlock()
117

118
	return copy
119
}
120

121
// SetLogger configures the logger that will be used. This only applies to the hystrix package.
122
func SetLogger(l logger) {
123
	log = l
124
}
125

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.