epsilon_greedy.go 5.6 KB

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