quotas.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package models
  2. import (
  3. "github.com/grafana/grafana/pkg/bus"
  4. "github.com/grafana/grafana/pkg/setting"
  5. "time"
  6. )
  7. type QuotaTarget string
  8. const (
  9. QUOTA_USER QuotaTarget = "user" //SQL table to query. ie. "select count(*) from user where org_id=?"
  10. QUOTA_DATASOURCE QuotaTarget = "data_source"
  11. QUOTA_DASHBOARD QuotaTarget = "dashboard"
  12. QUOTA_ENDPOINT QuotaTarget = "endpoint"
  13. QUOTA_COLLECTOR QuotaTarget = "collector"
  14. )
  15. // defaults are set from settings package.
  16. var DefaultQuotas map[QuotaTarget]int64
  17. func InitQuotaDefaults() {
  18. // set global defaults.
  19. DefaultQuotas = make(map[QuotaTarget]int64)
  20. quota := setting.Cfg.Section("quota")
  21. DefaultQuotas[QUOTA_USER] = quota.Key("user").MustInt64(10)
  22. DefaultQuotas[QUOTA_DATASOURCE] = quota.Key("data_source").MustInt64(10)
  23. DefaultQuotas[QUOTA_DASHBOARD] = quota.Key("dashboard").MustInt64(10)
  24. DefaultQuotas[QUOTA_ENDPOINT] = quota.Key("endpoint").MustInt64(10)
  25. DefaultQuotas[QUOTA_COLLECTOR] = quota.Key("collector").MustInt64(10)
  26. }
  27. type Quota struct {
  28. Id int64
  29. OrgId int64
  30. Target QuotaTarget
  31. Limit int64
  32. Created time.Time
  33. Updated time.Time
  34. }
  35. type QuotaDTO struct {
  36. OrgId int64 `json:"org_id"`
  37. Target QuotaTarget `json:"target"`
  38. Limit int64 `json:"limit"`
  39. Used int64 `json:"used"`
  40. }
  41. type GetQuotaByTargetQuery struct {
  42. Target QuotaTarget
  43. OrgId int64
  44. Result *QuotaDTO
  45. }
  46. type GetQuotasQuery struct {
  47. OrgId int64
  48. Result []*QuotaDTO
  49. }
  50. type UpdateQuotaCmd struct {
  51. Target QuotaTarget `json:"target"`
  52. Limit int64 `json:"limit"`
  53. OrgId int64 `json:"-"`
  54. }
  55. func QuotaReached(org_id int64, target QuotaTarget) (bool, error) {
  56. query := GetQuotaByTargetQuery{OrgId: org_id, Target: target}
  57. if err := bus.Dispatch(&query); err != nil {
  58. return true, err
  59. }
  60. if query.Result.Used >= query.Result.Limit {
  61. return true, nil
  62. }
  63. return false, nil
  64. }