errors.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2019 Yunion
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package quotas
  15. import (
  16. "fmt"
  17. "strings"
  18. "yunion.io/x/pkg/util/rbacscope"
  19. "yunion.io/x/onecloud/pkg/httperrors"
  20. )
  21. type SOutOfQuotaError struct {
  22. scope rbacscope.TRbacScope
  23. name string
  24. limit int
  25. used int
  26. request int
  27. }
  28. type SOutOfQuotaErrors struct {
  29. errors []SOutOfQuotaError
  30. }
  31. func (e *SOutOfQuotaError) Cause() error {
  32. return httperrors.ErrOutOfQuota
  33. }
  34. func (e *SOutOfQuotaError) Error() string {
  35. return fmt.Sprintf("[%s.%s] limit %d used %d request %d", e.scope, e.name, e.limit, e.used, e.request)
  36. }
  37. func (es *SOutOfQuotaErrors) Error() string {
  38. qs := make([]string, len(es.errors))
  39. for i := range es.errors {
  40. e := es.errors[i]
  41. qs[i] = e.Error()
  42. }
  43. return fmt.Sprintf("Out of quota: %s", strings.Join(qs, ", "))
  44. }
  45. func (es *SOutOfQuotaErrors) IsError() bool {
  46. if len(es.errors) == 0 {
  47. return false
  48. } else {
  49. return true
  50. }
  51. }
  52. func NewOutOfQuotaError() *SOutOfQuotaErrors {
  53. return &SOutOfQuotaErrors{
  54. errors: make([]SOutOfQuotaError, 0),
  55. }
  56. }
  57. func (es *SOutOfQuotaErrors) Add(quota IQuota, name string, limit int, used int, request int) {
  58. scope := quota.GetKeys().Scope()
  59. e := SOutOfQuotaError{
  60. scope: scope,
  61. name: name,
  62. limit: limit,
  63. used: used,
  64. request: request,
  65. }
  66. es.errors = append(es.errors, e)
  67. }
  68. func (es *SOutOfQuotaErrors) Cause() error {
  69. return httperrors.ErrOutOfQuota
  70. }