v2_client.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. stopped bool
  26. mu sync.RWMutex
  27. http.Client
  28. wg sync.WaitGroup
  29. }
  30. func newClient(tc *tls.Config) *v2client {
  31. tr := new(http.Transport)
  32. tr.TLSClientConfig = tc
  33. return &v2client{Client: http.Client{Transport: tr}}
  34. }
  35. func (c *v2client) CloseConnections() {
  36. c.stop()
  37. c.wg.Wait()
  38. tr := c.Transport.(*http.Transport)
  39. tr.CloseIdleConnections()
  40. }
  41. // CheckVersion returns true when the version check on the server returns 200.
  42. func (c *v2client) CheckVersion(url string, version int) (bool, *etcdErr.Error) {
  43. if c.runOne() == false {
  44. return false, clientError(errors.New("v2_client is stopped"))
  45. }
  46. defer c.finishOne()
  47. resp, err := c.Get(url + fmt.Sprintf("/version/%d/check", version))
  48. if err != nil {
  49. return false, clientError(err)
  50. }
  51. c.readBody(resp.Body)
  52. return resp.StatusCode == 200, nil
  53. }
  54. // GetVersion fetches the peer version of a cluster.
  55. func (c *v2client) GetVersion(url string) (int, *etcdErr.Error) {
  56. if c.runOne() == false {
  57. return 0, clientError(errors.New("v2_client is stopped"))
  58. }
  59. defer c.finishOne()
  60. resp, err := c.Get(url + "/version")
  61. if err != nil {
  62. return 0, clientError(err)
  63. }
  64. body, err := c.readBody(resp.Body)
  65. if err != nil {
  66. return 0, clientError(err)
  67. }
  68. // Parse version number.
  69. version, err := strconv.Atoi(string(body))
  70. if err != nil {
  71. return 0, clientError(err)
  72. }
  73. return version, nil
  74. }
  75. func (c *v2client) GetMachines(url string) ([]*machineMessage, *etcdErr.Error) {
  76. if c.runOne() == false {
  77. return nil, clientError(errors.New("v2_client is stopped"))
  78. }
  79. defer c.finishOne()
  80. resp, err := c.Get(url + "/v2/admin/machines/")
  81. if err != nil {
  82. return nil, clientError(err)
  83. }
  84. if resp.StatusCode != http.StatusOK {
  85. return nil, c.readErrorBody(resp.Body)
  86. }
  87. msgs := new([]*machineMessage)
  88. if uerr := c.readJSONBody(resp.Body, msgs); uerr != nil {
  89. return nil, uerr
  90. }
  91. return *msgs, nil
  92. }
  93. func (c *v2client) GetClusterConfig(url string) (*config.ClusterConfig, *etcdErr.Error) {
  94. if c.runOne() == false {
  95. return nil, clientError(errors.New("v2_client is stopped"))
  96. }
  97. defer c.finishOne()
  98. resp, err := c.Get(url + "/v2/admin/config")
  99. if err != nil {
  100. return nil, clientError(err)
  101. }
  102. if resp.StatusCode != http.StatusOK {
  103. return nil, c.readErrorBody(resp.Body)
  104. }
  105. config := new(config.ClusterConfig)
  106. if uerr := c.readJSONBody(resp.Body, config); uerr != nil {
  107. return nil, uerr
  108. }
  109. return config, nil
  110. }
  111. // AddMachine adds machine to the cluster.
  112. // The first return value is the commit index of join command.
  113. func (c *v2client) AddMachine(url string, name string, info *context) *etcdErr.Error {
  114. if c.runOne() == false {
  115. return clientError(errors.New("v2_client is stopped"))
  116. }
  117. defer c.finishOne()
  118. b, _ := json.Marshal(info)
  119. url = url + "/v2/admin/machines/" + name
  120. log.Printf("Send Join Request to %s", url)
  121. resp, err := c.put(url, b)
  122. if err != nil {
  123. return clientError(err)
  124. }
  125. if resp.StatusCode != http.StatusOK {
  126. return c.readErrorBody(resp.Body)
  127. }
  128. c.readBody(resp.Body)
  129. return nil
  130. }
  131. func (c *v2client) readErrorBody(body io.ReadCloser) *etcdErr.Error {
  132. b, err := c.readBody(body)
  133. if err != nil {
  134. return clientError(err)
  135. }
  136. uerr := &etcdErr.Error{}
  137. if err := json.Unmarshal(b, uerr); err != nil {
  138. str := strings.TrimSpace(string(b))
  139. return etcdErr.NewError(etcdErr.EcodeClientInternal, str, 0)
  140. }
  141. return nil
  142. }
  143. func (c *v2client) readJSONBody(body io.ReadCloser, val interface{}) *etcdErr.Error {
  144. if err := json.NewDecoder(body).Decode(val); err != nil {
  145. log.Printf("Error parsing join response: %v", err)
  146. return clientError(err)
  147. }
  148. c.readBody(body)
  149. return nil
  150. }
  151. func (c *v2client) readBody(body io.ReadCloser) ([]byte, error) {
  152. b, err := ioutil.ReadAll(body)
  153. body.Close()
  154. return b, err
  155. }
  156. // put sends server side PUT request.
  157. // It always follows redirects instead of stopping according to RFC 2616.
  158. func (c *v2client) put(urlStr string, body []byte) (*http.Response, error) {
  159. return c.doAlwaysFollowingRedirects("PUT", urlStr, body)
  160. }
  161. func (c *v2client) doAlwaysFollowingRedirects(method string, urlStr string, body []byte) (resp *http.Response, err error) {
  162. var req *http.Request
  163. for redirect := 0; redirect < 10; redirect++ {
  164. req, err = http.NewRequest(method, urlStr, bytes.NewBuffer(body))
  165. if err != nil {
  166. return
  167. }
  168. if resp, err = c.Do(req); err != nil {
  169. if resp != nil {
  170. resp.Body.Close()
  171. }
  172. return
  173. }
  174. if resp.StatusCode == http.StatusMovedPermanently || resp.StatusCode == http.StatusTemporaryRedirect {
  175. resp.Body.Close()
  176. if urlStr = resp.Header.Get("Location"); urlStr == "" {
  177. err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
  178. return
  179. }
  180. continue
  181. }
  182. return
  183. }
  184. err = errors.New("stopped after 10 redirects")
  185. return
  186. }
  187. func (c *v2client) runOne() bool {
  188. c.mu.RLock()
  189. defer c.mu.RUnlock()
  190. if c.stopped {
  191. return false
  192. }
  193. c.wg.Add(1)
  194. return true
  195. }
  196. func (c *v2client) finishOne() {
  197. c.wg.Done()
  198. }
  199. func (c *v2client) stop() {
  200. c.mu.Lock()
  201. c.stopped = true
  202. c.mu.Unlock()
  203. }
  204. func clientError(err error) *etcdErr.Error {
  205. return etcdErr.NewError(etcdErr.EcodeClientInternal, err.Error(), 0)
  206. }