Przejdź do głównej zawartości

Advanced context concepts

Working with multiple environments

Development workflow

import cgc.sdk.context as context
import cgc.sdk.resource as resource

def deploy_to_environment(context_number, app_config):
"""Deploy an application to a specific environment"""

# Switch to the target environment
context.switch_context(context_number)
print(f"Switched to context {context_number}")

# Deploy the application
response = resource.resource_create(**app_config)

if response['code'] == 200:
print(f"Successfully deployed to context {context_number}")
else:
print(f"Deployment failed: {response['message']}")

return response

# Application configuration
app = {
'name': 'my-app',
'image_name': 'nginx:latest',
'cpu': 1,
'memory': 2
}

# Deploy to development (context 1)
deploy_to_environment(1, app)

# Deploy to staging (context 2)
deploy_to_environment(2, app)

# Deploy to production (context 3) with more resources
prod_app = {**app, 'cpu': 4, 'memory': 8}
deploy_to_environment(3, prod_app)

Environment comparison

import cgc.sdk.context as context
import cgc.sdk.resource as resource

def compare_environments():
"""Compare resources across all environments"""

# Get all contexts
contexts_list = context.list_contexts()
environment_data = {}

for i, ctx in enumerate(contexts_list, 1):
# Switch to each context
context.switch_context(i)

# Get resources in this context
resources = resource.compute_list()

if resources['code'] == 200:
pods = resources['details']['pods_list']
app_names = [
pod['labels'].get('app-name', 'unknown')
for pod in pods
if 'app-name' in pod.get('labels', {})
]
environment_data[f"Context {i}"] = app_names
else:
environment_data[f"Context {i}"] = "Error fetching resources"

# Display comparison
for env, apps in environment_data.items():
print(f"\n{env}:")
if isinstance(apps, list):
for app in apps:
print(f" - {app}")
else:
print(f" {apps}")

return environment_data

# Compare all environments
comparison = compare_environments()

Context management patterns

Safe context switching

import cgc.sdk.context as context
import cgc.sdk.exceptions as exceptions

class ContextManager:
"""Helper class for safe context management"""

def __init__(self):
self.original_context = None

def switch_to(self, context_number):
"""Switch to a context with error handling"""
try:
context.switch_context(context_number)
print(f"Successfully switched to context {context_number}")
return True
except exceptions.SDKException as e:
if e.code == -1:
print(f"Context {context_number} does not exist")
else:
print(f"Failed to switch context: {e}")
return False

def with_context(self, context_number):
"""Context manager for temporary context switching"""
return ContextScope(context_number)

class ContextScope:
"""Context manager for temporary context switching"""

def __init__(self, target_context):
self.target_context = target_context
self.original_context = 1 # Default to 1

def __enter__(self):
# Save current context (simplified - assumes we track it)
# In production, you'd want to track the current context
context.switch_context(self.target_context)
return self

def __exit__(self, exc_type, exc_val, exc_tb):
# Restore original context
context.switch_context(self.original_context)

# Usage
manager = ContextManager()

# Simple switch
manager.switch_to(2)

# Temporary switch with context manager
with ContextScope(3):
# Work in context 3
resources = resource.compute_list()
print(f"Resources in context 3: {len(resources['details']['pods_list'])}")
# Automatically back to original context

Environment-specific operations

def perform_maintenance(context_number, operations):
"""Perform maintenance operations in a specific context"""

print(f"\nStarting maintenance in context {context_number}")

# Switch to target context
context.switch_context(context_number)

results = []
for op in operations:
try:
if op['action'] == 'restart':
# Delete and recreate
resource.resource_delete(op['name'])
response = resource.resource_create(**op['config'])
results.append({
'name': op['name'],
'action': 'restart',
'success': response['code'] == 200
})

elif op['action'] == 'scale':
# Update resource (delete and recreate with new specs)
resource.resource_delete(op['name'])
updated_config = {**op['config'], 'cpu': op['new_cpu'], 'memory': op['new_memory']}
response = resource.resource_create(**updated_config)
results.append({
'name': op['name'],
'action': 'scale',
'success': response['code'] == 200
})

except Exception as e:
results.append({
'name': op.get('name', 'unknown'),
'action': op['action'],
'success': False,
'error': str(e)
})

return results

# Define maintenance operations
maintenance_tasks = [
{
'action': 'restart',
'name': 'web-server',
'config': {
'name': 'web-server',
'image_name': 'nginx:latest',
'cpu': 2,
'memory': 4
}
},
{
'action': 'scale',
'name': 'api-server',
'config': {
'name': 'api-server',
'image_name': 'api:latest'
},
'new_cpu': 4,
'new_memory': 8
}
]

# Perform maintenance in staging
results = perform_maintenance(2, maintenance_tasks)

Multi-environment deployment

Progressive deployment strategy

import time

def progressive_deployment(app_config, contexts_order=[1, 2, 3]):
"""Deploy application progressively through environments"""

deployment_status = {}

for ctx in contexts_order:
env_name = {1: "Development", 2: "Staging", 3: "Production"}.get(ctx, f"Context {ctx}")

print(f"\n{'='*50}")
print(f"Deploying to {env_name} (Context {ctx})")
print(f"{'='*50}")

# Switch to context
try:
context.switch_context(ctx)
except exceptions.SDKException as e:
print(f"Failed to switch to context {ctx}: {e}")
deployment_status[env_name] = "Failed - Context switch error"
continue

# Deploy application
response = resource.resource_create(**app_config)

if response['code'] == 200:
print(f"✓ Deployment successful in {env_name}")

# Wait for resource to be ready
print(f"Waiting for application to be ready...")
max_wait = 60
waited = 0

while waited < max_wait:
if resource.resource_ready(app_config['name']):
print(f"✓ Application ready in {env_name}")
deployment_status[env_name] = "Success"
break
time.sleep(5)
waited += 5
else:
print(f"⚠ Application not ready after {max_wait} seconds")
deployment_status[env_name] = "Deployed but not ready"
else:
print(f"✗ Deployment failed in {env_name}: {response['message']}")
deployment_status[env_name] = f"Failed - {response['message']}"

# Stop progressive deployment on failure
if ctx < 3: # Not production yet
print("Stopping deployment due to failure")
break

# Summary
print(f"\n{'='*50}")
print("Deployment Summary:")
print(f"{'='*50}")
for env, status in deployment_status.items():
print(f"{env}: {status}")

return deployment_status

# Deploy application progressively
app = {
'name': 'progressive-app',
'image_name': 'myapp:v2.0',
'cpu': 2,
'memory': 4,
'environment_data': ['VERSION=2.0']
}

deployment_results = progressive_deployment(app)

Best practices

1. Always verify context

def verify_context(expected_context):
"""Verify you're in the expected context"""
contexts = context.list_contexts()

# This is a simplified check - in production you'd need
# to track the current context more reliably
if expected_context <= len(contexts):
return True
return False

# Before critical operations
if verify_context(3): # Production
print("Confirmed in production context")
# Perform production operations
else:
print("Not in expected context!")

2. Context-aware logging

import logging
from datetime import datetime

class ContextAwareLogger:
"""Logger that includes context information"""

def __init__(self):
self.current_context = 1

def log_operation(self, operation, context_num):
"""Log an operation with context information"""
timestamp = datetime.now().isoformat()
env_name = {
1: "DEV",
2: "STAGING",
3: "PROD"
}.get(context_num, f"CTX{context_num}")

log_entry = f"[{timestamp}] [{env_name}] {operation}"
print(log_entry)

# In production, write to file or logging service
with open('context_operations.log', 'a') as f:
f.write(log_entry + '\n')

def switch_and_log(self, target_context):
"""Switch context and log the operation"""
try:
context.switch_context(target_context)
self.current_context = target_context
self.log_operation(f"Switched to context {target_context}", target_context)
return True
except Exception as e:
self.log_operation(f"Failed to switch to context {target_context}: {e}", self.current_context)
return False

# Usage
logger = ContextAwareLogger()
logger.switch_and_log(2)
logger.log_operation("Deployed nginx:latest", 2)

3. Environment isolation

def isolated_operation(context_number, operation_func, *args, **kwargs):
"""Execute an operation in an isolated context"""

original_context = 1 # You'd need to track this properly

try:
# Switch to target context
context.switch_context(context_number)

# Perform operation
result = operation_func(*args, **kwargs)

return {'success': True, 'result': result}

except Exception as e:
return {'success': False, 'error': str(e)}

finally:
# Always restore original context
try:
context.switch_context(original_context)
except:
pass # Best effort restoration

# Use for isolated operations
result = isolated_operation(
2, # staging context
resource.resource_create,
name='test-app',
image_name='nginx:latest',
cpu=1,
memory=2
)

Error handling

Common exceptions

import cgc.sdk.context as context
import cgc.sdk.exceptions as exceptions

def handle_context_errors():
"""Demonstrate context error handling"""

try:
# Try to switch to non-existent context
context.switch_context(999)

except exceptions.SDKException as e:
if e.code == -1:
print(f"Context does not exist: {e}")

# List available contexts
available = context.list_contexts()
print(f"Available contexts: {available}")

# Use a valid context
if len(available) > 0:
context.switch_context(1)
print("Switched to default context")
else:
print(f"Unexpected SDK error: {e}")

except Exception as e:
print(f"Unexpected error: {e}")

# Handle errors gracefully
handle_context_errors()

Troubleshooting

Context not found

If you get "Context does not exist" error:

  1. List available contexts:
contexts = context.list_contexts()
print(f"Available: {contexts}")
  1. Check context files exist:
# Context files are named: cfg.json, 2.json, 3.json, etc.
import os
config_dir = os.path.expanduser("~/.cgc/") # Typical location
for file in os.listdir(config_dir):
if file.endswith('.json'):
print(f"Found: {file}")

Context switch not working

If context switching seems to have no effect:

  1. Verify the switch was successful:
try:
context.switch_context(2)
print("Switch successful")
except Exception as e:
print(f"Switch failed: {e}")
  1. Test with a simple operation:
# After switching, list resources to verify
resources = resource.compute_list()
print(f"Resources in context: {len(resources['details']['pods_list'])}")

Permission issues

If you get permission errors after switching contexts:

  1. Verify credentials for each context
  2. Check namespace access permissions
  3. Ensure configuration files are readable

Summary

Context management enables:

  • Multi-environment workflows
  • Safe production deployments
  • Environment isolation
  • Progressive deployment strategies

Key points:

  • Contexts are numbered (1, 2, 3, ...)
  • Each context is independent
  • Always verify context before critical operations
  • Use error handling for robust applications