Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions app_python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Python
__pycache__/
*.py[cod]
*.pyo
*.pyd
venv/
env/
*.log

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
.DS_Store
Thumbs.db
150 changes: 150 additions & 0 deletions app_python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# DevOps Info Service

A production-ready Python web service that provides comprehensive system and runtime information.

## Overview

The DevOps Info Service is a lightweight web application built to report detailed information about itself and its runtime environment. It exposes two main endpoints for service information and health checking, making it ideal for monitoring and DevOps workflows.

## Prerequisites

- Python 3.11 or higher
- pip (Python package installer)
- Virtual environment (recommended)

## Installation

1. Clone the repository and navigate to the app directory:
```bash
cd app_python
```

2. Create and activate a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```

3. Install dependencies:
```bash
pip install -r requirements.txt
```

## Running the Application

### Default Configuration

```bash
python app.py
```

The service will start on `0.0.0.0:5000` by default.

### Custom Configuration

Use environment variables to customize the service:

```bash
PORT=8080 python app.py
```

```bash
HOST=127.0.0.1 PORT=3000 DEBUG=true python app.py
```

## API Endpoints

### `GET /`

Returns comprehensive service and system information.

**Response:**
```json
{
"service": {
"name": "devops-info-service",
"version": "1.0.0",
"description": "DevOps course info service",
"framework": "Flask"
},
"system": {
"hostname": "my-laptop",
"platform": "Darwin",
"platform_version": "macOS-13.4-x86_64",
"architecture": "x86_64",
"cpu_count": 8,
"python_version": "3.11.5"
},
"runtime": {
"uptime_seconds": 3600,
"uptime_human": "1 hour, 0 minutes",
"current_time": "2026-01-07T14:30:00.000Z",
"timezone": "UTC"
},
"request": {
"client_ip": "127.0.0.1",
"user_agent": "curl/7.81.0",
"method": "GET",
"path": "/"
},
"endpoints": [
{"path": "/", "method": "GET", "description": "Service information"},
{"path": "/health", "method": "GET", "description": "Health check"}
]
}
```

### `GET /health`

Health check endpoint for monitoring and orchestration.

**Response:**
```json
{
"status": "healthy",
"timestamp": "2026-01-07T14:30:00.000Z",
"uptime_seconds": 3600
}
```

## Configuration

The service can be configured using environment variables:

| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `0.0.0.0` | Host address to bind to |
| `PORT` | `5000` | Port number to listen on |
| `DEBUG` | `False` | Enable debug mode |

## Testing

Test the endpoints using curl:

```bash
# Main endpoint
curl http://localhost:5000/

# Health check
curl http://localhost:5000/health

# Pretty print with jq
curl http://localhost:5000/ | jq .
```

## Architecture

The service is built with:
- **Flask 3.1**: Lightweight WSGI web framework
- **Python Standard Library**: Platform, socket, datetime modules for system introspection
- **Logging**: Structured logging for production monitoring
- **Error Handling**: Custom error handlers for 404 and 500 responses

## Development

The project follows Python best practices:
- PEP 8 compliant code style
- Type hints for better IDE support
- Modular function design
- Comprehensive error handling
- Production-ready logging
114 changes: 114 additions & 0 deletions app_python/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
"""
DevOps Info Service
Main application module
"""
import os
import socket
import platform
import logging
from datetime import datetime, timezone
from flask import Flask, jsonify, request

logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = Flask(__name__)

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)


def get_system_info():
"""Collect system information."""
return {
'hostname': socket.gethostname(),
'platform': platform.system(),
'platform_version': platform.platform(),
'architecture': platform.machine(),
'cpu_count': os.cpu_count(),
'python_version': platform.python_version()
}


def get_uptime():
"""Calculate application 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} hour{'s' if hours != 1 else ''}, {minutes} minute{'s' if minutes != 1 else ''}"
}


@app.route('/')
def index():
"""Main endpoint - service and system information."""
system_info = get_system_info()
uptime = get_uptime()

response = {
'service': {
'name': 'devops-info-service',
'version': '1.0.0',
'description': 'DevOps course info service',
'framework': 'Flask'
},
'system': system_info,
'runtime': {
'uptime_seconds': uptime['seconds'],
'uptime_human': uptime['human'],
'current_time': datetime.now(timezone.utc).isoformat(),
'timezone': 'UTC'
},
'request': {
'client_ip': request.remote_addr,
'user_agent': request.headers.get('User-Agent', 'Unknown'),
'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."""
return jsonify({
'status': 'healthy',
'timestamp': datetime.now(timezone.utc).isoformat(),
'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(500)
def internal_error(error):
return jsonify({
'error': 'Internal Server Error',
'message': 'An unexpected error occurred'
}), 500


if __name__ == '__main__':
logger.info(f'Starting DevOps Info Service on {HOST}:{PORT}')
app.run(host=HOST, port=PORT, debug=DEBUG)
Loading