hostpool.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. // Close the hostpool and release all resources.
  42. Close()
  43. }
  44. type standardHostPool struct {
  45. sync.RWMutex
  46. hosts map[string]*hostEntry
  47. hostList []*hostEntry
  48. initialRetryDelay time.Duration
  49. maxRetryInterval time.Duration
  50. nextHostIndex int
  51. }
  52. // ------ constants -------------------
  53. const epsilonBuckets = 120
  54. const epsilonDecay = 0.90 // decay the exploration rate
  55. const minEpsilon = 0.01 // explore one percent of the time
  56. const initialEpsilon = 0.3
  57. const defaultDecayDuration = time.Duration(5) * time.Minute
  58. // Construct a basic HostPool using the hostnames provided
  59. func New(hosts []string) HostPool {
  60. p := &standardHostPool{
  61. hosts: make(map[string]*hostEntry, len(hosts)),
  62. hostList: make([]*hostEntry, len(hosts)),
  63. initialRetryDelay: time.Duration(30) * time.Second,
  64. maxRetryInterval: time.Duration(900) * time.Second,
  65. }
  66. for i, h := range hosts {
  67. e := &hostEntry{
  68. host: h,
  69. retryDelay: p.initialRetryDelay,
  70. }
  71. p.hosts[h] = e
  72. p.hostList[i] = e
  73. }
  74. return p
  75. }
  76. func (r *standardHostPoolResponse) Host() string {
  77. return r.host
  78. }
  79. func (r *standardHostPoolResponse) hostPool() HostPool {
  80. return r.pool
  81. }
  82. func (r *standardHostPoolResponse) Mark(err error) {
  83. r.Do(func() {
  84. doMark(err, r)
  85. })
  86. }
  87. func doMark(err error, r HostPoolResponse) {
  88. if err == nil {
  89. r.hostPool().markSuccess(r)
  90. } else {
  91. r.hostPool().markFailed(r)
  92. }
  93. }
  94. // return an entry from the HostPool
  95. func (p *standardHostPool) Get() HostPoolResponse {
  96. p.Lock()
  97. defer p.Unlock()
  98. host := p.getRoundRobin()
  99. return &standardHostPoolResponse{host: host, pool: p}
  100. }
  101. func (p *standardHostPool) getRoundRobin() string {
  102. now := time.Now()
  103. hostCount := len(p.hostList)
  104. for i := range p.hostList {
  105. // iterate via sequenece from where we last iterated
  106. currentIndex := (i + p.nextHostIndex) % hostCount
  107. h := p.hostList[currentIndex]
  108. if !h.dead {
  109. p.nextHostIndex = currentIndex + 1
  110. return h.host
  111. }
  112. if h.nextRetry.Before(now) {
  113. h.willRetryHost(p.maxRetryInterval)
  114. p.nextHostIndex = currentIndex + 1
  115. return h.host
  116. }
  117. }
  118. // all hosts are down. re-add them
  119. p.doResetAll()
  120. p.nextHostIndex = 0
  121. return p.hostList[0].host
  122. }
  123. func (p *standardHostPool) ResetAll() {
  124. p.Lock()
  125. defer p.Unlock()
  126. p.doResetAll()
  127. }
  128. func (p *standardHostPool) SetHosts(hosts []string) {
  129. p.Lock()
  130. defer p.Unlock()
  131. p.setHosts(hosts)
  132. }
  133. func (p *standardHostPool) setHosts(hosts []string) {
  134. p.hosts = make(map[string]*hostEntry, len(hosts))
  135. p.hostList = make([]*hostEntry, len(hosts))
  136. for i, h := range hosts {
  137. e := &hostEntry{
  138. host: h,
  139. retryDelay: p.initialRetryDelay,
  140. }
  141. p.hosts[h] = e
  142. p.hostList[i] = e
  143. }
  144. }
  145. // this actually performs the logic to reset,
  146. // and should only be called when the lock has
  147. // already been acquired
  148. func (p *standardHostPool) doResetAll() {
  149. for _, h := range p.hosts {
  150. h.dead = false
  151. }
  152. }
  153. func (p *standardHostPool) Close() {
  154. for _, h := range p.hosts {
  155. h.dead = true
  156. }
  157. }
  158. func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
  159. host := hostR.Host()
  160. p.Lock()
  161. defer p.Unlock()
  162. h, ok := p.hosts[host]
  163. if !ok {
  164. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  165. }
  166. h.dead = false
  167. }
  168. func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
  169. host := hostR.Host()
  170. p.Lock()
  171. defer p.Unlock()
  172. h, ok := p.hosts[host]
  173. if !ok {
  174. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  175. }
  176. if !h.dead {
  177. h.dead = true
  178. h.retryCount = 0
  179. h.retryDelay = p.initialRetryDelay
  180. h.nextRetry = time.Now().Add(h.retryDelay)
  181. }
  182. }
  183. func (p *standardHostPool) Hosts() []string {
  184. hosts := make([]string, 0, len(p.hosts))
  185. for host := range p.hosts {
  186. hosts = append(hosts, host)
  187. }
  188. return hosts
  189. }