request.go 45 KB

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