resource.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 core
  15. import (
  16. "yunion.io/x/pkg/utils"
  17. )
  18. type value_t interface{}
  19. type ResourceAlgorithm interface {
  20. Sum(values []value_t) value_t
  21. Sub(sum value_t, reserved value_t) value_t
  22. }
  23. type DefaultResAlgorithm struct{}
  24. func (al *DefaultResAlgorithm) Sum(values []value_t) value_t {
  25. var ret int64 = 0
  26. for _, value := range values {
  27. if value != nil {
  28. ret += value.(int64)
  29. }
  30. }
  31. return ret
  32. }
  33. func (al *DefaultResAlgorithm) Sub(sum value_t, reserved value_t) value_t {
  34. if sum == nil {
  35. return nil
  36. }
  37. if reserved == nil {
  38. return sum
  39. }
  40. return sum.(int64) - reserved.(int64)
  41. }
  42. var (
  43. g_defaultResAlgorithm *DefaultResAlgorithm = &DefaultResAlgorithm{}
  44. )
  45. func GetResourceAlgorithm(res_name string) ResourceAlgorithm {
  46. switch res_name {
  47. //case "Groups":
  48. //return g_groupResAlgorithm
  49. case "FreeCPUCount", "FreeMemSize", "FreeLocalStorageSize", "Ports":
  50. return g_defaultResAlgorithm
  51. default:
  52. if utils.HasPrefix(res_name, "FreeStorageSize:") {
  53. return g_defaultResAlgorithm
  54. }
  55. return nil
  56. }
  57. }
  58. func ReservedSub(key string, value value_t, reserved value_t) value_t {
  59. al := GetResourceAlgorithm(key)
  60. if al != nil {
  61. return al.Sub(value, reserved)
  62. }
  63. return value
  64. }