errors.go 30 KB

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