errors.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Copyright 2016 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 streaming
  14. import (
  15. "net/http"
  16. "strconv"
  17. "google.golang.org/grpc/codes"
  18. grpcstatus "google.golang.org/grpc/status"
  19. )
  20. // NewErrorStreamingDisabled creates an error for disabled streaming method.
  21. func NewErrorStreamingDisabled(method string) error {
  22. return grpcstatus.Errorf(codes.NotFound, "streaming method %s disabled", method)
  23. }
  24. // NewErrorTooManyInFlight creates an error for exceeding the maximum number of in-flight requests.
  25. func NewErrorTooManyInFlight() error {
  26. return grpcstatus.Error(codes.ResourceExhausted, "maximum number of in-flight requests exceeded")
  27. }
  28. // WriteError translates a CRI streaming error into an appropriate HTTP response.
  29. func WriteError(err error, w http.ResponseWriter) error {
  30. s, _ := grpcstatus.FromError(err)
  31. var status int
  32. switch s.Code() {
  33. case codes.NotFound:
  34. status = http.StatusNotFound
  35. case codes.ResourceExhausted:
  36. // We only expect to hit this if there is a DoS, so we just wait the full TTL.
  37. // If this is ever hit in steady-state operations, consider increasing the maxInFlight requests,
  38. // or plumbing through the time to next expiration.
  39. w.Header().Set("Retry-After", strconv.Itoa(int(cacheTTL.Seconds())))
  40. status = http.StatusTooManyRequests
  41. default:
  42. status = http.StatusInternalServerError
  43. }
  44. w.WriteHeader(status)
  45. _, writeErr := w.Write([]byte(err.Error()))
  46. return writeErr
  47. }