request.go 43 KB

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