-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
275 lines (227 loc) · 9.03 KB
/
app.py
File metadata and controls
275 lines (227 loc) · 9.03 KB
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
import os, time, json, logging, re, yaml
from datetime import datetime
from urllib.parse import quote
from threading import RLock
from zoneinfo import ZoneInfo
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from dotenv import load_dotenv
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(threadName)s | %(message)s")
TZ = ZoneInfo("America/Sao_Paulo")
STATE_FILE = os.environ.get("STATE_FILE", "/app/data/monitor_state.json")
state = {}
_state_lock = RLock()
env_pattern = re.compile(r"\$\{(\w+)(?::-(.*?))?\}")
retry_cfg = Retry(total=3, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504], raise_on_status=False)
http = requests.Session()
http.mount("http://", HTTPAdapter(max_retries=retry_cfg))
http.mount("https://", HTTPAdapter(max_retries=retry_cfg))
SEVERITY_BY_STATUS = {"UP": "info", "WARN": "medium", "DOWN": "high"}
def load_config(path="config.yaml"):
with open(path, "r", encoding="utf-8") as f:
raw = f.read()
def repl(m):
var, default = m.group(1), m.group(2)
return os.environ.get(var, default if default is not None else f"<MISSING:{var}>")
expanded = env_pattern.sub(repl, raw)
return yaml.safe_load(expanded)
def load_state():
global state
try:
with open(STATE_FILE, "r", encoding="utf-8") as f:
state = json.load(f)
except Exception:
state = {}
def save_state():
try:
with _state_lock:
tmp = STATE_FILE + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(state, f)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, STATE_FILE)
except Exception as e:
logging.error("Falha ao salvar estado: %s", e)
def in_quiet_hours(quiet_cfg):
if not quiet_cfg:
return False
now = datetime.now(TZ).time()
try:
start = datetime.strptime(quiet_cfg["start"], "%H:%M").time()
end = datetime.strptime(quiet_cfg["end"], "%H:%M").time()
except Exception as e:
logging.warning("quiet_hours inválido: %s", e)
return False
if start == end:
return True
if start < end:
return start <= now <= end
return now >= start or now <= end
def notify_whatsapp(cfg, title, body, severity="info"):
if in_quiet_hours(cfg.get("quiet_hours")) and severity != "high":
logging.info("Quiet hours: suprimindo alerta não-alta prioridade.")
return
base = cfg["evolution_api_base"].rstrip("/")
key = cfg["instance_key"]
url = f"{base}/message/sendText/{key}"
headers = {"Content-Type": "application/json"}
api_key = cfg.get("api_key")
bearer = cfg.get("bearer_token")
if api_key and not api_key.startswith("<MISSING:"):
headers["apikey"] = api_key
if bearer and not bearer.startswith("<MISSING:"):
headers["Authorization"] = f"Bearer {bearer}"
number = cfg["to_number"]
text = f"*{title}*\n{body}"
payloads = [{"number": number, "text": text}, {"to": number, "text": text}]
last_status = None
last_text = None
for payload in payloads:
try:
r = http.post(url, json=payload, headers=headers, timeout=10)
last_status, last_text = r.status_code, r.text[:300]
if r.status_code < 300:
return
except Exception as e:
logging.warning("Erro notificando WhatsApp (payload=%s): %s", list(payload.keys()), e)
logging.warning("Falha ao enviar WhatsApp: %s %s", last_status, last_text)
def check_http(cfg):
req = cfg["request"]
url = req["url"]
timeout = req.get("timeout_ms", 3000) / 1000.0
method = req.get("method", "GET").upper()
headers = req.get("headers", {})
verify = req.get("verify_tls", True)
kwargs = {"headers": headers, "timeout": timeout, "verify": verify}
if "json" in req:
kwargs["json"] = req["json"]
elif "data" in req:
kwargs["data"] = req["data"]
elif "body" in req:
kwargs["data"] = req["body"]
if "files" in req:
kwargs["files"] = req["files"]
t0 = time.perf_counter()
try:
resp = http.request(method, url, **kwargs)
latency = int((time.perf_counter() - t0) * 1000)
exp = cfg.get("expect", {})
ok = True
if "status" in exp and resp.status_code != exp["status"]:
ok = False
if "max_latency_ms" in exp and latency > exp["max_latency_ms"]:
ok = False
contains = exp.get("contains")
if contains:
body = resp.text or ""
if exp.get("regex"):
if not re.search(contains, body):
ok = False
elif contains not in body:
ok = False
detail = f"status={resp.status_code}, latency={latency}ms"
if not ok:
return "DOWN", detail
warn_band = int(exp.get("max_latency_ms", 999_999) * 0.8)
if latency > warn_band:
return "WARN", detail
return "UP", detail
except requests.exceptions.RequestException as e:
return "DOWN", f"exception={type(e).__name__}: {e}"
def check_rabbit_queue(cfg):
rb = cfg["rabbit"]
base = rb["mgmt_url"].rstrip("/")
vhost = quote(rb.get("vhost", "/"), safe='')
queue = rb["queue"]
url = f"{base}/api/queues/{vhost}/{quote(queue, safe='')}"
verify = rb.get("verify_tls", True)
try:
r = http.get(url, auth=(rb["user"], rb["pass"]), timeout=5, verify=verify)
if r.status_code != 200:
return "DOWN", f"mgmt status={r.status_code}"
q = r.json()
ready = q.get("messages_ready", 0)
unacked = q.get("messages_unacknowledged", 0)
consumers = q.get("consumers", 0)
th = cfg.get("thresholds", {})
problems = []
if "max_ready" in th and ready > th["max_ready"]:
problems.append(f"ready>{th['max_ready']} ({ready})")
if "max_unacked" in th and unacked > th["max_unacked"]:
problems.append(f"unacked>{th['max_unacked']} ({unacked})")
if "min_consumers" in th and consumers < th["min_consumers"]:
problems.append(f"consumers<{th['min_consumers']} ({consumers})")
detail = f"ready={ready}, unacked={unacked}, consumers={consumers}"
if problems:
sev = "DOWN" if any(p.startswith("consumers<") for p in problems) else "WARN"
return sev, f"{detail} | {'; '.join(problems)}"
return "UP", detail
except requests.exceptions.RequestException as e:
return "DOWN", f"exception={type(e).__name__}: {e}"
CHECK_HANDLERS = {
"http": check_http,
"rabbitmq_queue": check_rabbit_queue,
}
def run_check(chk, notifier):
name = chk["name"]
handler = CHECK_HANDLERS.get(chk["type"])
if not handler:
logging.error("tipo de check desconhecido: %s", chk["type"])
return
status, detail = handler(chk)
prev = state.get(name, {}).get("status")
bootstrap_silent = chk.get("bootstrap_silent", True)
if prev is None and bootstrap_silent:
state[name] = {"status": status, "last_change": datetime.now(TZ).isoformat(), "detail": detail}
save_state()
logging.info("BOOTSTRAP %s: %s | %s", name, status, detail)
return
if prev != status:
title = f"[{status}] {name}"
sev = chk.get("severity", SEVERITY_BY_STATUS.get(status, "info"))
notify_whatsapp(notifier, title, detail, severity=sev)
state[name] = {"status": status, "last_change": datetime.now(TZ).isoformat(), "detail": detail}
save_state()
logging.info("STATE CHANGE %s: %s -> %s | %s", name, prev, status, detail)
else:
level = logging.INFO if status == "UP" else (logging.WARNING if status == "WARN" else logging.ERROR)
logging.log(level, "SAME %s: %s | %s", name, status, detail)
def assert_no_missing(cfg):
flat = json.dumps(cfg)
if "<MISSING:" in flat:
raise SystemExit("Config contém variáveis ausentes. Corrija o .env/config.yaml.")
def main():
load_dotenv()
cfg = load_config("config.yaml")
assert_no_missing(cfg)
notifier = cfg["notifier"]
load_state()
sched = BlockingScheduler(timezone=TZ)
for i, chk in enumerate(cfg["checks"]):
try:
trig = CronTrigger.from_crontab(chk["schedule"], timezone=TZ)
except Exception as e:
logging.error("schedule inválido em %s: %s", chk.get("name", f"check#{i}"), e)
continue
job_id = f"{chk['name']}-{i}"
sched.add_job(
run_check,
trigger=trig,
args=[chk, notifier],
id=job_id,
max_instances=1,
coalesce=True,
misfire_grace_time=60,
replace_existing=True,
)
logging.info("agendado: %s @ %s", chk["name"], chk["schedule"])
try:
sched.start()
except (KeyboardInterrupt, SystemExit):
sched.shutdown()
if __name__ == "__main__":
main()