epsilon_greedy.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package hostpool
  2. import (
  3. "errors"
  4. "log"
  5. "math/rand"
  6. "sync"
  7. "time"
  8. )
  9. type epsilonHostPoolResponse struct {
  10. HostPoolResponse
  11. started time.Time
  12. ended time.Time
  13. selector *epsilonGreedySelector
  14. }
  15. func (r *epsilonHostPoolResponse) Mark(err error) {
  16. if err == nil {
  17. r.ended = time.Now()
  18. r.selector.recordTiming(r)
  19. }
  20. r.HostPoolResponse.Mark(err)
  21. }
  22. type epsilonGreedySelector struct {
  23. Selector
  24. sync.Locker
  25. epsilon float32 // this is our exploration factor
  26. decayDuration time.Duration
  27. EpsilonValueCalculator // embed the epsilonValueCalculator
  28. timer
  29. }
  30. // Construct an Epsilon Greedy Selector
  31. //
  32. // Epsilon Greedy is an algorithm that allows HostPool not only to track failure state,
  33. // but also to learn about "better" options in terms of speed, and to pick from available hosts
  34. // based on how well they perform. This gives a weighted request rate to better
  35. // performing hosts, while still distributing requests to all hosts (proportionate to their performance).
  36. // The interface is the same as the standard HostPool, but be sure to mark the HostResponse immediately
  37. // after executing the request to the host, as that will stop the implicitly running request timer.
  38. //
  39. // A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
  40. //
  41. // To compute the weighting scores, we perform a weighted average of recent response times, over the course of
  42. // `decayDuration`. decayDuration may be set to 0 to use the default value of 5 minutes
  43. // We then use the supplied EpsilonValueCalculator to calculate a score from that weighted average response time.
  44. func NewEpsilonGreedy(decayDuration time.Duration, calc EpsilonValueCalculator) Selector {
  45. if decayDuration <= 0 {
  46. decayDuration = defaultDecayDuration
  47. }
  48. ss := &standardSelector{}
  49. s := &epsilonGreedySelector{
  50. Selector: ss,
  51. Locker: ss,
  52. epsilon: float32(initialEpsilon),
  53. decayDuration: decayDuration,
  54. EpsilonValueCalculator: calc,
  55. timer: &realTimer{},
  56. }
  57. return s
  58. }
  59. func (s *epsilonGreedySelector) Init(hosts []string) {
  60. s.Selector.Init(hosts)
  61. // allocate structures
  62. for _, h := range s.Selector.(*standardSelector).hostList {
  63. h.epsilonCounts = make([]int64, epsilonBuckets)
  64. h.epsilonValues = make([]int64, epsilonBuckets)
  65. }
  66. go s.epsilonGreedyDecay()
  67. }
  68. func (s *epsilonGreedySelector) epsilonGreedyDecay() {
  69. durationPerBucket := s.decayDuration / epsilonBuckets
  70. ticker := time.Tick(durationPerBucket)
  71. for {
  72. <-ticker
  73. s.performEpsilonGreedyDecay()
  74. }
  75. }
  76. func (s *epsilonGreedySelector) performEpsilonGreedyDecay() {
  77. s.Lock()
  78. for _, h := range s.Selector.(*standardSelector).hostList {
  79. h.epsilonIndex += 1
  80. h.epsilonIndex = h.epsilonIndex % epsilonBuckets
  81. h.epsilonCounts[h.epsilonIndex] = 0
  82. h.epsilonValues[h.epsilonIndex] = 0
  83. }
  84. s.Unlock()
  85. }
  86. func (s *epsilonGreedySelector) SelectNextHost() string {
  87. s.Lock()
  88. host, err := s.getEpsilonGreedy()
  89. s.Unlock()
  90. if err != nil {
  91. host = s.Selector.SelectNextHost()
  92. }
  93. return host
  94. }
  95. func (s *epsilonGreedySelector) getEpsilonGreedy() (string, error) {
  96. var hostToUse *hostEntry
  97. // this is our exploration phase
  98. if rand.Float32() < s.epsilon {
  99. s.epsilon = s.epsilon * epsilonDecay
  100. if s.epsilon < minEpsilon {
  101. s.epsilon = minEpsilon
  102. }
  103. return "", errors.New("Exploration")
  104. }
  105. // calculate values for each host in the 0..1 range (but not ormalized)
  106. var possibleHosts []*hostEntry
  107. now := time.Now()
  108. var sumValues float64
  109. for _, h := range s.Selector.(*standardSelector).hostList {
  110. if h.canTryHost(now) {
  111. v := h.getWeightedAverageResponseTime()
  112. if v > 0 {
  113. ev := s.CalcValueFromAvgResponseTime(v)
  114. h.epsilonValue = ev
  115. sumValues += ev
  116. possibleHosts = append(possibleHosts, h)
  117. }
  118. }
  119. }
  120. if len(possibleHosts) != 0 {
  121. // now normalize to the 0..1 range to get a percentage
  122. for _, h := range possibleHosts {
  123. h.epsilonPercentage = h.epsilonValue / sumValues
  124. }
  125. // do a weighted random choice among hosts
  126. ceiling := 0.0
  127. pickPercentage := rand.Float64()
  128. for _, h := range possibleHosts {
  129. ceiling += h.epsilonPercentage
  130. if pickPercentage <= ceiling {
  131. hostToUse = h
  132. break
  133. }
  134. }
  135. }
  136. if hostToUse == nil {
  137. if len(possibleHosts) != 0 {
  138. log.Println("Failed to randomly choose a host, Dan loses")
  139. }
  140. return "", errors.New("No host chosen")
  141. }
  142. return hostToUse.host, nil
  143. }
  144. func (s *epsilonGreedySelector) recordTiming(eHostR *epsilonHostPoolResponse) {
  145. host := eHostR.Host()
  146. duration := s.between(eHostR.started, eHostR.ended)
  147. s.Lock()
  148. defer s.Unlock()
  149. h, ok := s.Selector.(*standardSelector).hosts[host]
  150. if !ok {
  151. log.Fatalf("host %s not in HostPool", host)
  152. }
  153. h.epsilonCounts[h.epsilonIndex]++
  154. h.epsilonValues[h.epsilonIndex] += int64(duration.Seconds() * 1000)
  155. }
  156. func (s *epsilonGreedySelector) MakeHostResponse(host string) HostPoolResponse {
  157. resp := s.Selector.MakeHostResponse(host)
  158. return s.toEpsilonHostPoolResponse(resp)
  159. }
  160. // Convert regular response to one equipped for EG. Doesn't require lock, for now
  161. func (s *epsilonGreedySelector) toEpsilonHostPoolResponse(resp HostPoolResponse) *epsilonHostPoolResponse {
  162. started := time.Now()
  163. return &epsilonHostPoolResponse{
  164. HostPoolResponse: resp,
  165. started: started,
  166. selector: s,
  167. }
  168. }
  169. // --- timer: this just exists for testing
  170. type timer interface {
  171. between(time.Time, time.Time) time.Duration
  172. }
  173. type realTimer struct{}
  174. func (rt *realTimer) between(start time.Time, end time.Time) time.Duration {
  175. return end.Sub(start)
  176. }