hostpool.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // A Go package to intelligently and flexibly pool among multiple hosts from your Go application.
  2. // Host selection can operate in round robin or epsilon greedy mode, and unresponsive hosts are
  3. // avoided. A good overview of Epsilon Greedy is here http://stevehanov.ca/blog/index.php?id=132
  4. package hostpool
  5. import (
  6. "log"
  7. "sync"
  8. "time"
  9. )
  10. // Returns current version
  11. func Version() string {
  12. return "0.1"
  13. }
  14. // --- Response interfaces and structs ----
  15. // This interface represents the response from HostPool. You can retrieve the
  16. // hostname by calling Host(), and after making a request to the host you should
  17. // call Mark with any error encountered, which will inform the HostPool issuing
  18. // the HostPoolResponse of what happened to the request and allow it to update.
  19. type HostPoolResponse interface {
  20. Host() string
  21. Mark(error)
  22. hostPool() HostPool
  23. }
  24. type standardHostPoolResponse struct {
  25. host string
  26. sync.Once
  27. pool HostPool
  28. }
  29. // --- HostPool structs and interfaces ----
  30. // This is the main HostPool interface. Structs implementing this interface
  31. // allow you to Get a HostPoolResponse (which includes a hostname to use),
  32. // get the list of all Hosts, and use ResetAll to reset state.
  33. type HostPool interface {
  34. Get() HostPoolResponse
  35. // keep the marks separate so we can override independently
  36. markSuccess(HostPoolResponse)
  37. markFailed(HostPoolResponse)
  38. ResetAll()
  39. Hosts() []string
  40. SetHosts([]string)
  41. }
  42. type standardHostPool struct {
  43. sync.RWMutex
  44. hosts map[string]*hostEntry
  45. hostList []*hostEntry
  46. initialRetryDelay time.Duration
  47. maxRetryInterval time.Duration
  48. nextHostIndex int
  49. }
  50. // ------ constants -------------------
  51. const epsilonBuckets = 120
  52. const epsilonDecay = 0.90 // decay the exploration rate
  53. const minEpsilon = 0.01 // explore one percent of the time
  54. const initialEpsilon = 0.3
  55. const defaultDecayDuration = time.Duration(5) * time.Minute
  56. // Construct a basic HostPool using the hostnames provided
  57. func New(hosts []string) HostPool {
  58. p := &standardHostPool{
  59. hosts: make(map[string]*hostEntry, len(hosts)),
  60. hostList: make([]*hostEntry, len(hosts)),
  61. initialRetryDelay: time.Duration(30) * time.Second,
  62. maxRetryInterval: time.Duration(900) * time.Second,
  63. }
  64. for i, h := range hosts {
  65. e := &hostEntry{
  66. host: h,
  67. retryDelay: p.initialRetryDelay,
  68. }
  69. p.hosts[h] = e
  70. p.hostList[i] = e
  71. }
  72. return p
  73. }
  74. func (r *standardHostPoolResponse) Host() string {
  75. return r.host
  76. }
  77. func (r *standardHostPoolResponse) hostPool() HostPool {
  78. return r.pool
  79. }
  80. func (r *standardHostPoolResponse) Mark(err error) {
  81. r.Do(func() {
  82. doMark(err, r)
  83. })
  84. }
  85. func doMark(err error, r HostPoolResponse) {
  86. if err == nil {
  87. r.hostPool().markSuccess(r)
  88. } else {
  89. r.hostPool().markFailed(r)
  90. }
  91. }
  92. // return an entry from the HostPool
  93. func (p *standardHostPool) Get() HostPoolResponse {
  94. p.Lock()
  95. defer p.Unlock()
  96. host := p.getRoundRobin()
  97. return &standardHostPoolResponse{host: host, pool: p}
  98. }
  99. func (p *standardHostPool) getRoundRobin() string {
  100. now := time.Now()
  101. hostCount := len(p.hostList)
  102. for i := range p.hostList {
  103. // iterate via sequenece from where we last iterated
  104. currentIndex := (i + p.nextHostIndex) % hostCount
  105. h := p.hostList[currentIndex]
  106. if !h.dead {
  107. p.nextHostIndex = currentIndex + 1
  108. return h.host
  109. }
  110. if h.nextRetry.Before(now) {
  111. h.willRetryHost(p.maxRetryInterval)
  112. p.nextHostIndex = currentIndex + 1
  113. return h.host
  114. }
  115. }
  116. // all hosts are down. re-add them
  117. p.doResetAll()
  118. p.nextHostIndex = 0
  119. return p.hostList[0].host
  120. }
  121. func (p *standardHostPool) ResetAll() {
  122. p.Lock()
  123. defer p.Unlock()
  124. p.doResetAll()
  125. }
  126. func (p *standardHostPool) SetHosts(hosts []string) {
  127. p.Lock()
  128. defer p.Unlock()
  129. p.setHosts(hosts)
  130. }
  131. func (p *standardHostPool) setHosts(hosts []string) {
  132. p.hosts = make(map[string]*hostEntry, len(hosts))
  133. p.hostList = make([]*hostEntry, len(hosts))
  134. for i, h := range hosts {
  135. e := &hostEntry{
  136. host: h,
  137. retryDelay: p.initialRetryDelay,
  138. }
  139. p.hosts[h] = e
  140. p.hostList[i] = e
  141. }
  142. }
  143. // this actually performs the logic to reset,
  144. // and should only be called when the lock has
  145. // already been acquired
  146. func (p *standardHostPool) doResetAll() {
  147. for _, h := range p.hosts {
  148. h.dead = false
  149. }
  150. }
  151. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  152. host := hostR.Host()
  153. p.Lock()
  154. defer p.Unlock()
  155. h, ok := p.hosts[host]
  156. if !ok {
  157. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  158. }
  159. h.dead = false
  160. }
  161. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  162. host := hostR.Host()
  163. p.Lock()
  164. defer p.Unlock()
  165. h, ok := p.hosts[host]
  166. if !ok {
  167. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  168. }
  169. if !h.dead {
  170. h.dead = true
  171. h.retryCount = 0
  172. h.retryDelay = p.initialRetryDelay
  173. h.nextRetry = time.Now().Add(h.retryDelay)
  174. }
  175. }
  176. func (p *standardHostPool) Hosts() []string {
  177. hosts := make([]string, len(p.hosts))
  178. for host := range p.hosts {
  179. hosts = append(hosts, host)
  180. }
  181. return hosts
  182. }