request.go 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  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. "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. // 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. // generic components accessible via method setters
  81. verb string
  82. pathPrefix string
  83. subpath string
  84. params url.Values
  85. headers http.Header
  86. // structural elements of the request that are part of the Kubernetes API conventions
  87. namespace string
  88. namespaceSet bool
  89. resource string
  90. resourceName string
  91. subresource string
  92. // output
  93. err error
  94. body io.Reader
  95. retry WithRetry
  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. retry: &withRetry{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.subresource, 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. r.retry.SetMaxRetries(maxRetries)
  366. return r
  367. }
  368. // Body makes the request use obj as the body. Optional.
  369. // If obj is a string, try to read a file of that name.
  370. // If obj is a []byte, send it directly.
  371. // If obj is an io.Reader, use it directly.
  372. // If obj is a runtime.Object, marshal it correctly, and set Content-Type header.
  373. // If obj is a runtime.Object and nil, do nothing.
  374. // Otherwise, set an error.
  375. func (r *Request) Body(obj interface{}) *Request {
  376. if r.err != nil {
  377. return r
  378. }
  379. switch t := obj.(type) {
  380. case string:
  381. data, err := ioutil.ReadFile(t)
  382. if err != nil {
  383. r.err = err
  384. return r
  385. }
  386. glogBody("Request Body", data)
  387. r.body = bytes.NewReader(data)
  388. case []byte:
  389. glogBody("Request Body", t)
  390. r.body = bytes.NewReader(t)
  391. case io.Reader:
  392. r.body = t
  393. case runtime.Object:
  394. // callers may pass typed interface pointers, therefore we must check nil with reflection
  395. if reflect.ValueOf(t).IsNil() {
  396. return r
  397. }
  398. encoder, err := r.c.content.Negotiator.Encoder(r.c.content.ContentType, nil)
  399. if err != nil {
  400. r.err = err
  401. return r
  402. }
  403. data, err := runtime.Encode(encoder, t)
  404. if err != nil {
  405. r.err = err
  406. return r
  407. }
  408. glogBody("Request Body", data)
  409. r.body = bytes.NewReader(data)
  410. r.SetHeader("Content-Type", r.c.content.ContentType)
  411. default:
  412. r.err = fmt.Errorf("unknown type used for body: %+v", obj)
  413. }
  414. return r
  415. }
  416. // URL returns the current working URL.
  417. func (r *Request) URL() *url.URL {
  418. p := r.pathPrefix
  419. if r.namespaceSet && len(r.namespace) > 0 {
  420. p = path.Join(p, "namespaces", r.namespace)
  421. }
  422. if len(r.resource) != 0 {
  423. p = path.Join(p, strings.ToLower(r.resource))
  424. }
  425. // Join trims trailing slashes, so preserve r.pathPrefix's trailing slash for backwards compatibility if nothing was changed
  426. if len(r.resourceName) != 0 || len(r.subpath) != 0 || len(r.subresource) != 0 {
  427. p = path.Join(p, r.resourceName, r.subresource, r.subpath)
  428. }
  429. finalURL := &url.URL{}
  430. if r.c.base != nil {
  431. *finalURL = *r.c.base
  432. }
  433. finalURL.Path = p
  434. query := url.Values{}
  435. for key, values := range r.params {
  436. for _, value := range values {
  437. query.Add(key, value)
  438. }
  439. }
  440. // timeout is handled specially here.
  441. if r.timeout != 0 {
  442. query.Set("timeout", r.timeout.String())
  443. }
  444. finalURL.RawQuery = query.Encode()
  445. return finalURL
  446. }
  447. // finalURLTemplate is similar to URL(), but will make all specific parameter values equal
  448. // - instead of name or namespace, "{name}" and "{namespace}" will be used, and all query
  449. // parameters will be reset. This creates a copy of the url so as not to change the
  450. // underlying object.
  451. func (r Request) finalURLTemplate() url.URL {
  452. newParams := url.Values{}
  453. v := []string{"{value}"}
  454. for k := range r.params {
  455. newParams[k] = v
  456. }
  457. r.params = newParams
  458. url := r.URL()
  459. segments := strings.Split(url.Path, "/")
  460. groupIndex := 0
  461. index := 0
  462. trimmedBasePath := ""
  463. if url != nil && r.c.base != nil && strings.Contains(url.Path, r.c.base.Path) {
  464. p := strings.TrimPrefix(url.Path, r.c.base.Path)
  465. if !strings.HasPrefix(p, "/") {
  466. p = "/" + p
  467. }
  468. // store the base path that we have trimmed so we can append it
  469. // before returning the URL
  470. trimmedBasePath = r.c.base.Path
  471. segments = strings.Split(p, "/")
  472. groupIndex = 1
  473. }
  474. if len(segments) <= 2 {
  475. return *url
  476. }
  477. const CoreGroupPrefix = "api"
  478. const NamedGroupPrefix = "apis"
  479. isCoreGroup := segments[groupIndex] == CoreGroupPrefix
  480. isNamedGroup := segments[groupIndex] == NamedGroupPrefix
  481. if isCoreGroup {
  482. // checking the case of core group with /api/v1/... format
  483. index = groupIndex + 2
  484. } else if isNamedGroup {
  485. // checking the case of named group with /apis/apps/v1/... format
  486. index = groupIndex + 3
  487. } else {
  488. // this should not happen that the only two possibilities are /api... and /apis..., just want to put an
  489. // outlet here in case more API groups are added in future if ever possible:
  490. // https://kubernetes.io/docs/concepts/overview/kubernetes-api/#api-groups
  491. // if a wrong API groups name is encountered, return the {prefix} for url.Path
  492. url.Path = "/{prefix}"
  493. url.RawQuery = ""
  494. return *url
  495. }
  496. //switch segLength := len(segments) - index; segLength {
  497. switch {
  498. // case len(segments) - index == 1:
  499. // resource (with no name) do nothing
  500. case len(segments)-index == 2:
  501. // /$RESOURCE/$NAME: replace $NAME with {name}
  502. segments[index+1] = "{name}"
  503. case len(segments)-index == 3:
  504. if segments[index+2] == "finalize" || segments[index+2] == "status" {
  505. // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
  506. segments[index+1] = "{name}"
  507. } else {
  508. // /namespace/$NAMESPACE/$RESOURCE: replace $NAMESPACE with {namespace}
  509. segments[index+1] = "{namespace}"
  510. }
  511. case len(segments)-index >= 4:
  512. segments[index+1] = "{namespace}"
  513. // /namespace/$NAMESPACE/$RESOURCE/$NAME: replace $NAMESPACE with {namespace}, $NAME with {name}
  514. if segments[index+3] != "finalize" && segments[index+3] != "status" {
  515. // /$RESOURCE/$NAME/$SUBRESOURCE: replace $NAME with {name}
  516. segments[index+3] = "{name}"
  517. }
  518. }
  519. url.Path = path.Join(trimmedBasePath, path.Join(segments...))
  520. return *url
  521. }
  522. func (r *Request) tryThrottleWithInfo(ctx context.Context, retryInfo string) error {
  523. if r.rateLimiter == nil {
  524. return nil
  525. }
  526. now := time.Now()
  527. err := r.rateLimiter.Wait(ctx)
  528. latency := time.Since(now)
  529. var message string
  530. switch {
  531. case len(retryInfo) > 0:
  532. message = fmt.Sprintf("Waited for %v, %s - request: %s:%s", latency, retryInfo, r.verb, r.URL().String())
  533. default:
  534. message = fmt.Sprintf("Waited for %v due to client-side throttling, not priority and fairness, request: %s:%s", latency, r.verb, r.URL().String())
  535. }
  536. if latency > longThrottleLatency {
  537. klog.V(3).Info(message)
  538. }
  539. if latency > extraLongThrottleLatency {
  540. // If the rate limiter latency is very high, the log message should be printed at a higher log level,
  541. // but we use a throttled logger to prevent spamming.
  542. globalThrottledLogger.Infof("%s", message)
  543. }
  544. metrics.RateLimiterLatency.Observe(ctx, r.verb, r.finalURLTemplate(), latency)
  545. return err
  546. }
  547. func (r *Request) tryThrottle(ctx context.Context) error {
  548. return r.tryThrottleWithInfo(ctx, "")
  549. }
  550. type throttleSettings struct {
  551. logLevel klog.Level
  552. minLogInterval time.Duration
  553. lastLogTime time.Time
  554. lock sync.RWMutex
  555. }
  556. type throttledLogger struct {
  557. clock clock.PassiveClock
  558. settings []*throttleSettings
  559. }
  560. var globalThrottledLogger = &throttledLogger{
  561. clock: clock.RealClock{},
  562. settings: []*throttleSettings{
  563. {
  564. logLevel: 2,
  565. minLogInterval: 1 * time.Second,
  566. }, {
  567. logLevel: 0,
  568. minLogInterval: 10 * time.Second,
  569. },
  570. },
  571. }
  572. func (b *throttledLogger) attemptToLog() (klog.Level, bool) {
  573. for _, setting := range b.settings {
  574. if bool(klog.V(setting.logLevel).Enabled()) {
  575. // Return early without write locking if possible.
  576. if func() bool {
  577. setting.lock.RLock()
  578. defer setting.lock.RUnlock()
  579. return b.clock.Since(setting.lastLogTime) >= setting.minLogInterval
  580. }() {
  581. setting.lock.Lock()
  582. defer setting.lock.Unlock()
  583. if b.clock.Since(setting.lastLogTime) >= setting.minLogInterval {
  584. setting.lastLogTime = b.clock.Now()
  585. return setting.logLevel, true
  586. }
  587. }
  588. return -1, false
  589. }
  590. }
  591. return -1, false
  592. }
  593. // Infof will write a log message at each logLevel specified by the receiver's throttleSettings
  594. // as long as it hasn't written a log message more recently than minLogInterval.
  595. func (b *throttledLogger) Infof(message string, args ...interface{}) {
  596. if logLevel, ok := b.attemptToLog(); ok {
  597. klog.V(logLevel).Infof(message, args...)
  598. }
  599. }
  600. // Watch attempts to begin watching the requested location.
  601. // Returns a watch.Interface, or an error.
  602. func (r *Request) Watch(ctx context.Context) (watch.Interface, error) {
  603. // We specifically don't want to rate limit watches, so we
  604. // don't use r.rateLimiter here.
  605. if r.err != nil {
  606. return nil, r.err
  607. }
  608. client := r.c.Client
  609. if client == nil {
  610. client = http.DefaultClient
  611. }
  612. isErrRetryableFunc := func(request *http.Request, err error) bool {
  613. // The watch stream mechanism handles many common partial data errors, so closed
  614. // connections can be retried in many cases.
  615. if net.IsProbableEOF(err) || net.IsTimeout(err) {
  616. return true
  617. }
  618. return false
  619. }
  620. var retryAfter *RetryAfter
  621. url := r.URL().String()
  622. for {
  623. req, err := r.newHTTPRequest(ctx)
  624. if err != nil {
  625. return nil, err
  626. }
  627. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  628. if retryAfter != nil {
  629. // We are retrying the request that we already send to apiserver
  630. // at least once before.
  631. // This request should also be throttled with the client-internal rate limiter.
  632. if err := r.tryThrottleWithInfo(ctx, retryAfter.Reason); err != nil {
  633. return nil, err
  634. }
  635. retryAfter = nil
  636. }
  637. resp, err := client.Do(req)
  638. updateURLMetrics(ctx, r, resp, err)
  639. if r.c.base != nil {
  640. if err != nil {
  641. r.backoff.UpdateBackoff(r.c.base, err, 0)
  642. } else {
  643. r.backoff.UpdateBackoff(r.c.base, err, resp.StatusCode)
  644. }
  645. }
  646. if err == nil && resp.StatusCode == http.StatusOK {
  647. return r.newStreamWatcher(resp)
  648. }
  649. done, transformErr := func() (bool, error) {
  650. defer readAndCloseResponseBody(resp)
  651. var retry bool
  652. retryAfter, retry = r.retry.NextRetry(req, resp, err, isErrRetryableFunc)
  653. if retry {
  654. err := r.retry.BeforeNextRetry(ctx, r.backoff, retryAfter, url, r.body)
  655. if err == nil {
  656. return false, nil
  657. }
  658. klog.V(4).Infof("Could not retry request - %v", err)
  659. }
  660. if resp == nil {
  661. // the server must have sent us an error in 'err'
  662. return true, nil
  663. }
  664. if result := r.transformResponse(resp, req); result.err != nil {
  665. return true, result.err
  666. }
  667. return true, fmt.Errorf("for request %s, got status: %v", url, resp.StatusCode)
  668. }()
  669. if done {
  670. if isErrRetryableFunc(req, err) {
  671. return watch.NewEmptyWatch(), nil
  672. }
  673. if err == nil {
  674. // if the server sent us an HTTP Response object,
  675. // we need to return the error object from that.
  676. err = transformErr
  677. }
  678. return nil, err
  679. }
  680. }
  681. }
  682. func (r *Request) newStreamWatcher(resp *http.Response) (watch.Interface, error) {
  683. contentType := resp.Header.Get("Content-Type")
  684. mediaType, params, err := mime.ParseMediaType(contentType)
  685. if err != nil {
  686. klog.V(4).Infof("Unexpected content type from the server: %q: %v", contentType, err)
  687. }
  688. objectDecoder, streamingSerializer, framer, err := r.c.content.Negotiator.StreamDecoder(mediaType, params)
  689. if err != nil {
  690. return nil, err
  691. }
  692. handleWarnings(resp.Header, r.warningHandler)
  693. frameReader := framer.NewFrameReader(resp.Body)
  694. watchEventDecoder := streaming.NewDecoder(frameReader, streamingSerializer)
  695. return watch.NewStreamWatcher(
  696. restclientwatch.NewDecoder(watchEventDecoder, objectDecoder),
  697. // use 500 to indicate that the cause of the error is unknown - other error codes
  698. // are more specific to HTTP interactions, and set a reason
  699. errors.NewClientErrorReporter(http.StatusInternalServerError, r.verb, "ClientWatchDecoding"),
  700. ), nil
  701. }
  702. // updateURLMetrics is a convenience function for pushing metrics.
  703. // It also handles corner cases for incomplete/invalid request data.
  704. func updateURLMetrics(ctx context.Context, req *Request, resp *http.Response, err error) {
  705. url := "none"
  706. if req.c.base != nil {
  707. url = req.c.base.Host
  708. }
  709. // Errors can be arbitrary strings. Unbound label cardinality is not suitable for a metric
  710. // system so we just report them as `<error>`.
  711. if err != nil {
  712. metrics.RequestResult.Increment(ctx, "<error>", req.verb, url)
  713. } else {
  714. //Metrics for failure codes
  715. metrics.RequestResult.Increment(ctx, strconv.Itoa(resp.StatusCode), req.verb, url)
  716. }
  717. }
  718. // Stream formats and executes the request, and offers streaming of the response.
  719. // Returns io.ReadCloser which could be used for streaming of the response, or an error
  720. // 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.
  721. // 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.
  722. func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error) {
  723. if r.err != nil {
  724. return nil, r.err
  725. }
  726. if err := r.tryThrottle(ctx); err != nil {
  727. return nil, err
  728. }
  729. client := r.c.Client
  730. if client == nil {
  731. client = http.DefaultClient
  732. }
  733. var retryAfter *RetryAfter
  734. url := r.URL().String()
  735. for {
  736. req, err := r.newHTTPRequest(ctx)
  737. if err != nil {
  738. return nil, err
  739. }
  740. if r.body != nil {
  741. req.Body = ioutil.NopCloser(r.body)
  742. }
  743. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  744. if retryAfter != nil {
  745. // We are retrying the request that we already send to apiserver
  746. // at least once before.
  747. // This request should also be throttled with the client-internal rate limiter.
  748. if err := r.tryThrottleWithInfo(ctx, retryAfter.Reason); err != nil {
  749. return nil, err
  750. }
  751. retryAfter = nil
  752. }
  753. resp, err := client.Do(req)
  754. updateURLMetrics(ctx, r, resp, err)
  755. if r.c.base != nil {
  756. if err != nil {
  757. r.backoff.UpdateBackoff(r.URL(), err, 0)
  758. } else {
  759. r.backoff.UpdateBackoff(r.URL(), err, resp.StatusCode)
  760. }
  761. }
  762. if err != nil {
  763. // we only retry on an HTTP response with 'Retry-After' header
  764. return nil, err
  765. }
  766. switch {
  767. case (resp.StatusCode >= 200) && (resp.StatusCode < 300):
  768. handleWarnings(resp.Header, r.warningHandler)
  769. return resp.Body, nil
  770. default:
  771. done, transformErr := func() (bool, error) {
  772. defer resp.Body.Close()
  773. var retry bool
  774. retryAfter, retry = r.retry.NextRetry(req, resp, err, neverRetryError)
  775. if retry {
  776. err := r.retry.BeforeNextRetry(ctx, r.backoff, retryAfter, url, r.body)
  777. if err == nil {
  778. return false, nil
  779. }
  780. klog.V(4).Infof("Could not retry request - %v", err)
  781. }
  782. result := r.transformResponse(resp, req)
  783. if err := result.Error(); err != nil {
  784. return true, err
  785. }
  786. return true, fmt.Errorf("%d while accessing %v: %s", result.statusCode, url, string(result.body))
  787. }()
  788. if done {
  789. return nil, transformErr
  790. }
  791. }
  792. }
  793. }
  794. // requestPreflightCheck looks for common programmer errors on Request.
  795. //
  796. // We tackle here two programmer mistakes. The first one is to try to create
  797. // something(POST) using an empty string as namespace with namespaceSet as
  798. // true. If namespaceSet is true then namespace should also be defined. The
  799. // second mistake is, when under the same circumstances, the programmer tries
  800. // to GET, PUT or DELETE a named resource(resourceName != ""), again, if
  801. // namespaceSet is true then namespace must not be empty.
  802. func (r *Request) requestPreflightCheck() error {
  803. if !r.namespaceSet {
  804. return nil
  805. }
  806. if len(r.namespace) > 0 {
  807. return nil
  808. }
  809. switch r.verb {
  810. case "POST":
  811. return fmt.Errorf("an empty namespace may not be set during creation")
  812. case "GET", "PUT", "DELETE":
  813. if len(r.resourceName) > 0 {
  814. return fmt.Errorf("an empty namespace may not be set when a resource name is provided")
  815. }
  816. }
  817. return nil
  818. }
  819. func (r *Request) newHTTPRequest(ctx context.Context) (*http.Request, error) {
  820. url := r.URL().String()
  821. req, err := http.NewRequest(r.verb, url, r.body)
  822. if err != nil {
  823. return nil, err
  824. }
  825. req = req.WithContext(ctx)
  826. req.Header = r.headers
  827. return req, nil
  828. }
  829. // request connects to the server and invokes the provided function when a server response is
  830. // received. It handles retry behavior and up front validation of requests. It will invoke
  831. // fn at most once. It will return an error if a problem occurred prior to connecting to the
  832. // server - the provided function is responsible for handling server errors.
  833. func (r *Request) request(ctx context.Context, fn func(*http.Request, *http.Response)) error {
  834. //Metrics for total request latency
  835. start := time.Now()
  836. defer func() {
  837. metrics.RequestLatency.Observe(ctx, r.verb, r.finalURLTemplate(), time.Since(start))
  838. }()
  839. if r.err != nil {
  840. klog.V(4).Infof("Error in request: %v", r.err)
  841. return r.err
  842. }
  843. if err := r.requestPreflightCheck(); err != nil {
  844. return err
  845. }
  846. client := r.c.Client
  847. if client == nil {
  848. client = http.DefaultClient
  849. }
  850. // Throttle the first try before setting up the timeout configured on the
  851. // client. We don't want a throttled client to return timeouts to callers
  852. // before it makes a single request.
  853. if err := r.tryThrottle(ctx); err != nil {
  854. return err
  855. }
  856. if r.timeout > 0 {
  857. var cancel context.CancelFunc
  858. ctx, cancel = context.WithTimeout(ctx, r.timeout)
  859. defer cancel()
  860. }
  861. // Right now we make about ten retry attempts if we get a Retry-After response.
  862. var retryAfter *RetryAfter
  863. for {
  864. req, err := r.newHTTPRequest(ctx)
  865. if err != nil {
  866. return err
  867. }
  868. r.backoff.Sleep(r.backoff.CalculateBackoff(r.URL()))
  869. if retryAfter != nil {
  870. // We are retrying the request that we already send to apiserver
  871. // at least once before.
  872. // This request should also be throttled with the client-internal rate limiter.
  873. if err := r.tryThrottleWithInfo(ctx, retryAfter.Reason); err != nil {
  874. return err
  875. }
  876. retryAfter = nil
  877. }
  878. resp, err := client.Do(req)
  879. updateURLMetrics(ctx, r, resp, err)
  880. if err != nil {
  881. r.backoff.UpdateBackoff(r.URL(), err, 0)
  882. } else {
  883. r.backoff.UpdateBackoff(r.URL(), err, resp.StatusCode)
  884. }
  885. done := func() bool {
  886. defer readAndCloseResponseBody(resp)
  887. // if the the server returns an error in err, the response will be nil.
  888. f := func(req *http.Request, resp *http.Response) {
  889. if resp == nil {
  890. return
  891. }
  892. fn(req, resp)
  893. }
  894. var retry bool
  895. retryAfter, retry = r.retry.NextRetry(req, resp, err, func(req *http.Request, err error) bool {
  896. // "Connection reset by peer" or "apiserver is shutting down" are usually a transient errors.
  897. // Thus in case of "GET" operations, we simply retry it.
  898. // We are not automatically retrying "write" operations, as they are not idempotent.
  899. if r.verb != "GET" {
  900. return false
  901. }
  902. // For connection errors and apiserver shutdown errors retry.
  903. if net.IsConnectionReset(err) || net.IsProbableEOF(err) {
  904. return true
  905. }
  906. return false
  907. })
  908. if retry {
  909. err := r.retry.BeforeNextRetry(ctx, r.backoff, retryAfter, req.URL.String(), r.body)
  910. if err == nil {
  911. return false
  912. }
  913. klog.V(4).Infof("Could not retry request - %v", err)
  914. }
  915. f(req, resp)
  916. return true
  917. }()
  918. if done {
  919. return err
  920. }
  921. }
  922. }
  923. // Do formats and executes the request. Returns a Result object for easy response
  924. // processing.
  925. //
  926. // Error type:
  927. // * If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError
  928. // * http.Client.Do errors are returned directly.
  929. func (r *Request) Do(ctx context.Context) Result {
  930. var result Result
  931. err := r.request(ctx, func(req *http.Request, resp *http.Response) {
  932. result = r.transformResponse(resp, req)
  933. })
  934. if err != nil {
  935. return Result{err: err}
  936. }
  937. return result
  938. }
  939. // DoRaw executes the request but does not process the response body.
  940. func (r *Request) DoRaw(ctx context.Context) ([]byte, error) {
  941. var result Result
  942. err := r.request(ctx, func(req *http.Request, resp *http.Response) {
  943. result.body, result.err = ioutil.ReadAll(resp.Body)
  944. glogBody("Response Body", result.body)
  945. if resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent {
  946. result.err = r.transformUnstructuredResponseError(resp, req, result.body)
  947. }
  948. })
  949. if err != nil {
  950. return nil, err
  951. }
  952. return result.body, result.err
  953. }
  954. // transformResponse converts an API response into a structured API object
  955. func (r *Request) transformResponse(resp *http.Response, req *http.Request) Result {
  956. var body []byte
  957. if resp.Body != nil {
  958. data, err := ioutil.ReadAll(resp.Body)
  959. switch err.(type) {
  960. case nil:
  961. body = data
  962. case http2.StreamError:
  963. // This is trying to catch the scenario that the server may close the connection when sending the
  964. // response body. This can be caused by server timeout due to a slow network connection.
  965. // TODO: Add test for this. Steps may be:
  966. // 1. client-go (or kubectl) sends a GET request.
  967. // 2. Apiserver sends back the headers and then part of the body
  968. // 3. Apiserver closes connection.
  969. // 4. client-go should catch this and return an error.
  970. klog.V(2).Infof("Stream error %#v when reading response body, may be caused by closed connection.", err)
  971. streamErr := fmt.Errorf("stream error when reading response body, may be caused by closed connection. Please retry. Original error: %w", err)
  972. return Result{
  973. err: streamErr,
  974. }
  975. default:
  976. klog.Errorf("Unexpected error when reading response body: %v", err)
  977. unexpectedErr := fmt.Errorf("unexpected error when reading response body. Please retry. Original error: %w", err)
  978. return Result{
  979. err: unexpectedErr,
  980. }
  981. }
  982. }
  983. glogBody("Response Body", body)
  984. // verify the content type is accurate
  985. var decoder runtime.Decoder
  986. contentType := resp.Header.Get("Content-Type")
  987. if len(contentType) == 0 {
  988. contentType = r.c.content.ContentType
  989. }
  990. if len(contentType) > 0 {
  991. var err error
  992. mediaType, params, err := mime.ParseMediaType(contentType)
  993. if err != nil {
  994. return Result{err: errors.NewInternalError(err)}
  995. }
  996. decoder, err = r.c.content.Negotiator.Decoder(mediaType, params)
  997. if err != nil {
  998. // if we fail to negotiate a decoder, treat this as an unstructured error
  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. return Result{err: r.transformUnstructuredResponseError(resp, req, body)}
  1004. }
  1005. return Result{
  1006. body: body,
  1007. contentType: contentType,
  1008. statusCode: resp.StatusCode,
  1009. warnings: handleWarnings(resp.Header, r.warningHandler),
  1010. }
  1011. }
  1012. }
  1013. switch {
  1014. case resp.StatusCode == http.StatusSwitchingProtocols:
  1015. // no-op, we've been upgraded
  1016. case resp.StatusCode < http.StatusOK || resp.StatusCode > http.StatusPartialContent:
  1017. // calculate an unstructured error from the response which the Result object may use if the caller
  1018. // did not return a structured error.
  1019. retryAfter, _ := retryAfterSeconds(resp)
  1020. err := r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
  1021. return Result{
  1022. body: body,
  1023. contentType: contentType,
  1024. statusCode: resp.StatusCode,
  1025. decoder: decoder,
  1026. err: err,
  1027. warnings: handleWarnings(resp.Header, r.warningHandler),
  1028. }
  1029. }
  1030. return Result{
  1031. body: body,
  1032. contentType: contentType,
  1033. statusCode: resp.StatusCode,
  1034. decoder: decoder,
  1035. warnings: handleWarnings(resp.Header, r.warningHandler),
  1036. }
  1037. }
  1038. // truncateBody decides if the body should be truncated, based on the glog Verbosity.
  1039. func truncateBody(body string) string {
  1040. max := 0
  1041. switch {
  1042. case bool(klog.V(10).Enabled()):
  1043. return body
  1044. case bool(klog.V(9).Enabled()):
  1045. max = 10240
  1046. case bool(klog.V(8).Enabled()):
  1047. max = 1024
  1048. }
  1049. if len(body) <= max {
  1050. return body
  1051. }
  1052. return body[:max] + fmt.Sprintf(" [truncated %d chars]", len(body)-max)
  1053. }
  1054. // glogBody logs a body output that could be either JSON or protobuf. It explicitly guards against
  1055. // allocating a new string for the body output unless necessary. Uses a simple heuristic to determine
  1056. // whether the body is printable.
  1057. func glogBody(prefix string, body []byte) {
  1058. if klog.V(8).Enabled() {
  1059. if bytes.IndexFunc(body, func(r rune) bool {
  1060. return r < 0x0a
  1061. }) != -1 {
  1062. klog.Infof("%s:\n%s", prefix, truncateBody(hex.Dump(body)))
  1063. } else {
  1064. klog.Infof("%s: %s", prefix, truncateBody(string(body)))
  1065. }
  1066. }
  1067. }
  1068. // maxUnstructuredResponseTextBytes is an upper bound on how much output to include in the unstructured error.
  1069. const maxUnstructuredResponseTextBytes = 2048
  1070. // transformUnstructuredResponseError handles an error from the server that is not in a structured form.
  1071. // It is expected to transform any response that is not recognizable as a clear server sent error from the
  1072. // K8S API using the information provided with the request. In practice, HTTP proxies and client libraries
  1073. // introduce a level of uncertainty to the responses returned by servers that in common use result in
  1074. // unexpected responses. The rough structure is:
  1075. //
  1076. // 1. Assume the server sends you something sane - JSON + well defined error objects + proper codes
  1077. // - this is the happy path
  1078. // - when you get this output, trust what the server sends
  1079. // 2. Guard against empty fields / bodies in received JSON and attempt to cull sufficient info from them to
  1080. // generate a reasonable facsimile of the original failure.
  1081. // - Be sure to use a distinct error type or flag that allows a client to distinguish between this and error 1 above
  1082. // 3. Handle true disconnect failures / completely malformed data by moving up to a more generic client error
  1083. // 4. Distinguish between various connection failures like SSL certificates, timeouts, proxy errors, unexpected
  1084. // initial contact, the presence of mismatched body contents from posted content types
  1085. // - Give these a separate distinct error type and capture as much as possible of the original message
  1086. //
  1087. // TODO: introduce transformation of generic http.Client.Do() errors that separates 4.
  1088. func (r *Request) transformUnstructuredResponseError(resp *http.Response, req *http.Request, body []byte) error {
  1089. if body == nil && resp.Body != nil {
  1090. if data, err := ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: maxUnstructuredResponseTextBytes}); err == nil {
  1091. body = data
  1092. }
  1093. }
  1094. retryAfter, _ := retryAfterSeconds(resp)
  1095. return r.newUnstructuredResponseError(body, isTextResponse(resp), resp.StatusCode, req.Method, retryAfter)
  1096. }
  1097. // newUnstructuredResponseError instantiates the appropriate generic error for the provided input. It also logs the body.
  1098. func (r *Request) newUnstructuredResponseError(body []byte, isTextResponse bool, statusCode int, method string, retryAfter int) error {
  1099. // cap the amount of output we create
  1100. if len(body) > maxUnstructuredResponseTextBytes {
  1101. body = body[:maxUnstructuredResponseTextBytes]
  1102. }
  1103. message := "unknown"
  1104. if isTextResponse {
  1105. message = strings.TrimSpace(string(body))
  1106. }
  1107. var groupResource schema.GroupResource
  1108. if len(r.resource) > 0 {
  1109. groupResource.Group = r.c.content.GroupVersion.Group
  1110. groupResource.Resource = r.resource
  1111. }
  1112. return errors.NewGenericServerResponse(
  1113. statusCode,
  1114. method,
  1115. groupResource,
  1116. r.resourceName,
  1117. message,
  1118. retryAfter,
  1119. true,
  1120. )
  1121. }
  1122. // isTextResponse returns true if the response appears to be a textual media type.
  1123. func isTextResponse(resp *http.Response) bool {
  1124. contentType := resp.Header.Get("Content-Type")
  1125. if len(contentType) == 0 {
  1126. return true
  1127. }
  1128. media, _, err := mime.ParseMediaType(contentType)
  1129. if err != nil {
  1130. return false
  1131. }
  1132. return strings.HasPrefix(media, "text/")
  1133. }
  1134. // retryAfterSeconds returns the value of the Retry-After header and true, or 0 and false if
  1135. // the header was missing or not a valid number.
  1136. func retryAfterSeconds(resp *http.Response) (int, bool) {
  1137. if h := resp.Header.Get("Retry-After"); len(h) > 0 {
  1138. if i, err := strconv.Atoi(h); err == nil {
  1139. return i, true
  1140. }
  1141. }
  1142. return 0, false
  1143. }
  1144. // Result contains the result of calling Request.Do().
  1145. type Result struct {
  1146. body []byte
  1147. warnings []net.WarningHeader
  1148. contentType string
  1149. err error
  1150. statusCode int
  1151. decoder runtime.Decoder
  1152. }
  1153. // Raw returns the raw result.
  1154. func (r Result) Raw() ([]byte, error) {
  1155. return r.body, r.err
  1156. }
  1157. // Get returns the result as an object, which means it passes through the decoder.
  1158. // If the returned object is of type Status and has .Status != StatusSuccess, the
  1159. // additional information in Status will be used to enrich the error.
  1160. func (r Result) Get() (runtime.Object, error) {
  1161. if r.err != nil {
  1162. // Check whether the result has a Status object in the body and prefer that.
  1163. return nil, r.Error()
  1164. }
  1165. if r.decoder == nil {
  1166. return nil, fmt.Errorf("serializer for %s doesn't exist", r.contentType)
  1167. }
  1168. // decode, but if the result is Status return that as an error instead.
  1169. out, _, err := r.decoder.Decode(r.body, nil, nil)
  1170. if err != nil {
  1171. return nil, err
  1172. }
  1173. switch t := out.(type) {
  1174. case *metav1.Status:
  1175. // any status besides StatusSuccess is considered an error.
  1176. if t.Status != metav1.StatusSuccess {
  1177. return nil, errors.FromObject(t)
  1178. }
  1179. }
  1180. return out, nil
  1181. }
  1182. // StatusCode returns the HTTP status code of the request. (Only valid if no
  1183. // error was returned.)
  1184. func (r Result) StatusCode(statusCode *int) Result {
  1185. *statusCode = r.statusCode
  1186. return r
  1187. }
  1188. // Into stores the result into obj, if possible. If obj is nil it is ignored.
  1189. // If the returned object is of type Status and has .Status != StatusSuccess, the
  1190. // additional information in Status will be used to enrich the error.
  1191. func (r Result) Into(obj runtime.Object) error {
  1192. if r.err != nil {
  1193. // Check whether the result has a Status object in the body and prefer that.
  1194. return r.Error()
  1195. }
  1196. if r.decoder == nil {
  1197. return fmt.Errorf("serializer for %s doesn't exist", r.contentType)
  1198. }
  1199. if len(r.body) == 0 {
  1200. return fmt.Errorf("0-length response with status code: %d and content type: %s",
  1201. r.statusCode, r.contentType)
  1202. }
  1203. out, _, err := r.decoder.Decode(r.body, nil, obj)
  1204. if err != nil || out == obj {
  1205. return err
  1206. }
  1207. // if a different object is returned, see if it is Status and avoid double decoding
  1208. // the object.
  1209. switch t := out.(type) {
  1210. case *metav1.Status:
  1211. // any status besides StatusSuccess is considered an error.
  1212. if t.Status != metav1.StatusSuccess {
  1213. return errors.FromObject(t)
  1214. }
  1215. }
  1216. return nil
  1217. }
  1218. // WasCreated updates the provided bool pointer to whether the server returned
  1219. // 201 created or a different response.
  1220. func (r Result) WasCreated(wasCreated *bool) Result {
  1221. *wasCreated = r.statusCode == http.StatusCreated
  1222. return r
  1223. }
  1224. // Error returns the error executing the request, nil if no error occurred.
  1225. // If the returned object is of type Status and has Status != StatusSuccess, the
  1226. // additional information in Status will be used to enrich the error.
  1227. // See the Request.Do() comment for what errors you might get.
  1228. func (r Result) Error() error {
  1229. // if we have received an unexpected server error, and we have a body and decoder, we can try to extract
  1230. // a Status object.
  1231. if r.err == nil || !errors.IsUnexpectedServerError(r.err) || len(r.body) == 0 || r.decoder == nil {
  1232. return r.err
  1233. }
  1234. // attempt to convert the body into a Status object
  1235. // to be backwards compatible with old servers that do not return a version, default to "v1"
  1236. out, _, err := r.decoder.Decode(r.body, &schema.GroupVersionKind{Version: "v1"}, nil)
  1237. if err != nil {
  1238. klog.V(5).Infof("body was not decodable (unable to check for Status): %v", err)
  1239. return r.err
  1240. }
  1241. switch t := out.(type) {
  1242. case *metav1.Status:
  1243. // because we default the kind, we *must* check for StatusFailure
  1244. if t.Status == metav1.StatusFailure {
  1245. return errors.FromObject(t)
  1246. }
  1247. }
  1248. return r.err
  1249. }
  1250. // Warnings returns any warning headers received in the response
  1251. func (r Result) Warnings() []net.WarningHeader {
  1252. return r.warnings
  1253. }
  1254. // NameMayNotBe specifies strings that cannot be used as names specified as path segments (like the REST API or etcd store)
  1255. var NameMayNotBe = []string{".", ".."}
  1256. // NameMayNotContain specifies substrings that cannot be used in names specified as path segments (like the REST API or etcd store)
  1257. var NameMayNotContain = []string{"/", "%"}
  1258. // IsValidPathSegmentName validates the name can be safely encoded as a path segment
  1259. func IsValidPathSegmentName(name string) []string {
  1260. for _, illegalName := range NameMayNotBe {
  1261. if name == illegalName {
  1262. return []string{fmt.Sprintf(`may not be '%s'`, illegalName)}
  1263. }
  1264. }
  1265. var errors []string
  1266. for _, illegalContent := range NameMayNotContain {
  1267. if strings.Contains(name, illegalContent) {
  1268. errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
  1269. }
  1270. }
  1271. return errors
  1272. }
  1273. // IsValidPathSegmentPrefix validates the name can be used as a prefix for a name which will be encoded as a path segment
  1274. // It does not check for exact matches with disallowed names, since an arbitrary suffix might make the name valid
  1275. func IsValidPathSegmentPrefix(name string) []string {
  1276. var errors []string
  1277. for _, illegalContent := range NameMayNotContain {
  1278. if strings.Contains(name, illegalContent) {
  1279. errors = append(errors, fmt.Sprintf(`may not contain '%s'`, illegalContent))
  1280. }
  1281. }
  1282. return errors
  1283. }
  1284. // ValidatePathSegmentName validates the name can be safely encoded as a path segment
  1285. func ValidatePathSegmentName(name string, prefix bool) []string {
  1286. if prefix {
  1287. return IsValidPathSegmentPrefix(name)
  1288. }
  1289. return IsValidPathSegmentName(name)
  1290. }