"""
Pattern 279: Environment Management
Purpose: Environment provisioning, lifecycle management, and health monitoring
"""
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from collections import defaultdict
import random
class EnvironmentType(Enum):
"""Type of environment."""
DEVELOPMENT = "development"
STAGING = "staging"
PRODUCTION = "production"
TESTING = "testing"
UAT = "uat" # User Acceptance Testing
class EnvironmentStatus(Enum):
"""Status of environment."""
CREATING = "creating"
ACTIVE = "active"
DEGRADED = "degraded"
MAINTENANCE = "maintenance"
TERMINATING = "terminating"
TERMINATED = "terminated"
class ResourceType(Enum):
"""Type of resource."""
COMPUTE = "compute"
STORAGE = "storage"
NETWORK = "network"
DATABASE = "database"
class HealthStatus(Enum):
"""Health status of environment."""
HEALTHY = "healthy"
WARNING = "warning"
CRITICAL = "critical"
UNKNOWN = "unknown"
@dataclass
class Resource:
"""Represents a resource in an environment."""
resource_id: str
resource_type: ResourceType
name: str
capacity: float # Units depend on type (CPU cores, GB, etc.)
allocated: float = 0.0
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class HealthCheck:
"""Health check result."""
check_name: str
status: HealthStatus
message: str
timestamp: datetime = field(default_factory=datetime.now)
details: Dict[str, Any] = field(default_factory=dict)
@dataclass
class Environment:
"""Represents a deployment environment."""
environment_id: str
name: str
env_type: EnvironmentType
status: EnvironmentStatus
resources: Dict[str, Resource] = field(default_factory=dict)
health_checks: List[HealthCheck] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.now)
last_health_check: Optional[datetime] = None
metadata: Dict[str, Any] = field(default_factory=dict)
class EnvironmentManagement:
"""
Implements environment management pattern.
Features:
- Environment provisioning
- Resource allocation
- Health monitoring
- Environment lifecycle management
- Auto-scaling
- Environment isolation
"""
def __init__(self):
self.environments: Dict[str, Environment] = {}
self.resource_pool: Dict[ResourceType, float] = {
ResourceType.COMPUTE: 100.0,
ResourceType.STORAGE: 1000.0,
ResourceType.NETWORK: 10.0,
ResourceType.DATABASE: 10.0
}
# Statistics
self.statistics = {
"total_environments": 0,
"active_environments": 0,
"total_resources_allocated": 0,
"health_checks_performed": 0,
"critical_issues": 0,
"environments_scaled": 0
}
def create_environment(
self,
name: str,
env_type: EnvironmentType,
resources: Dict[ResourceType, float]
) -> Dict[str, Any]:
"""
Create a new environment.
Args:
name: Environment name
env_type: Type of environment
resources: Required resources {type: amount}
Returns:
Status of environment creation
"""
# Check resource availability
for res_type, amount in resources.items():
available = self.resource_pool[res_type]
allocated = sum(
env.resources[res.resource_id].allocated
for env in self.environments.values()
for res in env.resources.values()
if res.resource_type == res_type
)
remaining = available - allocated
if amount > remaining:
return {
"success": False,
"message": f"Insufficient {res_type.value} resources. "
f"Requested: {amount}, Available: {remaining}"
}
# Create environment
env_id = f"env-{len(self.environments) + 1:04d}"
environment = Environment(
environment_id=env_id,
name=name,
env_type=env_type,
status=EnvironmentStatus.CREATING
)
# Allocate resources
for res_type, amount in resources.items():
res_id = f"{env_id}-{res_type.value}-001"
resource = Resource(
resource_id=res_id,
resource_type=res_type,
name=f"{name}-{res_type.value}",
capacity=amount,
allocated=amount
)
environment.resources[res_id] = resource
environment.status = EnvironmentStatus.ACTIVE
self.environments[env_id] = environment
self.statistics["total_environments"] += 1
self.statistics["active_environments"] += 1
self.statistics["total_resources_allocated"] += len(resources)
return {
"success": True,
"environment_id": env_id,
"name": name,
"type": env_type.value,
"status": environment.status.value,
"resources": {
res_type.value: amount
for res_type, amount in resources.items()
},
"message": f"Environment '{name}' created successfully"
}
def terminate_environment(self, environment_id: str) -> Dict[str, Any]:
"""
Terminate an environment and release resources.
Args:
environment_id: ID of environment to terminate
Returns:
Status of termination
"""
if environment_id not in self.environments:
return {
"success": False,
"message": f"Environment '{environment_id}' not found"
}
environment = self.environments[environment_id]
# Mark as terminating
environment.status = EnvironmentStatus.TERMINATING
# Release resources
resources_released = len(environment.resources)
environment.resources.clear()
# Mark as terminated
environment.status = EnvironmentStatus.TERMINATED
self.statistics["active_environments"] -= 1
return {
"success": True,
"environment_id": environment_id,
"resources_released": resources_released,
"message": f"Environment '{environment_id}' terminated"
}
def perform_health_check(self, environment_id: str) -> Dict[str, Any]:
"""
Perform comprehensive health check on environment.
Args:
environment_id: ID of environment to check
Returns:
Health check results
"""
if environment_id not in self.environments:
return {
"success": False,
"message": f"Environment '{environment_id}' not found"
}
environment = self.environments[environment_id]
# Simulate health checks
checks = []
# Resource utilization check
for resource in environment.resources.values():
utilization = resource.allocated / resource.capacity if resource.capacity > 0 else 0
if utilization > 0.9:
status = HealthStatus.CRITICAL
message = f"High utilization: {utilization*100:.1f}%"
self.statistics["critical_issues"] += 1
elif utilization > 0.75:
status = HealthStatus.WARNING
message = f"Moderate utilization: {utilization*100:.1f}%"
else:
status = HealthStatus.HEALTHY
message = f"Normal utilization: {utilization*100:.1f}%"
check = HealthCheck(
check_name=f"{resource.name}_utilization",
status=status,
message=message,
details={"utilization": utilization}
)
checks.append(check)
# Service availability check (simulated)
availability = random.random()
if availability > 0.99:
status = HealthStatus.HEALTHY
message = "All services available"
elif availability > 0.95:
status = HealthStatus.WARNING
message = "Some services degraded"
else:
status = HealthStatus.CRITICAL
message = "Service outage detected"
self.statistics["critical_issues"] += 1
checks.append(HealthCheck(
check_name="service_availability",
status=status,
message=message,
details={"availability": availability}
))
# Update environment
environment.health_checks.extend(checks)
environment.last_health_check = datetime.now()
# Determine overall health
if any(c.status == HealthStatus.CRITICAL for c in checks):
overall_health = HealthStatus.CRITICAL
environment.status = EnvironmentStatus.DEGRADED
elif any(c.status == HealthStatus.WARNING for c in checks):
overall_health = HealthStatus.WARNING
else:
overall_health = HealthStatus.HEALTHY
if environment.status == EnvironmentStatus.DEGRADED:
environment.status = EnvironmentStatus.ACTIVE
self.statistics["health_checks_performed"] += 1
return {
"success": True,
"environment_id": environment_id,
"overall_health": overall_health.value,
"checks": [
{
"name": c.check_name,
"status": c.status.value,
"message": c.message
}
for c in checks
],
"message": f"Health check completed: {overall_health.value}"
}
def scale_environment(
self,
environment_id: str,
resource_type: ResourceType,
scale_factor: float
) -> Dict[str, Any]:
"""
Scale environment resources.
Args:
environment_id: ID of environment
resource_type: Type of resource to scale
scale_factor: Factor to scale by (1.5 = 50% increase)
Returns:
Status of scaling operation
"""
if environment_id not in self.environments:
return {
"success": False,
"message": f"Environment '{environment_id}' not found"
}
environment = self.environments[environment_id]
# Find resources of specified type
resources_to_scale = [
res for res in environment.resources.values()
if res.resource_type == resource_type
]
if not resources_to_scale:
return {
"success": False,
"message": f"No {resource_type.value} resources in environment"
}
# Calculate new allocation
total_current = sum(res.allocated for res in resources_to_scale)
total_new = total_current * scale_factor
additional = total_new - total_current
# Check availability
available = self.resource_pool[resource_type]
allocated_global = sum(
res.allocated
for env in self.environments.values()
for res in env.resources.values()
if res.resource_type == resource_type
)
remaining = available - allocated_global
if additional > remaining:
return {
"success": False,
"message": f"Insufficient resources. Requested: {additional}, Available: {remaining}"
}
# Scale resources
for resource in resources_to_scale:
old_allocated = resource.allocated
resource.allocated = old_allocated * scale_factor
resource.capacity = resource.allocated
self.statistics["environments_scaled"] += 1
return {
"success": True,
"environment_id": environment_id,
"resource_type": resource_type.value,
"scale_factor": scale_factor,
"previous_total": total_current,
"new_total": total_new,
"message": f"Scaled {resource_type.value} by {scale_factor}x"
}
def get_environment_info(self, environment_id: str) -> Dict[str, Any]:
"""Get detailed environment information."""
if environment_id not in self.environments:
return {
"success": False,
"message": f"Environment '{environment_id}' not found"
}
environment = self.environments[environment_id]
# Calculate resource usage
resources_summary = {}
for resource in environment.resources.values():
res_type = resource.resource_type.value
if res_type not in resources_summary:
resources_summary[res_type] = {
"total_capacity": 0,
"total_allocated": 0,
"count": 0
}
resources_summary[res_type]["total_capacity"] += resource.capacity
resources_summary[res_type]["total_allocated"] += resource.allocated
resources_summary[res_type]["count"] += 1
# Latest health status
latest_health = HealthStatus.UNKNOWN
if environment.health_checks:
latest_checks = environment.health_checks[-5:]
if any(c.status == HealthStatus.CRITICAL for c in latest_checks):
latest_health = HealthStatus.CRITICAL
elif any(c.status == HealthStatus.WARNING for c in latest_checks):
latest_health = HealthStatus.WARNING
else:
latest_health = HealthStatus.HEALTHY
return {
"success": True,
"environment_id": environment_id,
"name": environment.name,
"type": environment.env_type.value,
"status": environment.status.value,
"health": latest_health.value,
"created_at": environment.created_at.isoformat(),
"last_health_check": environment.last_health_check.isoformat() if environment.last_health_check else None,
"resources": resources_summary,
"total_health_checks": len(environment.health_checks)
}
def list_environments(
self,
env_type: Optional[EnvironmentType] = None,
status: Optional[EnvironmentStatus] = None
) -> Dict[str, Any]:
"""List environments with optional filters."""
environments_list = []
for env_id, env in self.environments.items():
if env_type and env.env_type != env_type:
continue
if status and env.status != status:
continue
environments_list.append({
"environment_id": env_id,
"name": env.name,
"type": env.env_type.value,
"status": env.status.value,
"resource_count": len(env.resources)
})
return {
"total": len(environments_list),
"environments": environments_list
}
def get_statistics(self) -> Dict[str, Any]:
"""Get environment management statistics."""
# Calculate resource utilization
total_capacity = {}
total_allocated = {}
for res_type in ResourceType:
total_capacity[res_type.value] = self.resource_pool[res_type]
total_allocated[res_type.value] = sum(
res.allocated
for env in self.environments.values()
for res in env.resources.values()
if res.resource_type == res_type
)
return {
"total_environments": self.statistics["total_environments"],
"active_environments": self.statistics["active_environments"],
"total_resources_allocated": self.statistics["total_resources_allocated"],
"health_checks_performed": self.statistics["health_checks_performed"],
"critical_issues": self.statistics["critical_issues"],
"environments_scaled": self.statistics["environments_scaled"],
"resource_utilization": {
res_type: {
"capacity": total_capacity[res_type],
"allocated": total_allocated[res_type],
"utilization": total_allocated[res_type] / total_capacity[res_type] if total_capacity[res_type] > 0 else 0
}
for res_type in total_capacity.keys()
}
}
class EnvironmentManagementPattern:
"""
Coordinator for environment management.
Manages environment lifecycle and resources.
"""
def __init__(self):
self.management = EnvironmentManagement()
def create_environment(self, name: str, env_type: EnvironmentType, resources: Dict[ResourceType, float]) -> Dict[str, Any]:
"""Create environment."""
return self.management.create_environment(name, env_type, resources)
def terminate_environment(self, environment_id: str) -> Dict[str, Any]:
"""Terminate environment."""
return self.management.terminate_environment(environment_id)
def perform_health_check(self, environment_id: str) -> Dict[str, Any]:
"""Perform health check."""
return self.management.perform_health_check(environment_id)
def scale_environment(self, environment_id: str, resource_type: ResourceType, scale_factor: float) -> Dict[str, Any]:
"""Scale environment."""
return self.management.scale_environment(environment_id, resource_type, scale_factor)
def get_environment_info(self, environment_id: str) -> Dict[str, Any]:
"""Get environment info."""
return self.management.get_environment_info(environment_id)
def list_environments(self) -> Dict[str, Any]:
"""List environments."""
return self.management.list_environments()
def get_statistics(self) -> Dict[str, Any]:
"""Get statistics."""
return self.management.get_statistics()
# Example usage
if __name__ == "__main__":
print("=== Environment Management Demo ===\n")
# Create environment management
pattern = EnvironmentManagementPattern()
print("1. Creating development environment...")
result = pattern.create_environment(
name="dev-app",
env_type=EnvironmentType.DEVELOPMENT,
resources={
ResourceType.COMPUTE: 10.0,
ResourceType.STORAGE: 100.0,
ResourceType.NETWORK: 1.0
}
)
dev_env_id = result["environment_id"]
print(f" {result['message']}")
print(f" Environment ID: {dev_env_id}")
print("\n2. Creating staging environment...")
result = pattern.create_environment(
name="staging-app",
env_type=EnvironmentType.STAGING,
resources={
ResourceType.COMPUTE: 20.0,
ResourceType.STORAGE: 200.0,
ResourceType.NETWORK: 2.0,
ResourceType.DATABASE: 2.0
}
)
staging_env_id = result["environment_id"]
print(f" {result['message']}")
print("\n3. Creating production environment...")
result = pattern.create_environment(
name="prod-app",
env_type=EnvironmentType.PRODUCTION,
resources={
ResourceType.COMPUTE: 40.0,
ResourceType.STORAGE: 400.0,
ResourceType.NETWORK: 4.0,
ResourceType.DATABASE: 4.0
}
)
prod_env_id = result["environment_id"]
print(f" {result['message']}")
# List environments
print("\n4. Listing all environments...")
envs = pattern.list_environments()
print(f" Total environments: {envs['total']}")
for env in envs['environments']:
print(f" - {env['name']} ({env['type']}): {env['status']}")
# Perform health checks
print("\n5. Performing health checks...")
for env_id in [dev_env_id, staging_env_id, prod_env_id]:
result = pattern.perform_health_check(env_id)
print(f" {result['environment_id']}: {result['overall_health']}")
for check in result['checks']:
print(f" - {check['name']}: {check['status']}")
# Scale production environment
print("\n6. Scaling production compute resources by 1.5x...")
result = pattern.scale_environment(prod_env_id, ResourceType.COMPUTE, 1.5)
if result['success']:
print(f" {result['message']}")
print(f" Previous: {result['previous_total']}, New: {result['new_total']}")
# Get environment info
print("\n7. Getting production environment details...")
info = pattern.get_environment_info(prod_env_id)
if info['success']:
print(f" Name: {info['name']}")
print(f" Type: {info['type']}")
print(f" Status: {info['status']}")
print(f" Health: {info['health']}")
print(" Resources:")
for res_type, details in info['resources'].items():
print(f" - {res_type}: {details['total_allocated']}/{details['total_capacity']}")
# Statistics
print("\n8. Environment management statistics:")
stats = pattern.get_statistics()
print(f" Total environments: {stats['total_environments']}")
print(f" Active environments: {stats['active_environments']}")
print(f" Health checks performed: {stats['health_checks_performed']}")
print(f" Environments scaled: {stats['environments_scaled']}")
print(" Resource utilization:")
for res_type, details in stats['resource_utilization'].items():
utilization = details['utilization'] * 100
print(f" - {res_type}: {utilization:.1f}% ({details['allocated']}/{details['capacity']})")
print("\n✓ Comprehensive environment management complete!")
Agentic Architecture Pattern: Environment Management
Pattern 279: 279 Environment Management – Line-by-Line Explanation
Overview
Pattern 279: Environment Management
Purpose: Environment provisioning, lifecycle management, and health monitoring
Code Structure Analysis
File Information
- Pattern Number: 279
- Pattern Name: 279 Environment Management
- File Path:
patterns\deployment\279_environment_management.py - Total Lines: 646
Detailed Code Explanation
Module Docstring
"""
Pattern 279: Environment Management
Purpose: Environment provisioning, lifecycle management, and health monitoring
"""
Explanation: This module docstring describes the purpose and key features of the 279 Environment Management pattern.
Imports Section
from typing import Dict, Any, List, Optional, Set
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from enum import Enum
from collections import defaultdict
import random # First 20 imports shown
Explanation: The module imports necessary dependencies:
– from typing import Dict, Any, List, Optional, Set: Type hints for better code documentation
– from dataclasses import dataclass, field: Data class decorators for clean data structures
– from datetime import datetime, timedelta: Date and time utilities
– from enum import Enum: Enumeration support for fixed sets of values
Enumerations
EnvironmentType (Line 15)
class EnvironmentType(Enum):
DEVELOPMENT
STAGING
PRODUCTION
TESTING
UAT
Purpose: Type of environment.
Values:
– DEVELOPMENT: Represents development
– STAGING: Represents staging
– PRODUCTION: Represents production
– TESTING: Represents testing
– UAT: Represents uat
EnvironmentStatus (Line 24)
class EnvironmentStatus(Enum):
CREATING
ACTIVE
DEGRADED
MAINTENANCE
TERMINATING
TERMINATED
Purpose: Status of environment.
Values:
– CREATING: Represents creating
– ACTIVE: Currently operational
– DEGRADED: Represents degraded
– MAINTENANCE: Represents maintenance
– TERMINATING: Represents terminating
– TERMINATED: Represents terminated
ResourceType (Line 34)
class ResourceType(Enum):
COMPUTE
STORAGE
NETWORK
DATABASE
Purpose: Type of resource.
Values:
– COMPUTE: Represents compute
– STORAGE: Represents storage
– NETWORK: Represents network
– DATABASE: Represents database
HealthStatus (Line 42)
class HealthStatus(Enum):
HEALTHY
WARNING
CRITICAL
UNKNOWN
Purpose: Health status of environment.
Values:
– HEALTHY: Represents healthy
– WARNING: Warning severity level
– CRITICAL: Represents critical
– UNKNOWN: Represents unknown
Classes
EnvironmentType (Line 15)
Description: Type of environment.
EnvironmentStatus (Line 24)
Description: Status of environment.
ResourceType (Line 34)
Description: Type of resource.
HealthStatus (Line 42)
Description: Health status of environment.
Resource (Line 51)
Description: Represents a resource in an environment.
HealthCheck (Line 62)
Description: Health check result.
Environment (Line 72)
Description: Represents a deployment environment.
EnvironmentManagement (Line 85)
Description: Implements environment management pattern.
Features: – Environment provisioning – Resource allocation – Health monitoring – Environment lifecycle management – Auto-scaling – Environment isolation
Methods:
__init__ (Line 98)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
create_environment (Line 117)
def create_environment(self, name, env_type, resources):
"""Create a new environment.
Args:
name: Environment name
env_type: Type of environment
resources: Required resources {type: amount}
Returns:
Status of environment creation"""
Purpose: Create a new environment.
Args: name: Environment name env_type: Type of environment resources: Required resources {type: amount}
Returns: Status of environment creation
Parameters:
– self: Instance reference
– name: Identifier or label
– env_type: Parameter for env_type
– resources: Parameter for resources
terminate_environment (Line 193)
def terminate_environment(self, environment_id):
"""Terminate an environment and release resources.
Args:
environment_id: ID of environment to terminate
Returns:
Status of termination"""
Purpose: Terminate an environment and release resources.
Args: environment_id: ID of environment to terminate
Returns: Status of termination
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
perform_health_check (Line 230)
def perform_health_check(self, environment_id):
"""Perform comprehensive health check on environment.
Args:
environment_id: ID of environment to check
Returns:
Health check results"""
Purpose: Perform comprehensive health check on environment.
Args: environment_id: ID of environment to check
Returns: Health check results
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
scale_environment (Line 326)
def scale_environment(self, environment_id, resource_type, scale_factor):
"""Scale environment resources.
Args:
environment_id: ID of environment
resource_type: Type of resource to scale
scale_factor: Factor to scale by (1.5 = 50% increase)
Returns:
Status of scaling operation"""
Purpose: Scale environment resources.
Args: environment_id: ID of environment resource_type: Type of resource to scale scale_factor: Factor to scale by (1.5 = 50% increase)
Returns: Status of scaling operation
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
– resource_type: Parameter for resource_type
– scale_factor: Parameter for scale_factor
get_environment_info (Line 402)
def get_environment_info(self, environment_id):
"""Get detailed environment information."""
Purpose: Get detailed environment information.
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
list_environments (Line 451)
def list_environments(self, env_type, status):
"""List environments with optional filters."""
Purpose: List environments with optional filters.
Parameters:
– self: Instance reference
– env_type: Parameter for env_type
– status: Parameter for status
get_statistics (Line 478)
def get_statistics(self):
"""Get environment management statistics."""
Purpose: Get environment management statistics.
Parameters:
– self: Instance reference
EnvironmentManagementPattern (Line 511)
Description: Coordinator for environment management.
Manages environment lifecycle and resources.
Methods:
__init__ (Line 518)
def __init__(self):
"""No method docstring."""
Purpose: No method docstring.
Parameters:
– self: Instance reference
create_environment (Line 521)
def create_environment(self, name, env_type, resources):
"""Create environment."""
Purpose: Create environment.
Parameters:
– self: Instance reference
– name: Identifier or label
– env_type: Parameter for env_type
– resources: Parameter for resources
terminate_environment (Line 525)
def terminate_environment(self, environment_id):
"""Terminate environment."""
Purpose: Terminate environment.
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
perform_health_check (Line 529)
def perform_health_check(self, environment_id):
"""Perform health check."""
Purpose: Perform health check.
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
scale_environment (Line 533)
def scale_environment(self, environment_id, resource_type, scale_factor):
"""Scale environment."""
Purpose: Scale environment.
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
– resource_type: Parameter for resource_type
– scale_factor: Parameter for scale_factor
get_environment_info (Line 537)
def get_environment_info(self, environment_id):
"""Get environment info."""
Purpose: Get environment info.
Parameters:
– self: Instance reference
– environment_id: Parameter for environment_id
list_environments (Line 541)
def list_environments(self):
"""List environments."""
Purpose: List environments.
Parameters:
– self: Instance reference
get_statistics (Line 545)
def get_statistics(self):
"""Get statistics."""
Purpose: Get statistics.
Parameters:
– self: Instance reference
Design Patterns Used
- Strategy Pattern: Different execution strategies for various scenarios
- State Pattern: Managing different states in the workflow
- Chain of Responsibility: Sequential processing through workflow nodes
- Observer Pattern: Tracking and monitoring pattern execution
- Factory Pattern: Creating instances with proper configuration
Usage Example
# Initialize the pattern
pattern = EnvironmentType(name="example", model_name="gpt-4")
# Configure and execute
result = pattern.execute(data={"key": "value"})
# Check results
print(result)
Key Concepts
- LLM Integration: Uses LangChain/OpenAI for intelligent decision-making
- Workflow Orchestration: LangGraph manages execution flow through nodes
- State Management: TypedDict defines workflow state structure
- Error Handling: Comprehensive error handling and fallback mechanisms
- Extensibility: Designed for easy customization and extension
Extension Points
This pattern can be extended by: 1. Adding custom workflow nodes 2. Implementing additional validation logic 3. Integrating with external services 4. Customizing LLM prompts and responses 5. Adding monitoring and logging capabilities