client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. "net/http"
  16. "net/url"
  17. "os"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/client-go/util/flowcontrol"
  25. )
  26. const (
  27. // Environment variables: Note that the duration should be long enough that the backoff
  28. // persists for some reasonable time (i.e. 120 seconds). The typical base might be "1".
  29. envBackoffBase = "KUBE_CLIENT_BACKOFF_BASE"
  30. envBackoffDuration = "KUBE_CLIENT_BACKOFF_DURATION"
  31. )
  32. // Interface captures the set of operations for generically interacting with Kubernetes REST apis.
  33. type Interface interface {
  34. GetRateLimiter() flowcontrol.RateLimiter
  35. Verb(verb string) *Request
  36. Post() *Request
  37. Put() *Request
  38. Patch(pt types.PatchType) *Request
  39. Get() *Request
  40. Delete() *Request
  41. APIVersion() schema.GroupVersion
  42. }
  43. // ClientContentConfig controls how RESTClient communicates with the server.
  44. //
  45. // TODO: ContentConfig will be updated to accept a Negotiator instead of a
  46. //
  47. // NegotiatedSerializer and NegotiatedSerializer will be removed.
  48. type ClientContentConfig struct {
  49. // AcceptContentTypes specifies the types the client will accept and is optional.
  50. // If not set, ContentType will be used to define the Accept header
  51. AcceptContentTypes string
  52. // ContentType specifies the wire format used to communicate with the server.
  53. // This value will be set as the Accept header on requests made to the server if
  54. // AcceptContentTypes is not set, and as the default content type on any object
  55. // sent to the server. If not set, "application/json" is used.
  56. ContentType string
  57. // GroupVersion is the API version to talk to. Must be provided when initializing
  58. // a RESTClient directly. When initializing a Client, will be set with the default
  59. // code version. This is used as the default group version for VersionedParams.
  60. GroupVersion schema.GroupVersion
  61. // Negotiator is used for obtaining encoders and decoders for multiple
  62. // supported media types.
  63. Negotiator runtime.ClientNegotiator
  64. }
  65. // RESTClient imposes common Kubernetes API conventions on a set of resource paths.
  66. // The baseURL is expected to point to an HTTP or HTTPS path that is the parent
  67. // of one or more resources. The server should return a decodable API resource
  68. // object, or an api.Status object which contains information about the reason for
  69. // any failure.
  70. //
  71. // Most consumers should use client.New() to get a Kubernetes API client.
  72. type RESTClient struct {
  73. // base is the root URL for all invocations of the client
  74. base *url.URL
  75. // versionedAPIPath is a path segment connecting the base URL to the resource root
  76. versionedAPIPath string
  77. // content describes how a RESTClient encodes and decodes responses.
  78. content ClientContentConfig
  79. // creates BackoffManager that is passed to requests.
  80. createBackoffMgr func() BackoffManager
  81. // rateLimiter is shared among all requests created by this client unless specifically
  82. // overridden.
  83. rateLimiter flowcontrol.RateLimiter
  84. // warningHandler is shared among all requests created by this client.
  85. // If not set, defaultWarningHandler is used.
  86. warningHandler WarningHandler
  87. // Set specific behavior of the client. If not set http.DefaultClient will be used.
  88. Client *http.Client
  89. }
  90. // NewRESTClient creates a new RESTClient. This client performs generic REST functions
  91. // such as Get, Put, Post, and Delete on specified paths.
  92. func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {
  93. if len(config.ContentType) == 0 {
  94. config.ContentType = "application/json"
  95. }
  96. base := *baseURL
  97. if !strings.HasSuffix(base.Path, "/") {
  98. base.Path += "/"
  99. }
  100. base.RawQuery = ""
  101. base.Fragment = ""
  102. return &RESTClient{
  103. base: &base,
  104. versionedAPIPath: versionedAPIPath,
  105. content: config,
  106. createBackoffMgr: readExpBackoffConfig,
  107. rateLimiter: rateLimiter,
  108. Client: client,
  109. }, nil
  110. }
  111. // GetRateLimiter returns rate limiter 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.rateLimiter
  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. // Verb begins a request with a verb (GET, POST, PUT, DELETE).
  135. //
  136. // Example usage of RESTClient's request building interface:
  137. // c, err := NewRESTClient(...)
  138. // if err != nil { ... }
  139. // resp, err := c.Verb("GET").
  140. //
  141. // Path("pods").
  142. // SelectorParam("labels", "area=staging").
  143. // Timeout(10*time.Second).
  144. // Do()
  145. //
  146. // if err != nil { ... }
  147. // list, ok := resp.(*api.PodList)
  148. func (c *RESTClient) Verb(verb string) *Request {
  149. return NewRequest(c).Verb(verb)
  150. }
  151. // Post begins a POST request. Short for c.Verb("POST").
  152. func (c *RESTClient) Post() *Request {
  153. return c.Verb("POST")
  154. }
  155. // Put begins a PUT request. Short for c.Verb("PUT").
  156. func (c *RESTClient) Put() *Request {
  157. return c.Verb("PUT")
  158. }
  159. // Patch begins a PATCH request. Short for c.Verb("Patch").
  160. func (c *RESTClient) Patch(pt types.PatchType) *Request {
  161. return c.Verb("PATCH").SetHeader("Content-Type", string(pt))
  162. }
  163. // Get begins a GET request. Short for c.Verb("GET").
  164. func (c *RESTClient) Get() *Request {
  165. return c.Verb("GET")
  166. }
  167. // Delete begins a DELETE request. Short for c.Verb("DELETE").
  168. func (c *RESTClient) Delete() *Request {
  169. return c.Verb("DELETE")
  170. }
  171. // APIVersion returns the APIVersion this RESTClient is expected to use.
  172. func (c *RESTClient) APIVersion() schema.GroupVersion {
  173. return c.content.GroupVersion
  174. }