forked from dapr/components-contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
253 lines (221 loc) · 7.65 KB
/
redis.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
/*
Copyright 2021 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package redis
import (
"context"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
jsoniter "github.com/json-iterator/go"
"github.com/dapr/components-contrib/configuration"
"github.com/dapr/components-contrib/configuration/redis/internal"
rediscomponent "github.com/dapr/components-contrib/internal/component/redis"
contribMetadata "github.com/dapr/components-contrib/metadata"
"github.com/dapr/kit/logger"
)
const (
connectedSlavesReplicas = "connected_slaves:"
infoReplicationDelimiter = "\r\n"
defaultBase = 10
defaultBitSize = 0
redisWrongTypeIdentifyStr = "WRONGTYPE"
)
// ConfigurationStore is a Redis configuration store.
type ConfigurationStore struct {
client rediscomponent.RedisClient
clientSettings *rediscomponent.Settings
json jsoniter.API
replicas int
subscribeStopChanMap sync.Map
logger logger.Logger
}
// NewRedisConfigurationStore returns a new redis state store.
func NewRedisConfigurationStore(logger logger.Logger) configuration.Store {
s := &ConfigurationStore{
json: jsoniter.ConfigFastest,
logger: logger,
}
return s
}
// Init does metadata and connection parsing.
func (r *ConfigurationStore) Init(ctx context.Context, metadata configuration.Metadata) error {
var err error
r.client, r.clientSettings, err = rediscomponent.ParseClientFromProperties(metadata.Properties, contribMetadata.ConfigurationStoreType)
if err != nil {
return err
}
if _, err = r.client.PingResult(ctx); err != nil {
return fmt.Errorf("redis store: error connecting to redis at %s: %s", r.clientSettings.Host, err)
}
r.replicas, err = r.getConnectedSlaves(ctx)
return err
}
func (r *ConfigurationStore) getConnectedSlaves(ctx context.Context) (int, error) {
res, err := r.client.DoRead(ctx, "INFO", "replication")
if err != nil {
return 0, err
}
// Response example: https://redis.io/commands/info#return-value
// # Replication\r\nrole:master\r\nconnected_slaves:1\r\n
s, _ := strconv.Unquote(fmt.Sprintf("%q", res))
if len(s) == 0 {
return 0, nil
}
return r.parseConnectedSlaves(s), nil
}
func (r *ConfigurationStore) parseConnectedSlaves(res string) int {
infos := strings.Split(res, infoReplicationDelimiter)
for _, info := range infos {
if strings.Contains(info, connectedSlavesReplicas) {
parsedReplicas, _ := strconv.ParseUint(info[len(connectedSlavesReplicas):], 10, 32)
return int(parsedReplicas)
}
}
return 0
}
func (r *ConfigurationStore) Get(ctx context.Context, req *configuration.GetRequest) (*configuration.GetResponse, error) {
keys := req.Keys
var err error
if len(keys) == 0 {
var res interface{}
if res, err = r.client.DoRead(ctx, "KEYS", "*"); err != nil {
r.logger.Errorf("failed to all keys, error is %s", err)
return nil, err
}
keyList := res.([]interface{})
for _, key := range keyList {
keys = append(keys, fmt.Sprint(key))
}
}
items := make(map[string]*configuration.Item, len(keys))
// query by keys
for _, redisKey := range keys {
item := &configuration.Item{
Metadata: map[string]string{},
}
redisValue, err := r.client.Get(ctx, redisKey)
if err != nil {
if err.Error() == redis.Nil.Error() {
r.logger.Warnf("redis key %s does not exist, ignore it\n", redisKey)
continue
}
if strings.Contains(err.Error(), redisWrongTypeIdentifyStr) {
r.logger.Warnf("redis key %s 's type is not supported, ignore it\n", redisKey)
continue
}
return &configuration.GetResponse{}, fmt.Errorf("fail to get configuration for redis key=%s, error is %s", redisKey, err)
}
val, version := internal.GetRedisValueAndVersion(redisValue)
item.Version = version
item.Value = val
if item.Value != "" {
items[redisKey] = item
}
}
return &configuration.GetResponse{
Items: items,
}, nil
}
func (r *ConfigurationStore) Subscribe(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler) (string, error) {
subscribeID := uuid.New().String()
keyStopChanMap := make(map[string]chan struct{})
if len(req.Keys) == 0 {
// subscribe all keys
stop := make(chan struct{})
allKeysChannel := internal.GetRedisChannelFromKey("*", r.clientSettings.DB)
keyStopChanMap[allKeysChannel] = stop
subscribeArgs := &rediscomponent.ConfigurationSubscribeArgs{
HandleSubscribedChange: r.handleSubscribedChange,
Req: req,
Handler: handler,
RedisChannel: allKeysChannel,
IsAllKeysChannel: true,
ID: subscribeID,
Stop: stop,
}
go r.client.ConfigurationSubscribe(ctx, subscribeArgs)
r.subscribeStopChanMap.Store(subscribeID, keyStopChanMap)
return subscribeID, nil
}
for _, k := range req.Keys {
// subscribe single key
stop := make(chan struct{})
redisChannel := internal.GetRedisChannelFromKey(k, r.clientSettings.DB)
keyStopChanMap[redisChannel] = stop
subscribeArgs := &rediscomponent.ConfigurationSubscribeArgs{
HandleSubscribedChange: r.handleSubscribedChange,
Req: req,
Handler: handler,
RedisChannel: redisChannel,
IsAllKeysChannel: false,
ID: subscribeID,
Stop: stop,
}
go r.client.ConfigurationSubscribe(ctx, subscribeArgs)
}
r.subscribeStopChanMap.Store(subscribeID, keyStopChanMap)
return subscribeID, nil
}
func (r *ConfigurationStore) Unsubscribe(ctx context.Context, req *configuration.UnsubscribeRequest) error {
if keyStopChanMap, ok := r.subscribeStopChanMap.Load(req.ID); ok {
// already exist subscription
for _, stop := range keyStopChanMap.(map[string]chan struct{}) {
close(stop)
}
r.subscribeStopChanMap.Delete(req.ID)
return nil
}
return fmt.Errorf("subscription with id %s does not exist", req.ID)
}
func (r *ConfigurationStore) handleSubscribedChange(ctx context.Context, req *configuration.SubscribeRequest, handler configuration.UpdateHandler, redisChannel string, id string) {
targetKey, err := internal.ParseRedisKeyFromChannel(redisChannel, r.clientSettings.DB)
if err != nil {
r.logger.Errorf("parse redis key failed: %s", err)
return
}
var items map[string]*configuration.Item
// get all keys if only one is changed
getResponse, errGet := r.Get(ctx, &configuration.GetRequest{
Metadata: req.Metadata,
Keys: []string{targetKey},
})
if errGet != nil {
r.logger.Errorf("get response from redis failed: %s", err)
return
}
items = getResponse.Items
if len(items) == 0 {
items = map[string]*configuration.Item{
targetKey: {},
}
}
e := &configuration.UpdateEvent{
Items: items,
ID: id,
}
err = handler(ctx, e)
if err != nil {
r.logger.Errorf("fail to call handler to notify event for configuration update subscribe: %s", err)
}
}
// GetComponentMetadata returns the metadata of the component.
func (r *ConfigurationStore) GetComponentMetadata() map[string]string {
metadataStruct := rediscomponent.Settings{}
metadataInfo := map[string]string{}
contribMetadata.GetMetadataInfoFromStructType(reflect.TypeOf(metadataStruct), &metadataInfo, contribMetadata.ConfigurationStoreType)
return metadataInfo
}