forked from FabioBartoli/semana_devops_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
94 lines (67 loc) · 2.29 KB
/
Copy pathmain.py
File metadata and controls
94 lines (67 loc) · 2.29 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
import os
import random
import time
import psutil
from fastapi import FastAPI
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
app = FastAPI()
# Modelo de dados
class SystemMetrics(BaseModel):
memoria: float # Uso de memória em %
cpu: float # Uso de CPU em %
disk: float # Uso de disco em %
# Endpoint principal
@app.get("/metrics", response_model=SystemMetrics, tags=["main"])
def get_system_metrics():
simulate_heavy_load_randomly()
memory = psutil.virtual_memory().percent
cpu = psutil.cpu_percent(interval=1)
disk = psutil.disk_usage("/").percent
return SystemMetrics(memoria=memory, cpu=cpu, disk=disk)
# Endpoints para o Kubernetes
@app.get("/health", tags=["k8s"])
@app.get("/healthz", tags=["k8s"])
@app.get("/ready", tags=["k8s"])
@app.get("/readyz", tags=["k8s"])
def health_check():
"""Para de enviar trafego se estiver em um estado inadequado."""
simulate_unhealthy_behavior_randomly()
return {"status": "ok"}
@app.get("/version", tags=["util"])
def version_check():
"""Verifica a versão da aplicação."""
return {"version": "2.0.0"}
@app.get("/liveness", tags=["k8s"])
def liveness_check():
"""Reinicia o Pod se estiver em um estado inadequado."""
simulate_delay_randomly()
return {"status": "ok"}
@app.get("/startup", tags=["k8s"])
def startup_check():
"""Verifica se o Pod está pronto para receber trafego."""
simulate_delay_randomly()
return {"status": "ok"}
# Redirect `/` para `/docs`
@app.get("/", tags=["util"])
def redirect_to_docs():
return RedirectResponse(url="/docs")
def simulate_heavy_load_randomly():
"""Simula um uso pesado aleatoriamente."""
if not os.getenv("SIMULATE_HEAVY_LOAD"):
return
if random.random() < 0.5:
time.sleep(random.uniform(0.1, 10))
else:
simulate_unhealthy_behavior_randomly()
def simulate_unhealthy_behavior_randomly():
"""Simula um comportamento inadequado aleatoriamente."""
if not os.getenv("SIMULATE_UNHEALTHY_BEHAVIOR"):
return
if random.random() < 0.5:
raise Exception("Simulação de comportamento inadequado")
def simulate_delay_randomly():
"""Simula um atraso aleatório."""
if not os.getenv("SIMULATE_DELAY"):
return
time.sleep(random.uniform(0.1, 10))