request.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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. "bytes"
  16. "context"
  17. "encoding/hex"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "mime"
  22. "net/http"
  23. "net/url"
  24. "path"
  25. "reflect"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "golang.org/x/net/http2"
  31. "k8s.io/apimachinery/pkg/api/errors"
  32. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  33. "k8s.io/apimachinery/pkg/runtime"
  34. "k8s.io/apimachinery/pkg/runtime/schema"
  35. "k8s.io/apimachinery/pkg/runtime/serializer/streaming"
  36. utilclock "k8s.io/apimachinery/pkg/util/clock"
  37. "k8s.io/apimachinery/pkg/util/net"
  38. "k8s.io/apimachinery/pkg/watch"
  39. restclientwatch "k8s.io/client-go/rest/watch"
  40. "k8s.io/client-go/tools/metrics"
  41. "k8s.io/client-go/util/flowcontrol"
  42. "k8s.io/klog/v2"
  43. )
  44. var (
  45. // longThrottleLatency defines threshold for logging requests. All requests being
  46. // throttled (via the provided rateLimiter) for more than longThrottleLatency will
  47. // be logged.
  48. longThrottleLatency = 50 * time.Millisecond
  49. // extraLongThrottleLatency defines the threshold for logging requests at log level 2.
  50. extraLongThrottleLatency = 1 * time.Second
  51. )
  52. // HTTPClient is an interface for testing a request object.
  53. type HTTPClient interface {
  54. Do(req *http.Request) (*http.Response, error)
  55. }
  56. // ResponseWrapper is an interface for getting a response.
  57. // The response may be either accessed as a raw data (the whole output is put into memory) or as a stream.
  58. type ResponseWrapper interface {
  59. DoRaw(context.Context) ([]byte, error)
  60. Stream(context.Context) (io.ReadCloser, error)
  61. }
  62. // RequestConstructionError is returned when there's an error assembling a request.
  63. type RequestConstructionError struct {
  64. Err error
  65. }
  66. // Error returns a textual description of 'r'.
  67. func (r *RequestConstructionError) Error() string {
  68. return fmt.Sprintf("request construction error: '%v'", r.Err)
  69. }
  70. var noBackoff = &NoBackoff{}
  71. // Request allows for building up a request to a server in a chained fashion.
  72. // Any errors are stored until the end of your call, so you only have to
  73. // check once.
  74. type Request struct {
  75. c *RESTClient
  76. warningHandler WarningHandler
  77. rateLimiter flowcontrol.RateLimiter
  78. backoff BackoffManager
  79. timeout time.Duration
  80. maxRetries int
  81. // generic components accessible via method setters
  82. verb string
  83. pathPrefix string
  84. subpath string
  85. params url.Values
  86. headers http.Header
  87. // structural elements of the request that are part of the Kubernetes API conventions
  88. namespace string
  89. namespaceSet bool
  90. resource string
  91. resourceName string
  92. subresource string
  93. // output
  94. err error
  95. body io.Reader
  96. }
  97. // NewRequest creates a new request helper object for accessing runtime.Objects on a server.
  98. func NewRequest(c *RESTClient) *Request {
  99. var backoff BackoffManager
  100. if c.createBackoffMgr != nil {
  101. backoff = c.createBackoffMgr()
  102. }
  103. if backoff == nil {
  104. backoff = noBackoff
  105. }
  106. var pathPrefix string
  107. if c.base != nil {
  108. pathPrefix = path.Join("/", c.base.Path, c.versionedAPIPath)
  109. } else {
  110. pathPrefix = path.Join("/", c.versionedAPIPath)
  111. }
  112. var timeout time.Duration
  113. if c.Client != nil {
  114. timeout = c.Client.Timeout
  115. }
  116. r := &Request{
  117. c: c,
  118. rateLimiter: c.rateLimiter,
  119. backoff: backoff,
  120. timeout: timeout,
  121. pathPrefix: pathPrefix,
  122. maxRetries: 10,
  123. warningHandler: c.warningHandler,
  124. }
  125. switch {
  126. case len(c.content.AcceptContentTypes) > 0:
  127. r.SetHeader("Accept", c.content.AcceptContentTypes)
  128. case len(c.content.ContentType) > 0:
  129. r.SetHeader("Accept", c.content.ContentType+", */*")
  130. }
  131. return r
  132. }
  133. // NewRequestWithClient creates a Request with an embedded RESTClient for use in test scenarios.
  134. func NewRequestWithClient(base *url.URL, versionedAPIPath string, content ClientContentConfig, client *http.Client) *Request {
  135. return NewRequest(&RESTClient{
  136. base: base,
  137. versionedAPIPath: versionedAPIPath,
  138. content: content,
  139. Client: client,
  140. })
  141. }
  142. // Verb sets the verb this request will use.
  143. func (r *Request) Verb(verb string) *Request {
  144. r.verb = verb
  145. return r
  146. }
  147. // Prefix adds segments to the relative beginning to the request path. These
  148. // items will be placed before the optional Namespace, Resource, or Name sections.
  149. // Setting AbsPath will clear any previously set Prefix segments
  150. func (r *Request) Prefix(segments ...string) *Request {
  151. if r.err != nil {
  152. return r
  153. }
  154. r.pathPrefix = path.Join(r.pathPrefix, path.Join(segments...))
  155. return r
  156. }
  157. // Suffix appends segments to the end of the path. These items will be placed after the prefix and optional
  158. // Namespace, Resource, or Name sections.
  159. func (r *Request) Suffix(segments ...string) *Request {
  160. if r.err != nil {
  161. return r
  162. }
  163. r.subpath = path.Join(r.subpath, path.Join(segments...))
  164. return r
  165. }
  166. // Resource sets the resource to access (<resource>/[ns/<namespace>/]<name>)
  167. func (r *Request) Resource(resource string) *Request {
  168. if r.err != nil {
  169. return r
  170. }
  171. if len(r.resource) != 0 {
  172. r.err = fmt.Errorf("resource already set to %q, cannot change to %q", r.resource, resource)
  173. return r
  174. }
  175. if msgs := IsValidPathSegmentName(resource); len(msgs) != 0 {
  176. r.err = fmt.Errorf("invalid resource %q: %v", resource, msgs)
  177. return r
  178. }
  179. r.resource = resource
  180. return r
  181. }
  182. // BackOff sets the request's backoff manager to the one specified,
  183. // or defaults to the stub implementation if nil is provided
  184. func (r *Request) BackOff(manager BackoffManager) *Request {
  185. if manager == nil {
  186. r.backoff = &NoBackoff{}
  187. return r
  188. }
  189. r.backoff = manager
  190. return r
  191. }
  192. // WarningHandler sets the handler this client uses when warning headers are encountered.
  193. // If set to nil, this client will use the default warning handler (see SetDefaultWarningHandler).
  194. func (r *Request) WarningHandler(handler WarningHandler) *Request {
  195. r.warningHandler = handler
  196. return r
  197. }
  198. // Throttle receives a rate-limiter and sets or replaces an existing request limiter
  199. func (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request {
  200. r.rateLimiter = limiter
  201. return r
  202. }
  203. // SubResource sets a sub-resource path which can be multiple segments after the resource
  204. // name but before the suffix.
  205. func (r *Request) SubResource(subresources ...string) *Request {
  206. if r.err != nil {
  207. return r
  208. }
  209. subresource := path.Join(subresources...)
  210. if len(r.subresource) != 0 {
  211. r.err = fmt.Errorf("subresource already set to %q, cannot change to %q", r.resource, subresource)
  212. return r
  213. }
  214. for _, s := range subresources {
  215. if msgs := IsValidPathSegmentName(s); len(msgs) != 0 {
  216. r.err = fmt.Errorf("invalid subresource %q: %v", s, msgs)
  217. return r
  218. }
  219. }
  220. r.subresource = subresource
  221. return r
  222. }
  223. // Name sets the name of a resource to access (<resource>/[ns/<namespace>/]<name>)
  224. func (r *Request) Name(resourceName string) *Request {
  225. if r.err != nil {
  226. return r
  227. }
  228. if len(resourceName) == 0 {
  229. r.err = fmt.Errorf("resource name may not be empty")
  230. return r
  231. }
  232. if len(r.resourceName) != 0 {
  233. r.err = fmt.Errorf("resource name already set to %q, cannot change to %q", r.resourceName, resourceName)
  234. return r
  235. }
  236. if msgs := IsValidPathSegmentName(resourceName); len(msgs) != 0 {
  237. r.err = fmt.Errorf("invalid resource name %q: %v", resourceName, msgs)
  238. return r
  239. }
  240. r.resourceName = resourceName
  241. return r
  242. }
  243. // Namespace applies the namespace scope to a request (<resource>/[ns/<namespace>/]<name>)
  244. func (r *Request) Namespace(namespace string) *Request {
  245. if r.err != nil {
  246. return r
  247. }
  248. if r.namespaceSet {
  249. r.err = fmt.Errorf("namespace already set to %q, cannot change to %q", r.namespace, namespace)
  250. return r
  251. }
  252. if msgs := IsValidPathSegmentName(namespace); len(msgs) != 0 {
  253. r.err = fmt.Errorf("invalid namespace %q: %v", namespace, msgs)
  254. return r
  255. }
  256. r.namespaceSet = true
  257. r.namespace = namespace
  258. return r
  259. }
  260. // NamespaceIfScoped is a convenience function to set a namespace if scoped is true
  261. func (r *Request) NamespaceIfScoped(namespace string, scoped bool) *Request {
  262. if scoped {
  263. return r.Namespace(namespace)
  264. }
  265. return r
  266. }
  267. // AbsPath overwrites an existing path with the segments provided. Trailing slashes are preserved
  268. // when a single segment is passed.
  269. func (r *Request) AbsPath(segments ...string) *Request {
  270. if r.err != nil {
  271. return r
  272. }
  273. r.pathPrefix = path.Join(r.c.base.Path, path.Join(segments...))
  274. if len(segments) == 1 && (len(r.c.base.Path) > 1 || len(segments[0]) > 1) && strings.HasSuffix(segments[0], "/") {
  275. // preserve any trailing slashes for legacy behavior
  276. r.pathPrefix += "/"
  277. }
  278. return r
  279. }
  280. // RequestURI overwrites existing path and parameters with the value of the provided server relative
  281. // URI.
  282. func (r *Request) RequestURI(uri string) *Request {
  283. if r.err != nil {
  284. return r
  285. }
  286. locator, err := url.Parse(uri)
  287. if err != nil {
  288. r.err = err
  289. return r
  290. }
  291. r.pathPrefix = locator.Path
  292. if len(locator.Query()) > 0 {
  293. if r.params == nil {
  294. r.params = make(url.Values)
  295. }
  296. for k, v := range locator.Query() {
  297. r.params[k] = v
  298. }
  299. }
  300. return r
  301. }
  302. // Param creates a query parameter with the given string value.
  303. func (r *Request) Param(paramName, s string) *Request {
  304. if r.err != nil {
  305. return r
  306. }
  307. return r.setParam(paramName, s)
  308. }
  309. // VersionedParams will take the provided object, serialize it to a map[string][]string using the
  310. // implicit RESTClient API version and the default parameter codec, and then add those as parameters
  311. // to the request. Use this to provide versioned query parameters from client libraries.
  312. // VersionedParams will not write query parameters that have omitempty set and are empty. If a
  313. // parameter has already been set it is appended to (Params and VersionedParams are additive).
  314. func (r *Request) VersionedParams(obj runtime.Object, codec runtime.ParameterCodec) *Request {
  315. return r.SpecificallyVersionedParams(obj, codec, r.c.content.GroupVersion)
  316. }
  317. func (r *Request) SpecificallyVersionedParams(obj runtime.Object, codec runtime.ParameterCodec, version schema.GroupVersion) *Request {
  318. if r.err != nil {
  319. return r
  320. }
  321. params, err := codec.EncodeParameters(obj, version)
  322. if err != nil {
  323. r.err = err
  324. return r
  325. }
  326. for k, v := range params {
  327. if r.params == nil {
  328. r.params = make(url.Values)
  329. }
  330. r.params[k] = append(r.params[k], v...)
  331. }
  332. return r
  333. }
  334. func (r *Request) setParam(paramName, value string) *Request {
  335. if r.params == nil {
  336. r.params = make(url.Values)
  337. }
  338. r.params[paramName] = append(r.params[paramName], value)
  339. return r
  340. }
  341. func (r *Request) SetHeader(key string, values ...string) *Request {
  342. if r.headers == nil {
  343. r.headers = http.Header{}
  344. }
  345. r.headers.Del(key)
  346. for _, value := range values {
  347. r.headers.Add(key, value)
  348. }
  349. return r
  350. }
  351. // Timeout makes the request use the given duration as an overall timeout for the
  352. // request. Additionally, if set passes the value as "timeout" parameter in URL.
  353. func (r *Request) Timeout(d time.Duration) *Request {
  354. if r.err != nil {
  355. return r
  356. }
  357. r.timeout = d
  358. return r
  359. }
  360. // MaxRetries makes the request use the given integer as a ceiling of retrying upon receiving
  361. // "Retry-After" headers and 429 status-code in the response. The default is 10 unless this
  362. // function is specifically called with a different value.
  363. // A zero maxRetries prevent it from doing retires and return an error immediately.
  364. func (r *Request) MaxRetries(maxRetries int) *Request {
  365. if maxRetries < 0 {
  366. maxRetries = 0
  367. }
  368. r.maxRetries = maxRetries
  369. return r
  370. }
  371. // Body makes the request use obj as the body. Optional.
  372. // If obj is a string, try to read a file of that name.
  373. // If obj is a []byte, send it directly.
  374. // If obj is an io.Reader, use it directly.
  375. // If obj is a runtime.Object, marshal it correctly, and set Content-Type header.
  376. // If obj is a runtime.Object and nil, do nothing.
  377. // Otherwise, set an error.
  378. func (r *Request) Body(obj interface{}) *Request {
  379. if r.err != nil {
  380. return r
  381. }
  382. switch t := obj.(type) {
  383. case string:
  384. data, err := ioutil.ReadFile(t)
  385. if err != nil {
  386. r.err = err
  387. return r
  388. }
  389. glogBody("Request Body", data)
  390. r.body = bytes.NewReader(data)
  391. case []byte:
  392. glogBody("Request Body", t)
  393. r.body = bytes.NewReader(t)
  394. case io.Reader:
  395. r.body = t
  396. case runtime.Object:
  397. // callers may pass typed interface pointers, therefore we must check nil with reflection
  398. if reflect.ValueOf(t).IsNil() {
  399. return r
  400. }
  401. encoder, err := r.c.content.Negotiator.Encoder(r.c.content.ContentType, nil)
  402. if err != nil {
  403. r.err = err
  404. return r
  405. }
  406. data, err := runtime.Encode(encoder, t)
  407. if err != nil {
  408. r.err = err
  409. return r
  410. }
  411. glogBody("Request Body", data)
  412. r.body = bytes.NewReader(data)
  413. r.SetHeader("Content-Type", r.c.content.ContentType)
  414. default:
  415. r.err = fmt.Errorf("unknown type used for body: %+v", obj)
  416. }
  417. return r
  418. }
  419. // URL returns the current working URL.
  420. func (r *Request) URL() *url.URL {
  421. p := r.pathPrefix
  422. if r.namespaceSet && len(r.namespace) > 0 {
  423. p = path.Join(p, "namespaces", r.namespace)
  424. }
  425. if len(r.resource) != 0 {
  426. p = path.Join(p, strings.ToLower(r.resource))
  427. }
  428. // Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compatibility if nothing was changed
  429. if len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 {
  430. p = path.Join(p, r.resourceName, r.subresource, r.subpath)
  431. }
  432. finalURL := &url.URL{}
  433. if r.c.base != nil {
  434. *finalURL = *r.c.base
  435. }
  436. finalURL.Path = p
  437. query := url.Values{}
  438. for key, values := range r.params {
  439. for _, value := range values {
  440. query.Add(key, value)
  441. }
  442. }
  443. // timeout is handled specially here.
  444. if r.timeout != 0 {
  445. query.Set("timeout", r.timeout.String())
  446. }
  447. finalURL.RawQuery = query.Encode()
  448. return finalURL
  449. }
  450. // finalURLTemplate is similar to URL(), but will make all specific parameter values equal
  451. // - instead of name or namespace, "{name}" and "{namespace}" will be used, and all query
  452. // parameters will be reset. This creates a copy of the url so as not to change the
  453. // underlying object.
  454. func (r Request) finalURLTemplate() url.URL {
  455. newParams := url.Values{}
  456. v := []string{"{value}"}
  457. for k := range r.params {
  458. newParams[k] = v
  459. }
  460. r.params = newParams
  461. url := r.URL()
  462. segments := strings.Split(r.URL().Path, "/")
  463. groupIndex := 0
  464. index := 0
  465. if r.URL() != nil && r.c.base != nil && strings.Contains(r.URL().Path, r.c.base.Path) {
  466. groupIndex += len(strings.Split(r.c.base.Path, "/"))
  467. }
  468. if groupIndex >= len(segments) {
  469. return *url
  470. }
  471. const CoreGroupPrefix = "api"
  472. const NamedGroupPrefix = "apis"
  473. isCoreGroup := segments[groupIndex] == CoreGroupPrefix
  474. isNamedGroup := segments[groupIndex] == NamedGroupPrefix
  475. if isCoreGroup {
  476. // checking the case of core group with /api/v1/... format
  477. index = groupIndex + 2
  478. } else if isNamedGroup {
  479. // checking the case of named group with /apis/apps/v1/... format
  480. index = groupIndex + 3
  481. } else {
  482. // this should not happen that the only two possibilities are /api... and /apis..., just want to put an
  483. // outlet here in case more API groups are added in future if ever possible:
  484. // https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups
  485. // if a wrong API groups name is encountered, return the {prefix} for url.Path
  486. url.Path = "/{prefix}"
  487. url.RawQuery = ""
  488. return *url
  489. }
  490. //switch segLength := len(segments) - index; segLength {
  491. switch {
  492. // case len(segments) - index == 1:
  493. // resource (with no name) do nothing
  494. case len(segments)-index == 2:
  495. // /$RESOURCE/$NAME: replace $NAME with {name}
  496. segments[index+1] = "{name}"
  497. case len(segments)-index == 3:
  498. if segments[index+2] == "finalize" || segments[index+2] == "status" {
  499. // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
  500. segments[index+1] = "{name}"
  501. } else {
  502. // /namespace/$NAMESPACE/$RESOURCE: replace $NAMESPACE with {namespace}
  503. segments[index+1] = "{namespace}"
  504. }
  505. case len(segments)-index >= 4:
  506. segments[index+1] = "{namespace}"
  507. // /namespace/$NAMESPACE/$RESOURCE/$NAME: replace $NAMESPACE with {namespace}, $NAME with {name}
  508. if segments[index+3] != "finalize" && segments[index+3] != "status" {
  509. // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
  510. segments[index+3] = "{name}"
  511. }
  512. }
  513. url.Path = path.Join(segments...)
  514. return *url
  515. }
  516. func (r *Request) tryThrottle(ctx context.Context) error {
  517. if r.rateLimiter == nil {
  518. return nil
  519. }
  520. now := time.Now()
  521. err := r.rateLimiter.Wait(ctx)
  522. latency := time.Since(now)
  523. if latency > longThrottleLatency {
  524. klog.V(3).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String())
  525. }
  526. if latency > extraLongThrottleLatency {
  527. // If the rate limiter latency is very high, the log message should be printed at a higher log level,
  528. // but we use a throttled logger to prevent spamming.
  529. globalThrottledLogger.Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String())
  530. }
  531. metrics.RateLimiterLatency.Observe(r.verb, r.finalURLTemplate(), latency)
  532. return err
  533. }
  534. type throttleSettings struct {
  535. logLevel klog.Level
  536. minLogInterval time.Duration
  537. lastLogTime time.Time
  538. lock sync.RWMutex
  539. }
  540. type throttledLogger struct {
  541. clock utilclock.PassiveClock
  542. settings []*throttleSettings
  543. }
  544. var globalThrottledLogger = &throttledLogger{
  545. clock: utilclock.RealClock{},
  546. settings: []*throttleSettings{
  547. {
  548. logLevel: 2,
  549. minLogInterval: 1 * time.Second,
  550. }, {
  551. logLevel: 0,
  552. minLogInterval: 10 * time.Second,
  553. },
  554. },
  555. }
  556. func (b *throttledLogger) attemptToLog() (klog.Level, bool) {
  557. for _, setting := range b.settings {
  558. if bool(klog.V(setting.logLevel).Enabled()) {
  559. // Return early without write locking if possible.
  560. if func() bool {
  561. setting.lock.RLock()
  562. defer setting.lock.RUnlock()
  563. return b.clock.Since(setting.lastLogTime) >= setting.minLogInterval
  564. }() {
  565. setting.lock.Lock()
  566. defer setting.lock.Unlock()
  567. if b.clock.Since(setting.lastLogTime) >= setting.minLogInterval {
  568. setting.lastLogTime = b.clock.Now()
  569. return setting.logLevel, true
  570. }
  571. }
  572. return -1, false
  573. }
  574. }
  575. return -1, false
  576. }
  577. // Infof will write a log message at each logLevel specified by the reciever's throttleSettings
  578. // as long as it hasn't written a log message more recently than minLogInterval.
  579. func (b *throttledLogger) Infof(message string, args ...interface{}) {
  580. if logLevel, ok := b.attemptToLog(); ok {
  581. klog.V(logLevel).Infof(message, args...)
  582. }
  583. }
  584. // Watch attempts to begin watching the requested location.
  585. // Returns a watch.Interface, or an error.
  586. func (r *Request) Watch(ctx context.Context) (watch.Interface, error) {
  587. // We specifically don't want to rate limit watches, so we
  588. // don't use r.rateLimiter here.
  589. if r.err != nil {
  590. return nil, r.err
  591. }
  592. url := r.URL().String()
  593. req, err := http.NewRequest(r.verb, url, r.body)
  594. if err != nil {
  595. return nil, err
  596. }
  597. req = req.WithContext(ctx)
  598. req.Header = r.headers
  599. client := r.c.Client
  600. if client == nil {
  601. client = http.DefaultClient
  602. }
  603. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  604. resp, err := client.Do(req)
  605. updateURLMetrics(r, resp, err)
  606. if r.c.base != nil {
  607. if err != nil {
  608. r.backoff.UpdateBackoff(r.c.base, err, 0)
  609. } else {
  610. r.backoff.UpdateBackoff(r.c.base, err, resp.StatusCode)
  611. }
  612. }
  613. if err != nil {
  614. // The watch stream mechanism handles many common partial data errors, so closed
  615. // connections can be retried in many cases.
  616. if net.IsProbableEOF(err) || net.IsTimeout(err) {
  617. return watch.NewEmptyWatch(), nil
  618. }
  619. return nil, err
  620. }
  621. if resp.StatusCode != http.StatusOK {
  622. defer resp.Body.Close()
  623. if result := r.transformResponse(resp, req); result.err != nil {
  624. return nil, result.err
  625. }
  626. return nil, fmt.Errorf("for request %s, got status: %v", url, resp.StatusCode)
  627. }
  628. contentType := resp.Header.Get("Content-Type")
  629. mediaType, params, err := mime.ParseMediaType(contentType)
  630. if err != nil {
  631. klog.V(4).Infof("Unexpected content type from the server: %q: %v", contentType, err)
  632. }
  633. objectDecoder, streamingSerializer, framer, err := r.c.content.Negotiator.StreamDecoder(mediaType, params)
  634. if err != nil {
  635. return nil, err
  636. }
  637. handleWarnings(resp.Header, r.warningHandler)
  638. frameReader := framer.NewFrameReader(resp.Body)
  639. watchEventDecoder := streaming.NewDecoder(frameReader, streamingSerializer)
  640. return watch.NewStreamWatcher(
  641. restclientwatch.NewDecoder(watchEventDecoder, objectDecoder),
  642. // use 500 to indicate that the cause of the error is unknown - other error codes
  643. // are more specific to HTTP interactions, and set a reason
  644. errors.NewClientErrorReporter(http.StatusInternalServerError, r.verb, "ClientWatchDecoding"),
  645. ), nil
  646. }
  647. // updateURLMetrics is a convenience function for pushing metrics.
  648. // It also handles corner cases for incomplete/invalid request data.
  649. func updateURLMetrics(req *Request, resp *http.Response, err error) {
  650. url := "none"
  651. if req.c.base != nil {
  652. url = req.c.base.Host
  653. }
  654. // Errors can be arbitrary strings. Unbound label cardinality is not suitable for a metric
  655. // system so we just report them as `<error>`.
  656. if err != nil {
  657. metrics.RequestResult.Increment("<error>", req.verb, url)
  658. } else {
  659. //Metrics for failure codes
  660. metrics.RequestResult.Increment(strconv.Itoa(resp.StatusCode), req.verb, url)
  661. }
  662. }
  663. // Stream formats and executes the request, and offers streaming of the response.
  664. // Returns io.ReadCloser which could be used for streaming of the response, or an error
  665. // Any non-2xx http status code causes an error. If we get a non-2xx code, we try to convert the body into an APIStatus object.
  666. // If we can, we return that as an error. Otherwise, we create an error that lists the http status and the content of the response.
  667. func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) {
  668. if r.err != nil {
  669. return nil, r.err
  670. }
  671. if err := r.tryThrottle(ctx); err != nil {
  672. return nil, err
  673. }
  674. url := r.URL().String()
  675. req, err := http.NewRequest(r.verb, url, nil)
  676. if err != nil {
  677. return nil, err
  678. }
  679. if r.body != nil {
  680. req.Body = ioutil.NopCloser(r.body)
  681. }
  682. req = req.WithContext(ctx)
  683. req.Header = r.headers
  684. client := r.c.Client
  685. if client == nil {
  686. client = http.DefaultClient
  687. }
  688. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  689. resp, err := client.Do(req)
  690. updateURLMetrics(r, resp, err)
  691. if r.c.base != nil {
  692. if err != nil {
  693. r.backoff.UpdateBackoff(r.URL(), err, 0)
  694. } else {
  695. r.backoff.UpdateBackoff(r.URL(), err, resp.StatusCode)
  696. }
  697. }
  698. if err != nil {
  699. return nil, err
  700. }
  701. switch {
  702. case (resp.StatusCode >= 200) && (resp.StatusCode < 300):
  703. handleWarnings(resp.Header, r.warningHandler)
  704. return resp.Body, nil
  705. default:
  706. // ensure we close the body before returning the error
  707. defer resp.Body.Close()
  708. result := r.transformResponse(resp, req)
  709. err := result.Error()
  710. if err == nil {
  711. err = fmt.Errorf("%d while accessing %v: %s", result.statusCode, url, string(result.body))
  712. }
  713. return nil, err
  714. }
  715. }
  716. // requestPreflightCheck looks for common programmer errors on Request.
  717. //
  718. // We tackle here two programmer mistakes. The first one is to try to create
  719. // something(POST) using an empty string as namespace with namespaceSet as
  720. // true. If namespaceSet is true then namespace should also be defined. The
  721. // second mistake is, when under the same circumstances, the programmer tries
  722. // to GET, PUT or DELETE a named resource(resourceName != ""), again, if
  723. // namespaceSet is true then namespace must not be empty.
  724. func (r *Request) requestPreflightCheck() error {
  725. if !r.namespaceSet {
  726. return nil
  727. }
  728. if len(r.namespace) > 0 {
  729. return nil
  730. }
  731. switch r.verb {
  732. case "POST":
  733. return fmt.Errorf("an empty namespace may not be set during creation")
  734. case "GET", "PUT", "DELETE":
  735. if len(r.resourceName) > 0 {
  736. return fmt.Errorf("an empty namespace may not be set when a resource name is provided")
  737. }
  738. }
  739. return nil
  740. }
  741. // request connects to the server and invokes the provided function when a server response is
  742. // received. It handles retry behavior and up front validation of requests. It will invoke
  743. // fn at most once. It will return an error if a problem occurred prior to connecting to the
  744. // server - the provided function is responsible for handling server errors.
  745. func (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Response)) error {
  746. //Metrics for total request latency
  747. start := time.Now()
  748. defer func() {
  749. metrics.RequestLatency.Observe(r.verb, r.finalURLTemplate(), time.Since(start))
  750. }()
  751. if r.err != nil {
  752. klog.V(4).Infof("Error in request: %v", r.err)
  753. return r.err
  754. }
  755. if err := r.requestPreflightCheck(); err != nil {
  756. return err
  757. }
  758. client := r.c.Client
  759. if client == nil {
  760. client = http.DefaultClient
  761. }
  762. // Throttle the first try before setting up the timeout configured on the
  763. // client. We don't want a throttled client to return timeouts to callers
  764. // before it makes a single request.
  765. if err := r.tryThrottle(ctx); err != nil {
  766. return err
  767. }
  768. if r.timeout > 0 {
  769. var cancel context.CancelFunc
  770. ctx, cancel = context.WithTimeout(ctx, r.timeout)
  771. defer cancel()
  772. }
  773. // Right now we make about ten retry attempts if we get a Retry-After response.
  774. retries := 0
  775. for {
  776. url := r.URL().String()
  777. req, err := http.NewRequest(r.verb, url, r.body)
  778. if err != nil {
  779. return err
  780. }
  781. req = req.WithContext(ctx)
  782. req.Header = r.headers
  783. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  784. if retries > 0 {
  785. // We are retrying the request that we already send to apiserver
  786. // at least once before.
  787. // This request should also be throttled with the client-internal rate limiter.
  788. if err := r.tryThrottle(ctx); err != nil {
  789. return err
  790. }
  791. }
  792. resp, err := client.Do(req)
  793. updateURLMetrics(r, resp, err)
  794. if err != nil {
  795. r.backoff.UpdateBackoff(r.URL(), err, 0)
  796. } else {
  797. r.backoff.UpdateBackoff(r.URL(), err, resp.StatusCode)
  798. }
  799. if err != nil {
  800. // "Connection reset by peer" or "apiserver is shutting down" are usually a transient errors.
  801. // Thus in case of "GET" operations, we simply retry it.
  802. // We are not automatically retrying "write" operations, as
  803. // they are not idempotent.
  804. if r.verb != "GET" {
  805. return err
  806. }
  807. // For connection errors and apiserver shutdown errors retry.
  808. if net.IsConnectionReset(err) || net.IsProbableEOF(err) {
  809. // For the purpose of retry, we set the artificial "retry-after" response.
  810. // TODO: Should we clean the original response if it exists?
  811. resp = &http.Response{
  812. StatusCode: http.StatusInternalServerError,
  813. Header: http.Header{"Retry-After": []string{"1"}},
  814. Body: ioutil.NopCloser(bytes.NewReader([]byte{})),
  815. }
  816. } else {
  817. return err
  818. }
  819. }
  820. done := func() bool {
  821. // Ensure the response body is fully read and closed
  822. // before we reconnect, so that we reuse the same TCP
  823. // connection.
  824. defer func() {
  825. const maxBodySlurpSize = 2 << 10
  826. if resp.ContentLength <= maxBodySlurpSize {
  827. io.Copy(ioutil.Discard, &io.LimitedReader{R: resp.Body, N: maxBodySlurpSize})
  828. }
  829. resp.Body.Close()
  830. }()
  831. retries++
  832. if seconds, wait := checkWait(resp); wait && retries <= r.maxRetries {
  833. if seeker, ok := r.body.(io.Seeker); ok && r.body != nil {
  834. _, err := seeker.Seek(0, 0)
  835. if err != nil {
  836. klog.V(4).Infof("Could not retry request, can't Seek() back to beginning of body for %T", r.body)
  837. fn(req, resp)
  838. return true
  839. }
  840. }
  841. klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", seconds, retries, url)
  842. r.backoff.Sleep(time.Duration(seconds) * time.Second)
  843. return false
  844. }
  845. fn(req, resp)
  846. return true
  847. }()
  848. if done {
  849. return nil
  850. }
  851. }
  852. }
  853. // Do formats and executes the request. Returns a Result object for easy response
  854. // processing.
  855. //
  856. // Error type:
  857. // * If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError
  858. // * http.Client.Do errors are returned directly.
  859. func (r *Request) Do(ctx context.Context) Result {
  860. var result Result
  861. err := r.request(ctx, func(req *http.Request, resp *http.Response) {
  862. result = r.transformResponse(resp, req)
  863. })
  864. if err != nil {
  865. return Result{err: err}
  866. }
  867. return result
  868. }
  869. // DoRaw executes the request but does not process the response body.
  870. func (r *Request) DoRaw(ctx context.Context) ([]byte, error) {
  871. var result Result
  872. err := r.request(ctx, func(req *http.Request, resp *http.Response) {
  873. result.body, result.err = ioutil.ReadAll(resp.Body)
  874. glogBody("Response Body", result.body)
  875. if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
  876. result.err = r.transformUnstructuredResponseError(resp, req, result.body)
  877. }
  878. })
  879. if err != nil {
  880. return nil, err
  881. }
  882. return result.body, result.err
  883. }
  884. // transformResponse converts an API response into a structured API object
  885. func (r *Request) transformResponse(resp *http.Response, req *http.Request) Result {
  886. var body []byte
  887. if resp.Body != nil {
  888. data, err := ioutil.ReadAll(resp.Body)
  889. switch err.(type) {
  890. case nil:
  891. body = data
  892. case http2.StreamError:
  893. // This is trying to catch the scenario that the server may close the connection when sending the
  894. // response body. This can be caused by server timeout due to a slow network connection.
  895. // TODO: Add test for this. Steps may be:
  896. // 1. client-go (or kubectl) sends a GET request.
  897. // 2. Apiserver sends back the headers and then part of the body
  898. // 3. Apiserver closes connection.
  899. // 4. client-go should catch this and return an error.
  900. klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err)
  901. streamErr := fmt.Errorf("stream error when reading response body, may be caused by closed connection. Please retry. Original error: %v", err)
  902. return Result{
  903. err: streamErr,
  904. }
  905. default:
  906. klog.Errorf("Unexpected error when reading response body: %v", err)
  907. unexpectedErr := fmt.Errorf("unexpected error when reading response body. Please retry. Original error: %v", err)
  908. return Result{
  909. err: unexpectedErr,
  910. }
  911. }
  912. }
  913. glogBody("Response Body", body)
  914. // verify the content type is accurate
  915. var decoder runtime.Decoder
  916. contentType := resp.Header.Get("Content-Type")
  917. if len(contentType) == 0 {
  918. contentType = r.c.content.ContentType
  919. }
  920. if len(contentType) > 0 {
  921. var err error
  922. mediaType, params, err := mime.ParseMediaType(contentType)
  923. if err != nil {
  924. return Result{err: errors.NewInternalError(err)}
  925. }
  926. decoder, err = r.c.content.Negotiator.Decoder(mediaType, params)
  927. if err != nil {
  928. // if we fail to negotiate a decoder, treat this as an unstructured error
  929. switch {
  930. case resp.StatusCode == http.StatusSwitchingProtocols:
  931. // no-op, we've been upgraded
  932. case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
  933. return Result{err: r.transformUnstructuredResponseError(resp, req, body)}
  934. }
  935. return Result{
  936. body: body,
  937. contentType: contentType,
  938. statusCode: resp.StatusCode,
  939. warnings: handleWarnings(resp.Header, r.warningHandler),
  940. }
  941. }
  942. }
  943. switch {
  944. case resp.StatusCode == http.StatusSwitchingProtocols:
  945. // no-op, we've been upgraded
  946. case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
  947. // calculate an unstructured error from the response which the Result object may use if the caller
  948. // did not return a structured error.
  949. retryAfter, _ := retryAfterSeconds(resp)
  950. err := r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
  951. return Result{
  952. body: body,
  953. contentType: contentType,
  954. statusCode: resp.StatusCode,
  955. decoder: decoder,
  956. err: err,
  957. warnings: handleWarnings(resp.Header, r.warningHandler),
  958. }
  959. }
  960. return Result{
  961. body: body,
  962. contentType: contentType,
  963. statusCode: resp.StatusCode,
  964. decoder: decoder,
  965. warnings: handleWarnings(resp.Header, r.warningHandler),
  966. }
  967. }
  968. // truncateBody decides if the body should be truncated, based on the glog Verbosity.
  969. func truncateBody(body string) string {
  970. max := 0
  971. switch {
  972. case bool(klog.V(10).Enabled()):
  973. return body
  974. case bool(klog.V(9).Enabled()):
  975. max = 10240
  976. case bool(klog.V(8).Enabled()):
  977. max = 1024
  978. }
  979. if len(body) <= max {
  980. return body
  981. }
  982. return body[:max] + fmt.Sprintf(" [truncated %d chars]", len(body)-max)
  983. }
  984. // glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against
  985. // allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
  986. // whether the body is printable.
  987. func glogBody(prefix string, body []byte) {
  988. if klog.V(8).Enabled() {
  989. if bytes.IndexFunc(body, func(r rune) bool {
  990. return r < 0x0a
  991. }) != -1 {
  992. klog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body)))
  993. } else {
  994. klog.Infof("%s: %s", prefix, truncateBody(string(body)))
  995. }
  996. }
  997. }
  998. // maxUnstructuredResponseTextBytes is an upper bound on how much output to include in the unstructured error.
  999. const maxUnstructuredResponseTextBytes = 2048
  1000. // transformUnstructuredResponseError handles an error from the server that is not in a structured form.
  1001. // It is expected to transform any response that is not recognizable as a clear server sent error from the
  1002. // K8S API using the information provided with the request. In practice, HTTP proxies and client libraries
  1003. // introduce a level of uncertainty to the responses returned by servers that in common use result in
  1004. // unexpected responses. The rough structure is:
  1005. //
  1006. // 1. Assume the server sends you something sane - JSON + well defined error objects + proper codes
  1007. // - this is the happy path
  1008. // - when you get this output, trust what the server sends
  1009. // 2. Guard against empty fields / bodies in received JSON and attempt to cull sufficient info from them to
  1010. // generate a reasonable facsimile of the original failure.
  1011. // - Be sure to use a distinct error type or flag that allows a client to distinguish between this and error 1 above
  1012. // 3. Handle true disconnect failures / completely malformed data by moving up to a more generic client error
  1013. // 4. Distinguish between various connection failures like SSL certificates, timeouts, proxy errors, unexpected
  1014. // initial contact, the presence of mismatched body contents from posted content types
  1015. // - Give these a separate distinct error type and capture as much as possible of the original message
  1016. //
  1017. // TODO: introduce transformation of generic http.Client.Do() errors that separates 4.
  1018. func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error {
  1019. if body == nil && resp.Body != nil {
  1020. if data, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil {
  1021. body = data
  1022. }
  1023. }
  1024. retryAfter, _ := retryAfterSeconds(resp)
  1025. return r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
  1026. }
  1027. // newUnstructuredResponseError instantiates the appropriate generic error for the provided input. It also logs the body.
  1028. func (r *Request) newUnstructuredResponseError(body []byte, isTextResponse bool, statusCode int, method string, retryAfter int) error {
  1029. // cap the amount of output we create
  1030. if len(body) > maxUnstructuredResponseTextBytes {
  1031. body = body[:maxUnstructuredResponseTextBytes]
  1032. }
  1033. message := "unknown"
  1034. if isTextResponse {
  1035. message = strings.TrimSpace(string(body))
  1036. }
  1037. var groupResource schema.GroupResource
  1038. if len(r.resource) > 0 {
  1039. groupResource.Group = r.c.content.GroupVersion.Group
  1040. groupResource.Resource = r.resource
  1041. }
  1042. return errors.NewGenericServerResponse(
  1043. statusCode,
  1044. method,
  1045. groupResource,
  1046. r.resourceName,
  1047. message,
  1048. retryAfter,
  1049. true,
  1050. )
  1051. }
  1052. // isTextResponse returns true if the response appears to be a textual media type.
  1053. func isTextResponse(resp *http.Response) bool {
  1054. contentType := resp.Header.Get("Content-Type")
  1055. if len(contentType) == 0 {
  1056. return true
  1057. }
  1058. media, _, err := mime.ParseMediaType(contentType)
  1059. if err != nil {
  1060. return false
  1061. }
  1062. return strings.HasPrefix(media, "text/")
  1063. }
  1064. // checkWait returns true along with a number of seconds if the server instructed us to wait
  1065. // before retrying.
  1066. func checkWait(resp *http.Response) (int, bool) {
  1067. switch r := resp.StatusCode; {
  1068. // any 500 error code and 429 can trigger a wait
  1069. case r == http.StatusTooManyRequests, r >= 500:
  1070. default:
  1071. return 0, false
  1072. }
  1073. i, ok := retryAfterSeconds(resp)
  1074. return i, ok
  1075. }
  1076. // retryAfterSeconds returns the value of the Retry-After header and true, or 0 and false if
  1077. // the header was missing or not a valid number.
  1078. func retryAfterSeconds(resp *http.Response) (int, bool) {
  1079. if h := resp.Header.Get("Retry-After"); len(h) > 0 {
  1080. if i, err := strconv.Atoi(h); err == nil {
  1081. return i, true
  1082. }
  1083. }
  1084. return 0, false
  1085. }
  1086. // Result contains the result of calling Request.Do().
  1087. type Result struct {
  1088. body []byte
  1089. warnings []net.WarningHeader
  1090. contentType string
  1091. err error
  1092. statusCode int
  1093. decoder runtime.Decoder
  1094. }
  1095. // Raw returns the raw result.
  1096. func (r Result) Raw() ([]byte, error) {
  1097. return r.body, r.err
  1098. }
  1099. // Get returns the result as an object, which means it passes through the decoder.
  1100. // If the returned object is of type Status and has .Status != StatusSuccess, the
  1101. // additional information in Status will be used to enrich the error.
  1102. func (r Result) Get() (runtime.Object, error) {
  1103. if r.err != nil {
  1104. // Check whether the result has a Status object in the body and prefer that.
  1105. return nil, r.Error()
  1106. }
  1107. if r.decoder == nil {
  1108. return nil, fmt.Errorf("serializer for %s doesn't exist", r.contentType)
  1109. }
  1110. // decode, but if the result is Status return that as an error instead.
  1111. out, _, err := r.decoder.Decode(r.body, nil, nil)
  1112. if err != nil {
  1113. return nil, err
  1114. }
  1115. switch t := out.(type) {
  1116. case *metav1.Status:
  1117. // any status besides StatusSuccess is considered an error.
  1118. if t.Status != metav1.StatusSuccess {
  1119. return nil, errors.FromObject(t)
  1120. }
  1121. }
  1122. return out, nil
  1123. }
  1124. // StatusCode returns the HTTP status code of the request. (Only valid if no
  1125. // error was returned.)
  1126. func (r Result) StatusCode(statusCode *int) Result {
  1127. *statusCode = r.statusCode
  1128. return r
  1129. }
  1130. // Into stores the result into obj, if possible. If obj is nil it is ignored.
  1131. // If the returned object is of type Status and has .Status != StatusSuccess, the
  1132. // additional information in Status will be used to enrich the error.
  1133. func (r Result) Into(obj runtime.Object) error {
  1134. if r.err != nil {
  1135. // Check whether the result has a Status object in the body and prefer that.
  1136. return r.Error()
  1137. }
  1138. if r.decoder == nil {
  1139. return fmt.Errorf("serializer for %s doesn't exist", r.contentType)
  1140. }
  1141. if len(r.body) == 0 {
  1142. return fmt.Errorf("0-length response with status code: %d and content type: %s",
  1143. r.statusCode, r.contentType)
  1144. }
  1145. out, _, err := r.decoder.Decode(r.body, nil, obj)
  1146. if err != nil || out == obj {
  1147. return err
  1148. }
  1149. // if a different object is returned, see if it is Status and avoid double decoding
  1150. // the object.
  1151. switch t := out.(type) {
  1152. case *metav1.Status:
  1153. // any status besides StatusSuccess is considered an error.
  1154. if t.Status != metav1.StatusSuccess {
  1155. return errors.FromObject(t)
  1156. }
  1157. }
  1158. return nil
  1159. }
  1160. // WasCreated updates the provided bool pointer to whether the server returned
  1161. // 201 created or a different response.
  1162. func (r Result) WasCreated(wasCreated *bool) Result {
  1163. *wasCreated = r.statusCode == http.StatusCreated
  1164. return r
  1165. }
  1166. // Error returns the error executing the request, nil if no error occurred.
  1167. // If the returned object is of type Status and has Status != StatusSuccess, the
  1168. // additional information in Status will be used to enrich the error.
  1169. // See the Request.Do() comment for what errors you might get.
  1170. func (r Result) Error() error {
  1171. // if we have received an unexpected server error, and we have a body and decoder, we can try to extract
  1172. // a Status object.
  1173. if r.err == nil || !errors.IsUnexpectedServerError(r.err) || len(r.body) == 0 || r.decoder == nil {
  1174. return r.err
  1175. }
  1176. // attempt to convert the body into a Status object
  1177. // to be backwards compatible with old servers that do not return a version, default to "v1"
  1178. out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil)
  1179. if err != nil {
  1180. klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err)
  1181. return r.err
  1182. }
  1183. switch t := out.(type) {
  1184. case *metav1.Status:
  1185. // because we default the kind, we *must* check for StatusFailure
  1186. if t.Status == metav1.StatusFailure {
  1187. return errors.FromObject(t)
  1188. }
  1189. }
  1190. return r.err
  1191. }
  1192. // Warnings returns any warning headers received in the response
  1193. func (r Result) Warnings() []net.WarningHeader {
  1194. return r.warnings
  1195. }
  1196. // NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store)
  1197. var NameMayNotBe = []string{".", ".."}
  1198. // NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store)
  1199. var NameMayNotContain = []string{"/", "%"}
  1200. // IsValidPathSegmentName validates the name can be safely encoded as a path segment
  1201. func IsValidPathSegmentName(name string) []string {
  1202. for _, illegalName := range NameMayNotBe {
  1203. if name == illegalName {
  1204. return []string{fmt.Sprintf(`may not be '%s'`, illegalName)}
  1205. }
  1206. }
  1207. var errors []string
  1208. for _, illegalContent := range NameMayNotContain {
  1209. if strings.Contains(name, illegalContent) {
  1210. errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
  1211. }
  1212. }
  1213. return errors
  1214. }
  1215. // IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment
  1216. // It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid
  1217. func IsValidPathSegmentPrefix(name string) []string {
  1218. var errors []string
  1219. for _, illegalContent := range NameMayNotContain {
  1220. if strings.Contains(name, illegalContent) {
  1221. errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
  1222. }
  1223. }
  1224. return errors
  1225. }
  1226. // ValidatePathSegmentName validates the name can be safely encoded as a path segment
  1227. func ValidatePathSegmentName(name string, prefix bool) []string {
  1228. if prefix {
  1229. return IsValidPathSegmentPrefix(name)
  1230. }
  1231. return IsValidPathSegmentName(name)
  1232. }