Skip to content
This repository was archived by the owner on Sep 30, 2024. It is now read-only.

Commit c222523

Browse files
authored
Redis: remove some direct pool usages (#64447)
We want to discourage direct usage of the Redis pool in favor of routing all calls through the main `KeyValue` interface. This PR removes several usages of `KeyValue.Pool`. To do so, it adds "PING" and "MGET" to the `KeyValue` interface.
1 parent d3a3d72 commit c222523

File tree

12 files changed

+319
-110
lines changed

12 files changed

+319
-110
lines changed

cmd/cody-gateway/internal/httpapi/BUILD.bazel

-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ go_library(
3636
"//internal/version",
3737
"//lib/errors",
3838
"//lib/pointers",
39-
"@com_github_gomodule_redigo//redis",
4039
"@com_github_gorilla_mux//:mux",
4140
"@com_github_khan_genqlient//graphql",
4241
"@com_github_sourcegraph_log//:log",

cmd/cody-gateway/internal/httpapi/diagnostics.go

+5-21
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"net/http"
77
"strings"
88

9-
"github.com/gomodule/redigo/redis"
109
"github.com/sourcegraph/log"
1110
"github.com/sourcegraph/log/hook"
1211
"github.com/sourcegraph/log/output"
@@ -17,16 +16,16 @@ import (
1716
"github.com/sourcegraph/sourcegraph/cmd/cody-gateway/internal/response"
1817
"github.com/sourcegraph/sourcegraph/internal/authbearer"
1918
"github.com/sourcegraph/sourcegraph/internal/instrumentation"
19+
"github.com/sourcegraph/sourcegraph/internal/redispool"
2020
sgtrace "github.com/sourcegraph/sourcegraph/internal/trace"
2121
"github.com/sourcegraph/sourcegraph/internal/version"
22-
"github.com/sourcegraph/sourcegraph/lib/errors"
2322
)
2423

2524
// NewDiagnosticsHandler creates a handler for diagnostic endpoints typically served
2625
// on "/-/..." paths. It should be placed before any authentication middleware, since
2726
// we do a simple auth on a static secret instead that is uniquely generated per
2827
// deployment.
29-
func NewDiagnosticsHandler(baseLogger log.Logger, next http.Handler, redisPool *redis.Pool, secret string, sources *actor.Sources) http.Handler {
28+
func NewDiagnosticsHandler(baseLogger log.Logger, next http.Handler, redisCache redispool.KeyValue, secret string, sources *actor.Sources) http.Handler {
3029
baseLogger = baseLogger.Scoped("diagnostics")
3130

3231
hasValidSecret := func(l log.Logger, w http.ResponseWriter, r *http.Request) (yes bool) {
@@ -58,7 +57,7 @@ func NewDiagnosticsHandler(baseLogger log.Logger, next http.Handler, redisPool *
5857
return
5958
}
6059

61-
if err := healthz(r.Context(), redisPool); err != nil {
60+
if err := healthz(r.Context(), redisCache); err != nil {
6261
logger.Error("check failed", log.Error(err))
6362

6463
w.WriteHeader(http.StatusInternalServerError)
@@ -110,21 +109,6 @@ func NewDiagnosticsHandler(baseLogger log.Logger, next http.Handler, redisPool *
110109
})
111110
}
112111

113-
func healthz(ctx context.Context, rpool *redis.Pool) error {
114-
// Check redis health
115-
rconn, err := rpool.GetContext(ctx)
116-
if err != nil {
117-
return errors.Wrap(err, "redis: failed to get conn")
118-
}
119-
defer rconn.Close()
120-
121-
data, err := rconn.Do("PING")
122-
if err != nil {
123-
return errors.Wrap(err, "redis: failed to ping")
124-
}
125-
if data != "PONG" {
126-
return errors.New("redis: failed to ping: no pong received")
127-
}
128-
129-
return nil
112+
func healthz(ctx context.Context, cache redispool.KeyValue) error {
113+
return cache.WithContext(ctx).Ping()
130114
}

cmd/cody-gateway/shared/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ func Main(ctx context.Context, obctx *observation.Context, ready service.ReadyFu
241241
return errors.Wrap(err, "httpapi.NewHandler")
242242
}
243243
// Diagnostic and Maintenance layers, exposing additional APIs and endpoints.
244-
handler = httpapi.NewDiagnosticsHandler(obctx.Logger, handler, redisCache.Pool(), cfg.DiagnosticsSecret, sources)
244+
handler = httpapi.NewDiagnosticsHandler(obctx.Logger, handler, redisCache, cfg.DiagnosticsSecret, sources)
245245
handler = httpapi.NewMaintenanceHandler(obctx.Logger, handler, cfg, redisCache)
246246

247247
// Collect request client for downstream handlers. Outside of dev, we always set up

cmd/frontend/internal/cli/serve_cmd.go

+1-14
Original file line numberDiff line numberDiff line change
@@ -450,19 +450,6 @@ func GetInternalAddr() string {
450450
return httpAddrInternal
451451
}
452452

453-
func pingRedis(kv redispool.KeyValue) error {
454-
conn := kv.Pool().Get()
455-
defer conn.Close()
456-
data, err := conn.Do("PING")
457-
if err != nil {
458-
return err
459-
}
460-
if data != "PONG" {
461-
return errors.New("no pong received")
462-
}
463-
return nil
464-
}
465-
466453
// waitForRedis waits up to a certain timeout for Redis to become reachable, to reduce the
467454
// likelihood of the HTTP handlers starting to serve requests while Redis (and therefore session
468455
// data) is still unavailable. After the timeout has elapsed, if Redis is still unreachable, it
@@ -473,7 +460,7 @@ func waitForRedis(logger sglog.Logger, kv redispool.KeyValue) {
473460
var err error
474461
for {
475462
time.Sleep(150 * time.Millisecond)
476-
err = pingRedis(kv)
463+
err = kv.Ping()
477464
if err == nil {
478465
return
479466
}

internal/metrics/store/BUILD.bazel

-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ go_library(
1212
deps = [
1313
"//internal/redispool",
1414
"//lib/errors",
15-
"@com_github_gomodule_redigo//redis",
1615
"@com_github_prometheus_client_golang//prometheus",
1716
"@com_github_prometheus_client_model//go",
1817
"@com_github_prometheus_common//expfmt",

internal/metrics/store/store.go

+5-22
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"io"
66
"strings"
77

8-
"github.com/gomodule/redigo/redis"
98
"github.com/prometheus/client_golang/prometheus"
109
dto "github.com/prometheus/client_model/go"
1110
"github.com/prometheus/common/expfmt"
@@ -20,16 +19,6 @@ type Store interface {
2019
prometheus.Gatherer
2120
}
2221

23-
func NewDefaultStore() Store {
24-
return &defaultStore{}
25-
}
26-
27-
type defaultStore struct{}
28-
29-
func (*defaultStore) Gather() ([]*dto.MetricFamily, error) {
30-
return prometheus.DefaultGatherer.Gather()
31-
}
32-
3322
type DistributedStore interface {
3423
Store
3524
Ingest(instance string, mfs []*dto.MetricFamily) error
@@ -48,13 +37,10 @@ type distributedStore struct {
4837
}
4938

5039
func (d *distributedStore) Gather() ([]*dto.MetricFamily, error) {
51-
pool := redispool.Cache.Pool()
52-
53-
reConn := pool.Get()
54-
defer reConn.Close()
40+
cache := redispool.Cache
5541

5642
// First, list all the keys for which we hold metrics.
57-
keys, err := redis.Values(reConn.Do("KEYS", d.prefix+"*"))
43+
keys, err := cache.Keys(d.prefix + "*")
5844
if err != nil {
5945
return nil, errors.Wrap(err, "listing entries from redis")
6046
}
@@ -64,7 +50,7 @@ func (d *distributedStore) Gather() ([]*dto.MetricFamily, error) {
6450
}
6551

6652
// Then bulk retrieve all the metrics blobs for all the instances.
67-
encodedMetrics, err := redis.Strings(reConn.Do("MGET", keys...))
53+
encodedMetrics, err := cache.MGet(keys).Strings()
6854
if err != nil {
6955
return nil, errors.Wrap(err, "retrieving blobs from redis")
7056
}
@@ -92,7 +78,7 @@ func (d *distributedStore) Gather() ([]*dto.MetricFamily, error) {
9278
}
9379

9480
func (d *distributedStore) Ingest(instance string, mfs []*dto.MetricFamily) error {
95-
pool := redispool.Cache.Pool()
81+
cache := redispool.Cache
9682

9783
// First, encode the metrics to text format so we can store them.
9884
var enc bytes.Buffer
@@ -106,13 +92,10 @@ func (d *distributedStore) Ingest(instance string, mfs []*dto.MetricFamily) erro
10692

10793
encodedMetrics := enc.String()
10894

109-
reConn := pool.Get()
110-
defer reConn.Close()
111-
11295
// Store the metrics and set an expiry on the key, if we haven't retrieved
11396
// an updated set of metric data, we consider the host down and prune it
11497
// from the gatherer.
115-
err := reConn.Send("SETEX", d.prefix+instance, d.expiry, encodedMetrics)
98+
err := cache.SetEx(d.prefix+instance, d.expiry, encodedMetrics)
11699
if err != nil {
117100
return errors.Wrap(err, "writing metrics blob to redis")
118101
}

internal/ratelimit/globallimiter.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -499,15 +499,11 @@ func SetupForTest(t TB) {
499499
t.Helper()
500500

501501
kvMock = redispool.NewTestKeyValue()
502-
503502
tokenBucketGlobalPrefix = "__test__" + t.Name()
504-
c := kvMock.Pool().Get()
505-
defer c.Close()
506503

507504
// If we are not on CI, skip the test if our redis connection fails.
508505
if os.Getenv("CI") == "" {
509-
_, err := c.Do("PING")
510-
if err != nil {
506+
if err := kvMock.Ping(); err != nil {
511507
t.Skip("could not connect to redis", err)
512508
}
513509
}

internal/rcache/rcache.go

+1-4
Original file line numberDiff line numberDiff line change
@@ -250,13 +250,10 @@ func SetupForTest(t testing.TB) redispool.KeyValue {
250250
})
251251

252252
globalPrefix = "__test__" + t.Name()
253-
c := kvMock.Pool().Get()
254-
defer c.Close()
255253

256254
// If we are not on CI, skip the test if our redis connection fails.
257255
if os.Getenv("CI") == "" {
258-
_, err := c.Do("PING")
259-
if err != nil {
256+
if err := kvMock.Ping(); err != nil {
260257
t.Skip("could not connect to redis", err)
261258
}
262259
}

0 commit comments

Comments
 (0)