github.com/thanos-io/thanos@v0.32.5/pkg/store/cache/factory.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package storecache
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/go-kit/log"
    11  	"github.com/go-kit/log/level"
    12  	"github.com/pkg/errors"
    13  	"github.com/prometheus/client_golang/prometheus"
    14  	"gopkg.in/yaml.v2"
    15  
    16  	"github.com/thanos-io/thanos/pkg/cacheutil"
    17  )
    18  
    19  type IndexCacheProvider string
    20  
    21  const (
    22  	INMEMORY  IndexCacheProvider = "IN-MEMORY"
    23  	MEMCACHED IndexCacheProvider = "MEMCACHED"
    24  	REDIS     IndexCacheProvider = "REDIS"
    25  )
    26  
    27  // IndexCacheConfig specifies the index cache config.
    28  type IndexCacheConfig struct {
    29  	Type   IndexCacheProvider `yaml:"type"`
    30  	Config interface{}        `yaml:"config"`
    31  }
    32  
    33  // NewIndexCache initializes and returns new index cache.
    34  func NewIndexCache(logger log.Logger, confContentYaml []byte, reg prometheus.Registerer) (IndexCache, error) {
    35  	level.Info(logger).Log("msg", "loading index cache configuration")
    36  	cacheConfig := &IndexCacheConfig{}
    37  	cacheMetrics := newCommonMetrics(reg)
    38  	if err := yaml.UnmarshalStrict(confContentYaml, cacheConfig); err != nil {
    39  		return nil, errors.Wrap(err, "parsing config YAML file")
    40  	}
    41  
    42  	backendConfig, err := yaml.Marshal(cacheConfig.Config)
    43  	if err != nil {
    44  		return nil, errors.Wrap(err, "marshal content of cache backend configuration")
    45  	}
    46  
    47  	var cache IndexCache
    48  	switch strings.ToUpper(string(cacheConfig.Type)) {
    49  	case string(INMEMORY):
    50  		cache, err = NewInMemoryIndexCache(logger, cacheMetrics, reg, backendConfig)
    51  	case string(MEMCACHED):
    52  		var memcached cacheutil.RemoteCacheClient
    53  		memcached, err = cacheutil.NewMemcachedClient(logger, "index-cache", backendConfig, reg)
    54  		if err == nil {
    55  			cache, err = NewRemoteIndexCache(logger, memcached, cacheMetrics, reg)
    56  		}
    57  	case string(REDIS):
    58  		var redisCache cacheutil.RemoteCacheClient
    59  		redisCache, err = cacheutil.NewRedisClient(logger, "index-cache", backendConfig, reg)
    60  		if err == nil {
    61  			cache, err = NewRemoteIndexCache(logger, redisCache, cacheMetrics, reg)
    62  		}
    63  	default:
    64  		return nil, errors.Errorf("index cache with type %s is not supported", cacheConfig.Type)
    65  	}
    66  	if err != nil {
    67  		return nil, errors.Wrap(err, fmt.Sprintf("create %s index cache", cacheConfig.Type))
    68  	}
    69  	return cache, nil
    70  }