hostpool.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. }
  23. type standardHostPoolResponse struct {
  24. host string
  25. pool *standardHostPool
  26. }
  27. // --- HostPool structs and interfaces ----
  28. // This is the main HostPool interface. Structs implementing this interface
  29. // allow you to Get a HostPoolResponse (which includes a hostname to use),
  30. // get the list of all Hosts, and use ResetAll to reset state.
  31. type HostPool interface {
  32. Get() HostPoolResponse
  33. ResetAll()
  34. Hosts() []string
  35. selectHost(string) HostPoolResponse
  36. }
  37. type standardHostPool struct {
  38. sync.RWMutex
  39. hosts map[string]*hostEntry
  40. hostList []*hostEntry
  41. initialRetryDelay time.Duration
  42. maxRetryInterval time.Duration
  43. nextHostIndex int
  44. }
  45. // ------ constants -------------------
  46. const epsilonBuckets = 120
  47. const epsilonDecay = 0.90 // decay the exploration rate
  48. const minEpsilon = 0.01 // explore one percent of the time
  49. const initialEpsilon = 0.3
  50. const defaultDecayDuration = time.Duration(5) * time.Minute
  51. // Construct a basic HostPool using the hostnames provided
  52. func New(hosts []string) HostPool {
  53. p := &standardHostPool{
  54. hosts: make(map[string]*hostEntry, len(hosts)),
  55. hostList: make([]*hostEntry, len(hosts)),
  56. initialRetryDelay: time.Duration(30) * time.Second,
  57. maxRetryInterval: time.Duration(900) * time.Second,
  58. }
  59. for i, h := range hosts {
  60. e := &hostEntry{
  61. host: h,
  62. retryDelay: p.initialRetryDelay,
  63. }
  64. p.hosts[h] = e
  65. p.hostList[i] = e
  66. }
  67. return p
  68. }
  69. func (r *standardHostPoolResponse) Host() string {
  70. return r.host
  71. }
  72. func (r *standardHostPoolResponse) Mark(err error) {
  73. if err == nil {
  74. r.pool.markSuccess(r)
  75. } else {
  76. r.pool.markFailed(r)
  77. }
  78. }
  79. // return an entry from the HostPool
  80. func (p *standardHostPool) Get() HostPoolResponse {
  81. p.Lock()
  82. host := p.getRoundRobin()
  83. p.Unlock()
  84. return p.selectHost(host)
  85. }
  86. func (p *standardHostPool) getRoundRobin() string {
  87. now := time.Now()
  88. hostCount := len(p.hostList)
  89. for i := range p.hostList {
  90. // iterate via sequenece from where we last iterated
  91. currentIndex := (i + p.nextHostIndex) % hostCount
  92. h := p.hostList[currentIndex]
  93. if h.canTryHost(now) {
  94. p.nextHostIndex = currentIndex + 1
  95. return h.host
  96. }
  97. }
  98. // all hosts are down. re-add them
  99. p.doResetAll()
  100. p.nextHostIndex = 0
  101. return p.hostList[0].host
  102. }
  103. func (p *standardHostPool) ResetAll() {
  104. p.Lock()
  105. defer p.Unlock()
  106. p.doResetAll()
  107. }
  108. // this actually performs the logic to reset,
  109. // and should only be called when the lock has
  110. // already been acquired
  111. func (p *standardHostPool) doResetAll() {
  112. for _, h := range p.hosts {
  113. h.dead = false
  114. }
  115. }
  116. func (p *standardHostPool) markSuccess(hostR *standardHostPoolResponse) {
  117. host := hostR.Host()
  118. p.Lock()
  119. defer p.Unlock()
  120. h, ok := p.hosts[host]
  121. if !ok {
  122. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  123. }
  124. h.dead = false
  125. }
  126. func (p *standardHostPool) markFailed(hostR *standardHostPoolResponse) {
  127. host := hostR.Host()
  128. p.Lock()
  129. defer p.Unlock()
  130. h, ok := p.hosts[host]
  131. if !ok {
  132. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  133. }
  134. if !h.dead {
  135. h.dead = true
  136. h.retryCount = 0
  137. h.retryDelay = p.initialRetryDelay
  138. h.nextRetry = time.Now().Add(h.retryDelay)
  139. }
  140. }
  141. func (p *standardHostPool) Hosts() []string {
  142. hosts := make([]string, len(p.hosts))
  143. for host, _ := range p.hosts {
  144. hosts = append(hosts, host)
  145. }
  146. return hosts
  147. }
  148. func (p *standardHostPool) selectHost(host string) HostPoolResponse {
  149. p.Lock()
  150. defer p.Unlock()
  151. h, ok := p.hosts[host]
  152. if !ok {
  153. log.Fatalf("host %s not in HostPool %v", host, p.Hosts())
  154. }
  155. now := time.Now()
  156. if h.dead && h.nextRetry.Before(now) {
  157. h.willRetryHost(p.maxRetryInterval)
  158. }
  159. return &standardHostPoolResponse{host: host, pool: p}
  160. }