Created
June 30, 2025 10:54
-
-
Save RndmCodeGuy20/ae1438bbd80a610fbc001c8fb157c5f7 to your computer and use it in GitHub Desktop.
Docker Container Profiler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import docker | |
| import threading | |
| import json | |
| import time | |
| import queue | |
| from datetime import datetime | |
| from collections import defaultdict | |
| class ContainerLifecycleMonitor: | |
| def __init__(self): | |
| self.client = docker.from_env() | |
| self.metrics_queue = queue.Queue() | |
| self.active_monitors = {} # container_id -> thread | |
| self.container_metrics = defaultdict(list) # Store all metrics per container | |
| self.stop_event = threading.Event() | |
| def start_monitoring(self): | |
| """Start the main event listener""" | |
| print("Starting container lifecycle monitor...") | |
| # Start the metrics processor thread | |
| processor_thread = threading.Thread(target=self._process_metrics_queue) | |
| processor_thread.daemon = True | |
| processor_thread.start() | |
| # Listen for Docker events | |
| try: | |
| for event in self.client.events(decode=True): | |
| if self.stop_event.is_set(): | |
| break | |
| self._handle_docker_event(event) | |
| except KeyboardInterrupt: | |
| print("\nStopping container monitor...") | |
| self.stop_event.set() | |
| def _handle_docker_event(self, event): | |
| """Process Docker daemon events""" | |
| if event.get('Type') != 'container': | |
| return | |
| action = event.get('Action') | |
| container_id = event.get('Actor', {}).get('ID', '')[:12] | |
| container_name = event.get('Actor', {}).get('Attributes', {}).get('name', 'unknown') | |
| print(f"[{datetime.now().strftime('%H:%M:%S')}] Container {container_name} ({container_id}): {action}") | |
| if action == 'start': | |
| self._start_container_monitoring(container_id, container_name) | |
| elif action in ['die', 'kill', 'stop']: | |
| self._stop_container_monitoring(container_id, container_name) | |
| elif action == 'destroy': | |
| self._finalize_container_metrics(container_id, container_name) | |
| def _start_container_monitoring(self, container_id, container_name): | |
| """Start monitoring a specific container immediately""" | |
| if container_id in self.active_monitors: | |
| return # Already monitoring | |
| print(f" → Starting metrics collection for {container_name}") | |
| # Create and start monitoring thread | |
| monitor_thread = threading.Thread( | |
| target=self._collect_container_metrics, | |
| args=(container_id, container_name) | |
| ) | |
| monitor_thread.daemon = True | |
| monitor_thread.start() | |
| self.active_monitors[container_id] = { | |
| 'thread': monitor_thread, | |
| 'name': container_name, | |
| 'start_time': datetime.now() | |
| } | |
| def _stop_container_monitoring(self, container_id, container_name): | |
| """Stop monitoring when container stops""" | |
| if container_id in self.active_monitors: | |
| print(f" → Stopping metrics collection for {container_name}") | |
| # Thread will stop automatically when container is no longer accessible | |
| def _finalize_container_metrics(self, container_id, container_name): | |
| """Clean up and save final metrics when container is destroyed""" | |
| if container_id in self.active_monitors: | |
| monitor_info = self.active_monitors.pop(container_id) | |
| end_time = datetime.now() | |
| duration = (end_time - monitor_info['start_time']).total_seconds() | |
| print(f" → Finalizing metrics for {container_name} (ran for {duration:.2f}s)") | |
| # Save container summary | |
| self._save_container_summary(container_id, container_name, duration) | |
| def _collect_container_metrics(self, container_id, container_name): | |
| """Collect metrics for a specific container until it stops""" | |
| collection_interval = 0.5 # Collect every 500ms for short-lived containers | |
| try: | |
| container = self.client.containers.get(container_id) | |
| while not self.stop_event.is_set(): | |
| try: | |
| # Check if container is still running | |
| container.reload() | |
| if container.status not in ['running']: | |
| break | |
| # Get metrics | |
| stats = container.stats(stream=False) | |
| metrics = { | |
| 'timestamp': datetime.now().isoformat(), | |
| 'container_id': container_id, | |
| 'container_name': container_name, | |
| 'cpu_percent': self._calculate_cpu_percent(stats), | |
| 'memory_usage_mb': stats.get('memory_stats', {}).get('usage', 0) / (1024 * 1024), | |
| 'memory_limit_mb': stats.get('memory_stats', {}).get('limit', 0) / (1024 * 1024), | |
| 'memory_percent': self._calculate_memory_percent(stats), | |
| 'network_rx_mb': self._get_network_rx(stats) / (1024 * 1024), | |
| 'network_tx_mb': self._get_network_tx(stats) / (1024 * 1024), | |
| 'disk_read_mb': self._get_disk_read(stats) / (1024 * 1024), | |
| 'disk_write_mb': self._get_disk_write(stats) / (1024 * 1024), | |
| 'process_count': stats.get('pids_stats', {}).get('current', 0) | |
| } | |
| # Add to queue for processing | |
| self.metrics_queue.put(metrics) | |
| time.sleep(collection_interval) | |
| except docker.errors.NotFound: | |
| # Container was removed | |
| break | |
| except Exception as e: | |
| print(f"Error collecting metrics for {container_name}: {e}") | |
| break | |
| except docker.errors.NotFound: | |
| print(f"Container {container_name} not found when starting monitoring") | |
| def _process_metrics_queue(self): | |
| """Process collected metrics from queue""" | |
| while not self.stop_event.is_set(): | |
| try: | |
| metrics = self.metrics_queue.get(timeout=1) | |
| # Store metrics | |
| container_id = metrics['container_id'] | |
| self.container_metrics[container_id].append(metrics) | |
| # Optional: Real-time display | |
| self._display_realtime_metrics(metrics) | |
| except queue.Empty: | |
| continue | |
| except Exception as e: | |
| print(f"Error processing metrics: {e}") | |
| def _display_realtime_metrics(self, metrics): | |
| """Display metrics in real-time (optional)""" | |
| name = metrics['container_name'][:15] | |
| cpu = metrics['cpu_percent'] | |
| memory = metrics['memory_percent'] | |
| timestamp = metrics['timestamp'].split('T')[1][:8] | |
| print(f"[{timestamp}] {name:<15} CPU: {cpu:6.1f}% MEM: {memory:6.1f}%") | |
| def _save_container_summary(self, container_id, container_name, duration): | |
| """Save summary metrics for the container""" | |
| if container_id not in self.container_metrics: | |
| return | |
| metrics_list = self.container_metrics[container_id] | |
| if not metrics_list: | |
| return | |
| # Calculate summary statistics | |
| cpu_values = [m['cpu_percent'] for m in metrics_list] | |
| memory_values = [m['memory_percent'] for m in metrics_list] | |
| summary = { | |
| 'container_name': container_name, | |
| 'container_id': container_id, | |
| 'duration_seconds': duration, | |
| 'total_samples': len(metrics_list), | |
| 'cpu_stats': { | |
| 'avg': sum(cpu_values) / len(cpu_values), | |
| 'max': max(cpu_values), | |
| 'min': min(cpu_values) | |
| }, | |
| 'memory_stats': { | |
| 'avg': sum(memory_values) / len(memory_values), | |
| 'max': max(memory_values), | |
| 'min': min(memory_values) | |
| }, | |
| 'peak_memory_mb': max([m['memory_usage_mb'] for m in metrics_list]), | |
| 'total_network_rx_mb': max([m['network_rx_mb'] for m in metrics_list]), | |
| 'total_network_tx_mb': max([m['network_tx_mb'] for m in metrics_list]), | |
| 'all_metrics': metrics_list # Full detailed metrics | |
| } | |
| # Save to file | |
| filename = f"container_metrics_{container_name}_{container_id}_{int(time.time())}.json" | |
| with open(filename, 'w') as f: | |
| json.dump(summary, f, indent=2) | |
| print(f" → Saved detailed metrics to {filename}") | |
| # Clean up from memory | |
| del self.container_metrics[container_id] | |
| # Helper methods for metric calculations | |
| def _calculate_cpu_percent(self, stats): | |
| cpu_stats = stats.get('cpu_stats', {}) | |
| precpu_stats = stats.get('precpu_stats', {}) | |
| cpu_delta = cpu_stats.get('cpu_usage', {}).get('total_usage', 0) - \ | |
| precpu_stats.get('cpu_usage', {}).get('total_usage', 0) | |
| system_delta = cpu_stats.get('system_cpu_usage', 0) - \ | |
| precpu_stats.get('system_cpu_usage', 0) | |
| if system_delta > 0: | |
| num_cpus = len(cpu_stats.get('cpu_usage', {}).get('percpu_usage', [1])) | |
| return (cpu_delta / system_delta) * num_cpus * 100 | |
| return 0 | |
| def _calculate_memory_percent(self, stats): | |
| memory_stats = stats.get('memory_stats', {}) | |
| usage = memory_stats.get('usage', 0) | |
| limit = memory_stats.get('limit', 0) | |
| return (usage / limit * 100) if limit > 0 else 0 | |
| def _get_network_rx(self, stats): | |
| return sum(interface.get('rx_bytes', 0) for interface in stats.get('networks', {}).values()) | |
| def _get_network_tx(self, stats): | |
| return sum(interface.get('tx_bytes', 0) for interface in stats.get('networks', {}).values()) | |
| def _get_disk_read(self, stats): | |
| io_stats = stats.get('blkio_stats', {}).get('io_service_bytes_recursive', []) | |
| return sum(entry.get('value', 0) for entry in io_stats if entry.get('op') == 'Read') | |
| def _get_disk_write(self, stats): | |
| io_stats = stats.get('blkio_stats', {}).get('io_service_bytes_recursive', []) | |
| return sum(entry.get('value', 0) for entry in io_stats if entry.get('op') == 'Write') | |
| # Usage | |
| if __name__ == "__main__": | |
| monitor = ContainerLifecycleMonitor() | |
| monitor.start_monitoring() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment