request.go 37 KB

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