errors.go 20 KB

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