client.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. // NegotiatedSerializer and NegotiatedSerializer will be removed.
  47. type ClientContentConfig struct {
  48. // AcceptContentTypes specifies the types the client will accept and is optional.
  49. // If not set, ContentType will be used to define the Accept header
  50. AcceptContentTypes string
  51. // ContentType specifies the wire format used to communicate with the server.
  52. // This value will be set as the Accept header on requests made to the server if
  53. // AcceptContentTypes is not set, and as the default content type on any object
  54. // sent to the server. If not set, "application/json" is used.
  55. ContentType string
  56. // GroupVersion is the API version to talk to. Must be provided when initializing
  57. // a RESTClient directly. When initializing a Client, will be set with the default
  58. // code version. This is used as the default group version for VersionedParams.
  59. GroupVersion schema.GroupVersion
  60. // Negotiator is used for obtaining encoders and decoders for multiple
  61. // supported media types.
  62. Negotiator runtime.ClientNegotiator
  63. }
  64. // RESTClient imposes common Kubernetes API conventions on a set of resource paths.
  65. // The baseURL is expected to point to an HTTP or HTTPS path that is the parent
  66. // of one or more resources. The server should return a decodable API resource
  67. // object, or an api.Status object which contains information about the reason for
  68. // any failure.
  69. //
  70. // Most consumers should use client.New() to get a Kubernetes API client.
  71. type RESTClient struct {
  72. // base is the root URL for all invocations of the client
  73. base *url.URL
  74. // versionedAPIPath is a path segment connecting the base URL to the resource root
  75. versionedAPIPath string
  76. // content describes how a RESTClient encodes and decodes responses.
  77. content ClientContentConfig
  78. // creates BackoffManager that is passed to requests.
  79. createBackoffMgr func() BackoffManager
  80. // rateLimiter is shared among all requests created by this client unless specifically
  81. // overridden.
  82. rateLimiter flowcontrol.RateLimiter
  83. // warningHandler is shared among all requests created by this client.
  84. // If not set, defaultWarningHandler is used.
  85. warningHandler WarningHandler
  86. // Set specific behavior of the client. If not set http.DefaultClient will be used.
  87. Client *http.Client
  88. }
  89. // NewRESTClient creates a new RESTClient. This client performs generic REST functions
  90. // such as Get, Put, Post, and Delete on specified paths.
  91. func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {
  92. if len(config.ContentType) == 0 {
  93. config.ContentType = "application/json"
  94. }
  95. base := *baseURL
  96. if !strings.HasSuffix(base.Path, "/") {
  97. base.Path += "/"
  98. }
  99. base.RawQuery = ""
  100. base.Fragment = ""
  101. return &RESTClient{
  102. base: &base,
  103. versionedAPIPath: versionedAPIPath,
  104. content: config,
  105. createBackoffMgr: readExpBackoffConfig,
  106. rateLimiter: rateLimiter,
  107. Client: client,
  108. }, nil
  109. }
  110. // GetRateLimiter returns rate limier for a given client, or nil if it's called on a nil client
  111. func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter {
  112. if c == nil {
  113. return nil
  114. }
  115. return c.rateLimiter
  116. }
  117. // readExpBackoffConfig handles the internal logic of determining what the
  118. // backoff policy is. By default if no information is available, NoBackoff.
  119. // TODO Generalize this see #17727 .
  120. func readExpBackoffConfig() BackoffManager {
  121. backoffBase := os.Getenv(envBackoffBase)
  122. backoffDuration := os.Getenv(envBackoffDuration)
  123. backoffBaseInt, errBase := strconv.ParseInt(backoffBase, 10, 64)
  124. backoffDurationInt, errDuration := strconv.ParseInt(backoffDuration, 10, 64)
  125. if errBase != nil || errDuration != nil {
  126. return &NoBackoff{}
  127. }
  128. return &URLBackoff{
  129. Backoff: flowcontrol.NewBackOff(
  130. time.Duration(backoffBaseInt)*time.Second,
  131. time.Duration(backoffDurationInt)*time.Second)}
  132. }
  133. // Verb begins a request with a verb (GET, POST, PUT, DELETE).
  134. //
  135. // Example usage of RESTClient's request building interface:
  136. // c, err := NewRESTClient(...)
  137. // if err != nil { ... }
  138. // resp, err := c.Verb("GET").
  139. // Path("pods").
  140. // SelectorParam("labels", "area=staging").
  141. // Timeout(10*time.Second).
  142. // Do()
  143. // if err != nil { ... }
  144. // list, ok := resp.(*api.PodList)
  145. //
  146. func (c *RESTClient) Verb(verb string) *Request {
  147. return NewRequest(c).Verb(verb)
  148. }
  149. // Post begins a POST request. Short for c.Verb("POST").
  150. func (c *RESTClient) Post() *Request {
  151. return c.Verb("POST")
  152. }
  153. // Put begins a PUT request. Short for c.Verb("PUT").
  154. func (c *RESTClient) Put() *Request {
  155. return c.Verb("PUT")
  156. }
  157. // Patch begins a PATCH request. Short for c.Verb("Patch").
  158. func (c *RESTClient) Patch(pt types.PatchType) *Request {
  159. return c.Verb("PATCH").SetHeader("Content-Type", string(pt))
  160. }
  161. // Get begins a GET request. Short for c.Verb("GET").
  162. func (c *RESTClient) Get() *Request {
  163. return c.Verb("GET")
  164. }
  165. // Delete begins a DELETE request. Short for c.Verb("DELETE").
  166. func (c *RESTClient) Delete() *Request {
  167. return c.Verb("DELETE")
  168. }
  169. // APIVersion returns the APIVersion this RESTClient is expected to use.
  170. func (c *RESTClient) APIVersion() schema.GroupVersion {
  171. return c.content.GroupVersion
  172. }