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
12 changes: 12 additions & 0 deletions app_python/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Python
__pycache__/
*.py[cod]
venv/
*.log

# IDE
.vscode/
.idea/

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

A FastAPI-based web service providing detailed information about the service, system, and runtime environment.

## Overview

This service is part of the DevOps course and provides:
- Comprehensive system information
- Health check endpoint for monitoring
- Runtime statistics
- Automatic OpenAPI documentation

## Prerequisites

- Python 3.11 or higher
- pip (Python package manager)

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd app_python
```

2. Create and activate virtual environment:
```bash
python -m venv venv
source venv/bin/activate
```

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

## Running the Application

### Basic usage:
```bash
python app.py
```

### With custom configuration:
```bash
# Custom port
PORT=8080 python app.py

# Custom host and port
HOST=127.0.0.1 PORT=3000 python app.py

# Enable debug mode
DEBUG=true python app.py
```

### Using uvicorn directly:
```bash
uvicorn app:app --host 0.0.0.0 --port 5000 --reload
```

### Testing

Test the endpoints using curl:

```bash
# Get service info
curl http://localhost:5000/

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

# Pretty-print JSON output
curl http://localhost:5000/ | python -m json.tool
```

## API Endpoints

### GET `/`
Returns comprehensive service and system information.

**Example Response:**
```json
{
"service": {
"name": "devops-info-service",
"version": "1.0.0",
"description": "DevOps course info service",
"framework": "FastAPI"
},
"system": {
"hostname": "my-laptop",
"platform": "Linux",
"platform_version": "Ubuntu 24.04",
"architecture": "x86_64",
"cpu_count": 8,
"python_version": "3.13.1"
},
"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 Kubernetes probes.

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

## Configuration

The application can be configured using environment variables:

| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `0.0.0.0` | Host to bind the server to |
| `PORT` | `5000` | Port to listen on |
| `DEBUG` | `False` | Enable debug mode and hot reload |
155 changes: 155 additions & 0 deletions app_python/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import os
import socket
import platform
import logging
from datetime import datetime, timezone
from typing import Dict, Any

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware

# Application configuration
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "5000"))
DEBUG = os.getenv("DEBUG", "False").lower() == "true"

# Configure logging
logging.basicConfig(
level=logging.DEBUG if DEBUG else logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Application start time
START_TIME = datetime.now(timezone.utc)

# Create FastAPI application
app = FastAPI(
title="DevOps Info Service",
version="1.0.0",
description="DevOps course information service",
)

# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

def get_system_info() -> Dict[str, Any]:
"""Collect and return system information."""
return {
"hostname": socket.gethostname(),
"platform": platform.system(),
"platform_version": platform.version(),
"architecture": platform.machine(),
"cpu_count": os.cpu_count(),
"python_version": platform.python_version(),
}

def get_uptime() -> Dict[str, Any]:
"""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} hours, {minutes} minutes"
}

def get_request_info(request: Request) -> Dict[str, Any]:
"""Extract request information."""
client_ip = request.client.host if request.client else "127.0.0.1"
user_agent = request.headers.get("user-agent", "Unknown")

return {
"client_ip": client_ip,
"user_agent": user_agent,
"method": request.method,
"path": request.url.path,
}

@app.get("/", response_model=Dict[str, Any])
async def root(request: Request) -> Dict[str, Any]:
"""
Main endpoint returning comprehensive service and system information.
"""
logger.info(f"GET / requested by {request.client.host if request.client else 'unknown'}")

return {
"service": {
"name": "devops-info-service",
"version": "1.0.0",
"description": "DevOps course info service",
"framework": "FastAPI",
},
"system": get_system_info(),
"runtime": {
"uptime_seconds": get_uptime()["seconds"],
"uptime_human": get_uptime()["human"],
"current_time": datetime.now(timezone.utc).isoformat(),
"timezone": "UTC",
},
"request": get_request_info(request),
"endpoints": [
{"path": "/", "method": "GET", "description": "Service information"},
{"path": "/health", "method": "GET", "description": "Health check"},
],
}

@app.get("/health", response_model=Dict[str, Any])
async def health() -> Dict[str, Any]:
"""
Health check endpoint for monitoring and Kubernetes probes.
"""
return {
"status": "healthy",
"timestamp": datetime.now(timezone.utc).isoformat(),
"uptime_seconds": get_uptime()["seconds"],
}

@app.exception_handler(404)
async def not_found(request: Request, exc):
"""Handle 404 errors."""
return JSONResponse(
status_code=404,
content={
"error": "Not Found",
"message": f"The requested endpoint {request.url.path} does not exist"
}
)

@app.exception_handler(500)
async def internal_error(request: Request, exc):
"""Handle 500 errors."""
logger.error(f"Internal server error: {exc}")
return JSONResponse(
status_code=500,
content={
"error": "Internal Server Error",
"message": "An unexpected error occurred"
}
)

def main():
"""Application entry point."""
logger.info(f"Starting DevOps Info Service on {HOST}:{PORT}")
logger.info(f"Debug mode: {DEBUG}")

import uvicorn
uvicorn.run(
"app:app",
host=HOST,
port=PORT,
reload=DEBUG,
log_level="debug" if DEBUG else "info"
)

if __name__ == "__main__":
main()
Loading