keepup-admin 0.1.0__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 keepup-admin might be problematic. Click here for more details.
- keepup/THIRD-PARTY.md +44 -0
- keepup/__init__.py +41 -0
- keepup/api_versions.py +100 -0
- keepup/audit.py +499 -0
- keepup/auth/__init__.py +7 -0
- keepup/auth/config.py +128 -0
- keepup/auth/dependencies.py +485 -0
- keepup/auth/dto/__init__.py +0 -0
- keepup/auth/dto/token.py +31 -0
- keepup/auth/factory.py +28 -0
- keepup/auth/login_throttle.py +151 -0
- keepup/auth/oidc.py +245 -0
- keepup/auth/oidc_policy.py +111 -0
- keepup/auth/oidc_routes.py +288 -0
- keepup/auth/panel_session.py +220 -0
- keepup/auth/permissions.py +59 -0
- keepup/auth/providers/__init__.py +0 -0
- keepup/auth/providers/base.py +168 -0
- keepup/auth/providers/local.py +180 -0
- keepup/auth/routes.py +660 -0
- keepup/auth/seed_accounts.py +322 -0
- keepup/auth/session_lifetime.py +104 -0
- keepup/auth/signing_key.py +138 -0
- keepup/auth/websocket.py +86 -0
- keepup/cluster.py +634 -0
- keepup/db.py +663 -0
- keepup/events.py +764 -0
- keepup/factory.py +484 -0
- keepup/instance.py +46 -0
- keepup/integrations.py +260 -0
- keepup/locks.py +412 -0
- keepup/logging_setup.py +690 -0
- keepup/metrics.py +818 -0
- keepup/metrics_retention.py +376 -0
- keepup/modules.py +572 -0
- keepup/notification_bus.py +355 -0
- keepup/plugins/__init__.py +9 -0
- keepup/plugins/admin.py +246 -0
- keepup/plugins/base.py +234 -0
- keepup/plugins/enablement.py +184 -0
- keepup/plugins/registry.py +171 -0
- keepup/plugins/route_mask.py +338 -0
- keepup/plugins/routes.py +376 -0
- keepup/roles.py +17 -0
- keepup/scheduler.py +93 -0
- keepup/schema.py +295 -0
- keepup/sections.json +104 -0
- keepup/settings.py +184 -0
- keepup/static/css/aos.css +1 -0
- keepup/static/css/main_nebula.css +232 -0
- keepup/static/css/main_new.css +852 -0
- keepup/static/css/tailwind.css +1 -0
- keepup/static/index_nebula.html +293 -0
- keepup/static/index_new.html +286 -0
- keepup/static/js/aos.js +1 -0
- keepup/static/js/feather-icons.js +13 -0
- keepup/static/js/main_new.js +1861 -0
- keepup/static/js/tailwind.js +83 -0
- keepup/static/modules/css/background_tasks.css +233 -0
- keepup/static/modules/css/cluster.css +16 -0
- keepup/static/modules/css/event_manager.css +386 -0
- keepup/static/modules/css/integration_logs.css +33 -0
- keepup/static/modules/css/metrics.css +115 -0
- keepup/static/modules/css/modules.css +189 -0
- keepup/static/modules/css/themes.css +563 -0
- keepup/static/modules/css/users.css +278 -0
- keepup/static/modules/js/background_tasks.js +657 -0
- keepup/static/modules/js/chart.js +14 -0
- keepup/static/modules/js/chartjs-adapter-date-fns.bundle.min.js +7 -0
- keepup/static/modules/js/cluster.js +363 -0
- keepup/static/modules/js/event_manager.js +979 -0
- keepup/static/modules/js/integration_logs.js +767 -0
- keepup/static/modules/js/metrics.js +908 -0
- keepup/static/modules/js/modules.js +1086 -0
- keepup/static/modules/js/themes.js +653 -0
- keepup/static/modules/js/users.js +784 -0
- keepup/tables.py +302 -0
- keepup/themes.py +496 -0
- keepup/web.py +182 -0
- keepup_admin-0.1.0.dist-info/METADATA +117 -0
- keepup_admin-0.1.0.dist-info/RECORD +86 -0
- keepup_admin-0.1.0.dist-info/WHEEL +5 -0
- keepup_admin-0.1.0.dist-info/licenses/LICENSE +202 -0
- keepup_admin-0.1.0.dist-info/licenses/NOTICE +22 -0
- keepup_admin-0.1.0.dist-info/licenses/THIRD-PARTY.md +44 -0
- keepup_admin-0.1.0.dist-info/top_level.txt +1 -0
keepup/integrations.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""The log of calls this application makes to other systems.
|
|
2
|
+
|
|
3
|
+
The counterpart of the incoming request audit: when an outside system answers
|
|
4
|
+
with a 500 or a gateway times out, this is where the request, the response and
|
|
5
|
+
the timing are, without which "their side or ours" cannot be settled after the
|
|
6
|
+
fact.
|
|
7
|
+
|
|
8
|
+
Calls are recorded against a user, and background work has no user of its own
|
|
9
|
+
-- hence the service account, looked up here rather than invented, so that an
|
|
10
|
+
unsigned row never appears.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import time
|
|
16
|
+
from datetime import datetime
|
|
17
|
+
from typing import Dict, Optional
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
from keepup.db import DatabaseManager
|
|
21
|
+
from keepup.auth.dependencies import get_user_by_id, get_user_by_username
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
from keepup.auth import seed_accounts
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class IntegrationLogger:
|
|
29
|
+
"""Records calls made to external systems."""
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
async def log_request(
|
|
33
|
+
user_id: int,
|
|
34
|
+
username: str,
|
|
35
|
+
host: str,
|
|
36
|
+
endpoint: str,
|
|
37
|
+
method: str,
|
|
38
|
+
request_body: Optional[Dict] = None,
|
|
39
|
+
response_body: Optional[Dict] = None,
|
|
40
|
+
status_code: Optional[int] = None,
|
|
41
|
+
duration_ms: Optional[int] = None
|
|
42
|
+
):
|
|
43
|
+
"""Record a request to an external API."""
|
|
44
|
+
try:
|
|
45
|
+
# Bodies are capped: a single large payload would otherwise dominate the log table.
|
|
46
|
+
request_body_str = json.dumps(request_body, ensure_ascii=False) if request_body else None
|
|
47
|
+
response_body_str = json.dumps(response_body, ensure_ascii=False) if response_body else None
|
|
48
|
+
|
|
49
|
+
if request_body_str and len(request_body_str) > 10000:
|
|
50
|
+
request_body_str = request_body_str[:10000] + "... [truncated]"
|
|
51
|
+
|
|
52
|
+
if response_body_str and len(response_body_str) > 10000:
|
|
53
|
+
response_body_str = response_body_str[:10000] + "... [truncated]"
|
|
54
|
+
|
|
55
|
+
DatabaseManager.execute_commit_only('''
|
|
56
|
+
INSERT INTO integration_logs
|
|
57
|
+
(user_id, username, host, endpoint, method, request_body, response_body, status_code, duration_ms)
|
|
58
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
59
|
+
''', (
|
|
60
|
+
user_id,
|
|
61
|
+
username,
|
|
62
|
+
host,
|
|
63
|
+
endpoint,
|
|
64
|
+
method.upper(),
|
|
65
|
+
request_body_str,
|
|
66
|
+
response_body_str,
|
|
67
|
+
status_code,
|
|
68
|
+
duration_ms
|
|
69
|
+
))
|
|
70
|
+
|
|
71
|
+
except Exception as e:
|
|
72
|
+
logger.error(f"Could not log the outgoing request: {str(e)}")
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def get_logs(
|
|
76
|
+
user_id: Optional[int] = None,
|
|
77
|
+
username: Optional[str] = None,
|
|
78
|
+
host: Optional[str] = None,
|
|
79
|
+
start_date: Optional[datetime] = None,
|
|
80
|
+
end_date: Optional[datetime] = None,
|
|
81
|
+
limit: int = 100,
|
|
82
|
+
offset: int = 0
|
|
83
|
+
):
|
|
84
|
+
"""Return log entries matching the given filters."""
|
|
85
|
+
query = """
|
|
86
|
+
SELECT * FROM integration_logs
|
|
87
|
+
WHERE 1=1
|
|
88
|
+
"""
|
|
89
|
+
params = []
|
|
90
|
+
|
|
91
|
+
if user_id:
|
|
92
|
+
query += " AND user_id = ?"
|
|
93
|
+
params.append(user_id)
|
|
94
|
+
|
|
95
|
+
if username:
|
|
96
|
+
query += " AND username = ?"
|
|
97
|
+
params.append(username)
|
|
98
|
+
|
|
99
|
+
if host:
|
|
100
|
+
query += " AND host = ?"
|
|
101
|
+
params.append(host)
|
|
102
|
+
|
|
103
|
+
if start_date:
|
|
104
|
+
query += " AND created_at >= ?"
|
|
105
|
+
params.append(start_date)
|
|
106
|
+
|
|
107
|
+
if end_date:
|
|
108
|
+
query += " AND created_at <= ?"
|
|
109
|
+
params.append(end_date)
|
|
110
|
+
|
|
111
|
+
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
|
|
112
|
+
params.extend([limit, offset])
|
|
113
|
+
|
|
114
|
+
return DatabaseManager.execute_sql(query, tuple(params))
|
|
115
|
+
|
|
116
|
+
@staticmethod
|
|
117
|
+
def get_logs_count(
|
|
118
|
+
user_id: Optional[int] = None,
|
|
119
|
+
username: Optional[str] = None,
|
|
120
|
+
host: Optional[str] = None,
|
|
121
|
+
start_date: Optional[datetime] = None,
|
|
122
|
+
end_date: Optional[datetime] = None
|
|
123
|
+
):
|
|
124
|
+
"""Return the number of log entries matching the given filters."""
|
|
125
|
+
query = """
|
|
126
|
+
SELECT COUNT(*) as count FROM integration_logs
|
|
127
|
+
WHERE 1=1
|
|
128
|
+
"""
|
|
129
|
+
params = []
|
|
130
|
+
|
|
131
|
+
if user_id:
|
|
132
|
+
query += " AND user_id = ?"
|
|
133
|
+
params.append(user_id)
|
|
134
|
+
|
|
135
|
+
if username:
|
|
136
|
+
query += " AND username = ?"
|
|
137
|
+
params.append(username)
|
|
138
|
+
|
|
139
|
+
if host:
|
|
140
|
+
query += " AND host = ?"
|
|
141
|
+
params.append(host)
|
|
142
|
+
|
|
143
|
+
if start_date:
|
|
144
|
+
query += " AND created_at >= ?"
|
|
145
|
+
params.append(start_date)
|
|
146
|
+
|
|
147
|
+
if end_date:
|
|
148
|
+
query += " AND created_at <= ?"
|
|
149
|
+
params.append(end_date)
|
|
150
|
+
|
|
151
|
+
result = DatabaseManager.execute_sql_one(query, tuple(params))
|
|
152
|
+
return result['count'] if result else 0
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
from functools import wraps
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def log_external_request(host: str, endpoint: str):
|
|
159
|
+
"""Decorator recording calls to an external service."""
|
|
160
|
+
|
|
161
|
+
def decorator(func):
|
|
162
|
+
@wraps(func)
|
|
163
|
+
async def wrapper(*args, **kwargs):
|
|
164
|
+
start_time = time.time()
|
|
165
|
+
status_code = 200
|
|
166
|
+
response_body = ""
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
result = await func(*args, **kwargs)
|
|
170
|
+
response_body = str(result)[:1000] if result else ""
|
|
171
|
+
return result
|
|
172
|
+
|
|
173
|
+
except Exception as e:
|
|
174
|
+
status_code = 500
|
|
175
|
+
response_body = str(e)[:1000]
|
|
176
|
+
raise
|
|
177
|
+
|
|
178
|
+
finally:
|
|
179
|
+
try:
|
|
180
|
+
user_id = extract_user_id_from_args(args, kwargs)
|
|
181
|
+
user = get_user_by_id(user_id)
|
|
182
|
+
username = 'unknown'
|
|
183
|
+
if not user:
|
|
184
|
+
logger.warning(f"User {user_id} not found, skipping log")
|
|
185
|
+
user = get_user_by_username('system')
|
|
186
|
+
username = user.get('username', 'unknown')
|
|
187
|
+
user_id = user.get('id')
|
|
188
|
+
else:
|
|
189
|
+
username = user.get('username', 'unknown')
|
|
190
|
+
|
|
191
|
+
DatabaseManager.execute_commit_only('''
|
|
192
|
+
INSERT INTO integration_logs
|
|
193
|
+
(user_id, username, host, endpoint, method, request_body, response_body, status_code, duration_ms)
|
|
194
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
195
|
+
''', (
|
|
196
|
+
user_id, username, host, endpoint, func.__name__,
|
|
197
|
+
str(kwargs.get('data', ''))[:1000],
|
|
198
|
+
response_body,
|
|
199
|
+
status_code,
|
|
200
|
+
int((time.time() - start_time) * 1000)
|
|
201
|
+
))
|
|
202
|
+
|
|
203
|
+
except Exception as log_error:
|
|
204
|
+
logger.error(f"Could not log the outgoing request: {log_error}")
|
|
205
|
+
|
|
206
|
+
return wrapper
|
|
207
|
+
|
|
208
|
+
return decorator
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def extract_user_id_from_args(args, kwargs) -> Optional[int]:
|
|
212
|
+
"""Extract user_id from the wrapped call's arguments, tolerating any shape."""
|
|
213
|
+
try:
|
|
214
|
+
if 'user_id' in kwargs:
|
|
215
|
+
return int(kwargs['user_id'])
|
|
216
|
+
if 'current_user' in kwargs:
|
|
217
|
+
user = kwargs['current_user']
|
|
218
|
+
return user.get('id') if isinstance(user, dict) else getattr(user, 'id', None)
|
|
219
|
+
|
|
220
|
+
for arg in args:
|
|
221
|
+
if isinstance(arg, dict) and 'id' in arg:
|
|
222
|
+
return arg.get('id')
|
|
223
|
+
elif hasattr(arg, 'id'):
|
|
224
|
+
return getattr(arg, 'id', None)
|
|
225
|
+
elif isinstance(arg, int) and arg > 0:
|
|
226
|
+
return arg
|
|
227
|
+
|
|
228
|
+
# Some integrations carry the user only inside a settings object.
|
|
229
|
+
for arg in args:
|
|
230
|
+
if isinstance(arg, dict) and 'client_id' in arg:
|
|
231
|
+
# Calls made outside any user context are attributed to the system user.
|
|
232
|
+
return get_system_user_id()
|
|
233
|
+
|
|
234
|
+
except (TypeError, ValueError, AttributeError) as e:
|
|
235
|
+
logger.debug(f"Error extracting user_id: {e}")
|
|
236
|
+
|
|
237
|
+
return None
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def get_system_user_id():
|
|
241
|
+
"""Return the id of the system user that background work is signed with.
|
|
242
|
+
|
|
243
|
+
The account itself is created once, at start-up, by
|
|
244
|
+
`keepup.auth.seed_accounts` -- without a password anyone could sign in with.
|
|
245
|
+
Creating it here as well is what let three spellings of it drift apart; a
|
|
246
|
+
missing account now means the schema has not been initialised, and inventing
|
|
247
|
+
one with a password of our own would only hide that.
|
|
248
|
+
"""
|
|
249
|
+
try:
|
|
250
|
+
system_user = get_user_by_username(seed_accounts.SYSTEM_USERNAME)
|
|
251
|
+
if system_user:
|
|
252
|
+
return system_user['id']
|
|
253
|
+
logger.error(
|
|
254
|
+
"The service account '%s' is not in the database: the schema was "
|
|
255
|
+
"not initialised. Background work will go unsigned.",
|
|
256
|
+
seed_accounts.SYSTEM_USERNAME)
|
|
257
|
+
return None
|
|
258
|
+
except Exception as e:
|
|
259
|
+
logger.error(f"Error getting system user: {e}")
|
|
260
|
+
return None
|
keepup/locks.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
"""Serialising background work across replicas.
|
|
2
|
+
|
|
3
|
+
The application runs as several replicas against one database, so a job that
|
|
4
|
+
must run once -- a feed sync, a billing pass -- cannot rely on being
|
|
5
|
+
alone in its process. The lock is a row in ``distributed_locks``: taking it is
|
|
6
|
+
an insert, and a holder that died without releasing is cleared by age, which is
|
|
7
|
+
why every lock carries both how long to wait for it and how long it may be held.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import functools
|
|
12
|
+
import logging
|
|
13
|
+
import time
|
|
14
|
+
from contextlib import asynccontextmanager
|
|
15
|
+
from datetime import datetime, timedelta
|
|
16
|
+
|
|
17
|
+
from fastapi import Depends, HTTPException, Query, status
|
|
18
|
+
|
|
19
|
+
from keepup.auth.dependencies import get_current_admin
|
|
20
|
+
from keepup.db import DatabaseManager, DatabaseManagerV2
|
|
21
|
+
from keepup.instance import get_instance_id
|
|
22
|
+
from keepup.roles import ROLE_ADMIN
|
|
23
|
+
|
|
24
|
+
#: What an application may import from this module. Everything else is
|
|
25
|
+
#: internal and may change without notice -- see doc/keepup.md.
|
|
26
|
+
__all__ = [
|
|
27
|
+
"DatabaseLock",
|
|
28
|
+
"distributed_lock",
|
|
29
|
+
"with_distributed_lock",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class DatabaseLock:
|
|
36
|
+
"""A lock held in the database, so that replicas can see each other's."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, lock_name: str, timeout: int = 300, max_lock_time: int = None):
|
|
39
|
+
self.lock_name = lock_name
|
|
40
|
+
self.timeout = timeout # how long to wait for the lock
|
|
41
|
+
self.max_lock_time = max_lock_time or (timeout * 2) # how long the lock may be held
|
|
42
|
+
self.instance_id = get_instance_id()
|
|
43
|
+
self.acquired = False
|
|
44
|
+
|
|
45
|
+
async def acquire(self) -> bool:
|
|
46
|
+
"""Take the lock, clearing stale holders first."""
|
|
47
|
+
try:
|
|
48
|
+
await self._cleanup_stale_locks()
|
|
49
|
+
result = DatabaseManager.execute_commit_only('''
|
|
50
|
+
INSERT INTO distributed_locks (lock_name, acquired_at, instance_id)
|
|
51
|
+
VALUES (?, CURRENT_TIMESTAMP, ?)
|
|
52
|
+
''', (self.lock_name, self.instance_id))
|
|
53
|
+
|
|
54
|
+
if result:
|
|
55
|
+
self.acquired = True
|
|
56
|
+
logger.info(f"Lock '{self.lock_name}' acquired by {self.instance_id}")
|
|
57
|
+
return True
|
|
58
|
+
|
|
59
|
+
except Exception as e:
|
|
60
|
+
if "unique constraint" in str(e).lower() or "duplicate" in str(e).lower():
|
|
61
|
+
return await self._try_acquire_existing()
|
|
62
|
+
logger.error(f"Error acquiring lock '{self.lock_name}': {str(e)}")
|
|
63
|
+
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
async def _cleanup_stale_locks(self):
|
|
67
|
+
"""Clear locks held longer than max_lock_time."""
|
|
68
|
+
try:
|
|
69
|
+
cutoff_time = datetime.utcnow() - timedelta(seconds=self.max_lock_time)
|
|
70
|
+
cleanup_query = '''
|
|
71
|
+
DELETE FROM distributed_locks
|
|
72
|
+
WHERE lock_name = :lock_name
|
|
73
|
+
AND acquired_at < :cutoff_time
|
|
74
|
+
'''
|
|
75
|
+
|
|
76
|
+
params = {
|
|
77
|
+
"lock_name": self.lock_name,
|
|
78
|
+
"cutoff_time": cutoff_time
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
deleted_count = DatabaseManagerV2.execute_commit(cleanup_query, params)
|
|
82
|
+
|
|
83
|
+
if deleted_count > 0:
|
|
84
|
+
logger.warning(f"Cleaned up {deleted_count} stale lock(s) for '{self.lock_name}' "
|
|
85
|
+
f"(older than {self.max_lock_time} seconds)")
|
|
86
|
+
|
|
87
|
+
except Exception as e:
|
|
88
|
+
logger.error(f"Error cleaning up stale locks for '{self.lock_name}': {str(e)}")
|
|
89
|
+
|
|
90
|
+
async def _try_acquire_existing(self) -> bool:
|
|
91
|
+
"""Take over an existing lock when it has expired."""
|
|
92
|
+
try:
|
|
93
|
+
lock = DatabaseManager.execute_sql_one(
|
|
94
|
+
"SELECT * FROM distributed_locks WHERE lock_name = ?",
|
|
95
|
+
(self.lock_name,)
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
if not lock:
|
|
99
|
+
return False
|
|
100
|
+
|
|
101
|
+
lock_time = lock['acquired_at']
|
|
102
|
+
if isinstance(lock_time, str):
|
|
103
|
+
lock_time = lock_time.replace('Z', '')
|
|
104
|
+
lock_time = datetime.fromisoformat(lock_time)
|
|
105
|
+
|
|
106
|
+
time_diff = (datetime.utcnow() - lock_time).total_seconds()
|
|
107
|
+
|
|
108
|
+
if time_diff > self.max_lock_time:
|
|
109
|
+
logger.warning(f"Lock '{self.lock_name}' expired (held for {time_diff:.1f}s, "
|
|
110
|
+
f"max: {self.max_lock_time}s), attempting to acquire...")
|
|
111
|
+
|
|
112
|
+
DatabaseManager.execute_commit_only(
|
|
113
|
+
"DELETE FROM distributed_locks WHERE lock_name = ?",
|
|
114
|
+
(self.lock_name,)
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
return await self.acquire()
|
|
118
|
+
|
|
119
|
+
except Exception as e:
|
|
120
|
+
logger.error(f"Error trying to acquire existing lock '{self.lock_name}': {str(e)}")
|
|
121
|
+
|
|
122
|
+
return False
|
|
123
|
+
|
|
124
|
+
async def renew(self):
|
|
125
|
+
"""Move the holder's timestamp forward while the work is still running.
|
|
126
|
+
|
|
127
|
+
Without this the lock had one fixed life and no way to say "still
|
|
128
|
+
here": a background task that ran longer than max_lock_time -- ten
|
|
129
|
+
minutes by default -- had its row deleted by the next replica, which
|
|
130
|
+
then started the same work beside it. For a billing pass or a call to
|
|
131
|
+
somebody else's API, that is the work done twice (task keepup-15).
|
|
132
|
+
|
|
133
|
+
Returns:
|
|
134
|
+
Whether the row was still ours to move.
|
|
135
|
+
"""
|
|
136
|
+
if not self.acquired:
|
|
137
|
+
return False
|
|
138
|
+
try:
|
|
139
|
+
moved = DatabaseManagerV2.execute_commit(
|
|
140
|
+
"UPDATE distributed_locks SET acquired_at = :now "
|
|
141
|
+
"WHERE lock_name = :name AND instance_id = :instance",
|
|
142
|
+
{"now": datetime.utcnow(), "name": self.lock_name,
|
|
143
|
+
"instance": self.instance_id})
|
|
144
|
+
if not moved:
|
|
145
|
+
# Somebody took it over already: saying so is the point, because
|
|
146
|
+
# the caller is now doing work it no longer holds the lock for.
|
|
147
|
+
logger.warning(f"Lock '{self.lock_name}' is no longer held by "
|
|
148
|
+
f"{self.instance_id}")
|
|
149
|
+
self.acquired = False
|
|
150
|
+
return bool(moved)
|
|
151
|
+
except Exception as e:
|
|
152
|
+
logger.error(f"Error renewing lock '{self.lock_name}': {str(e)}")
|
|
153
|
+
return False
|
|
154
|
+
|
|
155
|
+
async def release(self):
|
|
156
|
+
"""Release the lock."""
|
|
157
|
+
if not self.acquired:
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
DatabaseManager.execute_commit_only(
|
|
162
|
+
"DELETE FROM distributed_locks WHERE lock_name = ? AND instance_id = ?",
|
|
163
|
+
(self.lock_name, self.instance_id)
|
|
164
|
+
)
|
|
165
|
+
self.acquired = False
|
|
166
|
+
logger.info(f"Lock '{self.lock_name}' released by {self.instance_id}")
|
|
167
|
+
except Exception as e:
|
|
168
|
+
logger.error(f"Error releasing lock '{self.lock_name}': {str(e)}")
|
|
169
|
+
|
|
170
|
+
async def __aenter__(self):
|
|
171
|
+
await self.acquire()
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
175
|
+
await self.release()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
#: How much of max_lock_time may pass between renewals. A third leaves room
|
|
179
|
+
#: for two missed beats before the row looks abandoned.
|
|
180
|
+
RENEWAL_FRACTION = 3
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@asynccontextmanager
|
|
184
|
+
async def distributed_lock(lock_name: str, timeout: int = 300, max_lock_time: int = None):
|
|
185
|
+
"""Context manager taking a distributed lock, renewing it while it is held.
|
|
186
|
+
|
|
187
|
+
The renewal is what makes the lock usable for work of unknown length: the
|
|
188
|
+
holder says "still here" on a beat, and only a holder that stopped saying
|
|
189
|
+
it is taken over. Before this, a pass that ran past max_lock_time was
|
|
190
|
+
simply overtaken.
|
|
191
|
+
"""
|
|
192
|
+
lock = DatabaseLock(lock_name, timeout, max_lock_time)
|
|
193
|
+
renewal = None
|
|
194
|
+
try:
|
|
195
|
+
acquired = await lock.acquire()
|
|
196
|
+
if not acquired:
|
|
197
|
+
raise Exception(f"Could not acquire lock '{lock_name}'")
|
|
198
|
+
|
|
199
|
+
async def keep_saying_still_here():
|
|
200
|
+
beat = max(1, lock.max_lock_time // RENEWAL_FRACTION)
|
|
201
|
+
while True:
|
|
202
|
+
await asyncio.sleep(beat)
|
|
203
|
+
await lock.renew()
|
|
204
|
+
|
|
205
|
+
renewal = asyncio.create_task(keep_saying_still_here())
|
|
206
|
+
yield lock
|
|
207
|
+
finally:
|
|
208
|
+
if renewal is not None:
|
|
209
|
+
renewal.cancel()
|
|
210
|
+
try:
|
|
211
|
+
await renewal
|
|
212
|
+
except asyncio.CancelledError:
|
|
213
|
+
pass
|
|
214
|
+
await lock.release()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def with_distributed_lock(lock_key: str, timeout: int = 300, max_lock_time: int = None):
|
|
218
|
+
"""Decorator taking a distributed lock around a background task."""
|
|
219
|
+
|
|
220
|
+
def decorator(func):
|
|
221
|
+
@functools.wraps(func)
|
|
222
|
+
async def wrapper(*args, **kwargs):
|
|
223
|
+
lock_name = f"task_{lock_key}"
|
|
224
|
+
actual_max_lock_time = max_lock_time or (timeout * 2)
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
async with distributed_lock(lock_name, timeout, actual_max_lock_time):
|
|
228
|
+
logger.info(f"Acquired lock '{lock_name}' for task {func.__name__}")
|
|
229
|
+
start_time = time.time()
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
result = await func(*args, **kwargs)
|
|
233
|
+
execution_time = time.time() - start_time
|
|
234
|
+
logger.info(f"Task {func.__name__} completed in {execution_time:.2f}s")
|
|
235
|
+
return result
|
|
236
|
+
except Exception as e:
|
|
237
|
+
execution_time = time.time() - start_time
|
|
238
|
+
logger.error(f"Task {func.__name__} failed after {execution_time:.2f}s: {str(e)}")
|
|
239
|
+
raise
|
|
240
|
+
|
|
241
|
+
except Exception as e:
|
|
242
|
+
if "Could not acquire lock" in str(e):
|
|
243
|
+
logger.info(f"Task {func.__name__} skipped - lock '{lock_name}' already acquired")
|
|
244
|
+
return None
|
|
245
|
+
logger.error(f"Error in distributed lock for task {func.__name__}: {str(e)}")
|
|
246
|
+
raise
|
|
247
|
+
|
|
248
|
+
return wrapper
|
|
249
|
+
|
|
250
|
+
return decorator
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def register_lock_routes(app):
|
|
254
|
+
"""Register the administrative lock endpoints on the application."""
|
|
255
|
+
|
|
256
|
+
@app.get("/api/admin/locks")
|
|
257
|
+
async def get_active_locks(admin: dict = Depends(get_current_admin)):
|
|
258
|
+
"""Return the active locks (administrators only)."""
|
|
259
|
+
try:
|
|
260
|
+
if admin["role"] != ROLE_ADMIN:
|
|
261
|
+
logger.warning(f"Non-admin user {admin['username']} attempted to access locks endpoint")
|
|
262
|
+
raise HTTPException(
|
|
263
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
264
|
+
detail="Admin access required"
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
locks = DatabaseManager.execute_sql(
|
|
268
|
+
"SELECT * FROM distributed_locks ORDER BY acquired_at DESC"
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
logger.info(f"Admin {admin['username']} viewed active locks, count: {len(locks)}")
|
|
272
|
+
return {"locks": locks, "count": len(locks)}
|
|
273
|
+
|
|
274
|
+
except Exception as e:
|
|
275
|
+
logger.error(f"Error retrieving locks: {str(e)}")
|
|
276
|
+
raise HTTPException(
|
|
277
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
278
|
+
detail="Error retrieving lock information"
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@app.delete("/api/admin/locks/{lock_name}")
|
|
283
|
+
async def force_release_lock(
|
|
284
|
+
lock_name: str,
|
|
285
|
+
admin: dict = Depends(get_current_admin),
|
|
286
|
+
confirm: bool = Query(False, description="Confirm force release")
|
|
287
|
+
):
|
|
288
|
+
"""Force-release a lock (administrators only)."""
|
|
289
|
+
try:
|
|
290
|
+
if admin["role"] != ROLE_ADMIN:
|
|
291
|
+
logger.warning(f"Non-admin user {admin['username']} attempted to release lock {lock_name}")
|
|
292
|
+
raise HTTPException(
|
|
293
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
294
|
+
detail="Admin access required"
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
existing_lock = DatabaseManager.execute_sql_one(
|
|
298
|
+
"SELECT * FROM distributed_locks WHERE lock_name = ?",
|
|
299
|
+
(lock_name,)
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
if not existing_lock:
|
|
303
|
+
logger.info(f"Admin {admin['username']} attempted to release non-existent lock: {lock_name}")
|
|
304
|
+
return {
|
|
305
|
+
"success": False,
|
|
306
|
+
"message": f"Lock '{lock_name}' not found"
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if not confirm:
|
|
310
|
+
return {
|
|
311
|
+
"success": False,
|
|
312
|
+
"message": "Confirmation required. Use ?confirm=true to force release the lock.",
|
|
313
|
+
"lock_info": {
|
|
314
|
+
"lock_name": existing_lock["lock_name"],
|
|
315
|
+
"instance_id": existing_lock["instance_id"],
|
|
316
|
+
"acquired_at": existing_lock["acquired_at"]
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
result = DatabaseManager.execute_commit_only(
|
|
321
|
+
"DELETE FROM distributed_locks WHERE lock_name = ?",
|
|
322
|
+
(lock_name,)
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
if result:
|
|
326
|
+
logger.warning(
|
|
327
|
+
f"Lock '{lock_name}' force-released by admin {admin['username']}. "
|
|
328
|
+
f"Was held by instance: {existing_lock['instance_id']}, "
|
|
329
|
+
f"acquired at: {existing_lock['acquired_at']}"
|
|
330
|
+
)
|
|
331
|
+
|
|
332
|
+
try:
|
|
333
|
+
DatabaseManager.execute_commit_only('''
|
|
334
|
+
INSERT INTO system_metrics (metric_name, metric_value, app_instance, tags)
|
|
335
|
+
VALUES (?, ?, ?, ?)
|
|
336
|
+
''', (
|
|
337
|
+
"lock_force_released",
|
|
338
|
+
1,
|
|
339
|
+
get_instance_id(),
|
|
340
|
+
f"lock_name:{lock_name},admin:{admin['username']}"
|
|
341
|
+
))
|
|
342
|
+
except Exception as metrics_error:
|
|
343
|
+
logger.error(f"Failed to log lock release metric: {metrics_error}")
|
|
344
|
+
|
|
345
|
+
return {
|
|
346
|
+
"success": True,
|
|
347
|
+
"message": f"Lock '{lock_name}' force-released successfully",
|
|
348
|
+
"released_lock": {
|
|
349
|
+
"lock_name": existing_lock["lock_name"],
|
|
350
|
+
"instance_id": existing_lock["instance_id"],
|
|
351
|
+
"acquired_at": existing_lock["acquired_at"]
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
else:
|
|
355
|
+
return {
|
|
356
|
+
"success": False,
|
|
357
|
+
"message": "Failed to release lock"
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
except Exception as e:
|
|
361
|
+
logger.error(f"Error force-releasing lock '{lock_name}': {str(e)}")
|
|
362
|
+
raise HTTPException(
|
|
363
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
364
|
+
detail="Error releasing lock"
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
@app.get("/api/admin/locks/stats")
|
|
369
|
+
async def get_locks_stats(admin: dict = Depends(get_current_admin)):
|
|
370
|
+
"""Return lock statistics (administrators only)."""
|
|
371
|
+
try:
|
|
372
|
+
if admin["role"] != ROLE_ADMIN:
|
|
373
|
+
raise HTTPException(
|
|
374
|
+
status_code=status.HTTP_403_FORBIDDEN,
|
|
375
|
+
detail="Admin access required"
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
total_locks = DatabaseManager.execute_sql_one(
|
|
379
|
+
"SELECT COUNT(*) as count FROM distributed_locks"
|
|
380
|
+
)
|
|
381
|
+
|
|
382
|
+
locks_by_instance = DatabaseManager.execute_sql('''
|
|
383
|
+
SELECT instance_id, COUNT(*) as lock_count
|
|
384
|
+
FROM distributed_locks
|
|
385
|
+
GROUP BY instance_id
|
|
386
|
+
ORDER BY lock_count DESC
|
|
387
|
+
''')
|
|
388
|
+
|
|
389
|
+
oldest_locks = DatabaseManager.execute_sql('''
|
|
390
|
+
SELECT lock_name, instance_id, acquired_at,
|
|
391
|
+
(JULIANDAY('now') - JULIANDAY(acquired_at)) * 24 * 60 * 60 as seconds_held
|
|
392
|
+
FROM distributed_locks
|
|
393
|
+
ORDER BY acquired_at ASC
|
|
394
|
+
LIMIT 10
|
|
395
|
+
''')
|
|
396
|
+
|
|
397
|
+
stats = {
|
|
398
|
+
"total_active_locks": total_locks["count"] if total_locks else 0,
|
|
399
|
+
"locks_by_instance": locks_by_instance,
|
|
400
|
+
"oldest_locks": oldest_locks,
|
|
401
|
+
"current_instance": get_instance_id()
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
logger.info(f"Admin {admin['username']} viewed locks statistics")
|
|
405
|
+
return stats
|
|
406
|
+
|
|
407
|
+
except Exception as e:
|
|
408
|
+
logger.error(f"Error retrieving locks stats: {str(e)}")
|
|
409
|
+
raise HTTPException(
|
|
410
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
411
|
+
detail="Error retrieving lock statistics"
|
|
412
|
+
)
|