-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
92 lines (72 loc) · 2.49 KB
/
main.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
import logging
import google.auth
import google.auth.exceptions
import requests
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from google.auth.transport.requests import Request as GoogleRequest
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("uvicorn")
def get_current_project():
try:
_, project_id = google.auth.default()
if not project_id:
raise Exception(
"Failed to get current project from Google Cloud credentials"
)
return project_id
except google.auth.exceptions.DefaultCredentialsError as ex:
raise Exception(f"Error obtaining default credentials: {str(ex)}")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.api_route("/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy(path: str, request: Request):
path_parts = path.split("/", 1)
if path_parts[0] == "api":
project_id = get_current_project()
api_path = path
else:
project_id = path_parts[0]
api_path = path_parts[1] if len(path_parts) > 1 else ""
logger.info(f"Using Project ID: {project_id}")
GOOGLE_PROM_URL = f"https://monitoring.googleapis.com/v1/projects/{project_id}/location/global/prometheus"
credentials, _ = google.auth.default()
credentials.refresh(GoogleRequest())
headers = {
"Authorization": f"Bearer {credentials.token}",
"Content-Type": "application/json",
}
params = {k: v for k, v in request.query_params.items() if k != "refresh"}
if request.method == "GET":
resp = requests.get(
f"{GOOGLE_PROM_URL}/{api_path}", headers=headers, params=params
)
elif request.method == "POST":
data = await request.json()
data.pop("refresh", None)
resp = requests.post(
f"{GOOGLE_PROM_URL}/{api_path}", headers=headers, json=data
)
excluded_headers = [
"content-encoding",
"content-length",
"transfer-encoding",
"connection",
]
headers = [
(name, value)
for (name, value) in resp.raw.headers.items()
if name.lower() not in excluded_headers
]
return Response(
content=resp.content, status_code=resp.status_code, headers=dict(headers)
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8082)