-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
272 lines (228 loc) · 7.54 KB
/
Copy pathapi_server.py
File metadata and controls
272 lines (228 loc) · 7.54 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
import os
from datetime import datetime
from flask import Flask, request, jsonify
from flask_cors import CORS
from models.app_logger import AppLogger
from models.config_manager import ConfigManager
app = Flask(__name__)
CORS(app)
cfg_mgr = ConfigManager.instance()
# ============= LOGGING MIDDLEWARE =============
@app.before_request
def log_request_info():
# Only log state-changing methods to avoid spamming read logs
if request.method in ['POST', 'PUT', 'DELETE']:
AppLogger.log(f"API Request: {request.method} {request.path} from {request.remote_addr}", category="SYSTEM")
@app.after_request
def log_response_info(response):
# Log errors or significant state changes
log_category = "SYSTEM"
if response.status_code >= 400:
log_category = "ERROR"
AppLogger.log(f"API {request.method} {request.path} - Status: {response.status_code} {response.status}", category=log_category)
return response
# ============= API ENDPOINTS =============
@app.route('/api/status', methods=['GET'])
def api_status():
"""Check if API is alive"""
return jsonify({
"status": "online",
"service": "CafeSentinel Config API",
"timestamp": datetime.now().isoformat()
})
@app.route('/api/config', methods=['GET'])
def get_config():
"""Get current configuration"""
config = cfg_mgr.get_config()
if config:
return jsonify({
"status": "success",
"config": config
})
else:
return jsonify({
"status": "error",
"message": "Failed to read config"
}), 500
@app.route('/api/config', methods=['POST'])
def update_config():
"""Update configuration"""
try:
new_config = request.json
if not new_config:
return jsonify({
"status": "error",
"message": "No config data provided"
}), 400
success, message = cfg_mgr.update_config(new_config)
if success:
return jsonify({
"status": "success",
"message": message
})
else:
return jsonify({
"status": "error",
"message": message
}), 400
except Exception as e:
AppLogger.log(f"API error: {e}", category="ERROR")
return jsonify({
"status": "error",
"message": str(e)
}), 500
@app.route('/api/config/backups', methods=['GET'])
def list_backups():
"""List available config backups"""
try:
backups = cfg_mgr.get_backup_list()
return jsonify({
"status": "success",
"backups": backups
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
}), 500
@app.route('/api/logs', methods=['GET'])
def get_logs():
"""
Returns TODAY's logs.
- If lines <= 500: Serves from RAM (fast)
- If lines > 500: Reads from disk (complete history)
Query param: ?lines=500 (optional, default 500, max 5000)
"""
try:
line_count = request.args.get('lines', default=500, type=int)
line_count = max(10, min(line_count, 5000)) # Clamp between 10 and 5000
# Smart switching: RAM vs Disk
if line_count <= 500:
# Fast path: Memory buffer
logs = AppLogger.get_recent_logs(line_count)
source = "memory"
else:
# Deep history: Read from disk
logs = AppLogger.get_todays_log_from_disk(line_count)
source = "disk"
return jsonify({
"status": "success",
"lines": len(logs),
"source": source,
"logs": logs
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
}), 500
@app.route('/api/logs/archive', methods=['GET'])
def list_archived_logs():
"""
Lists all archived log files in probes/ folder.
Returns filenames sorted newest first.
"""
try:
archives = AppLogger.get_archive_list()
return jsonify({
"status": "success",
"count": len(archives),
"archives": archives
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
}), 500
@app.route('/api/logs/archive/<filename>', methods=['GET'])
def get_archived_log(filename):
"""
Returns the contents of a specific archived log.
Example: GET /api/logs/archive/info-2025-11-30.log
"""
try:
logs = AppLogger.get_archived_log(filename)
if logs is None:
return jsonify({
"status": "error",
"message": "Archive file not found"
}), 404
return jsonify({
"status": "success",
"filename": filename,
"lines": len(logs),
"logs": logs
})
except Exception as e:
return jsonify({
"status": "error",
"message": str(e)
}), 500
@app.route('/api/logs/archive/<filename>', methods=['DELETE'])
def delete_archived_log(filename):
"""
Permanently deletes an archived log file.
No recycle bin - file is destroyed immediately.
Example: DELETE /api/logs/archive/info-2025-11-28.log
"""
try:
# Security: Only allow deletion of archive files, not other system files
if not filename.startswith("info-") or not filename.endswith(".log"):
return jsonify({
"status": "error",
"message": "Invalid filename format"
}), 400
archive_path = AppLogger._get_archive_path()
file_path = os.path.join(archive_path, filename)
# Security: Prevent path traversal attacks
if not os.path.abspath(file_path).startswith(os.path.abspath(archive_path)):
return jsonify({
"status": "error",
"message": "Access denied"
}), 403
# Check if file exists
if not os.path.exists(file_path):
return jsonify({
"status": "error",
"message": "Archive file not found"
}), 404
# PERMANENT DELETION (no recycle bin)
os.remove(file_path)
AppLogger.log("Purged log file via API", category="ARCHIVE") # Don't log filename (security)
return jsonify({
"status": "success",
"message": "Archive deleted permanently"
})
except PermissionError:
return jsonify({
"status": "error",
"message": "Permission denied - file may be in use"
}), 403
except Exception as e:
AppLogger.log(f"Deletion failed - {type(e).__name__}", category="ARCHIVE") # Log error type, not details
return jsonify({
"status": "error",
"message": "Deletion failed"
}), 500
# Error handlers
@app.errorhandler(404)
def not_found(error):
return jsonify({
"status": "error",
"message": "Endpoint not found"
}), 404
@app.errorhandler(500)
def internal_error(error):
return jsonify({
"status": "error",
"message": "Internal server error"
}), 500
def run_api_server(host='0.0.0.0', port=5000):
"""Start Flask API server"""
try:
AppLogger.log(f"Starting Config API on {host}:{port}", category="SYSTEM")
app.run(host=host, port=port, debug=False, threaded=True)
except Exception as e:
AppLogger.log(f"API server failed: {e}", category="ERROR")
if __name__ == '__main__':
run_api_server()