request.go 39 KB

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