distcache.go 1.9 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 == "memcached" {
  29. return newMemcachedStorage(opts)
  30. }
  31. return newDatabaseCache(sqlstore)
  32. }
  33. // DistributedCache allows Grafana to cache data outside its own process
  34. type DistributedCache struct {
  35. log log.Logger
  36. Client CacheStorage
  37. SQLStore *sqlstore.SqlStore `inject:""`
  38. Cfg *setting.Cfg `inject:""`
  39. }
  40. type cachedItem struct {
  41. Val interface{}
  42. }
  43. func encodeGob(item *cachedItem) ([]byte, error) {
  44. buf := bytes.NewBuffer(nil)
  45. err := gob.NewEncoder(buf).Encode(item)
  46. return buf.Bytes(), err
  47. }
  48. func decodeGob(data []byte, out *cachedItem) error {
  49. buf := bytes.NewBuffer(data)
  50. return gob.NewDecoder(buf).Decode(&out)
  51. }
  52. // CacheStorage allows the caller to set, get and delete items in the cache.
  53. // Cached items are stored as byte arrays and marshalled using "encoding/gob"
  54. // so any struct added to the cache needs to be registred with `gob.Register`
  55. // ex `gob.Register(CacheableStruct{})``
  56. type CacheStorage interface {
  57. // Get reads object from Cache
  58. Get(key string) (interface{}, error)
  59. // Set sets an object into the cache
  60. Set(key string, value interface{}, expire time.Duration) error
  61. // Delete object from cache
  62. Delete(key string) error
  63. }