v2_client.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package etcd
  2. import (
  3. "bytes"
  4. "crypto/tls"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "github.com/coreos/etcd/config"
  16. etcdErr "github.com/coreos/etcd/error"
  17. )
  18. // v2client sends various requests using HTTP API.
  19. // It is different from raft communication, and doesn't record anything in the log.
  20. // The argument url is required to contain scheme and host only, and
  21. // there is no trailing slash in it.
  22. // Public functions return "etcd/error".Error intentionally to figure out
  23. // etcd error code easily.
  24. type v2client struct {
  25. http.Client
  26. wg sync.WaitGroup
  27. }
  28. func newClient(tc *tls.Config) *v2client {
  29. tr := new(http.Transport)
  30. tr.TLSClientConfig = tc
  31. return &v2client{Client: http.Client{Transport: tr}}
  32. }
  33. func (c *v2client) CloseConnections() {
  34. c.wg.Wait()
  35. tr := c.Transport.(*http.Transport)
  36. tr.CloseIdleConnections()
  37. }
  38. // CheckVersion returns true when the version check on the server returns 200.
  39. func (c *v2client) CheckVersion(url string, version int) (bool, *etcdErr.Error) {
  40. resp, err := c.Get(url + fmt.Sprintf("/version/%d/check", version))
  41. defer c.wg.Done()
  42. if err != nil {
  43. return false, clientError(err)
  44. }
  45. c.readBody(resp.Body)
  46. return resp.StatusCode == 200, nil
  47. }
  48. // GetVersion fetches the peer version of a cluster.
  49. func (c *v2client) GetVersion(url string) (int, *etcdErr.Error) {
  50. resp, err := c.Get(url + "/version")
  51. defer c.wg.Done()
  52. if err != nil {
  53. return 0, clientError(err)
  54. }
  55. body, err := c.readBody(resp.Body)
  56. if err != nil {
  57. return 0, clientError(err)
  58. }
  59. // Parse version number.
  60. version, err := strconv.Atoi(string(body))
  61. if err != nil {
  62. return 0, clientError(err)
  63. }
  64. return version, nil
  65. }
  66. func (c *v2client) GetMachines(url string) ([]*machineMessage, *etcdErr.Error) {
  67. resp, err := c.Get(url + "/v2/admin/machines/")
  68. defer c.wg.Done()
  69. if err != nil {
  70. return nil, clientError(err)
  71. }
  72. if resp.StatusCode != http.StatusOK {
  73. return nil, c.readErrorBody(resp.Body)
  74. }
  75. msgs := new([]*machineMessage)
  76. if uerr := c.readJSONBody(resp.Body, msgs); uerr != nil {
  77. return nil, uerr
  78. }
  79. return *msgs, nil
  80. }
  81. func (c *v2client) GetClusterConfig(url string) (*config.ClusterConfig, *etcdErr.Error) {
  82. resp, err := c.Get(url + "/v2/admin/config")
  83. defer c.wg.Done()
  84. if err != nil {
  85. return nil, clientError(err)
  86. }
  87. if resp.StatusCode != http.StatusOK {
  88. return nil, c.readErrorBody(resp.Body)
  89. }
  90. config := new(config.ClusterConfig)
  91. if uerr := c.readJSONBody(resp.Body, config); uerr != nil {
  92. return nil, uerr
  93. }
  94. return config, nil
  95. }
  96. // AddMachine adds machine to the cluster.
  97. // The first return value is the commit index of join command.
  98. func (c *v2client) AddMachine(url string, name string, info *context) *etcdErr.Error {
  99. b, _ := json.Marshal(info)
  100. url = url + "/v2/admin/machines/" + name
  101. log.Printf("Send Join Request to %s", url)
  102. resp, err := c.put(url, b)
  103. defer c.wg.Done()
  104. if err != nil {
  105. return clientError(err)
  106. }
  107. if resp.StatusCode != http.StatusOK {
  108. return c.readErrorBody(resp.Body)
  109. }
  110. c.readBody(resp.Body)
  111. return nil
  112. }
  113. func (c *v2client) readErrorBody(body io.ReadCloser) *etcdErr.Error {
  114. b, err := c.readBody(body)
  115. if err != nil {
  116. return clientError(err)
  117. }
  118. uerr := &etcdErr.Error{}
  119. if err := json.Unmarshal(b, uerr); err != nil {
  120. str := strings.TrimSpace(string(b))
  121. return etcdErr.NewError(etcdErr.EcodeClientInternal, str, 0)
  122. }
  123. return nil
  124. }
  125. func (c *v2client) readJSONBody(body io.ReadCloser, val interface{}) *etcdErr.Error {
  126. if err := json.NewDecoder(body).Decode(val); err != nil {
  127. log.Printf("Error parsing join response: %v", err)
  128. return clientError(err)
  129. }
  130. c.readBody(body)
  131. return nil
  132. }
  133. func (c *v2client) readBody(body io.ReadCloser) ([]byte, error) {
  134. b, err := ioutil.ReadAll(body)
  135. body.Close()
  136. return b, err
  137. }
  138. func (c *v2client) Get(url string) (*http.Response, error) {
  139. c.wg.Add(1)
  140. return c.Client.Get(url)
  141. }
  142. // put sends server side PUT request.
  143. // It always follows redirects instead of stopping according to RFC 2616.
  144. func (c *v2client) put(urlStr string, body []byte) (*http.Response, error) {
  145. c.wg.Add(1)
  146. return c.doAlwaysFollowingRedirects("PUT", urlStr, body)
  147. }
  148. func (c *v2client) doAlwaysFollowingRedirects(method string, urlStr string, body []byte) (resp *http.Response, err error) {
  149. var req *http.Request
  150. for redirect := 0; redirect < 10; redirect++ {
  151. req, err = http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  152. if err != nil {
  153. return
  154. }
  155. if resp, err = c.Do(req); err != nil {
  156. if resp != nil {
  157. resp.Body.Close()
  158. }
  159. return
  160. }
  161. if resp.StatusCode == http.StatusMovedPermanently || resp.StatusCode == http.StatusTemporaryRedirect {
  162. resp.Body.Close()
  163. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  164. err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  165. return
  166. }
  167. continue
  168. }
  169. return
  170. }
  171. err = errors.New("stopped after 10 redirects")
  172. return
  173. }
  174. func clientError(err error) *etcdErr.Error {
  175. return etcdErr.NewError(etcdErr.EcodeClientInternal, err.Error(), 0)
  176. }