fastpluggy-postgres-tools 0.1.13__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of fastpluggy-postgres-tools might be problematic. Click here for more details.
- fastpluggy_plugin/postgres_tools/__init__.py +1 -0
- fastpluggy_plugin/postgres_tools/plugin.py +28 -0
- fastpluggy_plugin/postgres_tools/routers/__init__.py +25 -0
- fastpluggy_plugin/postgres_tools/routers/alerts.py +371 -0
- fastpluggy_plugin/postgres_tools/routers/connections.py +117 -0
- fastpluggy_plugin/postgres_tools/routers/dashboard.py +321 -0
- fastpluggy_plugin/postgres_tools/routers/db_size.py +142 -0
- fastpluggy_plugin/postgres_tools/routers/indexes.py +75 -0
- fastpluggy_plugin/postgres_tools/routers/queries.py +148 -0
- fastpluggy_plugin/postgres_tools/routers/replication.py +200 -0
- fastpluggy_plugin/postgres_tools/routers/sequences.py +78 -0
- fastpluggy_plugin/postgres_tools/routers/tables.py +106 -0
- fastpluggy_plugin/postgres_tools/routers/vacuum.py +221 -0
- fastpluggy_plugin/postgres_tools/utils/__init__.py +11 -0
- fastpluggy_plugin/postgres_tools/utils/db_utils.py +104 -0
- fastpluggy_postgres_tools-0.1.13.dist-info/METADATA +155 -0
- fastpluggy_postgres_tools-0.1.13.dist-info/RECORD +20 -0
- fastpluggy_postgres_tools-0.1.13.dist-info/WHEEL +5 -0
- fastpluggy_postgres_tools-0.1.13.dist-info/entry_points.txt +2 -0
- fastpluggy_postgres_tools-0.1.13.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .plugin import PostgresToolsModule
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# plugin.py
|
|
2
|
+
|
|
3
|
+
from typing import Annotated, Any
|
|
4
|
+
|
|
5
|
+
from fastpluggy.core.module_base import FastPluggyBaseModule
|
|
6
|
+
from fastpluggy.core.tools.inspect_tools import InjectDependency
|
|
7
|
+
from fastpluggy.fastpluggy import FastPluggy
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_router():
|
|
11
|
+
from .routers import postgres_tools_router
|
|
12
|
+
return postgres_tools_router
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PostgresToolsModule(FastPluggyBaseModule):
|
|
16
|
+
module_name: str = "postgres_tools"
|
|
17
|
+
|
|
18
|
+
module_menu_name: str = "Postgres"
|
|
19
|
+
module_menu_icon: str = "fas fa-database"
|
|
20
|
+
|
|
21
|
+
depends_on: dict = {
|
|
22
|
+
"ui_tools": ">=0.0.4",
|
|
23
|
+
}
|
|
24
|
+
module_router: Any = get_router
|
|
25
|
+
|
|
26
|
+
def on_load_complete(self, fast_pluggy: Annotated[FastPluggy, InjectDependency]) -> None:
|
|
27
|
+
# Menu items are now added using the @menu_entry decorator in the router files
|
|
28
|
+
pass
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from fastapi import APIRouter, Depends
|
|
2
|
+
|
|
3
|
+
from fastpluggy.core.auth import require_authentication
|
|
4
|
+
from .sequences import sequences_router
|
|
5
|
+
from .db_size import db_size_router
|
|
6
|
+
from .indexes import indexes_router
|
|
7
|
+
from .tables import tables_router
|
|
8
|
+
from .queries import queries_router
|
|
9
|
+
from .connections import connections_router
|
|
10
|
+
from .vacuum import vacuum_router
|
|
11
|
+
from .replication import replication_router
|
|
12
|
+
from .alerts import alerts_router
|
|
13
|
+
from .dashboard import dashboard_router
|
|
14
|
+
|
|
15
|
+
postgres_tools_router = APIRouter()
|
|
16
|
+
postgres_tools_router.include_router(sequences_router, dependencies=[Depends(require_authentication)])
|
|
17
|
+
postgres_tools_router.include_router(db_size_router, dependencies=[Depends(require_authentication)])
|
|
18
|
+
postgres_tools_router.include_router(indexes_router, dependencies=[Depends(require_authentication)])
|
|
19
|
+
postgres_tools_router.include_router(tables_router, dependencies=[Depends(require_authentication)])
|
|
20
|
+
postgres_tools_router.include_router(queries_router, dependencies=[Depends(require_authentication)])
|
|
21
|
+
postgres_tools_router.include_router(connections_router, dependencies=[Depends(require_authentication)])
|
|
22
|
+
postgres_tools_router.include_router(vacuum_router, dependencies=[Depends(require_authentication)])
|
|
23
|
+
postgres_tools_router.include_router(replication_router, dependencies=[Depends(require_authentication)])
|
|
24
|
+
postgres_tools_router.include_router(alerts_router, dependencies=[Depends(require_authentication)])
|
|
25
|
+
postgres_tools_router.include_router(dashboard_router, dependencies=[Depends(require_authentication)])
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
from fastapi import APIRouter, Depends, Request, Form, HTTPException
|
|
2
|
+
from fastpluggy_plugin.ui_tools.extra_widget.display.card import CardWidget
|
|
3
|
+
from sqlalchemy import text, Table, Column, Integer, String, Float, Boolean, MetaData, create_engine
|
|
4
|
+
from sqlalchemy.orm import Session
|
|
5
|
+
import json
|
|
6
|
+
import httpx
|
|
7
|
+
import asyncio
|
|
8
|
+
from typing import List, Dict, Any, Optional
|
|
9
|
+
|
|
10
|
+
from fastpluggy.core.database import get_db
|
|
11
|
+
from fastpluggy.core.dependency import get_view_builder
|
|
12
|
+
from fastpluggy.core.widgets import TableWidget, FormWidget
|
|
13
|
+
from fastpluggy.core.menu.decorator import menu_entry
|
|
14
|
+
|
|
15
|
+
alerts_router = APIRouter(prefix="/alerts", tags=["postgres_alerts"])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def ensure_alerts_table(db: Session):
|
|
19
|
+
"""
|
|
20
|
+
Ensure the alerts configuration table exists
|
|
21
|
+
"""
|
|
22
|
+
query = text("""
|
|
23
|
+
CREATE TABLE IF NOT EXISTS pg_alerts (
|
|
24
|
+
id SERIAL PRIMARY KEY,
|
|
25
|
+
name VARCHAR(255) NOT NULL,
|
|
26
|
+
metric VARCHAR(255) NOT NULL,
|
|
27
|
+
condition VARCHAR(50) NOT NULL,
|
|
28
|
+
threshold FLOAT NOT NULL,
|
|
29
|
+
webhook_url VARCHAR(1024),
|
|
30
|
+
webhook_service VARCHAR(50),
|
|
31
|
+
enabled BOOLEAN DEFAULT TRUE,
|
|
32
|
+
last_triggered TIMESTAMP,
|
|
33
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
34
|
+
)
|
|
35
|
+
""")
|
|
36
|
+
|
|
37
|
+
db.execute(query)
|
|
38
|
+
db.commit()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def get_alerts(db: Session):
|
|
42
|
+
"""
|
|
43
|
+
Get all configured alerts
|
|
44
|
+
"""
|
|
45
|
+
ensure_alerts_table(db)
|
|
46
|
+
|
|
47
|
+
query = text("""
|
|
48
|
+
SELECT
|
|
49
|
+
id,
|
|
50
|
+
name,
|
|
51
|
+
metric,
|
|
52
|
+
condition,
|
|
53
|
+
threshold,
|
|
54
|
+
webhook_url,
|
|
55
|
+
webhook_service,
|
|
56
|
+
enabled,
|
|
57
|
+
last_triggered,
|
|
58
|
+
created_at
|
|
59
|
+
FROM pg_alerts
|
|
60
|
+
ORDER BY id
|
|
61
|
+
""")
|
|
62
|
+
|
|
63
|
+
result = db.execute(query).mappings()
|
|
64
|
+
return [dict(row) for row in result]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def create_alert(db: Session, alert_data: Dict[str, Any]):
|
|
68
|
+
"""
|
|
69
|
+
Create a new alert
|
|
70
|
+
"""
|
|
71
|
+
ensure_alerts_table(db)
|
|
72
|
+
|
|
73
|
+
query = text("""
|
|
74
|
+
INSERT INTO pg_alerts (
|
|
75
|
+
name,
|
|
76
|
+
metric,
|
|
77
|
+
condition,
|
|
78
|
+
threshold,
|
|
79
|
+
webhook_url,
|
|
80
|
+
webhook_service,
|
|
81
|
+
enabled
|
|
82
|
+
) VALUES (
|
|
83
|
+
:name,
|
|
84
|
+
:metric,
|
|
85
|
+
:condition,
|
|
86
|
+
:threshold,
|
|
87
|
+
:webhook_url,
|
|
88
|
+
:webhook_service,
|
|
89
|
+
:enabled
|
|
90
|
+
) RETURNING id
|
|
91
|
+
""")
|
|
92
|
+
|
|
93
|
+
result = db.execute(query, alert_data).mappings().first()
|
|
94
|
+
db.commit()
|
|
95
|
+
return result["id"]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def delete_alert(db: Session, alert_id: int):
|
|
99
|
+
"""
|
|
100
|
+
Delete an alert
|
|
101
|
+
"""
|
|
102
|
+
query = text("""
|
|
103
|
+
DELETE FROM pg_alerts
|
|
104
|
+
WHERE id = :alert_id
|
|
105
|
+
""")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
db.execute(query, {"alert_id": alert_id})
|
|
109
|
+
db.commit()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def update_alert(db: Session, alert_id: int, alert_data: Dict[str, Any]):
|
|
113
|
+
"""
|
|
114
|
+
Update an alert
|
|
115
|
+
"""
|
|
116
|
+
query = text("""
|
|
117
|
+
UPDATE pg_alerts
|
|
118
|
+
SET
|
|
119
|
+
name = :name,
|
|
120
|
+
metric = :metric,
|
|
121
|
+
condition = :condition,
|
|
122
|
+
threshold = :threshold,
|
|
123
|
+
webhook_url = :webhook_url,
|
|
124
|
+
webhook_service = :webhook_service,
|
|
125
|
+
enabled = :enabled
|
|
126
|
+
WHERE id = :alert_id
|
|
127
|
+
""")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
db.execute(query, {**alert_data, "alert_id": alert_id})
|
|
131
|
+
db.commit()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def get_available_metrics():
|
|
135
|
+
"""
|
|
136
|
+
Get available metrics for alerts
|
|
137
|
+
"""
|
|
138
|
+
return [
|
|
139
|
+
{"value": "table_bloat", "label": "Table Bloat Percentage"},
|
|
140
|
+
{"value": "index_scans", "label": "Index Scan Count"},
|
|
141
|
+
{"value": "query_duration", "label": "Query Duration (ms)"},
|
|
142
|
+
{"value": "connection_count", "label": "Active Connection Count"},
|
|
143
|
+
{"value": "vacuum_days", "label": "Days Since Last Vacuum"},
|
|
144
|
+
{"value": "replication_lag", "label": "Replication Lag (bytes)"},
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def get_available_conditions():
|
|
149
|
+
"""
|
|
150
|
+
Get available conditions for alerts
|
|
151
|
+
"""
|
|
152
|
+
return [
|
|
153
|
+
{"value": ">", "label": "Greater Than"},
|
|
154
|
+
{"value": "<", "label": "Less Than"},
|
|
155
|
+
{"value": "=", "label": "Equal To"},
|
|
156
|
+
{"value": ">=", "label": "Greater Than or Equal To"},
|
|
157
|
+
{"value": "<=", "label": "Less Than or Equal To"},
|
|
158
|
+
]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def get_available_webhook_services():
|
|
162
|
+
"""
|
|
163
|
+
Get available webhook services
|
|
164
|
+
"""
|
|
165
|
+
return [
|
|
166
|
+
{"value": "slack", "label": "Slack"},
|
|
167
|
+
{"value": "discord", "label": "Discord"},
|
|
168
|
+
{"value": "teams", "label": "Microsoft Teams"},
|
|
169
|
+
{"value": "pagerduty", "label": "PagerDuty"},
|
|
170
|
+
{"value": "custom", "label": "Custom Webhook"},
|
|
171
|
+
]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
async def test_webhook(webhook_url: str, webhook_service: str, message: str):
|
|
175
|
+
"""
|
|
176
|
+
Test a webhook by sending a test message
|
|
177
|
+
"""
|
|
178
|
+
payload = {}
|
|
179
|
+
|
|
180
|
+
if webhook_service == "slack":
|
|
181
|
+
payload = {
|
|
182
|
+
"text": message
|
|
183
|
+
}
|
|
184
|
+
elif webhook_service == "discord":
|
|
185
|
+
payload = {
|
|
186
|
+
"content": message
|
|
187
|
+
}
|
|
188
|
+
elif webhook_service == "teams":
|
|
189
|
+
payload = {
|
|
190
|
+
"text": message
|
|
191
|
+
}
|
|
192
|
+
elif webhook_service == "pagerduty":
|
|
193
|
+
payload = {
|
|
194
|
+
"incident": {
|
|
195
|
+
"title": "Test Alert",
|
|
196
|
+
"description": message,
|
|
197
|
+
"service": {
|
|
198
|
+
"id": "PostgreSQL",
|
|
199
|
+
"type": "service"
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
else: # custom
|
|
204
|
+
payload = {
|
|
205
|
+
"message": message,
|
|
206
|
+
"source": "postgres_tools",
|
|
207
|
+
"type": "test"
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
async with httpx.AsyncClient() as client:
|
|
212
|
+
response = await client.post(
|
|
213
|
+
webhook_url,
|
|
214
|
+
json=payload,
|
|
215
|
+
timeout=10.0
|
|
216
|
+
)
|
|
217
|
+
return response.status_code < 400
|
|
218
|
+
except Exception as e:
|
|
219
|
+
return False
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@alerts_router.get("")
|
|
223
|
+
@menu_entry(
|
|
224
|
+
label="Alerts & Webhooks",
|
|
225
|
+
icon="fa fa-bell",
|
|
226
|
+
parent="postgres_tools"
|
|
227
|
+
)
|
|
228
|
+
async def get_alerts_view(
|
|
229
|
+
request: Request,
|
|
230
|
+
db=Depends(get_db),
|
|
231
|
+
view_builder=Depends(get_view_builder)
|
|
232
|
+
):
|
|
233
|
+
"""
|
|
234
|
+
Get the PostgreSQL alerts and webhooks view
|
|
235
|
+
"""
|
|
236
|
+
# Get alerts data
|
|
237
|
+
alerts_data = get_alerts(db)
|
|
238
|
+
|
|
239
|
+
# Create widgets
|
|
240
|
+
alerts_table = TableWidget(
|
|
241
|
+
title="Configured Alerts",
|
|
242
|
+
endpoint="/postgres/alerts",
|
|
243
|
+
data=alerts_data,
|
|
244
|
+
description="Configure alerts based on database metrics and send notifications via webhooks."
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# Create a form for adding new alerts
|
|
248
|
+
new_alert_form = FormWidget(
|
|
249
|
+
title="Add New Alert",
|
|
250
|
+
endpoint="/postgres/alerts/create",
|
|
251
|
+
fields=[
|
|
252
|
+
{"name": "name", "label": "Alert Name", "type": "text", "required": True},
|
|
253
|
+
{"name": "metric", "label": "Metric", "type": "select", "options": get_available_metrics(), "required": True},
|
|
254
|
+
{"name": "condition", "label": "Condition", "type": "select", "options": get_available_conditions(), "required": True},
|
|
255
|
+
{"name": "threshold", "label": "Threshold", "type": "number", "required": True},
|
|
256
|
+
{"name": "webhook_url", "label": "Webhook URL", "type": "text", "required": False},
|
|
257
|
+
{"name": "webhook_service", "label": "Webhook Service", "type": "select", "options": get_available_webhook_services(), "required": False},
|
|
258
|
+
{"name": "enabled", "label": "Enabled", "type": "checkbox", "default": True}
|
|
259
|
+
]
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
# Create a card with webhook testing functionality
|
|
263
|
+
webhook_test_card = CardWidget(
|
|
264
|
+
title="Test Webhook",
|
|
265
|
+
content="Use the form below to test your webhook configuration."
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
# Render the view
|
|
269
|
+
return view_builder.generate(
|
|
270
|
+
request,
|
|
271
|
+
title="PostgreSQL Alerts & Webhooks",
|
|
272
|
+
widgets=[
|
|
273
|
+
alerts_table,
|
|
274
|
+
new_alert_form,
|
|
275
|
+
webhook_test_card
|
|
276
|
+
]
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
@alerts_router.post("/create")
|
|
281
|
+
async def create_alert_endpoint(
|
|
282
|
+
request: Request,
|
|
283
|
+
name: str = Form(...),
|
|
284
|
+
metric: str = Form(...),
|
|
285
|
+
condition: str = Form(...),
|
|
286
|
+
threshold: float = Form(...),
|
|
287
|
+
webhook_url: Optional[str] = Form(None),
|
|
288
|
+
webhook_service: Optional[str] = Form(None),
|
|
289
|
+
enabled: bool = Form(True),
|
|
290
|
+
db=Depends(get_db)
|
|
291
|
+
):
|
|
292
|
+
"""
|
|
293
|
+
Create a new alert
|
|
294
|
+
"""
|
|
295
|
+
alert_data = {
|
|
296
|
+
"name": name,
|
|
297
|
+
"metric": metric,
|
|
298
|
+
"condition": condition,
|
|
299
|
+
"threshold": threshold,
|
|
300
|
+
"webhook_url": webhook_url,
|
|
301
|
+
"webhook_service": webhook_service,
|
|
302
|
+
"enabled": enabled
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
alert_id = create_alert(db, alert_data)
|
|
306
|
+
|
|
307
|
+
# Redirect back to the alerts page
|
|
308
|
+
return {"success": True, "alert_id": alert_id}
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@alerts_router.post("/test-webhook")
|
|
312
|
+
async def test_webhook_endpoint(
|
|
313
|
+
request: Request,
|
|
314
|
+
webhook_url: str = Form(...),
|
|
315
|
+
webhook_service: str = Form(...),
|
|
316
|
+
message: str = Form("This is a test alert from PostgreSQL Tools")
|
|
317
|
+
):
|
|
318
|
+
"""
|
|
319
|
+
Test a webhook
|
|
320
|
+
"""
|
|
321
|
+
success = await test_webhook(webhook_url, webhook_service, message)
|
|
322
|
+
|
|
323
|
+
if success:
|
|
324
|
+
return {"success": True, "message": "Webhook test successful"}
|
|
325
|
+
else:
|
|
326
|
+
raise HTTPException(status_code=400, detail="Webhook test failed")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
@alerts_router.delete("/{alert_id}")
|
|
330
|
+
async def delete_alert_endpoint(
|
|
331
|
+
request: Request,
|
|
332
|
+
alert_id: int,
|
|
333
|
+
db=Depends(get_db)
|
|
334
|
+
):
|
|
335
|
+
"""
|
|
336
|
+
Delete an alert
|
|
337
|
+
"""
|
|
338
|
+
delete_alert(db, alert_id)
|
|
339
|
+
|
|
340
|
+
return {"success": True}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
@alerts_router.put("/{alert_id}")
|
|
344
|
+
async def update_alert_endpoint(
|
|
345
|
+
request: Request,
|
|
346
|
+
alert_id: int,
|
|
347
|
+
name: str = Form(...),
|
|
348
|
+
metric: str = Form(...),
|
|
349
|
+
condition: str = Form(...),
|
|
350
|
+
threshold: float = Form(...),
|
|
351
|
+
webhook_url: Optional[str] = Form(None),
|
|
352
|
+
webhook_service: Optional[str] = Form(None),
|
|
353
|
+
enabled: bool = Form(True),
|
|
354
|
+
db=Depends(get_db)
|
|
355
|
+
):
|
|
356
|
+
"""
|
|
357
|
+
Update an alert
|
|
358
|
+
"""
|
|
359
|
+
alert_data = {
|
|
360
|
+
"name": name,
|
|
361
|
+
"metric": metric,
|
|
362
|
+
"condition": condition,
|
|
363
|
+
"threshold": threshold,
|
|
364
|
+
"webhook_url": webhook_url,
|
|
365
|
+
"webhook_service": webhook_service,
|
|
366
|
+
"enabled": enabled
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
update_alert(db, alert_id, alert_data)
|
|
370
|
+
|
|
371
|
+
return {"success": True}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
from fastapi import APIRouter, Depends, Request
|
|
2
|
+
from sqlalchemy import text
|
|
3
|
+
from sqlalchemy.orm import Session
|
|
4
|
+
|
|
5
|
+
from fastpluggy.core.database import get_db
|
|
6
|
+
from fastpluggy.core.dependency import get_view_builder
|
|
7
|
+
from fastpluggy.core.widgets import TableWidget
|
|
8
|
+
from fastpluggy.core.menu.decorator import menu_entry
|
|
9
|
+
|
|
10
|
+
connections_router = APIRouter(prefix="/connections", tags=["postgres_connections"])
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_active_connections(db: Session , min_duration: float = None, state: str = None):
|
|
14
|
+
"""
|
|
15
|
+
Get active connections from the database
|
|
16
|
+
"""
|
|
17
|
+
where_conditions = ["state <> 'idle'"]
|
|
18
|
+
|
|
19
|
+
if min_duration:
|
|
20
|
+
where_conditions.append(f"EXTRACT(EPOCH FROM (now() - query_start)) > {min_duration}")
|
|
21
|
+
|
|
22
|
+
if state:
|
|
23
|
+
where_conditions.append(f"state = '{state}'")
|
|
24
|
+
|
|
25
|
+
where_clause = " AND ".join(where_conditions)
|
|
26
|
+
|
|
27
|
+
query = f"""
|
|
28
|
+
SELECT
|
|
29
|
+
pid,
|
|
30
|
+
datname,
|
|
31
|
+
usename,
|
|
32
|
+
state,
|
|
33
|
+
backend_start,
|
|
34
|
+
query_start,
|
|
35
|
+
EXTRACT(EPOCH FROM (now() - query_start)) AS duration_seconds,
|
|
36
|
+
query
|
|
37
|
+
FROM pg_stat_activity
|
|
38
|
+
WHERE {where_clause}
|
|
39
|
+
ORDER BY duration_seconds DESC
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
return db.execute(text(query))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_lock_contention(db_manager: Session):
|
|
46
|
+
"""
|
|
47
|
+
Get lock contention information from the database
|
|
48
|
+
"""
|
|
49
|
+
query = """
|
|
50
|
+
SELECT
|
|
51
|
+
l.locktype,
|
|
52
|
+
l.mode,
|
|
53
|
+
l.granted,
|
|
54
|
+
a.query AS blocking_query,
|
|
55
|
+
a.pid AS blocking_pid,
|
|
56
|
+
w.query AS waiting_query,
|
|
57
|
+
w.pid AS waiting_pid,
|
|
58
|
+
EXTRACT(EPOCH FROM (now() - w.query_start)) AS waiting_duration_seconds
|
|
59
|
+
FROM pg_locks l
|
|
60
|
+
JOIN pg_stat_activity a ON l.pid = a.pid
|
|
61
|
+
JOIN pg_locks bl ON (l.database = bl.database AND l.relation = bl.relation)
|
|
62
|
+
JOIN pg_stat_activity w ON bl.pid = w.pid
|
|
63
|
+
WHERE NOT l.granted AND bl.granted
|
|
64
|
+
ORDER BY waiting_duration_seconds DESC
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
return db_manager.execute(text(query))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@connections_router.get("")
|
|
71
|
+
@menu_entry(
|
|
72
|
+
label="Connections & Locks",
|
|
73
|
+
icon="fa fa-link",
|
|
74
|
+
parent="postgres_tools"
|
|
75
|
+
)
|
|
76
|
+
async def get_connections_view(
|
|
77
|
+
request: Request,
|
|
78
|
+
db=Depends(get_db),
|
|
79
|
+
view_builder=Depends(get_view_builder),
|
|
80
|
+
min_duration: float = None,
|
|
81
|
+
state: str = None
|
|
82
|
+
):
|
|
83
|
+
"""
|
|
84
|
+
Get the PostgreSQL connections and locks view
|
|
85
|
+
"""
|
|
86
|
+
# Create a connection manager for this request
|
|
87
|
+
# Get active connections
|
|
88
|
+
connections = get_active_connections(db, min_duration, state)
|
|
89
|
+
|
|
90
|
+
# Get lock contention information
|
|
91
|
+
locks = get_lock_contention(db)
|
|
92
|
+
|
|
93
|
+
# Create a table for active connections
|
|
94
|
+
connections_table = TableWidget(
|
|
95
|
+
title="Active Connections",
|
|
96
|
+
endpoint="/postgres/connections",
|
|
97
|
+
data=connections,
|
|
98
|
+
description="Active database connections and their current queries."
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
# Create a table for lock contention
|
|
102
|
+
locks_table = TableWidget(
|
|
103
|
+
title="Lock Contention",
|
|
104
|
+
endpoint="/postgres/connections/locks",
|
|
105
|
+
data=locks,
|
|
106
|
+
description="Blocking and waiting queries causing lock contention."
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# Render the view
|
|
110
|
+
return view_builder.generate(
|
|
111
|
+
request,
|
|
112
|
+
title="PostgreSQL Connections & Locks",
|
|
113
|
+
widgets=[
|
|
114
|
+
connections_table,
|
|
115
|
+
locks_table
|
|
116
|
+
]
|
|
117
|
+
)
|