-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
mrc_framework.py
390 lines (305 loc) · 12 KB
/
mrc_framework.py
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env python
# Copyright 2023 Google Inc.
#
# 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.
import redis
import subprocess
import time
from google.cloud import logging
import os
import json
import requests
def read_config():
"""
Read the configuration file.
Returns:
dict: The configuration dictionary.
"""
with open('config.json', 'r') as config_file:
config = json.load(config_file)
return config
OUTPUT_LOGS = read_config()['OUTPUT_LOGS']
class redisCluster(redis.cluster.RedisCluster):
"""
A class to interact with a Redis cluster.
Args:
host (str): The host of the Redis cluster.
port (int): The port of the Redis cluster.
password (str): The password of the Redis cluster.
"""
def __init__(self, host, port, password):
"""
Initialize the RedisCluster object.
Args:
host (str): The host of the Redis cluster.
port (int): The port of the Redis cluster.
password (str): The password of the Redis cluster.
"""
self.host = host
self.port = port
self.password = password
self.client = redis.cluster.RedisCluster(host=self.host, port=self.port, password=self.password, decode_responses=False)
# Connect to Redis
redis_client = self.client
# Get all nodes in the cluster
self.cluster_nodes = redis_client.execute_command('CLUSTER NODES')
super().__init__(host=host, port=port, password=password)
def getDBSize(self):
"""
Get the total number of keys in the Redis cluster.
Returns:
int: The total number of keys in the Redis cluster.
"""
cluster_nodes = self.cluster_nodes
key_count = {}
for node in cluster_nodes:
# Check if the node is a master
if 'master' not in str(cluster_nodes[node]['flags']):
continue
# Extract the IP and port of the node
node_ip, node_port = node.split(':')
# Connect to each node and get the key count
node_client = redis.Redis(host=node_ip, port=int(node_port), decode_responses=True)
key_count[node] = node_client.dbsize()
node_client.close()
# Print the key count for each node
for node, count in key_count.items():
node_ip = node.split(':')[0]
node_port = node.split(':')[1]
totalDBSize = sum(key_count.values())
return totalDBSize
def nrandomkeys(self, n):
"""
Get a list of `n` random keys from the Redis cluster.
Args:
n (int): The number of keys to return.
Returns:
set: A set of `n` random keys from the Redis cluster.
"""
redis_client = self.client
size = min(n, self.getDBSize())
keys = set()
counter = 0
while counter <=size :
key = redis_client.randomkey()
keys.add(key)
counter += 1
return keys
def delAllKeys(self):
"""
Delete all keys from the Redis cluster.
"""
cluster_nodes = self.cluster_nodes
for node in cluster_nodes:
node_port = node.split(':')[1]
node_ip = node.split(':')[0]
node_client = redis.cluster.RedisCluster(host=node_ip, port=int(node_port), decode_responses=True)
node_client.flushdb()
write_log(f"DB successfully flushed", target=OUTPUT_LOGS)
def getVal(self, key):
"""
Get the value of a key from the Redis cluster.
Args:
key (str): The key to get the value of.
Returns:
str: The value of the key.
"""
redis_client = self.client
key_type = redis_client.type(key)
if key_type == b'string':
return redis_client.get(key)
elif key_type == b'hash':
return redis_client.hgetall(key)
elif key_type == b'list':
return redis_client.lrange(key, 0, -1)
elif key_type == b'set':
return redis_client.smembers(key)
elif key_type == b'zset':
return redis_client.zrange(key, 0, -1)
else:
write_log(f"Key type not supported", target=OUTPUT_LOGS)
# Add more cases as needed
return None
def backup_cluster(self, cluster_name, gcs_bucket, file_type):
"""
Backup the Redis cluster to a GCS bucket.
Args:
cluster_name (str): The name of the Redis cluster.
gcs_bucket (str): The name of the GCS bucket to backup the cluster to.
"""
# Generate timestamp
timestamp = time.strftime("%Y%m%d%H%M%S")
write_log(f"Exporting Redis data to GCS at {timestamp}",target=OUTPUT_LOGS)
prefix = f"{gcs_bucket}/mrc-redis-backups/{cluster_name}"
# Construct the output filename
output_filename = f"export_{timestamp}.{file_type}"
# Construct the path
path = f"{prefix}/{output_filename}"
write_log(f"File will be placed at {path}", target=OUTPUT_LOGS)
# Check if the directory exists in case of local storage.
if not os.path.exists(prefix) and not gcs_bucket.startswith("gs://") :
# Create the directory
os.makedirs(prefix)
# Construct the bash command
riot_path = read_config()['riot_bin_path']
does_file_exist(riot_path)
bash_command = f"{riot_path}/riot -h {self.host} -p {self.port} -c file-export {path}"
write_log(f"Executing bash command: {bash_command}", target=OUTPUT_LOGS)
webhook_url = read_config()['SLACK_WEBHOOK_URL']
# Run the bash command
exec_subprocess(bash_command)
write_log(f"Export successful. File uploaded to: {path}", target=OUTPUT_LOGS)
send_slack_message(
webhook_url=webhook_url,
message=f"Backup successful for cluster {cluster_name} on {timestamp}")
def restore_cluster(self, restore_file, mode = 'append'):
"""
Restore the Redis cluster from a GCS backup.
Args:
restore_file (str): The path to the GCS backup file.
"""
riot_path = read_config()['riot_bin_path']
does_file_exist(riot_path)
does_file_exist(restore_file)
if mode == 'append':
pass
elif mode == 'replace':
self.delAllKeys()
else:
write_log(f"Invalid mode", target=OUTPUT_LOGS)
exit(1)
bash_command = f"{riot_path}/riot -h {self.host} -p {self.port} -c dump-import {restore_file}"
write_log(f"Executing bash command: {bash_command}", target=OUTPUT_LOGS)
exec_subprocess(bash_command)
write_log(f"Import successful.", target=OUTPUT_LOGS)
def exec_subprocess(bash_command):
try:
result = subprocess.run(bash_command, shell=True, check=True,capture_output = True, text = True)
write_log(f"{result.stdout}", target=OUTPUT_LOGS)
write_log(f"{result.stderr}", target=OUTPUT_LOGS)
except subprocess.CalledProcessError as e:
write_log(f"Error: {e.stderr}", target=OUTPUT_LOGS)
exit(1)
def does_file_exist(file):
"""
Check if a file exists.
Args:
file (str): The path to the file.
Returns:
bool: True if the file exists, False otherwise.
"""
if os.path.exists(file):
return True
else:
write_log(f"Error: {file} does not exist.",target=OUTPUT_LOGS)
exit(1)
# Write to the log
def write_log(message, target = "console"):
"""
Write a message to the log.
Args:
message (str): The message to write to the log.
"""
if target == "console":
print(message)
elif target == "cloud-logging":
client = logging.Client()
logger = client.logger('ms-validation-framework-logs')
logger.log_text(message)
else:
print(message)
client = logging.Client()
logger = client.logger('ms-validation-framework-logs')
logger.log_text(message)
def replicate_data(source , target, replication_mode = 'snapshot', verification_mode = ''):
"""
Replicate data from one Redis cluster to another.
Args:
source (redisCluster): The source Redis cluster.
target (redisCluster): The target Redis cluster.
"""
# Generate timestamp
sourcehost = source.host
sourceport = source.port
tgthost = target.host
tgtport = target.port
verificiation_mode = verification_mode
replication_mode = replication_mode
# Construct the bash command
riot_path = read_config()['riot_bin_path']
does_file_exist(riot_path)
bash_command = f"{riot_path}/riot -h {sourcehost} -p {sourceport} --cluster replicate --mode={replication_mode} -h {tgthost} -p {tgtport} --cluster {verificiation_mode}"
write_log(f"Executing bash command: {bash_command}", target=OUTPUT_LOGS)
try:
subprocess.run(bash_command, shell=True, check=True)
except subprocess.CalledProcessError as e:
write_log(f"Error: {e.stderr}", target=OUTPUT_LOGS)
exit(1)
write_log(f"Replication successful", target=OUTPUT_LOGS)
def validateCounts(source, target):
"""
Validate that the number of keys in two Redis clusters are the same.
Args:
source (redisCluster): The source Redis cluster.
target (redisCluster): The target Redis cluster.
"""
source_size = source.getDBSize()
target_size = target.getDBSize()
if source_size == target_size:
write_log(f"Source and target DB sizes match: {source_size}. Count validation successful", target=OUTPUT_LOGS)
return True
else:
write_log(f"Source and target DB sizes do not match: {source_size} != {target_size}", target=OUTPUT_LOGS)
return False
def deepValidate(sampling_factor, src, tgt):
"""
Deep validate the data in two Redis clusters.
Args:
sampling_factor (float): The sampling factor to use for the deep validation.
src (redisCluster): The source Redis cluster.
tgt (redisCluster): The target Redis cluster.
"""
sample_count = int(round(sampling_factor * src.getDBSize()))
# Get the samples to test in a list
samples = src.nrandomkeys(sample_count)
validationPassed = True
for key in samples:
key_exists = tgt.exists(key)
if key_exists:
srcVal = src.getVal(key)
tgtVal = tgt.getVal(key)
if srcVal != tgtVal:
write_log(f"Invalid Value for key '{key}':\n {tgtVal} \n {srcVal}", target=OUTPUT_LOGS)
validationPassed = False
else:
pass
else:
write_log(f"Key '{key}' is NOT present in Redis.", target=OUTPUT_LOGS)
validationPassed = False
if validationPassed:
write_log(f"Deep validation successful", target=OUTPUT_LOGS)
else:
write_log(f"Deep validation failed", target=OUTPUT_LOGS)
return validationPassed
def send_slack_message(webhook_url, message):
payload = {
"text": message
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(webhook_url, data=json.dumps(payload), headers=headers)
if response.status_code == 200:
write_log(f"Message sent successfully!", target=OUTPUT_LOGS)
else:
write_log(f"Message failed to send to SLACK", target=OUTPUT_LOGS)