distcache.go 1.7 KB

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