consul_client.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package multitenant
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "time"
  8. consul "github.com/hashicorp/consul/api"
  9. opentracing "github.com/opentracing/opentracing-go"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. const (
  13. longPollDuration = 10 * time.Second
  14. )
  15. // ConsulClient is a high-level client for Consul, that exposes operations
  16. // such as CAS and Watch which take callbacks. It also deals with serialisation.
  17. type ConsulClient interface {
  18. Get(ctx context.Context, key string, out interface{}) error
  19. CAS(ctx context.Context, key string, out interface{}, f CASCallback) error
  20. WatchPrefix(prefix string, out interface{}, done chan struct{}, f func(string, interface{}) bool)
  21. }
  22. // CASCallback is the type of the callback to CAS. If err is nil, out must be non-nil.
  23. type CASCallback func(in interface{}) (out interface{}, retry bool, err error)
  24. // NewConsulClient returns a new ConsulClient
  25. func NewConsulClient(addr string) (ConsulClient, error) {
  26. client, err := consul.NewClient(&consul.Config{
  27. Address: addr,
  28. Scheme: "http",
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. return &consulClient{client.KV()}, nil
  34. }
  35. var (
  36. queryOptions = &consul.QueryOptions{
  37. RequireConsistent: true,
  38. }
  39. writeOptions = &consul.WriteOptions{}
  40. // ErrNotFound is returned by ConsulClient.Get
  41. ErrNotFound = fmt.Errorf("Not found")
  42. )
  43. type kv interface {
  44. CAS(p *consul.KVPair, q *consul.WriteOptions) (bool, *consul.WriteMeta, error)
  45. Get(key string, q *consul.QueryOptions) (*consul.KVPair, *consul.QueryMeta, error)
  46. List(prefix string, q *consul.QueryOptions) (consul.KVPairs, *consul.QueryMeta, error)
  47. }
  48. type consulClient struct {
  49. kv kv
  50. }
  51. // Get and deserialise a JSON value from consul.
  52. func (c *consulClient) Get(ctx context.Context, key string, out interface{}) error {
  53. span, ctx := opentracing.StartSpanFromContext(ctx, "Consul Get", opentracing.Tag{Key: "key", Value: key})
  54. defer span.Finish()
  55. kvp, _, err := c.kv.Get(key, queryOptions)
  56. if err != nil {
  57. return err
  58. }
  59. if kvp == nil {
  60. return ErrNotFound
  61. }
  62. return json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out)
  63. }
  64. // CAS atomically modify a value in a callback.
  65. // If value doesn't exist you'll get nil as a argument to your callback.
  66. func (c *consulClient) CAS(ctx context.Context, key string, out interface{}, f CASCallback) error {
  67. span, ctx := opentracing.StartSpanFromContext(ctx, "Consul CAS", opentracing.Tag{Key: "key", Value: key})
  68. defer span.Finish()
  69. var (
  70. index = uint64(0)
  71. retries = 10
  72. retry = true
  73. intermediate interface{}
  74. )
  75. for i := 0; i < retries; i++ {
  76. kvp, _, err := c.kv.Get(key, queryOptions)
  77. if err != nil {
  78. log.Errorf("Error getting %s: %v", key, err)
  79. continue
  80. }
  81. if kvp != nil {
  82. if err := json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out); err != nil {
  83. log.Errorf("Error deserialising %s: %v", key, err)
  84. continue
  85. }
  86. index = kvp.ModifyIndex // if key doesn't exist, index will be 0
  87. intermediate = out
  88. }
  89. intermediate, retry, err = f(intermediate)
  90. if err != nil {
  91. log.Errorf("Error CASing %s: %v", key, err)
  92. if !retry {
  93. return err
  94. }
  95. continue
  96. }
  97. if intermediate == nil {
  98. panic("Callback must instantiate value!")
  99. }
  100. value := bytes.Buffer{}
  101. if err := json.NewEncoder(&value).Encode(intermediate); err != nil {
  102. log.Errorf("Error serialising value for %s: %v", key, err)
  103. continue
  104. }
  105. ok, _, err := c.kv.CAS(&consul.KVPair{
  106. Key: key,
  107. Value: value.Bytes(),
  108. ModifyIndex: index,
  109. }, writeOptions)
  110. if err != nil {
  111. log.Errorf("Error CASing %s: %v", key, err)
  112. continue
  113. }
  114. if !ok {
  115. log.Errorf("Error CASing %s, trying again %d", key, index)
  116. continue
  117. }
  118. return nil
  119. }
  120. return fmt.Errorf("Failed to CAS %s", key)
  121. }
  122. func (c *consulClient) WatchPrefix(prefix string, out interface{}, done chan struct{}, f func(string, interface{}) bool) {
  123. const (
  124. initialBackoff = 1 * time.Second
  125. maxBackoff = 1 * time.Minute
  126. )
  127. var (
  128. backoff = initialBackoff / 2
  129. index = uint64(0)
  130. )
  131. for {
  132. select {
  133. case <-done:
  134. return
  135. default:
  136. }
  137. kvps, meta, err := c.kv.List(prefix, &consul.QueryOptions{
  138. RequireConsistent: true,
  139. WaitIndex: index,
  140. WaitTime: longPollDuration,
  141. })
  142. if err != nil {
  143. log.Errorf("Error getting path %s: %v", prefix, err)
  144. backoff = backoff * 2
  145. if backoff > maxBackoff {
  146. backoff = maxBackoff
  147. }
  148. select {
  149. case <-done:
  150. return
  151. case <-time.After(backoff):
  152. continue
  153. }
  154. }
  155. backoff = initialBackoff
  156. if index == meta.LastIndex {
  157. continue
  158. }
  159. index = meta.LastIndex
  160. for _, kvp := range kvps {
  161. if err := json.NewDecoder(bytes.NewReader(kvp.Value)).Decode(out); err != nil {
  162. log.Errorf("Error deserialising %s: %v", kvp.Key, err)
  163. continue
  164. }
  165. if !f(kvp.Key, out) {
  166. return
  167. }
  168. }
  169. }
  170. }