errors.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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 errors
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "reflect"
  20. "strings"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apimachinery/pkg/util/validation/field"
  25. )
  26. // StatusError is an error intended for consumption by a REST API server; it can also be
  27. // reconstructed by clients from a REST response. Public to allow easy type switches.
  28. type StatusError struct {
  29. ErrStatus metav1.Status
  30. }
  31. // APIStatus is exposed by errors that can be converted to an api.Status object
  32. // for finer grained details.
  33. type APIStatus interface {
  34. Status() metav1.Status
  35. }
  36. var _ error = &StatusError{}
  37. // Error implements the Error interface.
  38. func (e *StatusError) Error() string {
  39. return e.ErrStatus.Message
  40. }
  41. // Status allows access to e's status without having to know the detailed workings
  42. // of StatusError.
  43. func (e *StatusError) Status() metav1.Status {
  44. return e.ErrStatus
  45. }
  46. // DebugError reports extended info about the error to debug output.
  47. func (e *StatusError) DebugError() (string, []interface{}) {
  48. if out, err := json.MarshalIndent(e.ErrStatus, "", " "); err == nil {
  49. return "server response object: %s", []interface{}{string(out)}
  50. }
  51. return "server response object: %#v", []interface{}{e.ErrStatus}
  52. }
  53. // HasStatusCause returns true if the provided error has a details cause
  54. // with the provided type name.
  55. func HasStatusCause(err error, name metav1.CauseType) bool {
  56. _, ok := StatusCause(err, name)
  57. return ok
  58. }
  59. // StatusCause returns the named cause from the provided error if it exists and
  60. // the error is of the type APIStatus. Otherwise it returns false.
  61. func StatusCause(err error, name metav1.CauseType) (metav1.StatusCause, bool) {
  62. apierr, ok := err.(APIStatus)
  63. if !ok || apierr == nil || apierr.Status().Details == nil {
  64. return metav1.StatusCause{}, false
  65. }
  66. for _, cause := range apierr.Status().Details.Causes {
  67. if cause.Type == name {
  68. return cause, true
  69. }
  70. }
  71. return metav1.StatusCause{}, false
  72. }
  73. // UnexpectedObjectError can be returned by FromObject if it's passed a non-status object.
  74. type UnexpectedObjectError struct {
  75. Object runtime.Object
  76. }
  77. // Error returns an error message describing 'u'.
  78. func (u *UnexpectedObjectError) Error() string {
  79. return fmt.Sprintf("unexpected object: %v", u.Object)
  80. }
  81. // FromObject generates an StatusError from an metav1.Status, if that is the type of obj; otherwise,
  82. // returns an UnexpecteObjectError.
  83. func FromObject(obj runtime.Object) error {
  84. switch t := obj.(type) {
  85. case *metav1.Status:
  86. return &StatusError{ErrStatus: *t}
  87. case runtime.Unstructured:
  88. var status metav1.Status
  89. obj := t.UnstructuredContent()
  90. if !reflect.DeepEqual(obj["kind"], "Status") {
  91. break
  92. }
  93. if err := runtime.DefaultUnstructuredConverter.FromUnstructured(t.UnstructuredContent(), &status); err != nil {
  94. return err
  95. }
  96. if status.APIVersion != "v1" && status.APIVersion != "meta.k8s.io/v1" {
  97. break
  98. }
  99. return &StatusError{ErrStatus: status}
  100. }
  101. return &UnexpectedObjectError{obj}
  102. }
  103. // NewNotFound returns a new error which indicates that the resource of the kind and the name was not found.
  104. func NewNotFound(qualifiedResource schema.GroupResource, name string) *StatusError {
  105. return &StatusError{metav1.Status{
  106. Status: metav1.StatusFailure,
  107. Code: http.StatusNotFound,
  108. Reason: metav1.StatusReasonNotFound,
  109. Details: &metav1.StatusDetails{
  110. Group: qualifiedResource.Group,
  111. Kind: qualifiedResource.Resource,
  112. Name: name,
  113. },
  114. Message: fmt.Sprintf("%s %q not found", qualifiedResource.String(), name),
  115. }}
  116. }
  117. // NewAlreadyExists returns an error indicating the item requested exists by that identifier.
  118. func NewAlreadyExists(qualifiedResource schema.GroupResource, name string) *StatusError {
  119. return &StatusError{metav1.Status{
  120. Status: metav1.StatusFailure,
  121. Code: http.StatusConflict,
  122. Reason: metav1.StatusReasonAlreadyExists,
  123. Details: &metav1.StatusDetails{
  124. Group: qualifiedResource.Group,
  125. Kind: qualifiedResource.Resource,
  126. Name: name,
  127. },
  128. Message: fmt.Sprintf("%s %q already exists", qualifiedResource.String(), name),
  129. }}
  130. }
  131. // NewUnauthorized returns an error indicating the client is not authorized to perform the requested
  132. // action.
  133. func NewUnauthorized(reason string) *StatusError {
  134. message := reason
  135. if len(message) == 0 {
  136. message = "not authorized"
  137. }
  138. return &StatusError{metav1.Status{
  139. Status: metav1.StatusFailure,
  140. Code: http.StatusUnauthorized,
  141. Reason: metav1.StatusReasonUnauthorized,
  142. Message: message,
  143. }}
  144. }
  145. // NewForbidden returns an error indicating the requested action was forbidden
  146. func NewForbidden(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
  147. var message string
  148. if qualifiedResource.Empty() {
  149. message = fmt.Sprintf("forbidden: %v", err)
  150. } else if name == "" {
  151. message = fmt.Sprintf("%s is forbidden: %v", qualifiedResource.String(), err)
  152. } else {
  153. message = fmt.Sprintf("%s %q is forbidden: %v", qualifiedResource.String(), name, err)
  154. }
  155. return &StatusError{metav1.Status{
  156. Status: metav1.StatusFailure,
  157. Code: http.StatusForbidden,
  158. Reason: metav1.StatusReasonForbidden,
  159. Details: &metav1.StatusDetails{
  160. Group: qualifiedResource.Group,
  161. Kind: qualifiedResource.Resource,
  162. Name: name,
  163. },
  164. Message: message,
  165. }}
  166. }
  167. // NewConflict returns an error indicating the item can't be updated as provided.
  168. func NewConflict(qualifiedResource schema.GroupResource, name string, err error) *StatusError {
  169. return &StatusError{metav1.Status{
  170. Status: metav1.StatusFailure,
  171. Code: http.StatusConflict,
  172. Reason: metav1.StatusReasonConflict,
  173. Details: &metav1.StatusDetails{
  174. Group: qualifiedResource.Group,
  175. Kind: qualifiedResource.Resource,
  176. Name: name,
  177. },
  178. Message: fmt.Sprintf("Operation cannot be fulfilled on %s %q: %v", qualifiedResource.String(), name, err),
  179. }}
  180. }
  181. // NewApplyConflict returns an error including details on the requests apply conflicts
  182. func NewApplyConflict(causes []metav1.StatusCause, message string) *StatusError {
  183. return &StatusError{ErrStatus: metav1.Status{
  184. Status: metav1.StatusFailure,
  185. Code: http.StatusConflict,
  186. Reason: metav1.StatusReasonConflict,
  187. Details: &metav1.StatusDetails{
  188. // TODO: Get obj details here?
  189. Causes: causes,
  190. },
  191. Message: message,
  192. }}
  193. }
  194. // NewGone returns an error indicating the item no longer available at the server and no forwarding address is known.
  195. // DEPRECATED: Please use NewResourceExpired instead.
  196. func NewGone(message string) *StatusError {
  197. return &StatusError{metav1.Status{
  198. Status: metav1.StatusFailure,
  199. Code: http.StatusGone,
  200. Reason: metav1.StatusReasonGone,
  201. Message: message,
  202. }}
  203. }
  204. // NewResourceExpired creates an error that indicates that the requested resource content has expired from
  205. // the server (usually due to a resourceVersion that is too old).
  206. func NewResourceExpired(message string) *StatusError {
  207. return &StatusError{metav1.Status{
  208. Status: metav1.StatusFailure,
  209. Code: http.StatusGone,
  210. Reason: metav1.StatusReasonExpired,
  211. Message: message,
  212. }}
  213. }
  214. // NewInvalid returns an error indicating the item is invalid and cannot be processed.
  215. func NewInvalid(qualifiedKind schema.GroupKind, name string, errs field.ErrorList) *StatusError {
  216. causes := make([]metav1.StatusCause, 0, len(errs))
  217. for i := range errs {
  218. err := errs[i]
  219. causes = append(causes, metav1.StatusCause{
  220. Type: metav1.CauseType(err.Type),
  221. Message: err.ErrorBody(),
  222. Field: err.Field,
  223. })
  224. }
  225. return &StatusError{metav1.Status{
  226. Status: metav1.StatusFailure,
  227. Code: http.StatusUnprocessableEntity,
  228. Reason: metav1.StatusReasonInvalid,
  229. Details: &metav1.StatusDetails{
  230. Group: qualifiedKind.Group,
  231. Kind: qualifiedKind.Kind,
  232. Name: name,
  233. Causes: causes,
  234. },
  235. Message: fmt.Sprintf("%s %q is invalid: %v", qualifiedKind.String(), name, errs.ToAggregate()),
  236. }}
  237. }
  238. // NewBadRequest creates an error that indicates that the request is invalid and can not be processed.
  239. func NewBadRequest(reason string) *StatusError {
  240. return &StatusError{metav1.Status{
  241. Status: metav1.StatusFailure,
  242. Code: http.StatusBadRequest,
  243. Reason: metav1.StatusReasonBadRequest,
  244. Message: reason,
  245. }}
  246. }
  247. // NewTooManyRequests creates an error that indicates that the client must try again later because
  248. // the specified endpoint is not accepting requests. More specific details should be provided
  249. // if client should know why the failure was limited4.
  250. func NewTooManyRequests(message string, retryAfterSeconds int) *StatusError {
  251. return &StatusError{metav1.Status{
  252. Status: metav1.StatusFailure,
  253. Code: http.StatusTooManyRequests,
  254. Reason: metav1.StatusReasonTooManyRequests,
  255. Message: message,
  256. Details: &metav1.StatusDetails{
  257. RetryAfterSeconds: int32(retryAfterSeconds),
  258. },
  259. }}
  260. }
  261. // NewServiceUnavailable creates an error that indicates that the requested service is unavailable.
  262. func NewServiceUnavailable(reason string) *StatusError {
  263. return &StatusError{metav1.Status{
  264. Status: metav1.StatusFailure,
  265. Code: http.StatusServiceUnavailable,
  266. Reason: metav1.StatusReasonServiceUnavailable,
  267. Message: reason,
  268. }}
  269. }
  270. // NewMethodNotSupported returns an error indicating the requested action is not supported on this kind.
  271. func NewMethodNotSupported(qualifiedResource schema.GroupResource, action string) *StatusError {
  272. return &StatusError{metav1.Status{
  273. Status: metav1.StatusFailure,
  274. Code: http.StatusMethodNotAllowed,
  275. Reason: metav1.StatusReasonMethodNotAllowed,
  276. Details: &metav1.StatusDetails{
  277. Group: qualifiedResource.Group,
  278. Kind: qualifiedResource.Resource,
  279. },
  280. Message: fmt.Sprintf("%s is not supported on resources of kind %q", action, qualifiedResource.String()),
  281. }}
  282. }
  283. // NewServerTimeout returns an error indicating the requested action could not be completed due to a
  284. // transient error, and the client should try again.
  285. func NewServerTimeout(qualifiedResource schema.GroupResource, operation string, retryAfterSeconds int) *StatusError {
  286. return &StatusError{metav1.Status{
  287. Status: metav1.StatusFailure,
  288. Code: http.StatusInternalServerError,
  289. Reason: metav1.StatusReasonServerTimeout,
  290. Details: &metav1.StatusDetails{
  291. Group: qualifiedResource.Group,
  292. Kind: qualifiedResource.Resource,
  293. Name: operation,
  294. RetryAfterSeconds: int32(retryAfterSeconds),
  295. },
  296. Message: fmt.Sprintf("The %s operation against %s could not be completed at this time, please try again.", operation, qualifiedResource.String()),
  297. }}
  298. }
  299. // NewServerTimeoutForKind should not exist. Server timeouts happen when accessing resources, the Kind is just what we
  300. // happened to be looking at when the request failed. This delegates to keep code sane, but we should work towards removing this.
  301. func NewServerTimeoutForKind(qualifiedKind schema.GroupKind, operation string, retryAfterSeconds int) *StatusError {
  302. return NewServerTimeout(schema.GroupResource{Group: qualifiedKind.Group, Resource: qualifiedKind.Kind}, operation, retryAfterSeconds)
  303. }
  304. // NewInternalError returns an error indicating the item is invalid and cannot be processed.
  305. func NewInternalError(err error) *StatusError {
  306. return &StatusError{metav1.Status{
  307. Status: metav1.StatusFailure,
  308. Code: http.StatusInternalServerError,
  309. Reason: metav1.StatusReasonInternalError,
  310. Details: &metav1.StatusDetails{
  311. Causes: []metav1.StatusCause{{Message: err.Error()}},
  312. },
  313. Message: fmt.Sprintf("Internal error occurred: %v", err),
  314. }}
  315. }
  316. // NewTimeoutError returns an error indicating that a timeout occurred before the request
  317. // could be completed. Clients may retry, but the operation may still complete.
  318. func NewTimeoutError(message string, retryAfterSeconds int) *StatusError {
  319. return &StatusError{metav1.Status{
  320. Status: metav1.StatusFailure,
  321. Code: http.StatusGatewayTimeout,
  322. Reason: metav1.StatusReasonTimeout,
  323. Message: fmt.Sprintf("Timeout: %s", message),
  324. Details: &metav1.StatusDetails{
  325. RetryAfterSeconds: int32(retryAfterSeconds),
  326. },
  327. }}
  328. }
  329. // NewTooManyRequestsError returns an error indicating that the request was rejected because
  330. // the server has received too many requests. Client should wait and retry. But if the request
  331. // is perishable, then the client should not retry the request.
  332. func NewTooManyRequestsError(message string) *StatusError {
  333. return &StatusError{metav1.Status{
  334. Status: metav1.StatusFailure,
  335. Code: http.StatusTooManyRequests,
  336. Reason: metav1.StatusReasonTooManyRequests,
  337. Message: fmt.Sprintf("Too many requests: %s", message),
  338. }}
  339. }
  340. // NewRequestEntityTooLargeError returns an error indicating that the request
  341. // entity was too large.
  342. func NewRequestEntityTooLargeError(message string) *StatusError {
  343. return &StatusError{metav1.Status{
  344. Status: metav1.StatusFailure,
  345. Code: http.StatusRequestEntityTooLarge,
  346. Reason: metav1.StatusReasonRequestEntityTooLarge,
  347. Message: fmt.Sprintf("Request entity too large: %s", message),
  348. }}
  349. }
  350. // NewGenericServerResponse returns a new error for server responses that are not in a recognizable form.
  351. func NewGenericServerResponse(code int, verb string, qualifiedResource schema.GroupResource, name, serverMessage string, retryAfterSeconds int, isUnexpectedResponse bool) *StatusError {
  352. reason := metav1.StatusReasonUnknown
  353. message := fmt.Sprintf("the server responded with the status code %d but did not return more information", code)
  354. switch code {
  355. case http.StatusConflict:
  356. if verb == "POST" {
  357. reason = metav1.StatusReasonAlreadyExists
  358. } else {
  359. reason = metav1.StatusReasonConflict
  360. }
  361. message = "the server reported a conflict"
  362. case http.StatusNotFound:
  363. reason = metav1.StatusReasonNotFound
  364. message = "the server could not find the requested resource"
  365. case http.StatusBadRequest:
  366. reason = metav1.StatusReasonBadRequest
  367. message = "the server rejected our request for an unknown reason"
  368. case http.StatusUnauthorized:
  369. reason = metav1.StatusReasonUnauthorized
  370. message = "the server has asked for the client to provide credentials"
  371. case http.StatusForbidden:
  372. reason = metav1.StatusReasonForbidden
  373. // the server message has details about who is trying to perform what action. Keep its message.
  374. message = serverMessage
  375. case http.StatusNotAcceptable:
  376. reason = metav1.StatusReasonNotAcceptable
  377. // the server message has details about what types are acceptable
  378. if len(serverMessage) == 0 || serverMessage == "unknown" {
  379. message = "the server was unable to respond with a content type that the client supports"
  380. } else {
  381. message = serverMessage
  382. }
  383. case http.StatusUnsupportedMediaType:
  384. reason = metav1.StatusReasonUnsupportedMediaType
  385. // the server message has details about what types are acceptable
  386. message = serverMessage
  387. case http.StatusMethodNotAllowed:
  388. reason = metav1.StatusReasonMethodNotAllowed
  389. message = "the server does not allow this method on the requested resource"
  390. case http.StatusUnprocessableEntity:
  391. reason = metav1.StatusReasonInvalid
  392. message = "the server rejected our request due to an error in our request"
  393. case http.StatusServiceUnavailable:
  394. reason = metav1.StatusReasonServiceUnavailable
  395. message = "the server is currently unable to handle the request"
  396. case http.StatusGatewayTimeout:
  397. reason = metav1.StatusReasonTimeout
  398. message = "the server was unable to return a response in the time allotted, but may still be processing the request"
  399. case http.StatusTooManyRequests:
  400. reason = metav1.StatusReasonTooManyRequests
  401. message = "the server has received too many requests and has asked us to try again later"
  402. default:
  403. if code >= 500 {
  404. reason = metav1.StatusReasonInternalError
  405. message = fmt.Sprintf("an error on the server (%q) has prevented the request from succeeding", serverMessage)
  406. }
  407. }
  408. switch {
  409. case !qualifiedResource.Empty() && len(name) > 0:
  410. message = fmt.Sprintf("%s (%s %s %s)", message, strings.ToLower(verb), qualifiedResource.String(), name)
  411. case !qualifiedResource.Empty():
  412. message = fmt.Sprintf("%s (%s %s)", message, strings.ToLower(verb), qualifiedResource.String())
  413. }
  414. var causes []metav1.StatusCause
  415. if isUnexpectedResponse {
  416. causes = []metav1.StatusCause{
  417. {
  418. Type: metav1.CauseTypeUnexpectedServerResponse,
  419. Message: serverMessage,
  420. },
  421. }
  422. } else {
  423. causes = nil
  424. }
  425. return &StatusError{metav1.Status{
  426. Status: metav1.StatusFailure,
  427. Code: int32(code),
  428. Reason: reason,
  429. Details: &metav1.StatusDetails{
  430. Group: qualifiedResource.Group,
  431. Kind: qualifiedResource.Resource,
  432. Name: name,
  433. Causes: causes,
  434. RetryAfterSeconds: int32(retryAfterSeconds),
  435. },
  436. Message: message,
  437. }}
  438. }
  439. // IsNotFound returns true if the specified error was created by NewNotFound.
  440. // It supports wrapped errors.
  441. func IsNotFound(err error) bool {
  442. return ReasonForError(err) == metav1.StatusReasonNotFound
  443. }
  444. // IsAlreadyExists determines if the err is an error which indicates that a specified resource already exists.
  445. // It supports wrapped errors.
  446. func IsAlreadyExists(err error) bool {
  447. return ReasonForError(err) == metav1.StatusReasonAlreadyExists
  448. }
  449. // IsConflict determines if the err is an error which indicates the provided update conflicts.
  450. // It supports wrapped errors.
  451. func IsConflict(err error) bool {
  452. return ReasonForError(err) == metav1.StatusReasonConflict
  453. }
  454. // IsInvalid determines if the err is an error which indicates the provided resource is not valid.
  455. // It supports wrapped errors.
  456. func IsInvalid(err error) bool {
  457. return ReasonForError(err) == metav1.StatusReasonInvalid
  458. }
  459. // IsGone is true if the error indicates the requested resource is no longer available.
  460. // It supports wrapped errors.
  461. func IsGone(err error) bool {
  462. return ReasonForError(err) == metav1.StatusReasonGone
  463. }
  464. // IsResourceExpired is true if the error indicates the resource has expired and the current action is
  465. // no longer possible.
  466. // It supports wrapped errors.
  467. func IsResourceExpired(err error) bool {
  468. return ReasonForError(err) == metav1.StatusReasonExpired
  469. }
  470. // IsNotAcceptable determines if err is an error which indicates that the request failed due to an invalid Accept header
  471. // It supports wrapped errors.
  472. func IsNotAcceptable(err error) bool {
  473. return ReasonForError(err) == metav1.StatusReasonNotAcceptable
  474. }
  475. // IsUnsupportedMediaType determines if err is an error which indicates that the request failed due to an invalid Content-Type header
  476. // It supports wrapped errors.
  477. func IsUnsupportedMediaType(err error) bool {
  478. return ReasonForError(err) == metav1.StatusReasonUnsupportedMediaType
  479. }
  480. // IsMethodNotSupported determines if the err is an error which indicates the provided action could not
  481. // be performed because it is not supported by the server.
  482. // It supports wrapped errors.
  483. func IsMethodNotSupported(err error) bool {
  484. return ReasonForError(err) == metav1.StatusReasonMethodNotAllowed
  485. }
  486. // IsServiceUnavailable is true if the error indicates the underlying service is no longer available.
  487. // It supports wrapped errors.
  488. func IsServiceUnavailable(err error) bool {
  489. return ReasonForError(err) == metav1.StatusReasonServiceUnavailable
  490. }
  491. // IsBadRequest determines if err is an error which indicates that the request is invalid.
  492. // It supports wrapped errors.
  493. func IsBadRequest(err error) bool {
  494. return ReasonForError(err) == metav1.StatusReasonBadRequest
  495. }
  496. // IsUnauthorized determines if err is an error which indicates that the request is unauthorized and
  497. // requires authentication by the user.
  498. // It supports wrapped errors.
  499. func IsUnauthorized(err error) bool {
  500. return ReasonForError(err) == metav1.StatusReasonUnauthorized
  501. }
  502. // IsForbidden determines if err is an error which indicates that the request is forbidden and cannot
  503. // be completed as requested.
  504. // It supports wrapped errors.
  505. func IsForbidden(err error) bool {
  506. return ReasonForError(err) == metav1.StatusReasonForbidden
  507. }
  508. // IsTimeout determines if err is an error which indicates that request times out due to long
  509. // processing.
  510. // It supports wrapped errors.
  511. func IsTimeout(err error) bool {
  512. return ReasonForError(err) == metav1.StatusReasonTimeout
  513. }
  514. // IsServerTimeout determines if err is an error which indicates that the request needs to be retried
  515. // by the client.
  516. // It supports wrapped errors.
  517. func IsServerTimeout(err error) bool {
  518. return ReasonForError(err) == metav1.StatusReasonServerTimeout
  519. }
  520. // IsInternalError determines if err is an error which indicates an internal server error.
  521. // It supports wrapped errors.
  522. func IsInternalError(err error) bool {
  523. return ReasonForError(err) == metav1.StatusReasonInternalError
  524. }
  525. // IsTooManyRequests determines if err is an error which indicates that there are too many requests
  526. // that the server cannot handle.
  527. // It supports wrapped errors.
  528. func IsTooManyRequests(err error) bool {
  529. if ReasonForError(err) == metav1.StatusReasonTooManyRequests {
  530. return true
  531. }
  532. if status := APIStatus(nil); errors.As(err, &status) {
  533. return status.Status().Code == http.StatusTooManyRequests
  534. }
  535. return false
  536. }
  537. // IsRequestEntityTooLargeError determines if err is an error which indicates
  538. // the request entity is too large.
  539. // It supports wrapped errors.
  540. func IsRequestEntityTooLargeError(err error) bool {
  541. if ReasonForError(err) == metav1.StatusReasonRequestEntityTooLarge {
  542. return true
  543. }
  544. if status := APIStatus(nil); errors.As(err, &status) {
  545. return status.Status().Code == http.StatusRequestEntityTooLarge
  546. }
  547. return false
  548. }
  549. // IsUnexpectedServerError returns true if the server response was not in the expected API format,
  550. // and may be the result of another HTTP actor.
  551. // It supports wrapped errors.
  552. func IsUnexpectedServerError(err error) bool {
  553. if status := APIStatus(nil); errors.As(err, &status) && status.Status().Details != nil {
  554. for _, cause := range status.Status().Details.Causes {
  555. if cause.Type == metav1.CauseTypeUnexpectedServerResponse {
  556. return true
  557. }
  558. }
  559. }
  560. return false
  561. }
  562. // IsUnexpectedObjectError determines if err is due to an unexpected object from the master.
  563. // It supports wrapped errors.
  564. func IsUnexpectedObjectError(err error) bool {
  565. uoe := &UnexpectedObjectError{}
  566. return err != nil && errors.As(err, &uoe)
  567. }
  568. // SuggestsClientDelay returns true if this error suggests a client delay as well as the
  569. // suggested seconds to wait, or false if the error does not imply a wait. It does not
  570. // address whether the error *should* be retried, since some errors (like a 3xx) may
  571. // request delay without retry.
  572. // It supports wrapped errors.
  573. func SuggestsClientDelay(err error) (int, bool) {
  574. if t := APIStatus(nil); errors.As(err, &t) && t.Status().Details != nil {
  575. switch t.Status().Reason {
  576. // this StatusReason explicitly requests the caller to delay the action
  577. case metav1.StatusReasonServerTimeout:
  578. return int(t.Status().Details.RetryAfterSeconds), true
  579. }
  580. // If the client requests that we retry after a certain number of seconds
  581. if t.Status().Details.RetryAfterSeconds > 0 {
  582. return int(t.Status().Details.RetryAfterSeconds), true
  583. }
  584. }
  585. return 0, false
  586. }
  587. // ReasonForError returns the HTTP status for a particular error.
  588. // It supports wrapped errors.
  589. func ReasonForError(err error) metav1.StatusReason {
  590. if status := APIStatus(nil); errors.As(err, &status) {
  591. return status.Status().Reason
  592. }
  593. return metav1.StatusReasonUnknown
  594. }
  595. // ErrorReporter converts generic errors into runtime.Object errors without
  596. // requiring the caller to take a dependency on meta/v1 (where Status lives).
  597. // This prevents circular dependencies in core watch code.
  598. type ErrorReporter struct {
  599. code int
  600. verb string
  601. reason string
  602. }
  603. // NewClientErrorReporter will respond with valid v1.Status objects that report
  604. // unexpected server responses. Primarily used by watch to report errors when
  605. // we attempt to decode a response from the server and it is not in the form
  606. // we expect. Because watch is a dependency of the core api, we can't return
  607. // meta/v1.Status in that package and so much inject this interface to convert a
  608. // generic error as appropriate. The reason is passed as a unique status cause
  609. // on the returned status, otherwise the generic "ClientError" is returned.
  610. func NewClientErrorReporter(code int, verb string, reason string) *ErrorReporter {
  611. return &ErrorReporter{
  612. code: code,
  613. verb: verb,
  614. reason: reason,
  615. }
  616. }
  617. // AsObject returns a valid error runtime.Object (a v1.Status) for the given
  618. // error, using the code and verb of the reporter type. The error is set to
  619. // indicate that this was an unexpected server response.
  620. func (r *ErrorReporter) AsObject(err error) runtime.Object {
  621. status := NewGenericServerResponse(r.code, r.verb, schema.GroupResource{}, "", err.Error(), 0, true)
  622. if status.ErrStatus.Details == nil {
  623. status.ErrStatus.Details = &metav1.StatusDetails{}
  624. }
  625. reason := r.reason
  626. if len(reason) == 0 {
  627. reason = "ClientError"
  628. }
  629. status.ErrStatus.Details.Causes = append(status.ErrStatus.Details.Causes, metav1.StatusCause{
  630. Type: metav1.CauseType(reason),
  631. Message: err.Error(),
  632. })
  633. return &status.ErrStatus
  634. }