forked from inno-devops-labs/DevOps-Core-Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
285 lines (233 loc) · 7.4 KB
/
app.py
File metadata and controls
285 lines (233 loc) · 7.4 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
273
274
275
276
277
278
279
280
281
282
283
284
285
import json
import logging
import os
import platform
import socket
import sys
import time
from datetime import datetime, timezone
from flask import Flask, g, has_request_context, jsonify, request
from werkzeug.exceptions import HTTPException
SERVICE_NAME = "devops-info-service"
SERVICE_VERSION = "1.0.0"
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", 5000))
DEBUG = os.getenv("DEBUG", "False").lower() == "true"
START_TIME = datetime.now(timezone.utc)
class JSONFormatter(logging.Formatter):
"""Format log records as structured JSON for Loki/Grafana."""
EXTRA_FIELDS = (
"event",
"service",
"host",
"port",
"debug",
"method",
"path",
"endpoint",
"status_code",
"client_ip",
"user_agent",
"duration_ms",
)
def format(self, record: logging.LogRecord) -> str:
payload = {
"timestamp": datetime.fromtimestamp(
record.created, tz=timezone.utc
).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
"level": record.levelname,
"logger": record.name,
"message": record.getMessage(),
"service": SERVICE_NAME,
}
for field in self.EXTRA_FIELDS:
value = getattr(record, field, None)
if value is not None:
payload[field] = value
if record.exc_info:
payload["exception"] = self.formatException(record.exc_info)
return json.dumps(payload, ensure_ascii=False)
def configure_logging() -> logging.Logger:
"""Configure application logging to stdout in JSON format."""
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JSONFormatter())
root_logger = logging.getLogger()
root_logger.handlers.clear()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(handler)
werkzeug_logger = logging.getLogger("werkzeug")
werkzeug_logger.handlers.clear()
werkzeug_logger.propagate = False
werkzeug_logger.disabled = True
return logging.getLogger(SERVICE_NAME)
logger = configure_logging()
app = Flask(__name__)
def get_platform_version() -> str:
"""Return a platform version."""
try:
if hasattr(platform, "freedesktop_os_release"):
info = platform.freedesktop_os_release()
if info.get("PRETTY_NAME"):
return info["PRETTY_NAME"]
except Exception:
pass
return platform.platform()
def get_uptime() -> dict:
"""Calculate the application's uptime."""
delta = datetime.now(timezone.utc) - START_TIME
seconds = int(delta.total_seconds())
hours = seconds // 3600
minutes = (seconds % 3600) // 60
return {
"seconds": seconds,
"human": f"{hours} hours, {minutes} minutes",
}
def get_system_info() -> dict:
"""Collect system information."""
return {
"hostname": socket.gethostname(),
"platform": platform.system(),
"platform_version": get_platform_version(),
"architecture": platform.machine(),
"cpu_count": os.cpu_count(),
"python_version": platform.python_version(),
}
def get_client_ip() -> str | None:
"""Return the client IP, preferring X-Forwarded-For when present."""
if not has_request_context():
return None
forwarded_for = request.headers.get("X-Forwarded-For", "")
if forwarded_for:
return forwarded_for.split(",")[0].strip()
return request.remote_addr
def build_request_log_context(status_code: int | None = None) -> dict:
"""Build structured context for request-related logs."""
context: dict[str, object] = {"event": "http.request", "service": SERVICE_NAME}
if not has_request_context():
return context
context.update(
{
"method": request.method,
"path": request.path,
"endpoint": request.endpoint,
"client_ip": get_client_ip(),
"user_agent": request.headers.get("User-Agent"),
}
)
if status_code is not None:
context["status_code"] = status_code
started_at = getattr(g, "request_started_at", None)
if started_at is not None:
context["duration_ms"] = round((time.perf_counter() - started_at) * 1000, 2)
return context
@app.before_request
def track_request_start() -> None:
"""Store request start time for structured logging."""
g.request_started_at = time.perf_counter()
@app.after_request
def log_response(response):
"""Log every completed HTTP request as JSON."""
level = logging.INFO
if response.status_code >= 400:
level = logging.ERROR
logger.log(
level,
"HTTP request completed",
extra=build_request_log_context(response.status_code),
)
return response
@app.route("/")
def index():
"""Main endpoint - service and system information."""
uptime = get_uptime()
response = {
"service": {
"name": SERVICE_NAME,
"version": SERVICE_VERSION,
"description": "DevOps course info service",
"framework": "Flask",
},
"system": get_system_info(),
"runtime": {
"uptime_seconds": uptime["seconds"],
"uptime_human": uptime["human"],
"current_time": datetime.now(timezone.utc)
.isoformat(timespec="milliseconds")
.replace("+00:00", "Z"),
"timezone": "UTC",
},
"request": {
"client_ip": get_client_ip(),
"user_agent": request.headers.get("User-Agent"),
"method": request.method,
"path": request.path,
},
"endpoints": [
{"path": "/", "method": "GET", "description": "Service information"},
{"path": "/health", "method": "GET", "description": "Health check"},
],
}
return jsonify(response)
@app.route("/health")
def health():
"""Health check endpoint for monitoring."""
return jsonify(
{
"status": "healthy",
"timestamp": datetime.now(timezone.utc)
.isoformat(timespec="milliseconds")
.replace("+00:00", "Z"),
"uptime_seconds": get_uptime()["seconds"],
}
)
@app.errorhandler(404)
def not_found(error):
return (
jsonify(
{
"error": "Not Found",
"message": "Endpoint does not exist",
}
),
404,
)
@app.errorhandler(405)
def method_not_allowed(error):
return (
jsonify(
{
"error": "Method Not Allowed",
"message": "Method is not allowed for this endpoint",
}
),
405,
)
@app.errorhandler(Exception)
def handle_unexpected_error(error):
if isinstance(error, HTTPException):
return error
logger.exception(
"Unhandled application error",
extra=build_request_log_context(status_code=500),
)
return (
jsonify(
{
"error": "Internal Server Error",
"message": "An unexpected error occurred",
}
),
500,
)
if __name__ == "__main__":
logger.info(
"Application startup",
extra={
"event": "app.startup",
"service": SERVICE_NAME,
"host": HOST,
"port": PORT,
"debug": DEBUG,
},
)
app.run(host=HOST, port=PORT, debug=DEBUG)