Explore Create a Python CLI tool using docker-py that manages Docker containers. I need a watch… Save Share Download ▾ ReportCreate a Python CLI tool using docker-py that manages Docker containers. I need a watch command that listens to the Docker events stream and triggers a callback whenever a container dies with a non-zero exit code.
AssistantCopy response Copy first prompt Copy first response
Other models, same or similar prompt Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Details
Provider anthropic
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language —
Added to archive Nov 21, 2026
ID 01m7y9mmrzdc98dknm5ez8nx8rSource & license Imported from Frontier Reasoning Traces (source ). Imported records earn no Research Points.
Upstream record: train-1.parquet:9858
SultanR/frontier-reasoning-traces-sft, revision 0e6b23142b95f5fe.
License: Apache-2.0
Dataset releases Not yet included in a published release.
The user wants a Python CLI tool using docker-py that manages Docker containers. Specifically, they need a watch command that:
Listens to Docker events stream
Triggers a callback when a container dies with a non-zero exit code
I'll create a comprehensive CLI tool using docker-py that includes:
Main container management commands
A watch command with event listening
Callback handling for container death events with exit codes
Use argparse for CLI argument parsing
Proper error handling
Let me create a well-structured solution:
python Copy code
import docker
import argparse
import logging
import sys
from typing import Callable, Optional
from datetime import datetime
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class DockerContainerManager:
def __init__(self):
self.client = docker.from_env()
def list_containers(self, all_containers=False):
"""List all containers"""
containers = self.client.containers.list(all=all_containers)
for container in containers:
status = container.status
print(f"{container.short_id} - {container.name}: {status}")
def start_container(self, container_name):
"""Start a container"""
try:
container = self.client.containers.get(container_name)
container.start()
print(f"Started container: {container_name}")
except Exception as e:
logger.error(f"Error starting container: {e}")
def stop_container(self, container_name):
"""Stop a container"""
try:
container = self.client.containers.get(container_name)
container.stop()
print(f"Stopped container: {container_name}")
except Exception as e:
logger.error(f"Error stopping container: {e}")
def watch_events(self, callback: Callable[[dict], None]):
"""Watch Docker events"""
try:
for event in self.client.events(decode=True):
callback(event)
except KeyboardInterrupt:
logger.info("Stopping event watcher")
except Exception as e:
logger.error(f"Error watching events: {e}")
class ContainerEventWatcher:
def __init__(self, on_death_callback: Optional[Callable] = None):
self.client = docker.from_env()
self.on_death_callback = on_death_callback
The event watcher class initializes a Docker client and stores the death callback. When watching events, it filters for die events and checks the exit code, triggering the callback only when a container exits with a non-zero status.
def handle_event(self, event: dict):
"""Handle individual events"""
if event.get('Type') == 'container' and event.get('Action') == 'die':
exit_code = event.get('Actor', {}).get('Attributes', {}).get('exitCode', '0')
container_id = event.get('Actor', {}).get('ID', 'unknown')
container_name = event.get('Actor', {}).get('Attributes', {}).get('name', 'unknown')
try:
exit_code = int(exit_code)
except (ValueError, TypeError):
exit_code = -1
# Only trigger callback for non-zero exit codes
if exit_code != 0:
logger.warning(
f"Container died with non-zero exit code: "
f"name={container_name}, id={container_id}, exit_code={exit_code}"
)
if self.on_death_callback:
self.on_death_callback({
'container_id': container_id,
'container_name': container_name,
'exit_code': exit_code,
'timestamp': datetime.now()
})
def watch(self):
"""Start watching events"""
logger.info("Starting container event watcher")
try:
for event in self.client.events(decode=True):
self.handle_event(event)
except KeyboardInterrupt:
logger.info("Stopping event watcher")
except Exception as e:
logger.error(f"Error in event watcher: {e}")
The watch method streams Docker events with decoding enabled, processes each one through the event handler, and gracefully manages interrupts or errors that occur during monitoring.
For the command-line interface, I'm setting up subparsers for list, start, stop, and watch operations. The list command accepts an optional flag to show all containers, while start and stop require a container identifier. The watch command takes an optional log file path for recording container failures.
In the main function, I route commands to the appropriate manager methods. For the watch command specifically, I define a callback that formats container death events with timestamp and exit code information, then writes them to the specified log file if provided. The watcher is instantiated with this callback and begins monitoring.</think>
# Docker Container Management CLI Tool
I'll create a comprehensive CLI tool using docker-py that manages containers with a robust watch command. Here's the complete solution:
## Project Structure
docker-container-cli/
├── requirements.txt
├── setup.py
├── docker_cli/
│ ├── init .py
│ ├── main.py
│ ├── manager.py
│ ├── watcher.py
│ ├── callbacks.py
│ └── config.py
└── examples/
├── custom_callback.py
└── config.yaml
code Copy code
## 1. Requirements
**requirements.txt**
```txt
docker>=6.1.0
pyyaml>=6.0
click>=8.1.0
tabulate>=0.9.0
2. Core Files
docker_cli/init .py
python Copy code
__version__ = "1.0.0"
__all__ = ["DockerContainerManager", "ContainerEventWatcher"]
docker_cli/config.py
python Copy code
import yaml
import os
from pathlib import Path
from dataclasses import dataclass
from typing import Optional, Dict, Any
@dataclass
class WatcherConfig:
"""Configuration for container event watcher"""
log_file: Optional[str] = None
log_to_syslog: bool = False
notify_webhook: Optional[str] = None
filter_containers: Optional[list] = None
exit_codes_to_monitor: Optional[list] = None
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'WatcherConfig':
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
class ConfigLoader:
"""Load configuration from YAML file"""
@staticmethod
def load(config_path: str) -> WatcherConfig:
"""Load config from YAML file"""
if not os.path.exists(config_path):
raise FileNotFoundError(f"Config file not found: {config_path}")
with open(config_path, 'r') as f:
data = yaml.safe_load(f) or {}
watcher_config = data.get('watcher', {})
return WatcherConfig.from_dict(watcher_config)
@staticmethod
def get_default_config() -> WatcherConfig:
"""Get default configuration"""
return WatcherConfig()
docker_cli/callbacks.py
docker_cli/watcher.py
docker_cli/manager.py
docker_cli/main.py
3. Setup Files
setup.py
python Copy code
from setuptools import setup, find_packages
with open("requirements.txt") as f:
requirements = f.read().splitlines()
setup(
name="docker-container-cli",
version="1.0.0",
description="Docker Container Management CLI Tool",
author="Your Name",
author_email="your.email@example.com",
packages=find_packages(),
install_requires=requirements,
entry_points={
"console_scripts": [
"docker-cli=docker_cli.main:main",
],
},
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
)
4. Example Configuration
examples/config.yaml
yaml Copy code
watcher:
log_file: /var/log/docker-cli/containers.log
log_to_syslog: true
notify_webhook: http://localhost:5000/webhook
filter_containers:
- app-*
- web-*
exit_codes_to_monitor:
- 1
- 127
- 139
examples/custom_callback.py
python Copy code
#!/usr/bin/env python3
"""Example of using the CLI with a custom callback"""
import sys
from docker_cli.watcher import ContainerEventWatcher
from docker_cli.callbacks import CallbackHandler, ConsoleHandler, LogFileHandler
def custom_callback(context):
"""Custom callback for container deaths"""
print(f"🔔 Custom Alert!")
print(f" Container: {context['container_name']}")
print(f" Exit Code: {context['exit_code']}")
print(f" Time: {context['timestamp'].isoformat()}")
# Add custom logic here (e.g., send email, trigger restart, etc.)
if context['exit_code'] > 128:
print(f" ⚠️ Fatal signal detected!")
if __name__ == '__main__':
handler = CallbackHandler()
handler.register(ConsoleHandler(verbose=True))
handler.register(LogFileHandler('/tmp/container-events.log'))
handler.register(custom_callback)
watcher = ContainerEventWatcher(callback_handler=handler)
try:
watcher.watch()
except KeyboardInterrupt:
print("\nStopped watching")
5. Installation & Usage
bash Copy code
# Install the package
pip install -r requirements.txt
pip install -e .
# Basic usage
docker-cli list
docker-cli list --all
docker-cli inspect my-container
# Start/Stop containers
docker-cli start my-container
docker-cli stop my-container --timeout 15
# Watch for failures
docker-cli watch
docker-cli watch --log-file failures.log --verbose
docker-cli watch --webhook http://localhost:5000/notify
# Watch with config file
docker-cli watch --config examples/config.yaml
# Show logs
docker-cli logs my-container --tail 50
# Show stats
docker-cli stats my-container
# Debug mode
docker-cli --debug watch
Key Features
✅ Event Watching : Listens to Docker events stream
✅ Non-zero Exit Code Detection : Filters container deaths by exit code
✅ Multiple Handlers : Log file, console, syslog, webhook
✅ Configuration File Support : YAML-based configuration
✅ Async Watching : Optional threaded event watching
✅ Rich CLI : Beautiful output with click and tabulate
✅ Error Handling : Comprehensive exception handling
✅ Logging : Full logging support with configurable levels
✅ Container Management : List, start, stop, restart, remove operations
✅ Extensible : Easy to add custom callbacks
This tool provides a production-ready solution for monitoring Docker container health!
Show full message · 1,055 lines import logging
import json
import requests
from datetime import datetime
from typing import Dict, Any, Optional
from pathlib import Path
logger = logging.getLogger(__name__)
class CallbackHandler:
"""Handles various callback actions for container events"""
def __init__(self):
self.handlers = []
def register(self, handler: callable) -> None:
"""Register a callback handler"""
self.handlers.append(handler)
def execute(self, context: Dict[str, Any]) -> None:
"""Execute all registered handlers"""
for handler in self.handlers:
try:
handler(context)
except Exception as e:
logger.error(f"Error executing handler {handler.__name__}: {e}")
class LogFileHandler:
"""Handler that logs events to a file"""
def __init__(self, log_file: str):
self.log_file = Path(log_file)
self.log_file.parent.mkdir(parents=True, exist_ok=True)
def __call__(self, context: Dict[str, Any]) -> None:
"""Log event to file"""
message = self._format_message(context)
try:
with open(self.log_file, 'a') as f:
f.write(message + '\n')
logger.debug(f"Logged event to {self.log_file}")
except IOError as e:
logger.error(f"Failed to write to log file: {e}")
@staticmethod
def _format_message(context: Dict[str, Any]) -> str:
"""Format event context as a log message"""
return (
f"[{context['timestamp'].isoformat()}] "
f"Container: {context['container_name']} | "
f"ID: {context['container_id'][:12]} | "
f"Exit Code: {context['exit_code']} | "
f"Status: {context.get('status', 'unknown')}"
)
class SyslogHandler:
"""Handler that sends events to syslog"""
def __init__(self, facility: int = 16): # LOG_LOCAL0
import syslog
self.syslog = syslog
self.facility = facility
def __call__(self, context: Dict[str, Any]) -> None:
"""Send event to syslog"""
try:
priority = self.syslog.LOG_WARNING
message = (
f"Container {context['container_name']} "
f"died with exit code {context['exit_code']}"
)
self.syslog.syslog(priority, message)
logger.debug("Logged event to syslog")
except Exception as e:
logger.error(f"Failed to write to syslog: {e}")
class WebhookHandler:
"""Handler that sends events to a webhook"""
def __init__(self, webhook_url: str, timeout: int = 5):
self.webhook_url = webhook_url
self.timeout = timeout
def __call__(self, context: Dict[str, Any]) -> None:
"""Send event to webhook"""
payload = self._prepare_payload(context)
try:
response = requests.post(
self.webhook_url,
json=payload,
timeout=self.timeout
)
response.raise_for_status()
logger.debug(f"Webhook sent successfully: {response.status_code}")
except requests.exceptions.RequestException as e:
logger.error(f"Webhook request failed: {e}")
@staticmethod
def _prepare_payload(context: Dict[str, Any]) -> Dict[str, Any]:
"""Prepare JSON payload for webhook"""
return {
"event_type": "container_died",
"container_name": context['container_name'],
"container_id": context['container_id'],
"exit_code": context['exit_code'],
"timestamp": context['timestamp'].isoformat(),
"status": context.get('status', 'unknown')
}
class ConsoleHandler:
"""Handler that prints events to console"""
def __init__(self, verbose: bool = False):
self.verbose = verbose
def __call__(self, context: Dict[str, Any]) -> None:
"""Print event to console"""
message = self._format_message(context)
print(message)
def _format_message(self, context: Dict[str, Any]) -> str:
"""Format message for console output"""
base = (
f"❌ Container died: {context['container_name']} "
f"(exit code: {context['exit_code']})"
)
if self.verbose:
base += f"\n ID: {context['container_id']}"
base += f"\n Time: {context['timestamp'].isoformat()}"
return base
import docker
import logging
from datetime import datetime
from typing import Optional, Callable, Dict, Any, List
from threading import Thread, Event
logger = logging.getLogger(__name__)
class ContainerEventWatcher:
"""Watches Docker events stream and handles container lifecycle events"""
def __init__(self, callback_handler=None):
"""
Initialize the watcher
Args:
callback_handler: CallbackHandler instance for event notifications
"""
self.client = docker.from_env()
self.callback_handler = callback_handler
self._stop_event = Event()
self._running = False
def _get_container_info(self, container_id: str) -> Dict[str, Any]:
"""Get container information"""
try:
container = self.client.containers.get(container_id)
return {
'name': container.name,
'image': container.image.tags[0] if container.image.tags else 'unknown'
}
except Exception as e:
logger.debug(f"Could not retrieve container info: {e}")
return {'name': 'unknown', 'image': 'unknown'}
def handle_event(self, event: Dict[str, Any]) -> None:
"""
Handle individual Docker events
Args:
event: Docker event dictionary
"""
event_type = event.get('Type')
action = event.get('Action')
if event_type != 'container':
return
if action == 'die':
self._handle_container_death(event)
elif action == 'start':
self._handle_container_start(event)
elif action == 'stop':
self._handle_container_stop(event)
def _handle_container_death(self, event: Dict[str, Any]) -> None:
"""Handle container death event"""
actor = event.get('Actor', {})
attributes = actor.get('Attributes', {})
container_id = actor.get('ID', 'unknown')
container_name = attributes.get('name', 'unknown')
exit_code = self._parse_exit_code(attributes.get('exitCode', '0'))
# Only process non-zero exit codes
if exit_code != 0:
context = {
'container_id': container_id,
'container_name': container_name,
'exit_code': exit_code,
'timestamp': datetime.now(),
'event_type': 'die',
'status': 'exited'
}
logger.warning(
f"Container died: {container_name} "
f"(ID: {container_id[:12]}, Exit Code: {exit_code})"
)
if self.callback_handler:
self.callback_handler.execute(context)
def _handle_container_start(self, event: Dict[str, Any]) -> None:
"""Handle container start event"""
actor = event.get('Actor', {})
attributes = actor.get('Attributes', {})
container_name = attributes.get('name', 'unknown')
logger.info(f"Container started: {container_name}")
def _handle_container_stop(self, event: Dict[str, Any]) -> None:
"""Handle container stop event"""
actor = event.get('Actor', {})
attributes = actor.get('Attributes', {})
container_name = attributes.get('name', 'unknown')
logger.info(f"Container stopped: {container_name}")
@staticmethod
def _parse_exit_code(exit_code_str: str) -> int:
"""Parse exit code from string"""
try:
return int(exit_code_str)
except (ValueError, TypeError):
logger.warning(f"Could not parse exit code: {exit_code_str}")
return -1
def watch(self) -> None:
"""Start watching Docker events"""
logger.info("Starting container event watcher")
self._running = True
try:
for event in self.client.events(decode=True):
if self._stop_event.is_set():
break
self.handle_event(event)
except KeyboardInterrupt:
logger.info("Event watcher interrupted by user")
except Exception as e:
logger.error(f"Error in event watcher: {e}")
finally:
self._running = False
logger.info("Event watcher stopped")
def watch_async(self) -> Thread:
"""Start watching Docker events in a separate thread"""
thread = Thread(target=self.watch, daemon=False)
thread.start()
return thread
def stop(self) -> None:
"""Stop the event watcher"""
logger.info("Stopping event watcher")
self._stop_event.set()
import docker
import logging
from typing import List, Dict, Optional
from docker.models.containers import Container
from tabulate import tabulate
logger = logging.getLogger(__name__)
class DockerContainerManager:
"""Manages Docker containers operations"""
def __init__(self):
self.client = docker.from_env()
def list_containers(self, all: bool = False, name_filter: Optional[str] = None) -> List[Dict]:
"""
List all containers
Args:
all: Show all containers including stopped ones
name_filter: Filter containers by name pattern
Returns:
List of container information dictionaries
"""
try:
containers = self.client.containers.list(all=all)
data = []
for container in containers:
if name_filter and name_filter.lower() not in container.name.lower():
continue
status = container.status
image = container.image.tags[0] if container.image.tags else 'unknown'
data.append({
'ID': container.short_id,
'Name': container.name,
'Image': image,
'Status': status,
'Created': container.attrs['Created'][:19]
})
if data:
print(tabulate(data, headers='keys', tablefmt='grid'))
else:
print("No containers found")
return data
except Exception as e:
logger.error(f"Error listing containers: {e}")
return []
def inspect_container(self, container_name: str) -> Optional[Dict]:
"""
Inspect container details
Args:
container_name: Container name or ID
Returns:
Container information dictionary
"""
try:
container = self.client.containers.get(container_name)
info = {
'ID': container.id,
'Name': container.name,
'Image': container.image.tags[0] if container.image.tags else 'unknown',
'Status': container.status,
'State': container.attrs['State'],
'Config': {
'Hostname': container.attrs['Config']['Hostname'],
'Image': container.attrs['Config']['Image'],
'Env': container.attrs['Config']['Env'][:3] # First 3 env vars
}
}
print(f"Container: {container.name}")
print(f" Status: {info['Status']}")
print(f" Image: {info['Image']}")
print(f" State: {info['State']}")
return info
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return None
except Exception as e:
logger.error(f"Error inspecting container: {e}")
return None
def start_container(self, container_name: str) -> bool:
"""
Start a container
Args:
container_name: Container name or ID
Returns:
Success status
"""
try:
container = self.client.containers.get(container_name)
container.start()
logger.info(f"Started container: {container.name}")
return True
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return False
except Exception as e:
logger.error(f"Error starting container: {e}")
return False
def stop_container(self, container_name: str, timeout: int = 10) -> bool:
"""
Stop a container
Args:
container_name: Container name or ID
timeout: Timeout in seconds
Returns:
Success status
"""
try:
container = self.client.containers.get(container_name)
container.stop(timeout=timeout)
logger.info(f"Stopped container: {container.name}")
return True
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return False
except Exception as e:
logger.error(f"Error stopping container: {e}")
return False
def restart_container(self, container_name: str, timeout: int = 10) -> bool:
"""
Restart a container
Args:
container_name: Container name or ID
timeout: Timeout in seconds
Returns:
Success status
"""
try:
container = self.client.containers.get(container_name)
container.restart(timeout=timeout)
logger.info(f"Restarted container: {container.name}")
return True
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return False
except Exception as e:
logger.error(f"Error restarting container: {e}")
return False
def remove_container(self, container_name: str, force: bool = False, volumes: bool = False) -> bool:
"""
Remove a container
Args:
container_name: Container name or ID
force: Force remove
volumes: Remove volumes
Returns:
Success status
"""
try:
container = self.client.containers.get(container_name)
container.remove(force=force, v=volumes)
logger.info(f"Removed container: {container.name}")
return True
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return False
except Exception as e:
logger.error(f"Error removing container: {e}")
return False
def get_container_logs(self, container_name: str, tail: int = 100) -> Optional[str]:
"""
Get container logs
Args:
container_name: Container name or ID
tail: Number of lines to get
Returns:
Log content
"""
try:
container = self.client.containers.get(container_name)
logs = container.logs(tail=tail).decode('utf-8')
return logs
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return None
except Exception as e:
logger.error(f"Error getting logs: {e}")
return None
def get_container_stats(self, container_name: str) -> Optional[Dict]:
"""
Get container statistics
Args:
container_name: Container name or ID
Returns:
Stats dictionary
"""
try:
container = self.client.containers.get(container_name)
stats = container.stats(stream=False)
# Extract useful information
cpu_delta = stats['cpu_stats']['cpu_usage']['total_usage'] - \
stats['precpu_stats']['cpu_usage']['total_usage']
system_delta = stats['cpu_stats']['system_cpu_usage'] - \
stats['precpu_stats']['system_cpu_usage']
cpu_percent = (cpu_delta / system_delta) * 100.0 if system_delta > 0 else 0
memory_usage = stats['memory_stats']['usage']
memory_limit = stats['memory_stats']['limit']
memory_percent = (memory_usage / memory_limit) * 100 if memory_limit > 0 else 0
return {
'cpu_percent': f"{cpu_percent:.2f}%",
'memory_usage': f"{memory_usage / 1024 / 1024:.2f} MB",
'memory_limit': f"{memory_limit / 1024 / 1024:.2f} MB",
'memory_percent': f"{memory_percent:.2f}%"
}
except docker.errors.NotFound:
logger.error(f"Container not found: {container_name}")
return None
except Exception as e:
logger.error(f"Error getting stats: {e}")
return None
import click
import logging
import sys
from typing import Optional
from docker_cli.manager import DockerContainerManager
from docker_cli.watcher import ContainerEventWatcher
from docker_cli.callbacks import (
CallbackHandler, LogFileHandler, ConsoleHandler,
SyslogHandler, WebhookHandler
)
from docker_cli.config import ConfigLoader
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@click.group()
@click.option('--debug', is_flag=True, help='Enable debug mode')
def cli(debug):
"""Docker Container Management CLI"""
if debug:
logging.getLogger().setLevel(logging.DEBUG)
@cli.command()
@click.option('--all', '-a', is_flag=True, help='Show all containers')
@click.option('--filter', '-f', type=str, help='Filter containers by name')
def list(all, filter):
"""List Docker containers"""
manager = DockerContainerManager()
manager.list_containers(all=all, name_filter=filter)
@cli.command()
@click.argument('container_name')
def inspect(container_name):
"""Inspect container details"""
manager = DockerContainerManager()
manager.inspect_container(container_name)
@cli.command()
@click.argument('container_name')
def start(container_name):
"""Start a container"""
manager = DockerContainerManager()
if manager.start_container(container_name):
click.echo(f"✓ Started container: {container_name}", fg='green')
else:
click.echo(f"✗ Failed to start container: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.argument('container_name')
@click.option('--timeout', '-t', type=int, default=10, help='Timeout in seconds')
def stop(container_name, timeout):
"""Stop a container"""
manager = DockerContainerManager()
if manager.stop_container(container_name, timeout=timeout):
click.echo(f"✓ Stopped container: {container_name}", fg='green')
else:
click.echo(f"✗ Failed to stop container: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.argument('container_name')
@click.option('--timeout', '-t', type=int, default=10, help='Timeout in seconds')
def restart(container_name, timeout):
"""Restart a container"""
manager = DockerContainerManager()
if manager.restart_container(container_name, timeout=timeout):
click.echo(f"✓ Restarted container: {container_name}", fg='green')
else:
click.echo(f"✗ Failed to restart container: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.argument('container_name')
@click.option('--force', '-f', is_flag=True, help='Force remove')
@click.option('--volumes', '-v', is_flag=True, help='Remove volumes')
def remove(container_name, force, volumes):
"""Remove a container"""
manager = DockerContainerManager()
if manager.remove_container(container_name, force=force, volumes=volumes):
click.echo(f"✓ Removed container: {container_name}", fg='green')
else:
click.echo(f"✗ Failed to remove container: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.argument('container_name')
@click.option('--tail', type=int, default=100, help='Number of lines to show')
def logs(container_name, tail):
"""Show container logs"""
manager = DockerContainerManager()
logs_content = manager.get_container_logs(container_name, tail=tail)
if logs_content:
click.echo(logs_content)
else:
click.echo(f"✗ Failed to get logs for: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.argument('container_name')
def stats(container_name):
"""Show container statistics"""
manager = DockerContainerManager()
container_stats = manager.get_container_stats(container_name)
if container_stats:
for key, value in container_stats.items():
click.echo(f" {key}: {value}")
else:
click.echo(f"✗ Failed to get stats for: {container_name}", fg='red')
sys.exit(1)
@cli.command()
@click.option('--log-file', type=str, help='Log failed containers to file')
@click.option('--log-syslog', is_flag=True, help='Log to syslog')
@click.option('--webhook', type=str, help='Send events to webhook URL')
@click.option('--config', type=str, help='Load configuration from YAML file')
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
def watch(log_file, log_syslog, webhook, config, verbose):
"""Watch for container events
Listens to Docker events stream and triggers callbacks
when containers die with non-zero exit codes.
Examples:
# Basic watch with console output
$ docker-cli watch
# Log to file
$ docker-cli watch --log-file failures.log
# Send to webhook
$ docker-cli watch --webhook http://localhost:5000/webhook
# Load from config file
$ docker-cli watch --config config.yaml
"""
callback_handler = CallbackHandler()
# Load configuration if provided
if config:
try:
cfg = ConfigLoader.load(config)
log_file = log_file or cfg.log_file
log_syslog = log_syslog or cfg.log_to_syslog
webhook = webhook or cfg.notify_webhook
except Exception as e:
click.echo(f"✗ Failed to load config: {e}", fg='red')
sys.exit(1)
# Register handlers
callback_handler.register(ConsoleHandler(verbose=verbose))
if log_file:
try:
callback_handler.register(LogFileHandler(log_file))
click.echo(f"✓ Logging to file: {log_file}", fg='green')
except Exception as e:
click.echo(f"✗ Failed to setup file logging: {e}", fg='red')
sys.exit(1)
if log_syslog:
try:
callback_handler.register(SyslogHandler())
click.echo(f"✓ Logging to syslog", fg='green')
except Exception as e:
click.echo(f"✗ Failed to setup syslog: {e}", fg='red')
if webhook:
try:
callback_handler.register(WebhookHandler(webhook))
click.echo(f"✓ Sending to webhook: {webhook}", fg='green')
except Exception as e:
click.echo(f"✗ Failed to setup webhook: {e}", fg='red')
# Start watching
try:
watcher = ContainerEventWatcher(callback_handler=callback_handler)
click.echo("Starting container event watcher... (Press Ctrl+C to stop)", fg='yellow')
watcher.watch()
except KeyboardInterrupt:
click.echo("\n✓ Event watcher stopped", fg='green')
except Exception as e:
click.echo(f"✗ Watcher error: {e}", fg='red')
sys.exit(1)
def main():
"""Entry point"""
cli()
if __name__ == '__main__':
main()