Skip to content

Commit 54cb469

Browse files
authored
Merge pull request #6 from RamzeusInno/lab07
lab7
2 parents ac2d04d + 99aaed9 commit 54cb469

18 files changed

Lines changed: 898 additions & 86 deletions

.github/workflows/ansible-deploy.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@ on:
44
push:
55
branches: [ main, master ]
66
paths:
7-
- 'ansible/'
7+
- 'ansible/**'
88
- '.github/workflows/ansible-deploy.yml'
99
pull_request:
1010
branches: [ main, master ]
1111
paths:
12-
- 'ansible/'
12+
- 'ansible/**'
1313

1414
jobs:
1515
lint:

app_python/Dockerfile

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,12 @@
1-
FROM python:3.12-slim
1+
FROM python:3.11-slim
22

33
WORKDIR /app
44

5-
RUN groupadd -r appuser && useradd -r -g appuser appuser
6-
75
COPY requirements.txt .
86
RUN pip install --no-cache-dir -r requirements.txt
97

108
COPY app.py .
11-
COPY . .
12-
13-
RUN chown -R appuser:appuser /app
14-
15-
USER appuser
169

1710
EXPOSE 5000
1811

19-
CMD ["python", "app.py"]
12+
CMD ["python", "app.py"]

app_python/app.py

Lines changed: 17 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,8 @@
1-
import os
2-
import socket
3-
import platform
4-
import logging
5-
from datetime import datetime, timezone, timedelta
6-
from flask import Flask, jsonify, request
7-
8-
# Configuration
9-
HOST = os.getenv('HOST', '0.0.0.0')
10-
PORT = int(os.getenv('PORT', '5000'))
11-
DEBUG = os.getenv('DEBUG', 'False').lower() == 'true'
12-
13-
# Application Setup
14-
app = Flask(__name__)
15-
app_start_time = datetime.now(timezone.utc)
16-
17-
# Logging Configuration
18-
logging.basicConfig(
19-
level=logging.DEBUG if DEBUG else logging.INFO,
20-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
21-
)
22-
logger = logging.getLogger(__name__)
23-
24-
# Helper Functions
25-
def get_system_info():
26-
"""Collect comprehensive system information."""
27-
return {
28-
'hostname': socket.gethostname(),
29-
'platform': platform.system(),
30-
'platform_version': platform.version(),
31-
'architecture': platform.machine(),
32-
'cpu_count': os.cpu_count() or 0,
33-
'python_version': platform.python_version()
34-
}
35-
36-
def get_uptime():
37-
"""Calculate application uptime in seconds and human-readable format."""
38-
delta = datetime.now(timezone.utc) - app_start_time
39-
seconds = int(delta.total_seconds())
40-
41-
# Calculate human-readable format
42-
days, remainder = divmod(seconds, 86400)
43-
hours, remainder = divmod(remainder, 3600)
44-
minutes, seconds = divmod(remainder, 60)
45-
46-
human_parts = []
47-
if days > 0:
48-
human_parts.append(f"{days} day{'s' if days != 1 else ''}")
49-
if hours > 0:
50-
human_parts.append(f"{hours} hour{'s' if hours != 1 else ''}")
51-
if minutes > 0:
52-
human_parts.append(f"{minutes} minute{'s' if minutes != 1 else ''}")
53-
if seconds > 0 or not human_parts:
54-
human_parts.append(f"{seconds} second{'s' if seconds != 1 else ''}")
55-
56-
return {
57-
'seconds': seconds,
58-
'human': ', '.join(human_parts)
59-
}
60-
611
# Application Endpoints
622
@app.route('/')
633
def main_endpoint():
644
"""Main endpoint returning service and system information."""
65-
logger.info(f"Main endpoint accessed by {request.remote_addr}")
66-
5+
logger.info('Main endpoint accessed')
676
return jsonify({
687
'service': {
698
'name': 'devops-info-service',
@@ -93,8 +32,7 @@ def main_endpoint():
9332
@app.route('/health')
9433
def health_check():
9534
"""Health check endpoint for monitoring and probes."""
96-
logger.debug(f"Health check from {request.remote_addr}")
97-
35+
logger.debug('Health check performed')
9836
return jsonify({
9937
'status': 'healthy',
10038
'timestamp': datetime.now(timezone.utc).isoformat(),
@@ -104,7 +42,10 @@ def health_check():
10442
# Error Handlers
10543
@app.errorhandler(404)
10644
def not_found(error):
107-
logger.warning(f"404 error: {request.path}")
45+
logger.warning('404 Not Found', extra={
46+
'path': request.path,
47+
'method': request.method
48+
})
10849
return jsonify({
10950
'error': 'Not Found',
11051
'message': 'The requested endpoint does not exist',
@@ -113,14 +54,20 @@ def not_found(error):
11354

11455
@app.errorhandler(500)
11556
def internal_error(error):
116-
logger.error(f"500 error: {str(error)}")
57+
logger.error('500 Internal Server Error', exc_info=True, extra={
58+
'path': request.path,
59+
'method': request.method
60+
})
11761
return jsonify({
11862
'error': 'Internal Server Error',
11963
'message': 'An unexpected error occurred'
12064
}), 500
12165

12266
# Application Entry Point
123-
if __name__ == '__main__':
124-
logger.info(f"Starting DevOps Info Service on {HOST}:{PORT}")
125-
logger.info(f"Debug mode: {DEBUG}")
126-
app.run(host=HOST, port=PORT, debug=DEBUG)
67+
if name == 'main':
68+
logger.info('Application starting', extra={
69+
'host': HOST,
70+
'port': PORT,
71+
'debug': DEBUG
72+
})
73+
app.run(host=HOST, port=PORT, debug=DEBUG)

0 commit comments

Comments
 (0)