client.go 8.3 KB

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