client.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  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 restclient
  14. import (
  15. "fmt"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "k8s.io/kubernetes/pkg/api"
  23. "k8s.io/kubernetes/pkg/api/unversioned"
  24. "k8s.io/kubernetes/pkg/runtime"
  25. "k8s.io/kubernetes/pkg/util/flowcontrol"
  26. )
  27. const (
  28. // Environment variables: Note that the duration should be long enough that the backoff
  29. // persists for some reasonable time (i.e. 120 seconds). The typical base might be "1".
  30. envBackoffBase = "KUBE_CLIENT_BACKOFF_BASE"
  31. envBackoffDuration = "KUBE_CLIENT_BACKOFF_DURATION"
  32. )
  33. // RESTClient imposes common Kubernetes API conventions on a set of resource paths.
  34. // The baseURL is expected to point to an HTTP or HTTPS path that is the parent
  35. // of one or more resources. The server should return a decodable API resource
  36. // object, or an api.Status object which contains information about the reason for
  37. // any failure.
  38. //
  39. // Most consumers should use client.New() to get a Kubernetes API client.
  40. type RESTClient struct {
  41. // base is the root URL for all invocations of the client
  42. base *url.URL
  43. // versionedAPIPath is a path segment connecting the base URL to the resource root
  44. versionedAPIPath string
  45. // contentConfig is the information used to communicate with the server.
  46. contentConfig ContentConfig
  47. // serializers contain all serializers for undelying content type.
  48. serializers Serializers
  49. // creates BackoffManager that is passed to requests.
  50. createBackoffMgr func() BackoffManager
  51. // TODO extract this into a wrapper interface via the RESTClient interface in kubectl.
  52. Throttle flowcontrol.RateLimiter
  53. // Set specific behavior of the client. If not set http.DefaultClient will be used.
  54. Client *http.Client
  55. }
  56. type Serializers struct {
  57. Encoder runtime.Encoder
  58. Decoder runtime.Decoder
  59. StreamingSerializer runtime.Serializer
  60. Framer runtime.Framer
  61. RenegotiatedDecoder func(contentType string, params map[string]string) (runtime.Decoder, error)
  62. }
  63. // NewRESTClient creates a new RESTClient. This client performs generic REST functions
  64. // such as Get, Put, Post, and Delete on specified paths. Codec controls encoding and
  65. // decoding of responses from the server.
  66. func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ContentConfig, maxQPS float32, maxBurst int, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {
  67. base := *baseURL
  68. if !strings.HasSuffix(base.Path, "/") {
  69. base.Path += "/"
  70. }
  71. base.RawQuery = ""
  72. base.Fragment = ""
  73. if config.GroupVersion == nil {
  74. config.GroupVersion = &unversioned.GroupVersion{}
  75. }
  76. if len(config.ContentType) == 0 {
  77. config.ContentType = "application/json"
  78. }
  79. serializers, err := createSerializers(config)
  80. if err != nil {
  81. return nil, err
  82. }
  83. var throttle flowcontrol.RateLimiter
  84. if maxQPS > 0 && rateLimiter == nil {
  85. throttle = flowcontrol.NewTokenBucketRateLimiter(maxQPS, maxBurst)
  86. } else if rateLimiter != nil {
  87. throttle = rateLimiter
  88. }
  89. return &RESTClient{
  90. base: &base,
  91. versionedAPIPath: versionedAPIPath,
  92. contentConfig: config,
  93. serializers: *serializers,
  94. createBackoffMgr: readExpBackoffConfig,
  95. Throttle: throttle,
  96. Client: client,
  97. }, nil
  98. }
  99. // GetRateLimiter returns rate limier for a given client, or nil if it's called on a nil client
  100. func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {
  101. if c == nil {
  102. return nil
  103. }
  104. return c.Throttle
  105. }
  106. // readExpBackoffConfig handles the internal logic of determining what the
  107. // backoff policy is. By default if no information is available, NoBackoff.
  108. // TODO Generalize this see #17727 .
  109. func readExpBackoffConfig() BackoffManager {
  110. backoffBase := os.Getenv(envBackoffBase)
  111. backoffDuration := os.Getenv(envBackoffDuration)
  112. backoffBaseInt, errBase := strconv.ParseInt(backoffBase, 10, 64)
  113. backoffDurationInt, errDuration := strconv.ParseInt(backoffDuration, 10, 64)
  114. if errBase != nil || errDuration != nil {
  115. return &NoBackoff{}
  116. }
  117. return &URLBackoff{
  118. Backoff: flowcontrol.NewBackOff(
  119. time.Duration(backoffBaseInt)*time.Second,
  120. time.Duration(backoffDurationInt)*time.Second)}
  121. }
  122. // createSerializers creates all necessary serializers for given contentType.
  123. func createSerializers(config ContentConfig) (*Serializers, error) {
  124. negotiated := config.NegotiatedSerializer
  125. contentType := config.ContentType
  126. info, ok := negotiated.SerializerForMediaType(contentType, nil)
  127. if !ok {
  128. return nil, fmt.Errorf("serializer for %s not registered", contentType)
  129. }
  130. streamInfo, ok := negotiated.StreamingSerializerForMediaType(contentType, nil)
  131. if !ok {
  132. return nil, fmt.Errorf("streaming serializer for %s not registered", contentType)
  133. }
  134. internalGV := unversioned.GroupVersion{
  135. Group: config.GroupVersion.Group,
  136. Version: runtime.APIVersionInternal,
  137. }
  138. return &Serializers{
  139. Encoder: negotiated.EncoderForVersion(info.Serializer, *config.GroupVersion),
  140. Decoder: negotiated.DecoderToVersion(info.Serializer, internalGV),
  141. StreamingSerializer: streamInfo.Serializer,
  142. Framer: streamInfo.Framer,
  143. RenegotiatedDecoder: func(contentType string, params map[string]string) (runtime.Decoder, error) {
  144. renegotiated, ok := negotiated.SerializerForMediaType(contentType, params)
  145. if !ok {
  146. return nil, fmt.Errorf("serializer for %s not registered", contentType)
  147. }
  148. return negotiated.DecoderToVersion(renegotiated.Serializer, internalGV), nil
  149. },
  150. }, nil
  151. }
  152. // Verb begins a request with a verb (GET, POST, PUT, DELETE).
  153. //
  154. // Example usage of RESTClient's request building interface:
  155. // c, err := NewRESTClient(...)
  156. // if err != nil { ... }
  157. // resp, err := c.Verb("GET").
  158. // Path("pods").
  159. // SelectorParam("labels", "area=staging").
  160. // Timeout(10*time.Second).
  161. // Do()
  162. // if err != nil { ... }
  163. // list, ok := resp.(*api.PodList)
  164. //
  165. func (c *RESTClient) Verb(verb string) *Request {
  166. backoff := c.createBackoffMgr()
  167. if c.Client == nil {
  168. return NewRequest(nil, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle)
  169. }
  170. return NewRequest(c.Client, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle)
  171. }
  172. // Post begins a POST request. Short for c.Verb("POST").
  173. func (c *RESTClient) Post() *Request {
  174. return c.Verb("POST")
  175. }
  176. // Put begins a PUT request. Short for c.Verb("PUT").
  177. func (c *RESTClient) Put() *Request {
  178. return c.Verb("PUT")
  179. }
  180. // Patch begins a PATCH request. Short for c.Verb("Patch").
  181. func (c *RESTClient) Patch(pt api.PatchType) *Request {
  182. return c.Verb("PATCH").SetHeader("Content-Type", string(pt))
  183. }
  184. // Get begins a GET request. Short for c.Verb("GET").
  185. func (c *RESTClient) Get() *Request {
  186. return c.Verb("GET")
  187. }
  188. // Delete begins a DELETE request. Short for c.Verb("DELETE").
  189. func (c *RESTClient) Delete() *Request {
  190. return c.Verb("DELETE")
  191. }
  192. // APIVersion returns the APIVersion this RESTClient is expected to use.
  193. func (c *RESTClient) APIVersion() unversioned.GroupVersion {
  194. return *c.contentConfig.GroupVersion
  195. }