distcache.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package distcache
  2. import (
  3. "bytes"
  4. "encoding/gob"
  5. "errors"
  6. "github.com/grafana/grafana/pkg/log"
  7. "github.com/grafana/grafana/pkg/services/sqlstore"
  8. "github.com/grafana/grafana/pkg/registry"
  9. )
  10. var (
  11. ErrCacheItemNotFound = errors.New("cache item not found")
  12. )
  13. func init() {
  14. registry.RegisterService(&DistributedCache{})
  15. }
  16. // Init initializes the service
  17. func (ds *DistributedCache) Init() error {
  18. ds.log = log.New("distributed.cache")
  19. ds.Client = createClient(CacheOpts{}, ds.SQLStore)
  20. return nil
  21. }
  22. type CacheOpts struct {
  23. name string
  24. }
  25. func createClient(opts CacheOpts, sqlstore *sqlstore.SqlStore) cacheStorage {
  26. if opts.name == "redis" {
  27. return nil
  28. }
  29. if opts.name == "memcache" {
  30. return nil
  31. }
  32. if opts.name == "memory" {
  33. return nil
  34. }
  35. return &databaseCache{SQLStore: sqlstore}
  36. }
  37. // DistributedCache allows Grafana to cache data outside its own process
  38. type DistributedCache struct {
  39. log log.Logger
  40. Client cacheStorage
  41. SQLStore *sqlstore.SqlStore `inject:""`
  42. }
  43. type Item struct {
  44. Val interface{}
  45. Created int64
  46. Expire int64
  47. }
  48. func EncodeGob(item *Item) ([]byte, error) {
  49. buf := bytes.NewBuffer(nil)
  50. err := gob.NewEncoder(buf).Encode(item)
  51. return buf.Bytes(), err
  52. }
  53. func DecodeGob(data []byte, out *Item) error {
  54. buf := bytes.NewBuffer(data)
  55. return gob.NewDecoder(buf).Decode(&out)
  56. }
  57. type cacheStorage interface {
  58. // Get reads object from Cache
  59. Get(key string) (interface{}, error)
  60. // Puts an object into the cache
  61. Put(key string, value interface{}, expire int64) error
  62. // Delete object from cache
  63. Delete(key string) error
  64. }