grafana/pkg/services/datasources/cache.go

59 lines
1.3 KiB
Go
Raw Normal View History

2018-10-26 03:40:33 -05:00
package datasources
import (
"fmt"
"time"
"github.com/grafana/grafana/pkg/infra/localcache"
"github.com/grafana/grafana/pkg/models"
2018-10-26 03:40:33 -05:00
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/sqlstore"
2018-10-26 03:40:33 -05:00
)
type CacheService interface {
GetDatasource(datasourceID int64, user *models.SignedInUser, skipCache bool) (*models.DataSource, error)
2018-10-26 03:40:33 -05:00
}
type CacheServiceImpl struct {
CacheService *localcache.CacheService `inject:""`
SQLStore *sqlstore.SQLStore `inject:""`
2018-10-26 03:40:33 -05:00
}
func init() {
registry.Register(&registry.Descriptor{
Name: "DatasourceCacheService",
Instance: &CacheServiceImpl{},
InitPriority: registry.Low,
})
2018-10-26 03:40:33 -05:00
}
func (dc *CacheServiceImpl) Init() error {
return nil
}
func (dc *CacheServiceImpl) GetDatasource(
datasourceID int64,
user *models.SignedInUser,
skipCache bool,
) (*models.DataSource, error) {
2018-10-26 03:40:33 -05:00
cacheKey := fmt.Sprintf("ds-%d", datasourceID)
if !skipCache {
if cached, found := dc.CacheService.Get(cacheKey); found {
ds := cached.(*models.DataSource)
2018-10-26 03:40:33 -05:00
if ds.OrgId == user.OrgId {
return ds, nil
}
}
}
plog.Debug("Querying for data source via SQL store", "id", datasourceID, "orgId", user.OrgId)
ds, err := dc.SQLStore.GetDataSourceByID(datasourceID, user.OrgId)
if err != nil {
2018-10-26 03:40:33 -05:00
return nil, err
}
dc.CacheService.Set(cacheKey, ds, time.Second*5)
return ds, nil
2018-10-26 03:40:33 -05:00
}