director.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package proxy
  14. import (
  15. "errors"
  16. "log"
  17. "net/url"
  18. "sync"
  19. "time"
  20. )
  21. const (
  22. // amount of time an endpoint will be held in a failed
  23. // state before being reconsidered for proxied requests
  24. endpointFailureWait = 5 * time.Second
  25. )
  26. func newDirector(scheme string, addrs []string) (*director, error) {
  27. if len(addrs) == 0 {
  28. return nil, errors.New("one or more upstream addresses required")
  29. }
  30. endpoints := make([]*endpoint, len(addrs))
  31. for i, addr := range addrs {
  32. u := url.URL{Scheme: scheme, Host: addr}
  33. endpoints[i] = newEndpoint(u)
  34. }
  35. d := director{ep: endpoints}
  36. return &d, nil
  37. }
  38. type director struct {
  39. ep []*endpoint
  40. }
  41. func (d *director) endpoints() []*endpoint {
  42. filtered := make([]*endpoint, 0)
  43. for _, ep := range d.ep {
  44. if ep.Available {
  45. filtered = append(filtered, ep)
  46. }
  47. }
  48. return filtered
  49. }
  50. func newEndpoint(u url.URL) *endpoint {
  51. ep := endpoint{
  52. URL: u,
  53. Available: true,
  54. failFunc: timedUnavailabilityFunc(endpointFailureWait),
  55. }
  56. return &ep
  57. }
  58. type endpoint struct {
  59. sync.Mutex
  60. URL url.URL
  61. Available bool
  62. failFunc func(ep *endpoint)
  63. }
  64. func (ep *endpoint) Failed() {
  65. ep.Lock()
  66. if !ep.Available {
  67. ep.Unlock()
  68. return
  69. }
  70. ep.Available = false
  71. ep.Unlock()
  72. log.Printf("proxy: marked endpoint %s unavailable", ep.URL.String())
  73. if ep.failFunc == nil {
  74. log.Printf("proxy: no failFunc defined, endpoint %s will be unavailable forever.", ep.URL.String())
  75. return
  76. }
  77. ep.failFunc(ep)
  78. }
  79. func timedUnavailabilityFunc(wait time.Duration) func(*endpoint) {
  80. return func(ep *endpoint) {
  81. time.AfterFunc(wait, func() {
  82. ep.Available = true
  83. log.Printf("proxy: marked endpoint %s available", ep.URL.String())
  84. })
  85. }
  86. }