context.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "container/list"
  17. "context"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/appctx"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/onecloud/pkg/mcclient"
  22. )
  23. const (
  24. APP_CONTEXT_KEY_PENDINGUSAGES = appctx.AppContextKey("pendingusages")
  25. )
  26. func initPendingUsagesInContext(ctx context.Context) context.Context {
  27. return context.WithValue(ctx, APP_CONTEXT_KEY_PENDINGUSAGES, list.New())
  28. }
  29. func appContextPendingUsages(ctx context.Context) []IQuota {
  30. val := ctx.Value(APP_CONTEXT_KEY_PENDINGUSAGES)
  31. if val != nil {
  32. quotaList := val.(*list.List)
  33. ret := make([]IQuota, 0)
  34. for e := quotaList.Front(); e != nil; e = e.Next() {
  35. ret = append(ret, e.Value.(IQuota))
  36. }
  37. return ret
  38. } else {
  39. return nil
  40. }
  41. }
  42. func clearPendingUsagesInContext(ctx context.Context) {
  43. val := ctx.Value(APP_CONTEXT_KEY_PENDINGUSAGES)
  44. if val != nil {
  45. quotaList := val.(*list.List)
  46. for quotaList.Len() > 0 {
  47. quotaList.Remove(quotaList.Front())
  48. }
  49. }
  50. }
  51. func savePendingUsagesInContext(ctx context.Context, quotas ...IQuota) {
  52. val := ctx.Value(APP_CONTEXT_KEY_PENDINGUSAGES)
  53. if val != nil {
  54. quotaList := val.(*list.List)
  55. for i := range quotas {
  56. quotaList.PushBack(quotas[i])
  57. }
  58. }
  59. }
  60. func cancelPendingUsagesInContext(ctx context.Context, userCred mcclient.TokenCredential) error {
  61. quotas := appContextPendingUsages(ctx)
  62. if quotas == nil {
  63. return nil
  64. }
  65. errs := make([]error, 0)
  66. for i := range quotas {
  67. // cancel and do not save pending usage
  68. err := CancelPendingUsage(ctx, userCred, quotas[i], quotas[i], false)
  69. if err != nil {
  70. errs = append(errs, errors.Wrapf(err, "CancelPendingUsage %s", jsonutils.Marshal(quotas[i])))
  71. }
  72. }
  73. if len(errs) > 0 {
  74. return errors.NewAggregate(errs)
  75. }
  76. clearPendingUsagesInContext(ctx)
  77. return nil
  78. }