-
Notifications
You must be signed in to change notification settings - Fork 0
/
standalone-redis-server-script.py
288 lines (224 loc) · 10.1 KB
/
standalone-redis-server-script.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
# -*- coding: utf-8 -*-
import sys
import os
import json
import argparse
from dotenv import load_dotenv
import os
from datetime import datetime
from threading import Thread
import requests
import logging
import warnings
import time
import redis
from rediscluster import RedisCluster
from Redis_Service import Redis_Client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from json import dumps
import logging_loki
warnings.filterwarnings("ignore")
load_dotenv()
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
logging_loki.emitter.LokiEmitter.level_tag = "level"
# assign to a variable named handler
handler = logging_loki.LokiHandler(
url="http://{}:3100/loki/api/v1/push".format(os.getenv("LOKI_HOST")),
version="1",
)
# create a new logger instance, name it whatever you want
logger = logging.getLogger("alert-logger")
logger.addHandler(handler)
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
''' HTTP Listeners'''
def _send_cors_headers(self):
''' set headers requried for CORS'''
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
self.send_header("Access-Control-Allow-Headers", "x-api-key, Content-Type")
def send_dict_response(self, d):
''' send a dict as Json back to the client '''
self.wfile.write(bytes(dumps(d), "utf8"))
def do_GET(self):
''' http://localhost:9999/health?kafka_url=localhost:29092,localhost:39092,localhost:49092&es_url=localhost:9200,localhost:9201,localhost:9203'''
response_dict = {"message" : "Hello World!"}
logging.info(response_dict)
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self._send_cors_headers()
self.end_headers()
self.send_dict_response(response_dict)
def work():
''' get redis all keys from kibana instance'''
def get_es_configuration_files(path):
''' json.loads es-configuration file'''
with open(path, "r") as read_file:
data = json.load(read_file)
return data
def write_es_configuration_files(data):
try:
with open(os.getenv("ES_CONFIGURATION_FILE"), 'w') as f:
# json.dump(data, f)
f.write(json.dumps(data, indent=2))
except Exception as e:
logging.error(e)
logger.error("Prometheus-Alert-Service",
extra={"tags": {"service": "prometheus-alert-service", "message" : str(e)}},
)
def get_mapping_host_config():
''' get_hostname_from_domain '''
try:
''' get all hots '''
mapping_hosts = get_es_configuration_files(os.getenv("ES_CONFIGURATION_MAPPING_FILE"))
# self.logger.info(f"get_mapping_host_config : {hosts}")
# print(f"get_mapping_host_config : {mapping_hosts}")
''' get ./repositoy/mail_config.json '''
return mapping_hosts
except Exception as e:
logging.error(e)
logger.error("Prometheus-Alert-Service",
extra={"tags": {"service": "prometheus-alert-service", "message" : str(e)}},
)
def transform_json(mapping_host_dict, configuration_data, key, alert_bool_option):
''' load and transform data'''
try:
logging.info(f"transform_json")
key = key.decode('utf-8')
alert_bool_option = str(alert_bool_option)
# logging.info(f"key : {key}, value : {str(alert_bool_option).lower()}")
# logging.info(f"type(alert_bool_option) : {type(alert_bool_option)}")
alert_value = True if str(alert_bool_option).lower() == "true" else False
logging.info(f"alert_value : {alert_value}, type(alert_value) : {type(alert_value)}")
''' get host name matched env name to read their json configuraion'''
real_host_name = mapping_host_dict.get(key)
logging.info(f"key : {real_host_name}")
if real_host_name in configuration_data.keys():
logging.info(f"OK #1")
configuration_data[real_host_name]["is_mailing"] = alert_value
''' only update sms for Prod env's'''
if "prod" in key or "dev" in key:
logging.info(f"OK #2")
configuration_data[real_host_name]["is_sms"] = alert_value
except Exception as e:
logging.error(e)
logger.error("Prometheus-Alert-Service",
extra={"tags": {"service": "prometheus-alert-service", "message" : str(e)}},
)
def retry_connnection():
# ... get redis connection here, or pass it in. up to you.
try:
redis_client = Redis_Client(os.getenv('REDIS_SERVER_HOST'))
redis_client.Set_Connect()
return redis_client
except (redis.exceptions.ConnectionError,
redis.exceptions.BusyLoadingError):
logging.error(e)
return None
try:
''' Initial Connection'''
redis_client = retry_connnection()
while True:
''' get es configuration file'''
configuration_data = get_es_configuration_files(os.getenv("ES_CONFIGURATION_FILE"))
# logging.info(f"configuration_data : {json.dumps(configuration_data, indent=2)}")
"""
# startup_nodes = [
# {"host": os.getenv('REDIS_SERVER_HOST'), "port": 6379},
# ]
# r = RedisCluster(startup_nodes=startup_nodes, decode_responses=True, skip_full_coverage_check=False)
r = redis.StrictRedis(host=os.getenv('REDIS_SERVER_HOST'), port=6379, db=0)
"""
logging.info("\n\n")
if redis_client:
logging.info(f"Redis is Active")
else:
''' Retry connection'''
redis_client = retry_connnection()
"""
json_test = {
"alert" : "false"
}
jsonDataDict = json.dumps(json_test, ensure_ascii=False).encode('utf-8')
r.set("dev", jsonDataDict)
"""
logging.info(f"The number of all keys is {len(list(redis_client.Get_keys()))} ..")
''' --------------- '''
''' get host name matched env name to read their json configuraion'''
''' --------------- '''
mapping_host_dict = get_mapping_host_config()
is_any_updated = False
if len(list(redis_client.Get_keys())) > 0:
is_any_updated = True
# Get all keys
for key in redis_client.Get_keys():
print(key, redis_client.Get_Memory_dict(key), redis_client.Get_Memory_dict(key)["alert"], json.dumps(redis_client.Get_Memory_dict(key), indent=2))
transform_json(mapping_host_dict, configuration_data, key, redis_client.Get_Memory_dict(key)["alert"])
key = key.decode('utf-8')
message = "[{}] Alert : {}, {}".format(str(key).upper(), redis_client.Get_Memory_dict(key)["alert"], redis_client.Get_Memory_dict(key)["message"]),
logger.info("Prometheus-Alert-Service - {}".format(message),
extra={"tags": {"service": "prometheus-alert-service", "message" : "{} -> {}, notes : {}".format(key, redis_client.Get_Memory_dict(key)["alert"], redis_client.Get_Memory_dict(key)["message"])}},
)
''' delete key'''
# r.delete(key)
redis_client.Set_Delete_Keys(key)
''' Check all keys'''
# logging.info(f"Length of all keys from Redis : {len(list(redis_client.Get_keys()))}")
# logging.info(f"configuration_data - {json.dumps(configuration_data, indent=2)}")
if is_any_updated:
write_es_configuration_files(configuration_data)
time.sleep(3)
except (KeyboardInterrupt, SystemExit) as e:
logging.info("#Interrupted..")
message = "[{}]".format(str(key).upper()),
logger.error("Prometheus-Alert-Service {}".format(message),
extra={"tags": {"service": "prometheus-alert-service", "message" : str(e)}},
)
finally:
redis_client.Set_Close()
def HTTP_Server():
''' Add HTTP Server for checking this process'''
try:
port = 9116
server = ThreadingHTTPServer(('0.0.0.0', port), SimpleHTTPRequestHandler)
logging.info('Http Server running on port:{}'.format(port))
server.serve_forever()
except KeyboardInterrupt:
logging.info("#Interrupted..")
if __name__ == '__main__':
"""
https://hyewon-s-dev.tistory.com/5
dis default port: 6379
./scr/redis-server --daemonize yes --protected-mode no
./redis-cli ping
./redis-cli shutdown
./redis-cli
"""
parser = argparse.ArgumentParser(description="Index into Elasticsearch using this script")
# parser.add_argument('-t', '--ts', dest='ts', default="https://localhost:9201", help='host target')
args = parser.parse_args()
# if args.ts:
# target_server = args.ts
# --
# Only One process we can use due to 'Global Interpreter Lock'
# 'Multiprocessing' is that we can use for running with multiple process
# --
try:
''' Add HTTP Server for checking this process'''
# HTTP_Server()
T = []
th1 = Thread(target=work, args=())
th1.daemon = True
th1.start()
T.append(th1)
''' http://localhost:9116/ -> Add HTTP Server for checking this process'''
th2 = Thread(target=HTTP_Server, args=())
th2.daemon = True
th2.start()
T.append(th2)
for t in T:
while t.is_alive():
t.join(0.5)
# work(target_server)
except Exception as e:
logging.error(e)
pass