hostpool.go 4.2 KB

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